@ref0/workspace 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ import { Schema } from "effect";
2
+ // src/lint/generic/folder-layers.ts
3
+ const decodeFolderImportsOptions = Schema.decodeUnknownSync(Schema.Tuple([Schema.Struct({
4
+ root: Schema.String,
5
+ sources: Schema.Record(Schema.String, Schema.Struct({
6
+ layers: Schema.Array(Schema.Array(Schema.String)),
7
+ exceptions: Schema.optionalKey(Schema.Record(Schema.String, Schema.Array(Schema.String))),
8
+ features: Schema.optionalKey(Schema.Array(Schema.String)),
9
+ entries: Schema.optionalKey(Schema.Literals(["reexports", "code"]))
10
+ }))
11
+ })]));
12
+ /** The rule's options as decoded: the root, and each source with its places' ranks. */
13
+ const folderImportsOf = (options) => {
14
+ const [{ root, sources }] = decodeFolderImportsOptions(options);
15
+ return {
16
+ root,
17
+ sources: Object.entries(sources).map(([folder, source]) => ({
18
+ ...source,
19
+ folder,
20
+ ranks: new Map(source.layers.flatMap((layer, rank) => layer.map((place) => [place, rank])))
21
+ }))
22
+ };
23
+ };
24
+ /** The module a path names, without its extension, such as `protocol/bytes/sha1`. */
25
+ const moduleNamed = (path) => path.replace(/\.[cm]?[jt]sx?$/, "");
26
+ /** Whether a module sits at the top of its source. */
27
+ const atTop = (module) => !module.includes("/");
28
+ /**
29
+ * The place that holds `module`: the deepest place it's in, such as `protocol/bytes` for
30
+ * `protocol/bytes/sha1`. A module in no place gives the first folder on its path that holds no
31
+ * place, such as `drafts` for `drafts/idea`, or the module itself.
32
+ */
33
+ const placeOf = (source, module) => {
34
+ const places = [...source.ranks.keys()];
35
+ const holding = places.filter((place) => module === place || module.startsWith(`${place}/`)).toSorted((a, b) => b.length - a.length)[0];
36
+ if (holding !== void 0) return holding;
37
+ const folders = module.split("/").slice(0, -1);
38
+ return folders.map((_, depth) => folders.slice(0, depth + 1).join("/")).find((folder) => !places.some((place) => place.startsWith(`${folder}/`))) ?? module;
39
+ };
40
+ const testingFile = /(^|\/)testing\//;
41
+ /**
42
+ * What's wrong with `file` importing `module`, both from the source's folder, if anything: a place
43
+ * in no layer, an entry point imported, a feature imported from outside it, or a place beside its
44
+ * own or above it. The source's exceptions aren't read here.
45
+ */
46
+ const layerProblem = (source, file, module) => {
47
+ const fromModule = moduleNamed(file);
48
+ if (source.entries !== void 0 && atTop(fromModule)) return void 0;
49
+ const from = placeOf(source, fromModule);
50
+ if (source.entries !== void 0 && atTop(module)) return {
51
+ messageId: "entry",
52
+ data: {
53
+ from,
54
+ to: module
55
+ }
56
+ };
57
+ const to = placeOf(source, module);
58
+ if (from === to) return void 0;
59
+ const fromRank = source.ranks.get(from);
60
+ const toRank = source.ranks.get(to);
61
+ if (fromRank === void 0 || toRank === void 0) return {
62
+ messageId: "unplaced",
63
+ data: { place: fromRank === void 0 ? from : to }
64
+ };
65
+ const features = source.features ?? [];
66
+ if (features.includes(to) && !features.includes(from) && !testingFile.test(file)) return {
67
+ messageId: "feature",
68
+ data: {
69
+ from,
70
+ to
71
+ }
72
+ };
73
+ if (toRank < fromRank) return void 0;
74
+ return {
75
+ messageId: toRank === fromRank ? "beside" : "above",
76
+ data: {
77
+ from,
78
+ to
79
+ }
80
+ };
81
+ };
82
+ export { folderImportsOf, layerProblem, moduleNamed, placeOf };
@@ -0,0 +1,34 @@
1
+ import { Schema } from "effect";
2
+ // src/lint/generic/imports.ts
3
+ const isString = Schema.is(Schema.String);
4
+ /** The module a dynamic import names, when it's written out. */
5
+ const sourceOf = (node) => {
6
+ if (node.type === "Literal") return isString(node.value) ? node.value : void 0;
7
+ return node.type === "TemplateLiteral" && node.expressions.length === 0 ? node.quasis[0]?.value.cooked ?? void 0 : void 0;
8
+ };
9
+ /**
10
+ * A visitor that hands `check` each import in a file: its node, the module it names, and whether
11
+ * it takes only types, so it loads nothing. That's an import, a re-export, a dynamic import whose
12
+ * module is written out, and an `import()` type. `import { type A }` isn't types only:
13
+ * `verbatimModuleSyntax` keeps it as `import {} from`, which still loads its module. It visits
14
+ * Oxlint's tree in a rule, and oxc's from `parseSync`, so each node is only what it reads.
15
+ */
16
+ const importsVisitor = (check) => ({
17
+ ImportDeclaration(node) {
18
+ check(node, node.source.value, node.importKind === "type");
19
+ },
20
+ ExportNamedDeclaration(node) {
21
+ if (node.source !== null) check(node, node.source.value, node.exportKind === "type");
22
+ },
23
+ ExportAllDeclaration(node) {
24
+ check(node, node.source.value, node.exportKind === "type");
25
+ },
26
+ ImportExpression(node) {
27
+ const source = sourceOf(node.source);
28
+ if (source !== void 0) check(node, source, false);
29
+ },
30
+ TSImportType(node) {
31
+ check(node, node.source.value, true);
32
+ }
33
+ });
34
+ export { importsVisitor };
@@ -0,0 +1,79 @@
1
+ import { decodeBudget, docTargetsVisitor, kindOf } from "./comments.mjs";
2
+ import { existsSync, readFileSync, statSync } from "node:fs";
3
+ import { join, relative, resolve, sep } from "node:path";
4
+ import { Schema } from "effect";
5
+ import { defineRule } from "vite-plus/lint/plugins";
6
+ // src/lint/generic/no-comments.ts
7
+ /**
8
+ * What the rule takes: the repo's root, as an absolute path, and `budget`, the budget file's path
9
+ * from it, such as `lint/comment-budget.json`, which `ref0-workspace comment-budget` writes.
10
+ */
11
+ const decodeOptions = Schema.decodeUnknownSync(Schema.Tuple([Schema.Struct({
12
+ root: Schema.String,
13
+ budget: Schema.String
14
+ })]));
15
+ /** Each budget file as last read, by its absolute path, with its modified time then. */
16
+ const budgets = /* @__PURE__ */ new Map();
17
+ /**
18
+ * The budget file at `path`, read again only when it has changed, as an editor's lint runs on. A
19
+ * repo with none yet gives every file a budget of none.
20
+ */
21
+ const budgetAt = (path) => {
22
+ if (!existsSync(path)) return {};
23
+ const at = statSync(path).mtimeMs;
24
+ const kept = budgets.get(path);
25
+ if (kept?.at === at) return kept.budget;
26
+ const budget = decodeBudget(readFileSync(path, "utf8"));
27
+ budgets.set(path, {
28
+ at,
29
+ budget
30
+ });
31
+ return budget;
32
+ };
33
+ /**
34
+ * Code says what it does, and a comment beside it goes stale, excuses a hack or repeats it. A file
35
+ * holds none, but for a tool's directive, a `SAFETY:` note on a type assertion, and a doc comment
36
+ * on a declaration, which says why it is as it is. Files older than the rule keep the banned
37
+ * comments they had, as a budget that only shrinks: `ref0-workspace comment-budget --write` lowers
38
+ * each file's to what's left.
39
+ */
40
+ const noCommentsRule = defineRule({
41
+ meta: {
42
+ messages: { overBudget: "This file holds {{count}} comments that are neither a doc comment on a declaration, a `SAFETY:` note nor a directive, and its budget is {{budget}}. Make the code say it, or put the reason in the doc comment of the declaration it explains." },
43
+ schema: [{
44
+ type: "object",
45
+ properties: {
46
+ root: { type: "string" },
47
+ budget: { type: "string" }
48
+ },
49
+ required: ["root", "budget"],
50
+ additionalProperties: false
51
+ }]
52
+ },
53
+ create(context) {
54
+ const [{ root, budget: budgetPath }] = decodeOptions(context.options);
55
+ const path = relative(root, resolve(context.filename)).split(sep).join("/");
56
+ const budget = budgetAt(join(root, budgetPath))[path] ?? 0;
57
+ const targets = /* @__PURE__ */ new Set();
58
+ return {
59
+ ...docTargetsVisitor((start) => targets.add(start)),
60
+ "Program:exit"() {
61
+ const text = context.sourceCode.text;
62
+ const firstStatement = context.sourceCode.ast.body[0];
63
+ if (firstStatement !== void 0) targets.add(firstStatement.start);
64
+ const banned = context.sourceCode.getAllComments().filter((comment) => kindOf(comment, text, targets) === "banned");
65
+ const firstOver = banned[budget];
66
+ if (firstOver === void 0) return;
67
+ context.report({
68
+ loc: context.sourceCode.getLoc(firstOver),
69
+ messageId: "overBudget",
70
+ data: {
71
+ count: String(banned.length),
72
+ budget: String(budget)
73
+ }
74
+ });
75
+ }
76
+ };
77
+ }
78
+ });
79
+ export { noCommentsRule };
@@ -0,0 +1,36 @@
1
+ import { Workspace } from "./workspace-packages.mjs";
2
+ /**
3
+ * How a package may import an entry point of another: `values`, anything; `types`, only with
4
+ * `import type`, which loads nothing; or `tests`, anything, but only in its tests and the modules
5
+ * in a `testing/` folder they share.
6
+ */
7
+ export type How = 'values' | 'types' | 'tests';
8
+ /**
9
+ * The entry points of a package another imports, by how it may import each. An entry point is a
10
+ * key of the package's `exports` without its `./`, such as `cast`, or `.` for its root. A
11
+ * pattern's is its folder: `testing/vectors` for `./testing/vectors/*.json`.
12
+ */
13
+ export type Edge = { readonly [Kind in How]?: ReadonlyArray<string>; };
14
+ /**
15
+ * What each package and app may import of the others, by name, then by entry point. Every package
16
+ * and app is named, with `{}` when it imports none of the others. `From` and `To` let a repo hold
17
+ * its graph to its own names, as `satisfies PackageGraph<Library | App, Library>`.
18
+ */
19
+ export type PackageGraph<From extends string = string, To extends string = string> = { readonly [Name in From]: { readonly [Name in To]?: Edge; }; };
20
+ /**
21
+ * What `ref0-generic/package-imports` takes: where the packages are, the graph, and `nodeFiles`,
22
+ * the files of a package that run only in Node, by its name, from its folder, which take values
23
+ * where it takes only types.
24
+ */
25
+ export interface PackageGraphOptions extends Workspace {
26
+ readonly graph: PackageGraph;
27
+ readonly nodeFiles?: {
28
+ readonly [name: string]: ReadonlyArray<string>;
29
+ };
30
+ }
31
+ /**
32
+ * What's wrong with the graph itself: a package it leaves out, a name no package has, an edge to
33
+ * an app, an edge to a package its importer doesn't depend on, an entry point the target doesn't
34
+ * export, and a Node-only file that isn't there. A repo's test expects none.
35
+ */
36
+ export declare const graphProblems: (options: PackageGraphOptions) => ReadonlyArray<string>;
@@ -0,0 +1,111 @@
1
+ import { ownerOf, workspacePackages } from "./workspace-packages.mjs";
2
+ import { existsSync } from "node:fs";
3
+ import { join, posix } from "node:path";
4
+ import { Schema } from "effect";
5
+ // src/lint/generic/package-graph.ts
6
+ const hows = [
7
+ "values",
8
+ "types",
9
+ "tests"
10
+ ];
11
+ const Edge = Schema.Struct({
12
+ values: Schema.optionalKey(Schema.Array(Schema.String)),
13
+ types: Schema.optionalKey(Schema.Array(Schema.String)),
14
+ tests: Schema.optionalKey(Schema.Array(Schema.String))
15
+ });
16
+ const PackageGraphOptions = Schema.Struct({
17
+ root: Schema.String,
18
+ packages: Schema.Array(Schema.String),
19
+ apps: Schema.optionalKey(Schema.Array(Schema.String)),
20
+ graph: Schema.Record(Schema.String, Schema.Record(Schema.String, Edge)),
21
+ nodeFiles: Schema.optionalKey(Schema.Record(Schema.String, Schema.Array(Schema.String)))
22
+ });
23
+ const decodePackageGraphOptions = Schema.decodeUnknownSync(Schema.Tuple([PackageGraphOptions]));
24
+ /** A test: what a test runner runs. */
25
+ const testFile = /\.(test|spec)(-d)?\.[cm]?[jt]sx?$/;
26
+ /** Code only tests run: a test, or a module in a `testing/` folder that tests share. */
27
+ const testCode = (path) => testFile.test(path) || /\/testing\/[^/]+$/.test(path);
28
+ /** The workspace package an import names, such as `@acme/ui` for `@acme/ui/cast`. */
29
+ const packageNamed = (source, packages) => {
30
+ const parts = source.split("/");
31
+ return packages.get(source.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? "");
32
+ };
33
+ /** Whether `subpath`, such as `./testing/vectors/keys.json`, matches an `exports` pattern. */
34
+ const matches = (pattern, subpath) => {
35
+ const [before = "", after = ""] = pattern.split("*");
36
+ return subpath.startsWith(before) && subpath.endsWith(after);
37
+ };
38
+ /**
39
+ * The entry point of `to` an import names, as the graph writes it: `cast` for `@acme/ui/cast`, `.`
40
+ * for `@acme/ui`, `base.css` for `@acme/ui/base.css?raw`, and a pattern's folder,
41
+ * `testing/vectors` for `@acme/core/testing/vectors/keys.json`.
42
+ */
43
+ const entryNamed = (to, source) => {
44
+ const subpath = `.${source.replace(/\?.*$/, "").slice(to.name.length)}`;
45
+ const pattern = to.entries.find((key) => key.includes("*") && matches(key, subpath));
46
+ const entry = pattern === void 0 ? subpath : pattern.slice(0, pattern.indexOf("/*"));
47
+ return entry === "." ? entry : entry.slice(2);
48
+ };
49
+ /** Whether `to` exports `entry`, as the graph writes it. */
50
+ const exported = (to, entry) => to.entries.some((key) => key === (entry === "." ? "." : `./${entry}`) || key.startsWith(`./${entry}/*`));
51
+ /** An entry point as an import names it, such as `@acme/ui/cast`, or `@acme/ui` for `.`. */
52
+ const shown = (to, entry) => entry === "." ? to : `${to}/${entry}`;
53
+ /** The entry points an edge lists, each in backticks, in order. */
54
+ const listed = (edge) => hows.flatMap((how) => edge[how] ?? []).toSorted().map((entry) => `\`${entry}\``).join(", ");
55
+ /** Why `path`, in `from`, may not import `to`'s `entry` as it does, if it may not. */
56
+ const edgeProblem = ({ graph, nodeFiles }, from, to, entry, path, typesOnly) => {
57
+ if (to.app) return "app";
58
+ const edge = graph[from.name]?.[to.name];
59
+ if (edge === void 0) return "edge";
60
+ if (entry === void 0) return "relative";
61
+ const how = hows.find((kind) => edge[kind]?.includes(entry) === true);
62
+ if (how === void 0) return "entry";
63
+ if (how === "tests" && !testCode(path)) return "tests";
64
+ const runsInNode = testFile.test(path) || (nodeFiles?.[from.name] ?? []).some((file) => `${from.directory}/${file}` === path);
65
+ return how === "types" && !typesOnly && !runsInNode ? "types" : void 0;
66
+ };
67
+ /** What the file at `path` imports by `source`: a package, or a relative path's target from the root. */
68
+ const importedBy = (packages, path, source) => {
69
+ if (!source.startsWith(".")) return {
70
+ to: packageNamed(source, packages),
71
+ target: void 0
72
+ };
73
+ const target = posix.normalize(posix.join(posix.dirname(path), source.replace(/\?.*$/, "")));
74
+ return {
75
+ to: ownerOf(target, packages),
76
+ target
77
+ };
78
+ };
79
+ /**
80
+ * What's wrong with the graph itself: a package it leaves out, a name no package has, an edge to
81
+ * an app, an edge to a package its importer doesn't depend on, an entry point the target doesn't
82
+ * export, and a Node-only file that isn't there. A repo's test expects none.
83
+ */
84
+ const graphProblems = (options) => {
85
+ const { root, graph, nodeFiles = {} } = options;
86
+ const packages = workspacePackages(options);
87
+ const missing = [...packages.keys()].flatMap((name) => graph[name] === void 0 ? [`${name} isn't in the graph: add it, with {} if it imports none of the others.`] : []);
88
+ const edges = Object.entries(graph).flatMap(([from, targets]) => {
89
+ const source = packages.get(from);
90
+ if (source === void 0) return [`${from} is no workspace package: remove it.`];
91
+ return Object.entries(targets).flatMap(([to, edge = {}]) => {
92
+ const target = packages.get(to);
93
+ if (target === void 0) return [`${from}'s edge names ${to}, which is no workspace package.`];
94
+ if (target.app) return [`${from}'s edge names ${to}, an app, which nothing imports.`];
95
+ const undeclared = source.dependencies.has(to) ? [] : [`${from} imports ${to} but its package.json doesn't depend on it.`];
96
+ const unexported = hows.flatMap((how) => (edge[how] ?? []).flatMap((entry) => exported(target, entry) ? [] : [`${from}'s edge lists ${shown(to, entry)}, which ${to} doesn't export.`]));
97
+ return [...undeclared, ...unexported];
98
+ });
99
+ });
100
+ const nodeOnly = Object.entries(nodeFiles).flatMap(([name, files]) => {
101
+ const owner = packages.get(name);
102
+ if (owner === void 0) return [`nodeFiles names ${name}, which is no workspace package.`];
103
+ return files.flatMap((file) => existsSync(join(root, owner.directory, file)) ? [] : [`nodeFiles lists ${owner.directory}/${file}, which isn't there.`]);
104
+ });
105
+ return [
106
+ ...missing,
107
+ ...edges,
108
+ ...nodeOnly
109
+ ];
110
+ };
111
+ export { decodePackageGraphOptions, edgeProblem, entryNamed, graphProblems, importedBy, listed, packageNamed, shown, testFile };
@@ -0,0 +1,85 @@
1
+ import { importsVisitor } from "./imports.mjs";
2
+ import { decodePackageGraphOptions, edgeProblem, entryNamed, importedBy, listed, shown, testFile } from "./package-graph.mjs";
3
+ import { decodedOnce } from "./rule-options.mjs";
4
+ import { fromRoot, ownerOf, workspacePackages } from "./workspace-packages.mjs";
5
+ import { resolve } from "node:path";
6
+ import { defineRule } from "vite-plus/lint/plugins";
7
+ // src/lint/generic/package-imports.ts
8
+ const optionsOf = decodedOnce((options) => decodePackageGraphOptions(options)[0]);
9
+ const packageImportsRule = defineRule({
10
+ meta: {
11
+ messages: {
12
+ app: "Nothing imports an app, and {{to}} is one. Move what {{from}} needs into a package.",
13
+ edge: "{{from}} doesn't import {{to}}: the package graph has no such edge.",
14
+ entry: "{{from}} doesn't import {{entry}}: its edge to {{to}} in the package graph lists {{listed}}. To import another entry point, add it to that edge.",
15
+ tests: "{{from}} imports {{entry}} only in its tests, as the package graph says.",
16
+ types: "{{from}} takes only types from {{entry}}, as the package graph says. Write `import type`, which loads nothing: `import { type … }` still loads {{entry}}.",
17
+ relative: "This relative path leaves {{from}} for {{to}}. Import {{to}} by its name, through its exports.",
18
+ outside: "This relative path leaves {{from}} for a file no package or app holds.",
19
+ self: "{{from}} imports itself by name, which goes around its folder layers. Import the module by its relative path."
20
+ },
21
+ schema: [{
22
+ type: "object",
23
+ properties: {
24
+ root: { type: "string" },
25
+ packages: {
26
+ type: "array",
27
+ items: { type: "string" }
28
+ },
29
+ apps: {
30
+ type: "array",
31
+ items: { type: "string" }
32
+ },
33
+ graph: { type: "object" },
34
+ nodeFiles: { type: "object" }
35
+ },
36
+ required: [
37
+ "root",
38
+ "packages",
39
+ "graph"
40
+ ],
41
+ additionalProperties: false
42
+ }]
43
+ },
44
+ create(context) {
45
+ const options = optionsOf(context.options);
46
+ const packages = workspacePackages(options);
47
+ const path = fromRoot(options.root, resolve(context.filename));
48
+ const from = ownerOf(path, packages);
49
+ if (from === void 0) return {};
50
+ const check = (node, source, typesOnly) => {
51
+ const { to, target } = importedBy(packages, path, source);
52
+ if (to === from) {
53
+ if (target === void 0 && !testFile.test(path)) context.report({
54
+ node,
55
+ messageId: "self",
56
+ data: { from: from.name }
57
+ });
58
+ return;
59
+ }
60
+ if (to === void 0) {
61
+ if (target !== void 0) context.report({
62
+ node,
63
+ messageId: "outside",
64
+ data: { from: from.name }
65
+ });
66
+ return;
67
+ }
68
+ const entry = target === void 0 ? entryNamed(to, source) : void 0;
69
+ const messageId = edgeProblem(options, from, to, entry, path, typesOnly);
70
+ if (messageId === void 0) return;
71
+ context.report({
72
+ node,
73
+ messageId,
74
+ data: {
75
+ from: from.name,
76
+ to: to.name,
77
+ entry: entry === void 0 ? to.name : shown(to.name, entry),
78
+ listed: listed(options.graph[from.name]?.[to.name] ?? {})
79
+ }
80
+ });
81
+ };
82
+ return importsVisitor(check);
83
+ }
84
+ });
85
+ export { packageImportsRule };
@@ -1,6 +1,8 @@
1
1
  /**
2
- * Rules any ref-0 repo can turn on, each over the files its config names. Only `entry-reexports`
3
- * takes options: the repo's root, its packages and its source condition.
2
+ * Rules any ref-0 repo can turn on, each over the files its config names. Four take options:
3
+ * `entry-reexports` the repo's root, its packages and its source condition, `no-comments` the
4
+ * repo's root and its comment budget's file, `package-imports` where its packages are and their
5
+ * graph, and `folder-imports` its sources' layers.
4
6
  */
5
7
  declare const _default: import("vite-plus/lint/plugins").Plugin;
6
8
  export { _default as default };
@@ -2,14 +2,19 @@ import { effectEncodingRule } from "./effect-encoding.mjs";
2
2
  import { entryReexportsRule } from "./entry-reexports.mjs";
3
3
  import { envAtEntrypointsRule } from "./env-at-entrypoints.mjs";
4
4
  import { exportTypeSideEffectsRule } from "./export-type-side-effects.mjs";
5
+ import { folderImportsRule } from "./folder-imports.mjs";
5
6
  import { indexBarrelOnlyRule } from "./index-barrel.mjs";
6
7
  import { logMessagesRule } from "./log-messages.mjs";
8
+ import { noCommentsRule } from "./no-comments.mjs";
9
+ import { packageImportsRule } from "./package-imports.mjs";
7
10
  import { seededPropertiesRule } from "./seeded-properties.mjs";
8
11
  import { definePlugin } from "vite-plus/lint/plugins";
9
12
  // src/lint/generic/plugin.ts
10
13
  /**
11
- * Rules any ref-0 repo can turn on, each over the files its config names. Only `entry-reexports`
12
- * takes options: the repo's root, its packages and its source condition.
14
+ * Rules any ref-0 repo can turn on, each over the files its config names. Four take options:
15
+ * `entry-reexports` the repo's root, its packages and its source condition, `no-comments` the
16
+ * repo's root and its comment budget's file, `package-imports` where its packages are and their
17
+ * graph, and `folder-imports` its sources' layers.
13
18
  */
14
19
  var plugin_default = definePlugin({
15
20
  meta: { name: "ref0-generic" },
@@ -18,8 +23,11 @@ var plugin_default = definePlugin({
18
23
  "entry-reexports": entryReexportsRule,
19
24
  "env-at-entrypoints": envAtEntrypointsRule,
20
25
  "export-type-side-effects": exportTypeSideEffectsRule,
26
+ "folder-imports": folderImportsRule,
21
27
  "index-barrel-only": indexBarrelOnlyRule,
22
28
  "log-messages": logMessagesRule,
29
+ "no-comments": noCommentsRule,
30
+ "package-imports": packageImportsRule,
23
31
  "seeded-properties": seededPropertiesRule
24
32
  }
25
33
  });
@@ -0,0 +1,17 @@
1
+ // src/lint/generic/rule-options.ts
2
+ /**
3
+ * A rule's decoded options, kept for each options array. Oxlint hands every file a run lints under
4
+ * one config the same array, so a large option, such as a package graph, is decoded once a run
5
+ * rather than once a file.
6
+ */
7
+ const decodedOnce = (decode) => {
8
+ const kept = /* @__PURE__ */ new WeakMap();
9
+ return (options) => {
10
+ const known = kept.get(options);
11
+ if (known !== void 0) return known;
12
+ const fresh = decode(options);
13
+ kept.set(options, fresh);
14
+ return fresh;
15
+ };
16
+ };
17
+ export { decodedOnce };
@@ -0,0 +1,29 @@
1
+ /** Where a repo's packages are: its root, and the folders that hold each kind, as globs from it. */
2
+ export interface Workspace {
3
+ /** The repo's root, as an absolute path. */
4
+ readonly root: string;
5
+ /** Globs of the folders that hold libraries, which others import, such as `packages/*`. */
6
+ readonly packages: ReadonlyArray<string>;
7
+ /** Globs of the folders that hold apps, which nothing imports, such as `apps/*`. */
8
+ readonly apps?: ReadonlyArray<string>;
9
+ }
10
+ /** A workspace package: its name, its folder from the root, and what the checks read of it. */
11
+ export interface WorkspacePackage {
12
+ readonly name: string;
13
+ /** Its folder from the root, with `/` between its parts, such as `packages/ui`. */
14
+ readonly directory: string;
15
+ /** Whether it's an app, which nothing imports. */
16
+ readonly app: boolean;
17
+ /**
18
+ * Its entry points, as its `exports` keys them, such as `.`, `./cast` or `./vectors/*.json`. A
19
+ * package with no `exports`, or `exports` of a single target, has only `.`.
20
+ */
21
+ readonly entries: ReadonlyArray<string>;
22
+ /** Every package it depends on, by any kind of dependency. */
23
+ readonly dependencies: ReadonlySet<string>;
24
+ }
25
+ /**
26
+ * The workspace's packages and apps, by name: each folder a glob matches that holds a
27
+ * `package.json`. Two folders with one name throw, since an import can't tell them apart.
28
+ */
29
+ export declare const workspacePackages: ({ root, packages, apps }: Workspace) => ReadonlyMap<string, WorkspacePackage>;
@@ -0,0 +1,78 @@
1
+ import { globSync, readFileSync } from "node:fs";
2
+ import { join, posix, relative, sep } from "node:path";
3
+ import { Schema } from "effect";
4
+ // src/lint/generic/workspace-packages.ts
5
+ const dependencyKinds = [
6
+ "dependencies",
7
+ "devDependencies",
8
+ "peerDependencies",
9
+ "optionalDependencies"
10
+ ];
11
+ const Dependencies = Schema.optionalKey(Schema.Record(Schema.String, Schema.String));
12
+ /** A package's `exports`: one target, or targets by subpath or by condition. */
13
+ const Exports = Schema.Union([Schema.String, Schema.Record(Schema.String, Schema.Json)]);
14
+ /**
15
+ * What discovery reads of a workspace package's `package.json`: its name, its `exports`, whose keys
16
+ * are its entry points, and what it depends on.
17
+ */
18
+ const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Struct({
19
+ name: Schema.String,
20
+ exports: Schema.optionalKey(Exports),
21
+ dependencies: Dependencies,
22
+ devDependencies: Dependencies,
23
+ peerDependencies: Dependencies,
24
+ optionalDependencies: Dependencies
25
+ })));
26
+ const isString = Schema.is(Schema.String);
27
+ /** The entry points an `exports` field keys: its keys when each is a subpath, `.` otherwise. */
28
+ const entriesOf = (exports) => {
29
+ const keys = exports === void 0 || isString(exports) ? [] : Object.keys(exports);
30
+ return keys.length > 0 && keys.every((key) => key.startsWith(".")) ? keys : ["."];
31
+ };
32
+ /** A path from the root, with `/` between its parts. */
33
+ const fromRoot = (root, path) => relative(root, path).split(sep).join("/");
34
+ /** The folders from the root that hold a `package.json`, for each glob, in order. */
35
+ const foldersOf = (root, globs) => globs.flatMap((glob) => globSync(posix.join(glob, "package.json"), {
36
+ cwd: root,
37
+ exclude: (path) => path.split(/[\\/]/).includes("node_modules")
38
+ }).map((path) => posix.dirname(path.split(sep).join("/")))).toSorted();
39
+ /** Each workspace's packages as last read, by its options, so a lint run reads each manifest once. */
40
+ const read = /* @__PURE__ */ new Map();
41
+ /**
42
+ * The workspace's packages and apps, by name: each folder a glob matches that holds a
43
+ * `package.json`. Two folders with one name throw, since an import can't tell them apart.
44
+ */
45
+ const workspacePackages = ({ root, packages, apps = [] }) => {
46
+ const key = JSON.stringify([
47
+ root,
48
+ packages,
49
+ apps
50
+ ]);
51
+ const known = read.get(key);
52
+ if (known !== void 0) return known;
53
+ const found = /* @__PURE__ */ new Map();
54
+ const folders = [...foldersOf(root, packages).map((directory) => ({
55
+ directory,
56
+ app: false
57
+ })), ...foldersOf(root, apps).map((directory) => ({
58
+ directory,
59
+ app: true
60
+ }))];
61
+ for (const { directory, app } of folders) {
62
+ const manifest = decodeManifest(readFileSync(join(root, directory, "package.json"), "utf8"));
63
+ const twin = found.get(manifest.name);
64
+ if (twin !== void 0 && twin.directory !== directory) throw new Error(`${twin.directory} and ${directory} are both named ${manifest.name}.`);
65
+ found.set(manifest.name, {
66
+ name: manifest.name,
67
+ directory,
68
+ app: twin?.app === true || app,
69
+ entries: entriesOf(manifest.exports),
70
+ dependencies: new Set(dependencyKinds.flatMap((kind) => Object.keys(manifest[kind] ?? {})))
71
+ });
72
+ }
73
+ read.set(key, found);
74
+ return found;
75
+ };
76
+ /** The package that holds a path from the root: the deepest whose folder it's in. */
77
+ const ownerOf = (path, packages) => [...packages.values()].filter(({ directory }) => path.startsWith(`${directory}/`)).toSorted((a, b) => b.directory.length - a.directory.length)[0];
78
+ export { fromRoot, ownerOf, workspacePackages };
@@ -0,0 +1,4 @@
1
+ import { FolderImportsOptions, FolderLayers, SourceLayers } from "./generic/folder-layers.mjs";
2
+ import { Edge, How, PackageGraph, PackageGraphOptions, graphProblems } from "./generic/package-graph.mjs";
3
+ import { Workspace, WorkspacePackage, workspacePackages } from "./generic/workspace-packages.mjs";
4
+ export { type Edge, type FolderImportsOptions, type FolderLayers, type How, type PackageGraph, type PackageGraphOptions, type SourceLayers, type Workspace, type WorkspacePackage, graphProblems, workspacePackages };
@@ -0,0 +1,3 @@
1
+ import { graphProblems } from "./generic/package-graph.mjs";
2
+ import { workspacePackages } from "./generic/workspace-packages.mjs";
3
+ export { graphProblems, workspacePackages };