Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,50 @@
import js from "@eslint/js";
import globals from "globals";
import tseslint from "typescript-eslint";
import inspa from "./scripts/eslint-boundaries.mjs";

// Imports that crossed a package boundary when the boundary rule landed (#5). Each is `{ file, import }`, the import
// exactly as written. Only remove entries: a new crossing import fails lint, and scripts/eslint-boundaries.test.mjs
// fails on an entry whose import is gone. Owners: e2e specs belong to their feature's lane, the rest to engine.
const BOUNDARY_ALLOW = [
// e2e specs drive the CLI's proxy and MCP selection tool directly; `inspa` exports neither.
{ file: "e2e/proxy-hmr.spec.ts", import: "../packages/cli/src/proxy/index" },
{ file: "e2e/proxy-webpack-hmr.spec.ts", import: "../packages/cli/src/proxy/index" },
{ file: "e2e/runtime-source.spec.ts", import: "../packages/cli/src/proxy/index" },
{ file: "e2e/selection-agent-loop.spec.ts", import: "../packages/cli/src/mcp/tools/selection" },
{ file: "e2e/selection-stale-page.spec.ts", import: "../packages/cli/src/mcp/tools/selection" },
{ file: "e2e/selection-sync.spec.ts", import: "../packages/cli/src/mcp/tools/selection" },
// The demo app's unit tests stamp JSX from source so they run without a build (`@inspa/vite-plugin/transform`
// resolves to dist/).
{ file: "examples/invoices/vitest.config.ts", import: "../../packages/vite-plugin/src/transform.js" },
// Tests from inplace that cross between the proxy (cli) and the overlay's runtime source (vite-plugin), which
// share code neither package exports. They go away when @inspa/overlay and @inspa/daemon are split out.
{ file: "packages/cli/src/mcp/server.test.ts", import: "../../../vite-plugin/src/transform.js" },
{
file: "packages/cli/src/proxy/react19/react19.test.ts",
import: "../../../../vite-plugin/src/overlay/runtime-source/react19/capture.js",
},
{
file: "packages/cli/src/proxy/webpack-runtime.test.ts",
import: "../../../vite-plugin/src/overlay/runtime-source/bundled.js",
},
{
file: "packages/cli/src/proxy/webpack-runtime.test.ts",
import: "../../../vite-plugin/src/overlay/runtime-source/react19/capture.js",
},
{ file: "packages/cli/test/components-api.integration.test.ts", import: "../../vite-plugin/src/transform.js" },
{ file: "packages/core/src/source-resolve.test.ts", import: "../../vite-plugin/src/overlay/runtime-source/hash.js" },
{
file: "packages/vite-plugin/src/overlay/runtime-source/react19/arguments.test.ts",
import: "../../../../../cli/src/proxy/react19/runtime-uses.js",
},
{
file: "packages/vite-plugin/src/overlay/runtime-source/react19/engines.test.ts",
import: "../../../../../cli/src/proxy/react19/runtime-uses.js",
},
// Checks the plugin's token themes against core's; @inspa/core does not export token-themes.
{ file: "packages/vite-plugin/test/token-themes-parity.test.ts", import: "../../core/src/token-themes.js" },
];

export default tseslint.config(
{
Expand Down Expand Up @@ -30,4 +74,9 @@ export default tseslint.config(
],
},
},
// Packages import only each other's public entry points (#5, scripts/eslint-boundaries.mjs).
{
plugins: { inspa },
rules: { "inspa/package-boundaries": ["error", { allow: BOUNDARY_ALLOW }] },
},
);
174 changes: 174 additions & 0 deletions scripts/eslint-boundaries.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
// ESLint rule `inspa/package-boundaries` (#5): packages talk only through each other's public entry points
// (docs/architecture.md, rules for the port: "Cross a boundary only through `@inspa/protocol` and public exports").
//
// It reports two kinds of import:
// - a bare import into another package's source: `@inspa/<pkg>/src/...`, or `<workspace name>/src/...`
// (`inspa/src/...`). Import the package name or one of its `exports` subpaths instead.
// - a relative import that leaves the file's package folder for another one (`../../vite-plugin/src/x.js`
// from `packages/cli`, `../packages/cli/src/...` from `e2e/`). A package folder is a workspace folder
// (`packages/*`, `apps/*`, `examples/*` from the root package.json); everything else is the root.
//
// Every way a module path is written down counts: import/export ... from, `import()`, `require()`, TypeScript
// `import("...")` types and `import x = require()`, and vitest's `vi.mock()`-family calls.
//
// Existing violations are allow-listed one by one in eslint.config.js as `{ file, import }` (file relative to the
// repo root, the import exactly as written), each with a comment saying why it is still there. A new import, even
// in an allow-listed file, fails. scripts/eslint-boundaries.test.mjs fails on an allow-list entry whose import is
// gone, so the list only shrinks.
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";

export const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");

const toPosix = (p) => p.split(sep).join("/");

/** The root package.json's workspace globs as parent folders: `packages/*` -> `packages`. Only `dir/*` globs. */
export function workspaceParents(root = ROOT) {
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
const globs = Array.isArray(pkg.workspaces) ? pkg.workspaces : (pkg.workspaces?.packages ?? []);
return globs.filter((g) => /^[^*]+\/\*$/.test(g)).map((g) => g.slice(0, -2));
}

/** Workspace folder -> its package name (null when the folder has no package.json, e.g. apps/desktop today). */
export function workspaces(root = ROOT) {
const out = new Map();
for (const parent of workspaceParents(root)) {
const dir = join(root, parent);
if (!existsSync(dir)) continue;
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
const pj = join(dir, entry.name, "package.json");
const name = existsSync(pj) ? (JSON.parse(readFileSync(pj, "utf8")).name ?? null) : null;
out.set(`${parent}/${entry.name}`, name);
}
}
return out;
}

/** The package folder a repo-relative posix path is in (`packages/core`), or "" for the root. */
export function packageFolder(relPath, parents) {
const parts = relPath.split("/");
if (parts[0] === ".." || parts.length < 2) return "";
return parents.includes(parts[0]) ? `${parts[0]}/${parts[1]}` : "";
}

/** The package name a bare specifier reaches into the source of, or null. `@inspa/core/src/x` -> `@inspa/core`. */
export function deepSourceImport(spec, names) {
const m = /^(@[^/]+\/[^/]+|[^@./][^/]*)\/src(?:\/|$)/.exec(spec);
if (!m) return null;
return m[1].startsWith("@inspa/") || names.has(m[1]) ? m[1] : null;
}

/**
* Why importing `spec` from `filename` (absolute) crosses a package boundary, or null when it doesn't.
* Returns `{ kind: "deep", pkg }` or `{ kind: "relative", from, to, pkg }`.
*/
export function boundaryViolation(filename, spec, { root = ROOT, parents, folders } = {}) {
parents ??= workspaceParents(root);
folders ??= workspaces(root);
if (spec.startsWith(".")) {
const fromRel = toPosix(relative(root, filename));
const toRel = toPosix(relative(root, resolve(dirname(filename), spec)));
const from = packageFolder(fromRel, parents);
const to = packageFolder(toRel, parents);
if (to && to !== from) return { kind: "relative", from: from || "the repo root", to, pkg: folders.get(to) ?? null };
return null;
}
const pkg = deepSourceImport(spec, new Set([...folders.values()].filter(Boolean)));
return pkg ? { kind: "deep", pkg } : null;
}

let layout = null;
/** The repo's workspace layout, read once per lint run. */
function repoLayout() {
layout ??= { parents: workspaceParents(), folders: workspaces() };
return layout;
}

const VI_MODULE_CALLS = new Set(["mock", "doMock", "unmock", "doUnmock", "importActual", "importMock"]);

function stringValue(node) {
if (!node) return null;
if (node.type === "Literal" && typeof node.value === "string") return node.value;
if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked;
return null;
}

const rule = {
meta: {
type: "problem",
docs: { description: "Packages import only each other's public entry points" },
schema: [
{
type: "object",
properties: {
allow: {
type: "array",
items: {
type: "object",
properties: { file: { type: "string" }, import: { type: "string" } },
required: ["file", "import"],
additionalProperties: false,
},
},
},
additionalProperties: false,
},
],
messages: {
deep: "`{{spec}}` reaches into the source of {{pkg}}. Import `{{pkg}}` or one of its `exports` subpaths instead (#5).",
relative:
"`{{spec}}` crosses from {{from}} into {{to}}. Import {{target}} through its public entry point instead (#5).",
},
},
create(context) {
const filename = context.filename ?? context.getFilename();
const fileRel = toPosix(relative(ROOT, filename));
const allowed = new Set(
(context.options[0]?.allow ?? []).filter((a) => a.file === fileRel).map((a) => a.import),
);
const { parents, folders } = repoLayout();

function check(node) {
const spec = stringValue(node);
if (spec === null || allowed.has(spec)) return;
const v = boundaryViolation(filename, spec, { parents, folders });
if (!v) return;
if (v.kind === "deep") context.report({ node, messageId: "deep", data: { spec, pkg: v.pkg } });
else
context.report({
node,
messageId: "relative",
data: { spec, from: v.from, to: v.to, target: v.pkg ? `\`${v.pkg}\`` : v.to },
});
}

return {
ImportDeclaration: (n) => check(n.source),
ExportAllDeclaration: (n) => check(n.source),
ExportNamedDeclaration: (n) => n.source && check(n.source),
ImportExpression: (n) => check(n.source),
TSImportType(n) {
// typescript-eslint 8 has `source` (a string literal); older versions wrap it in `argument`.
const arg = n.source ?? n.argument;
check(arg?.type === "TSLiteralType" ? arg.literal : arg);
},
TSExternalModuleReference: (n) => check(n.expression),
CallExpression(n) {
const c = n.callee;
if (c.type === "Identifier" && c.name === "require") return check(n.arguments[0]);
if (
c.type === "MemberExpression" &&
!c.computed &&
c.object.type === "Identifier" &&
c.object.name === "vi" &&
VI_MODULE_CALLS.has(c.property.name)
)
return check(n.arguments[0]);
},
};
},
};

export default { meta: { name: "inspa" }, rules: { "package-boundaries": rule } };
134 changes: 134 additions & 0 deletions scripts/eslint-boundaries.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { Linter } from "eslint";
import tseslint from "typescript-eslint";
import { describe, expect, it } from "vitest";
import config from "../eslint.config.js";
import inspa, { deepSourceImport, packageFolder, ROOT, workspaceParents, workspaces } from "./eslint-boundaries.mjs";

const RULE = "inspa/package-boundaries";

function lint(file, code, allow = []) {
const linter = new Linter({ configType: "flat", cwd: ROOT });
const messages = linter.verify(
code,
[
{
files: ["**/*.ts", "**/*.mjs"],
languageOptions: { parser: tseslint.parser, ecmaVersion: 2022, sourceType: "module" },
plugins: { inspa },
rules: { [RULE]: ["error", { allow }] },
},
],
{ filename: join(ROOT, file) },
);
const fatal = messages.filter((m) => m.fatal);
if (fatal.length) throw new Error(fatal.map((m) => m.message).join("\n"));
return messages.map((m) => m.message);
}

describe("package boundaries lint (#5)", () => {
it("reads the workspace folders from the root package.json", () => {
expect(workspaceParents()).toEqual(expect.arrayContaining(["packages", "apps", "examples"]));
const folders = workspaces();
expect(folders.get("packages/core")).toBe("@inspa/core");
expect(folders.get("packages/cli")).toBe("inspa");
});

it("finds the package folder of a path", () => {
const parents = ["packages", "apps", "examples"];
expect(packageFolder("packages/core/src/index.ts", parents)).toBe("packages/core");
expect(packageFolder("apps/desktop/src-tauri/x.rs", parents)).toBe("apps/desktop");
expect(packageFolder("e2e/a.spec.ts", parents)).toBe("");
expect(packageFolder("vitest.config.ts", parents)).toBe("");
expect(packageFolder("../elsewhere/x.ts", parents)).toBe("");
});

it("spots bare imports into a package's source", () => {
const names = new Set(["@inspa/core", "inspa", "invoices"]);
expect(deepSourceImport("@inspa/core/src/edit/index.js", names)).toBe("@inspa/core");
expect(deepSourceImport("@inspa/protocol/src", names)).toBe("@inspa/protocol");
expect(deepSourceImport("inspa/src/proxy/index.js", names)).toBe("inspa");
expect(deepSourceImport("@inspa/core", names)).toBeNull();
expect(deepSourceImport("@inspa/core/guardrails", names)).toBeNull();
expect(deepSourceImport("@inspa/core/srcmaps", names)).toBeNull();
expect(deepSourceImport("react/src/x", names)).toBeNull();
});

it("fails relative imports that leave the package, in every form", () => {
const into = "../../vite-plugin/src/transform.js";
const file = "packages/cli/src/a.ts";
for (const code of [
`import { x } from "${into}";`,
`import "${into}";`,
`import type { X } from "${into}";`,
`export * from "${into}";`,
`export { x } from "${into}";`,
`await import("${into}");`,
`await import(\`${into}\`);`,
`require("${into}");`,
`vi.mock("${into}", () => ({}));`,
`await vi.importActual("${into}");`,
`type T = typeof import("${into}");`,
`import x = require("${into}");`,
]) {
const msgs = lint(file, code);
expect(msgs, code).toHaveLength(1);
expect(msgs[0]).toContain("crosses from packages/cli into packages/vite-plugin");
expect(msgs[0]).toContain("`@inspa/vite-plugin`");
}
});

it("fails root files (e2e, scripts) reaching into a package, and names folders without a package.json", () => {
expect(lint("e2e/a.spec.ts", `import { startProxy } from "../packages/cli/src/proxy/index";`)[0]).toContain(
"crosses from the repo root into packages/cli",
);
expect(lint("scripts/a.mjs", `import "../apps/nothing-here/src/main.js";`)[0]).toContain(
"into apps/nothing-here",
);
});

it("fails deep bare imports", () => {
expect(lint("packages/ui/src/a.ts", `import { x } from "@inspa/core/src/edit/index.js";`)[0]).toContain(
"reaches into the source of @inspa/core",
);
expect(lint("e2e/a.spec.ts", `import "inspa/src/proxy/index.js";`)).toHaveLength(1);
});

it("allows public entry points, imports inside a package, root-to-root imports and plain strings", () => {
const ok = [
`import { x } from "@inspa/core";`,
`import { y } from "@inspa/core/guardrails";`,
`import { z } from "./local.js";`,
`import { w } from "../proxy/index.js";`,
`import { v } from "../test/helpers.js";`,
`const s = "import x from '../../vite-plugin/src/transform.js'";`,
`const t = \`\${dir}/../../core/src/a.ts\`;`,
`foo.mock("../../core/src/a.js");`,
];
for (const code of ok) expect(lint("packages/cli/src/a.ts", code), code).toEqual([]);
expect(lint("e2e/a.spec.ts", `import { h } from "./helpers/app";`)).toEqual([]);
expect(lint("e2e/a.spec.ts", `import { h } from "../scripts/edit-timings.mjs";`)).toEqual([]);
});

it("allow-lists one exact import in one file, not the file", () => {
const allow = [{ file: "packages/cli/src/a.ts", import: "../../core/src/a.js" }];
expect(lint("packages/cli/src/a.ts", `import "../../core/src/a.js";`, allow)).toEqual([]);
expect(lint("packages/cli/src/a.ts", `import "../../core/src/b.js";`, allow)).toHaveLength(1);
expect(lint("packages/cli/src/other.ts", `import "../../core/src/a.js";`, allow)).toHaveLength(1);
});

it("every allow-list entry in eslint.config.js is still a real import (the list only shrinks)", () => {
const entry = config.find((c) => c.rules?.[RULE]);
expect(entry, "eslint.config.js turns the rule on").toBeTruthy();
const allow = entry.rules[RULE][1].allow;
expect(allow.length).toBeGreaterThan(0);
const stale = allow.filter(({ file, import: spec }) => {
const abs = join(ROOT, file);
if (!existsSync(abs)) return true;
const src = readFileSync(abs, "utf8");
return ![`"${spec}"`, `'${spec}'`, `\`${spec}\``].some((q) => src.includes(q));
});
expect(stale, "remove these entries from BOUNDARY_ALLOW in eslint.config.js").toEqual([]);
});
});
Loading