@mark1russell7/boundaries 0.0.0-bootstrap.0 → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mark Russell
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,73 @@
1
1
  # @mark1russell7/boundaries
2
2
 
3
- This version is a placeholder. The release workflow of https://github.com/mark1russell7/template publishes the real versions. Use a later version.
3
+ This package gives the import boundaries of a pnpm workspace as a [dependency-cruiser](https://github.com/sverweij/dependency-cruiser) configuration. Each package is a unit. Another package imports it only through an entry of its `package.json`.
4
+
5
+ ## Rules
6
+
7
+ | Rule | It fails when |
8
+ |---|---|
9
+ | `relative-import-out-of-<package>` | A relative import (`../../b/src/x.js`) goes into the folder of a different package. |
10
+ | `deep-import-into-<package>` | An import gets to a file of a package that is not an entry of its `package.json` (`exports`, `main`, `module`, `types` or `bin`). |
11
+ | `not-a-declared-export` | An import of a workspace package does not resolve. The path is not in its `exports`, or the package is not built. |
12
+ | `import-of-the-app-<package>` | A package imports an app. An app is a leaf of the graph. This rule is only on with the option `apps`. |
13
+
14
+ A type-only import is a boundary too. Tests, fixtures and declaration files are not part of a boundary.
15
+
16
+ ## Use
17
+
18
+ Install the package, `dependency-cruiser` and, for TypeScript 7 or for source with no TypeScript compiler, `@swc/core`:
19
+
20
+ ```sh
21
+ pnpm add -D @mark1russell7/boundaries dependency-cruiser @swc/core
22
+ ```
23
+
24
+ Write `.dependency-cruiser.mjs` at the root of the repository:
25
+
26
+ ```js
27
+ import { boundaries } from "@mark1russell7/boundaries";
28
+
29
+ export default boundaries(import.meta.dirname);
30
+ ```
31
+
32
+ Add the script `"check:boundaries": "depcruise --config .dependency-cruiser.mjs packages"`. The shared CI of the template starts `check:boundaries` after `build` (`CI.md`).
33
+
34
+ ## Options
35
+
36
+ `boundaries(root, options)` reads the packages of `pnpm-workspace.yaml`. These options change it:
37
+
38
+ | Option | Default | What it sets |
39
+ |---|---|---|
40
+ | `packages` | the `packages` list of `pnpm-workspace.yaml` | The globs of the package folders. |
41
+ | `apps` | none | The apps. `"private"` makes each private package an app. |
42
+ | `reference` | none | A text before each comment, for example the name of the decision record. |
43
+ | `forbidden` | none | More rules of the repository, after the rules of the boundaries. |
44
+ | `options` | the default options | More options of dependency-cruiser. They replace the default options that have the same key. |
45
+
46
+ An example with the rules of a repository:
47
+
48
+ ```js
49
+ const { boundaries } = require("@mark1russell7/boundaries");
50
+
51
+ module.exports = boundaries(__dirname, {
52
+ apps: "private",
53
+ reference: "Invariant I9 of ARCHITECTURE.md.",
54
+ forbidden: [
55
+ {
56
+ name: "transport-imports-server",
57
+ severity: "error",
58
+ from: { path: "^packages/client/src/adapters/" },
59
+ to: { path: "^packages/server/" },
60
+ },
61
+ ],
62
+ });
63
+ ```
64
+
65
+ ## The parser
66
+
67
+ dependency-cruiser reads TypeScript with the TypeScript compiler of the repository only for TypeScript 2 to 6. With TypeScript 7, or with no TypeScript, `boundaries()` sets the parser `swc` when `@swc/core` is installed. Without `@swc/core`, dependency-cruiser reads only JavaScript. That is enough for a check of built JavaScript.
68
+
69
+ ## Other exports
70
+
71
+ - `boundaryRules(packages, options)` gives only the rules, for a list of packages.
72
+ - `workspacePackages(root, globs)` gives the packages of the workspace and their entries.
73
+ - `defaultOptions(root)` and `parserOptions(root)` give the default options.
@@ -0,0 +1,269 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_fs = require("node:fs");
3
+ let node_module = require("node:module");
4
+ let node_path = require("node:path");
5
+ // src/index.ts
6
+ /**
7
+ * The import boundaries of a workspace, as a dependency-cruiser configuration. Each package is a
8
+ * unit. Another package imports it only through an entry of its package.json (`exports`, `main`,
9
+ * `module`, `types`, `bin`). A relative path or a deep path into its folder is not an entry.
10
+ *
11
+ * A repository uses it from its `.dependency-cruiser.cjs`:
12
+ *
13
+ * ```js
14
+ * const { boundaries } = require("@mark1russell7/boundaries");
15
+ * module.exports = boundaries(__dirname, { apps: "private" });
16
+ * ```
17
+ */
18
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19
+ /** The `packages` list of a pnpm-workspace.yaml file. It reads only that list, with no YAML library. */
20
+ function workspaceGlobs(yaml) {
21
+ const globs = [];
22
+ let inList = false;
23
+ for (const raw of yaml.split(/\r?\n/)) {
24
+ const hash = raw.indexOf(" #");
25
+ const line = (hash === -1 ? raw : raw.slice(0, hash)).trimEnd();
26
+ const trimmed = line.trimStart();
27
+ if (trimmed === "" || trimmed.startsWith("#")) continue;
28
+ if (/^packages\s*:/.test(line)) {
29
+ inList = true;
30
+ continue;
31
+ }
32
+ if (!inList) continue;
33
+ if (trimmed === line) break;
34
+ if (!trimmed.startsWith("-")) continue;
35
+ const item = trimmed.slice(1).trim().replace(/^["']/, "").replace(/["']$/, "");
36
+ if (item) globs.push(item);
37
+ }
38
+ return globs;
39
+ }
40
+ function isDir(path) {
41
+ try {
42
+ return (0, node_fs.statSync)(path).isDirectory();
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+ /** The folders that a glob of pnpm-workspace.yaml gives: "a/b", "a/*" and "a/**". */
48
+ function expand(root, glob) {
49
+ const clean = glob.replace(/^\.\//, "").replace(/\/$/, "");
50
+ const star = clean.indexOf("*");
51
+ if (star === -1) return isDir((0, node_path.join)(root, clean)) ? [clean] : [];
52
+ const base = clean.slice(0, star).replace(/\/$/, "");
53
+ const recursive = clean.slice(star).startsWith("**");
54
+ const found = [];
55
+ const walk = (dir, depth) => {
56
+ let entries;
57
+ try {
58
+ entries = (0, node_fs.readdirSync)((0, node_path.join)(root, dir), { withFileTypes: true });
59
+ } catch {
60
+ return;
61
+ }
62
+ for (const entry of entries) {
63
+ if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith(".")) continue;
64
+ const child = dir === "" ? entry.name : `${dir}/${entry.name}`;
65
+ found.push(child);
66
+ if (recursive && depth < 6) walk(child, depth + 1);
67
+ }
68
+ };
69
+ walk(base, 0);
70
+ return found;
71
+ }
72
+ /** The leaf strings of an `exports` value, with their subpath keys. */
73
+ function exportTargets(value, out = []) {
74
+ if (typeof value === "string") out.push(value);
75
+ else if (Array.isArray(value)) for (const item of value) exportTargets(item, out);
76
+ else if (value && typeof value === "object") for (const item of Object.values(value)) exportTargets(item, out);
77
+ return out;
78
+ }
79
+ /**
80
+ * The RegExp source of an entry target of a package. The extension can change, because
81
+ * dependency-cruiser resolves "./x.js" to the source file x.ts, and "*" of a subpath pattern matches
82
+ * each path.
83
+ */
84
+ function entryPattern(dir, target) {
85
+ return `^${node_path.posix.normalize(node_path.posix.join(dir, target.replace(/^\.\//, ""))).replace(/\.d\.[cm]?ts$|\.[cm]?[jt]sx?$/, "").split("*").map(escape).join(".*")}(${EXTENSIONS})?$`;
86
+ }
87
+ const EXTENSIONS = [
88
+ ".js",
89
+ ".mjs",
90
+ ".cjs",
91
+ ".jsx",
92
+ ".ts",
93
+ ".mts",
94
+ ".cts",
95
+ ".tsx",
96
+ ".d.ts",
97
+ ".d.mts",
98
+ ".d.cts"
99
+ ].map(escape).join("|");
100
+ /** The entries of a package.json: the files that other packages can import. */
101
+ function packageEntries(dir, manifest) {
102
+ const targets = exportTargets(manifest["exports"]);
103
+ for (const field of [
104
+ "main",
105
+ "module",
106
+ "types",
107
+ "typings"
108
+ ]) {
109
+ const value = manifest[field];
110
+ if (typeof value === "string") targets.push(value);
111
+ }
112
+ if (typeof manifest["bin"] === "string") targets.push(manifest["bin"]);
113
+ else if (manifest["bin"] && typeof manifest["bin"] === "object") targets.push(...exportTargets(manifest["bin"]));
114
+ if (targets.length === 0 && manifest["exports"] === void 0) targets.push("./index.js");
115
+ return [...new Set(targets.filter((t) => !t.endsWith(".json") || t === "./package.json").map((t) => entryPattern(dir, t)))];
116
+ }
117
+ /** The packages of the workspace in the folder `root`. */
118
+ function workspacePackages(root, globs) {
119
+ let list = globs;
120
+ if (!list) {
121
+ try {
122
+ list = workspaceGlobs((0, node_fs.readFileSync)((0, node_path.join)(root, "pnpm-workspace.yaml"), "utf8"));
123
+ } catch {
124
+ list = [];
125
+ }
126
+ if (list.length === 0) list = ["packages/*"];
127
+ }
128
+ const excluded = list.filter((g) => g.startsWith("!")).flatMap((g) => expand(root, g.slice(1)));
129
+ const dirs = [...new Set(list.filter((g) => !g.startsWith("!")).flatMap((g) => expand(root, g)))].filter((d) => !excluded.includes(d));
130
+ const found = [];
131
+ for (const dir of dirs.sort()) {
132
+ let manifest;
133
+ try {
134
+ manifest = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(root, dir, "package.json"), "utf8"));
135
+ } catch {
136
+ continue;
137
+ }
138
+ if (typeof manifest["name"] !== "string") continue;
139
+ found.push({
140
+ name: manifest["name"],
141
+ dir,
142
+ private: manifest["private"] === true,
143
+ entries: packageEntries(dir, manifest)
144
+ });
145
+ }
146
+ return found;
147
+ }
148
+ /** The rules of the boundaries for a list of packages. `boundaries()` reads the list from the workspace. */
149
+ function boundaryRules(packages, opts = {}) {
150
+ const why = (text) => opts.reference ? `${opts.reference} ${text}` : text;
151
+ const anyPackage = packages.map((p) => `^${escape(p.dir)}/`);
152
+ const rules = [];
153
+ for (const pkg of packages) {
154
+ const own = `^${escape(pkg.dir)}/`;
155
+ const others = anyPackage.filter((path) => path !== own);
156
+ if (others.length > 0) rules.push({
157
+ name: `relative-import-out-of-${slug(pkg.name)}`,
158
+ severity: "error",
159
+ comment: why(`A relative import leaves the package ${pkg.name}. Import the other package by its name, through an entry of its package.json.`),
160
+ from: { path: own },
161
+ to: {
162
+ path: others,
163
+ pathNot: own,
164
+ dependencyTypes: ["local"]
165
+ }
166
+ });
167
+ rules.push({
168
+ name: `deep-import-into-${slug(pkg.name)}`,
169
+ severity: "error",
170
+ comment: why(`An import reaches into the folder of ${pkg.name} at a file that is not an entry of its package.json (exports, main, module, types or bin). Import an entry, or add the file to the exports of ${pkg.name}.`),
171
+ from: { pathNot: own },
172
+ to: pkg.entries.length > 0 ? {
173
+ path: own,
174
+ pathNot: pkg.entries
175
+ } : { path: own }
176
+ });
177
+ }
178
+ const names = packages.map((p) => escape(p.name));
179
+ if (names.length > 0) rules.push({
180
+ name: "not-a-declared-export",
181
+ severity: "error",
182
+ comment: why("An import of a package of this workspace does not resolve. The path is not an entry of its exports, or the package is not built."),
183
+ from: {},
184
+ to: {
185
+ path: `^(${names.join("|")})(/|$)`,
186
+ couldNotResolve: true
187
+ }
188
+ });
189
+ const apps = opts.apps === "private" ? packages.filter((p) => p.private) : packages.filter((p) => (opts.apps ?? []).includes(p.name));
190
+ for (const app of apps) rules.push({
191
+ name: `import-of-the-app-${slug(app.name)}`,
192
+ severity: "error",
193
+ comment: why(`A package imports the app ${app.name}. An app is a leaf: no other package imports it. Move the shared code to a library package.`),
194
+ from: { pathNot: `^${escape(app.dir)}/` },
195
+ to: { path: `^${escape(app.dir)}/` }
196
+ });
197
+ return rules;
198
+ }
199
+ const slug = (name) => name.replace(/^@/, "").replace(/[^A-Za-z0-9]+/g, "-");
200
+ /**
201
+ * The parser of the TypeScript source. dependency-cruiser reads TypeScript with the TypeScript
202
+ * compiler of the repository only for TypeScript 2 to 6. With TypeScript 7 or no TypeScript, it reads
203
+ * TypeScript with swc when @swc/core is installed. Else it reads only JavaScript (acorn): that is
204
+ * enough for a check of built JavaScript.
205
+ */
206
+ function parserOptions(root) {
207
+ if (!root) return {};
208
+ const require$1 = (0, node_module.createRequire)((0, node_path.join)(root, "package.json"));
209
+ try {
210
+ const { version } = require$1("typescript/package.json");
211
+ if (Number(version.split(".")[0]) < 7) return { tsPreCompilationDeps: true };
212
+ } catch {}
213
+ for (const from of [require$1, (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)]) try {
214
+ from.resolve("@swc/core");
215
+ return { parser: "swc" };
216
+ } catch {}
217
+ return {};
218
+ }
219
+ /**
220
+ * The default options: the source of the packages, with type-only imports, resolved as Node resolves
221
+ * them. There is no `includeOnly`, because it also removes the imports that do not resolve, and the
222
+ * rule not-a-declared-export needs them. The "types" condition is not used: it resolves to a
223
+ * declaration file, and the analysis excludes declaration files, so a deep import does not show.
224
+ */
225
+ function defaultOptions(root) {
226
+ return {
227
+ ...parserOptions(root),
228
+ exclude: { path: [
229
+ "(^|/)node_modules/",
230
+ "\\.(test|spec|e2e)\\.[cm]?[jt]sx?$",
231
+ "\\.d\\.[cm]?ts$",
232
+ "/(test|tests|e2e|__tests__|fixtures)/"
233
+ ] },
234
+ doNotFollow: { path: ["(^|/)node_modules/"] },
235
+ enhancedResolveOptions: {
236
+ exportsFields: ["exports"],
237
+ conditionNames: [
238
+ "import",
239
+ "require",
240
+ "node",
241
+ "default"
242
+ ],
243
+ mainFields: ["module", "main"]
244
+ },
245
+ skipAnalysisNotInRules: true
246
+ };
247
+ }
248
+ /** The dependency-cruiser configuration of the boundaries for the workspace in the folder `root`. */
249
+ function boundaries(root, opts = {}) {
250
+ const packages = workspacePackages(root, opts.packages);
251
+ const options = {
252
+ ...defaultOptions(root),
253
+ ...opts.options
254
+ };
255
+ return {
256
+ forbidden: [...boundaryRules(packages, opts), ...opts.forbidden ?? []],
257
+ options
258
+ };
259
+ }
260
+ exports.boundaries = boundaries;
261
+ exports.boundaryRules = boundaryRules;
262
+ exports.defaultOptions = defaultOptions;
263
+ exports.entryPattern = entryPattern;
264
+ exports.packageEntries = packageEntries;
265
+ exports.parserOptions = parserOptions;
266
+ exports.workspaceGlobs = workspaceGlobs;
267
+ exports.workspacePackages = workspacePackages;
268
+
269
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["statSync","join","readdirSync","posix","readFileSync","require","createRequire"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * The import boundaries of a workspace, as a dependency-cruiser configuration. Each package is a\n * unit. Another package imports it only through an entry of its package.json (`exports`, `main`,\n * `module`, `types`, `bin`). A relative path or a deep path into its folder is not an entry.\n *\n * A repository uses it from its `.dependency-cruiser.cjs`:\n *\n * ```js\n * const { boundaries } = require(\"@mark1russell7/boundaries\");\n * module.exports = boundaries(__dirname, { apps: \"private\" });\n * ```\n */\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, posix } from \"node:path\";\n\n/** A rule of dependency-cruiser (the `forbidden` list). The package does not depend on the types of dependency-cruiser. */\nexport interface Rule {\n name: string;\n severity: \"error\" | \"warn\" | \"info\" | \"ignore\";\n comment?: string;\n from: Record<string, unknown>;\n to: Record<string, unknown>;\n}\n\n/** A dependency-cruiser configuration. */\nexport interface Config {\n forbidden: Rule[];\n options: Record<string, unknown>;\n}\n\n/** A package of the workspace. */\nexport interface WorkspacePackage {\n /** The name in package.json. */\n name: string;\n /** The folder, relative to the root, with \"/\". */\n dir: string;\n private: boolean;\n /** RegExp sources of the files that other packages can import. */\n entries: string[];\n}\n\nexport interface BoundaryOptions {\n /**\n * Globs of the package folders, for example `[\"packages/*\"]`. The default is the `packages` list of\n * pnpm-workspace.yaml, or `[\"packages/*\"]` when the file does not exist.\n */\n packages?: string[];\n /** The apps: the leaves of the graph, which no other package imports. \"private\" means each private package. */\n apps?: \"private\" | string[];\n /** A text before each comment, for example the decision record of the rules. */\n reference?: string;\n /** More rules, after the rules of the boundaries. */\n forbidden?: Rule[];\n /** More options of dependency-cruiser. They replace the default options with the same key. */\n options?: Record<string, unknown>;\n}\n\nconst escape = (text: string): string => text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/** The `packages` list of a pnpm-workspace.yaml file. It reads only that list, with no YAML library. */\nexport function workspaceGlobs(yaml: string): string[] {\n const globs: string[] = [];\n let inList = false;\n // String operations, not one large RegExp: a RegExp with nested whitespace groups can be slow on some input.\n for (const raw of yaml.split(/\\r?\\n/)) {\n const hash = raw.indexOf(\" #\");\n const line = (hash === -1 ? raw : raw.slice(0, hash)).trimEnd();\n const trimmed = line.trimStart();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n if (/^packages\\s*:/.test(line)) {\n inList = true;\n continue;\n }\n if (!inList) continue;\n if (trimmed === line) break;\n if (!trimmed.startsWith(\"-\")) continue;\n const item = trimmed.slice(1).trim().replace(/^[\"']/, \"\").replace(/[\"']$/, \"\");\n if (item) globs.push(item);\n }\n return globs;\n}\n\nfunction isDir(path: string): boolean {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\n/** The folders that a glob of pnpm-workspace.yaml gives: \"a/b\", \"a/*\" and \"a/**\". */\nfunction expand(root: string, glob: string): string[] {\n const clean = glob.replace(/^\\.\\//, \"\").replace(/\\/$/, \"\");\n const star = clean.indexOf(\"*\");\n if (star === -1) return isDir(join(root, clean)) ? [clean] : [];\n const base = clean.slice(0, star).replace(/\\/$/, \"\");\n const recursive = clean.slice(star).startsWith(\"**\");\n const found: string[] = [];\n const walk = (dir: string, depth: number): void => {\n let entries;\n try {\n entries = readdirSync(join(root, dir), { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n const child = dir === \"\" ? entry.name : `${dir}/${entry.name}`;\n found.push(child);\n if (recursive && depth < 6) walk(child, depth + 1);\n }\n };\n walk(base, 0);\n return found;\n}\n\n/** The leaf strings of an `exports` value, with their subpath keys. */\nfunction exportTargets(value: unknown, out: string[] = []): string[] {\n if (typeof value === \"string\") out.push(value);\n else if (Array.isArray(value)) for (const item of value) exportTargets(item, out);\n else if (value && typeof value === \"object\") for (const item of Object.values(value)) exportTargets(item, out);\n return out;\n}\n\n/**\n * The RegExp source of an entry target of a package. The extension can change, because\n * dependency-cruiser resolves \"./x.js\" to the source file x.ts, and \"*\" of a subpath pattern matches\n * each path.\n */\nexport function entryPattern(dir: string, target: string): string {\n const path = posix.normalize(posix.join(dir, target.replace(/^\\.\\//, \"\")));\n const stem = path.replace(/\\.d\\.[cm]?ts$|\\.[cm]?[jt]sx?$/, \"\");\n const source = stem.split(\"*\").map(escape).join(\".*\");\n // A flat list, because dependency-cruiser refuses a RegExp with nested quantifiers (safe-regex).\n return `^${source}(${EXTENSIONS})?$`;\n}\n\nconst EXTENSIONS = [\".js\", \".mjs\", \".cjs\", \".jsx\", \".ts\", \".mts\", \".cts\", \".tsx\", \".d.ts\", \".d.mts\", \".d.cts\"].map(escape).join(\"|\");\n\n/** The entries of a package.json: the files that other packages can import. */\nexport function packageEntries(dir: string, manifest: Record<string, unknown>): string[] {\n const targets = exportTargets(manifest[\"exports\"]);\n for (const field of [\"main\", \"module\", \"types\", \"typings\"]) {\n const value = manifest[field];\n if (typeof value === \"string\") targets.push(value);\n }\n if (typeof manifest[\"bin\"] === \"string\") targets.push(manifest[\"bin\"]);\n else if (manifest[\"bin\"] && typeof manifest[\"bin\"] === \"object\") targets.push(...exportTargets(manifest[\"bin\"]));\n // With no entry field, Node resolves the package to index.js.\n if (targets.length === 0 && manifest[\"exports\"] === undefined) targets.push(\"./index.js\");\n return [...new Set(targets.filter((t) => !t.endsWith(\".json\") || t === \"./package.json\").map((t) => entryPattern(dir, t)))];\n}\n\n/** The packages of the workspace in the folder `root`. */\nexport function workspacePackages(root: string, globs?: string[]): WorkspacePackage[] {\n let list = globs;\n if (!list) {\n try {\n list = workspaceGlobs(readFileSync(join(root, \"pnpm-workspace.yaml\"), \"utf8\"));\n } catch {\n list = [];\n }\n if (list.length === 0) list = [\"packages/*\"];\n }\n const excluded = list.filter((g) => g.startsWith(\"!\")).flatMap((g) => expand(root, g.slice(1)));\n const dirs = [...new Set(list.filter((g) => !g.startsWith(\"!\")).flatMap((g) => expand(root, g)))].filter((d) => !excluded.includes(d));\n const found: WorkspacePackage[] = [];\n for (const dir of dirs.sort()) {\n let manifest: Record<string, unknown>;\n try {\n manifest = JSON.parse(readFileSync(join(root, dir, \"package.json\"), \"utf8\")) as Record<string, unknown>;\n } catch {\n continue;\n }\n if (typeof manifest[\"name\"] !== \"string\") continue;\n found.push({ name: manifest[\"name\"], dir, private: manifest[\"private\"] === true, entries: packageEntries(dir, manifest) });\n }\n return found;\n}\n\n/** The rules of the boundaries for a list of packages. `boundaries()` reads the list from the workspace. */\nexport function boundaryRules(packages: WorkspacePackage[], opts: Pick<BoundaryOptions, \"apps\" | \"reference\"> = {}): Rule[] {\n const why = (text: string): string => (opts.reference ? `${opts.reference} ${text}` : text);\n const anyPackage = packages.map((p) => `^${escape(p.dir)}/`);\n const rules: Rule[] = [];\n for (const pkg of packages) {\n const own = `^${escape(pkg.dir)}/`;\n const others = anyPackage.filter((path) => path !== own);\n if (others.length > 0) {\n rules.push({\n name: `relative-import-out-of-${slug(pkg.name)}`,\n severity: \"error\",\n comment: why(`A relative import leaves the package ${pkg.name}. Import the other package by its name, through an entry of its package.json.`),\n from: { path: own },\n to: { path: others, pathNot: own, dependencyTypes: [\"local\"] },\n });\n }\n rules.push({\n name: `deep-import-into-${slug(pkg.name)}`,\n severity: \"error\",\n comment: why(\n `An import reaches into the folder of ${pkg.name} at a file that is not an entry of its package.json (exports, main, module, types or bin). Import an entry, or add the file to the exports of ${pkg.name}.`,\n ),\n from: { pathNot: own },\n to: pkg.entries.length > 0 ? { path: own, pathNot: pkg.entries } : { path: own },\n });\n }\n const names = packages.map((p) => escape(p.name));\n if (names.length > 0) {\n rules.push({\n name: \"not-a-declared-export\",\n severity: \"error\",\n comment: why(\"An import of a package of this workspace does not resolve. The path is not an entry of its exports, or the package is not built.\"),\n from: {},\n to: { path: `^(${names.join(\"|\")})(/|$)`, couldNotResolve: true },\n });\n }\n const apps =\n opts.apps === \"private\" ? packages.filter((p) => p.private) : packages.filter((p) => (opts.apps ?? []).includes(p.name));\n for (const app of apps) {\n rules.push({\n name: `import-of-the-app-${slug(app.name)}`,\n severity: \"error\",\n comment: why(`A package imports the app ${app.name}. An app is a leaf: no other package imports it. Move the shared code to a library package.`),\n from: { pathNot: `^${escape(app.dir)}/` },\n to: { path: `^${escape(app.dir)}/` },\n });\n }\n return rules;\n}\n\nconst slug = (name: string): string => name.replace(/^@/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\");\n\n/**\n * The parser of the TypeScript source. dependency-cruiser reads TypeScript with the TypeScript\n * compiler of the repository only for TypeScript 2 to 6. With TypeScript 7 or no TypeScript, it reads\n * TypeScript with swc when @swc/core is installed. Else it reads only JavaScript (acorn): that is\n * enough for a check of built JavaScript.\n */\nexport function parserOptions(root?: string): Record<string, unknown> {\n if (!root) return {};\n const require = createRequire(join(root, \"package.json\"));\n try {\n const { version } = require(\"typescript/package.json\") as { version: string };\n // A type-only import is a boundary too. This option needs the TypeScript compiler.\n if (Number(version.split(\".\")[0]) < 7) return { tsPreCompilationDeps: true };\n } catch {\n // No TypeScript in the repository\n }\n // @swc/core from the repository, or next to this package (a peer dependency)\n for (const from of [require, createRequire(import.meta.url)]) {\n try {\n from.resolve(\"@swc/core\");\n return { parser: \"swc\" };\n } catch {\n // Not there\n }\n }\n return {};\n}\n\n/**\n * The default options: the source of the packages, with type-only imports, resolved as Node resolves\n * them. There is no `includeOnly`, because it also removes the imports that do not resolve, and the\n * rule not-a-declared-export needs them. The \"types\" condition is not used: it resolves to a\n * declaration file, and the analysis excludes declaration files, so a deep import does not show.\n */\nexport function defaultOptions(root?: string): Record<string, unknown> {\n return {\n ...parserOptions(root),\n exclude: {\n path: [\"(^|/)node_modules/\", \"\\\\.(test|spec|e2e)\\\\.[cm]?[jt]sx?$\", \"\\\\.d\\\\.[cm]?ts$\", \"/(test|tests|e2e|__tests__|fixtures)/\"],\n },\n doNotFollow: { path: [\"(^|/)node_modules/\"] },\n enhancedResolveOptions: {\n exportsFields: [\"exports\"],\n conditionNames: [\"import\", \"require\", \"node\", \"default\"],\n mainFields: [\"module\", \"main\"],\n },\n skipAnalysisNotInRules: true,\n };\n}\n\n/** The dependency-cruiser configuration of the boundaries for the workspace in the folder `root`. */\nexport function boundaries(root: string, opts: BoundaryOptions = {}): Config {\n const packages = workspacePackages(root, opts.packages);\n const options = { ...defaultOptions(root), ...opts.options };\n return {\n forbidden: [...boundaryRules(packages, opts), ...(opts.forbidden ?? [])],\n options,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0DA,MAAM,UAAU,SAAyB,KAAK,QAAQ,uBAAuB,MAAM;;AAGnF,SAAgB,eAAe,MAAwB;CACrD,MAAM,QAAkB,CAAC;CACzB,IAAI,SAAS;CAEb,KAAK,MAAM,OAAO,KAAK,MAAM,OAAO,GAAG;EACrC,MAAM,OAAO,IAAI,QAAQ,IAAI;EAC7B,MAAM,QAAQ,SAAS,KAAK,MAAM,IAAI,MAAM,GAAG,IAAI,EAAA,CAAG,QAAQ;EAC9D,MAAM,UAAU,KAAK,UAAU;EAC/B,IAAI,YAAY,MAAM,QAAQ,WAAW,GAAG,GAAG;EAC/C,IAAI,gBAAgB,KAAK,IAAI,GAAG;GAC9B,SAAS;GACT;EACF;EACA,IAAI,CAAC,QAAQ;EACb,IAAI,YAA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AAwB;CAC1B;AACF;;AAGA,SAAgB,WAAW,MAAc,OAAwB,CAAC,GAAW;CAC3E,MAAM,WAAW,kBAAkB,MAAM,KAAK,QAAQ;CACtD,MAAM,UAAU;EAAE,GAAG,eAAe,IAAI;EAAG,GAAG,KAAK;CAAQ;CAC3D,OAAO;EACL,WAAW,CAAC,GAAG,cAAc,UAAU,IAAI,GAAG,GAAI,KAAK,aAAa,CAAC,CAAE;EACvE;CACF;AACF"}
@@ -0,0 +1,69 @@
1
+ /** A rule of dependency-cruiser (the `forbidden` list). The package does not depend on the types of dependency-cruiser. */
2
+ export interface Rule {
3
+ name: string;
4
+ severity: "error" | "warn" | "info" | "ignore";
5
+ comment?: string;
6
+ from: Record<string, unknown>;
7
+ to: Record<string, unknown>;
8
+ }
9
+ /** A dependency-cruiser configuration. */
10
+ export interface Config {
11
+ forbidden: Rule[];
12
+ options: Record<string, unknown>;
13
+ }
14
+ /** A package of the workspace. */
15
+ export interface WorkspacePackage {
16
+ /** The name in package.json. */
17
+ name: string;
18
+ /** The folder, relative to the root, with "/". */
19
+ dir: string;
20
+ private: boolean;
21
+ /** RegExp sources of the files that other packages can import. */
22
+ entries: string[];
23
+ }
24
+ export interface BoundaryOptions {
25
+ /**
26
+ * Globs of the package folders, for example `["packages/*"]`. The default is the `packages` list of
27
+ * pnpm-workspace.yaml, or `["packages/*"]` when the file does not exist.
28
+ */
29
+ packages?: string[];
30
+ /** The apps: the leaves of the graph, which no other package imports. "private" means each private package. */
31
+ apps?: "private" | string[];
32
+ /** A text before each comment, for example the decision record of the rules. */
33
+ reference?: string;
34
+ /** More rules, after the rules of the boundaries. */
35
+ forbidden?: Rule[];
36
+ /** More options of dependency-cruiser. They replace the default options with the same key. */
37
+ options?: Record<string, unknown>;
38
+ }
39
+ /** The `packages` list of a pnpm-workspace.yaml file. It reads only that list, with no YAML library. */
40
+ export declare function workspaceGlobs(yaml: string): string[];
41
+ /**
42
+ * The RegExp source of an entry target of a package. The extension can change, because
43
+ * dependency-cruiser resolves "./x.js" to the source file x.ts, and "*" of a subpath pattern matches
44
+ * each path.
45
+ */
46
+ export declare function entryPattern(dir: string, target: string): string;
47
+ /** The entries of a package.json: the files that other packages can import. */
48
+ export declare function packageEntries(dir: string, manifest: Record<string, unknown>): string[];
49
+ /** The packages of the workspace in the folder `root`. */
50
+ export declare function workspacePackages(root: string, globs?: string[]): WorkspacePackage[];
51
+ /** The rules of the boundaries for a list of packages. `boundaries()` reads the list from the workspace. */
52
+ export declare function boundaryRules(packages: WorkspacePackage[], opts?: Pick<BoundaryOptions, "apps" | "reference">): Rule[];
53
+ /**
54
+ * The parser of the TypeScript source. dependency-cruiser reads TypeScript with the TypeScript
55
+ * compiler of the repository only for TypeScript 2 to 6. With TypeScript 7 or no TypeScript, it reads
56
+ * TypeScript with swc when @swc/core is installed. Else it reads only JavaScript (acorn): that is
57
+ * enough for a check of built JavaScript.
58
+ */
59
+ export declare function parserOptions(root?: string): Record<string, unknown>;
60
+ /**
61
+ * The default options: the source of the packages, with type-only imports, resolved as Node resolves
62
+ * them. There is no `includeOnly`, because it also removes the imports that do not resolve, and the
63
+ * rule not-a-declared-export needs them. The "types" condition is not used: it resolves to a
64
+ * declaration file, and the analysis excludes declaration files, so a deep import does not show.
65
+ */
66
+ export declare function defaultOptions(root?: string): Record<string, unknown>;
67
+ /** The dependency-cruiser configuration of the boundaries for the workspace in the folder `root`. */
68
+ export declare function boundaries(root: string, opts?: BoundaryOptions): Config;
69
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";iBAiBiB;EACf;EACA;EACA;EACA,MAAM;EACN,IAAI;;;iBAIW;EACf,WAAW;EACX,SAAS;;;iBAIM;;EAEf;;EAEA;EACA;;EAEA;;iBAGe;;;;;EAKf;;EAEA;;EAEA;;EAEA,YAAY;;EAEZ,UAAU;;;wBAMI,eAAe;;;;;;wBAqEf,aAAa,aAAa;;wBAW1B,eAAe,aAAa,UAAU;;wBActC,kBAAkB,cAAc,mBAAmB;;wBA2BnD,cAAc,UAAU,oBAAoB,OAAM,KAAK,yCAA8C;;;;;;;wBA0DrG,cAAc,gBAAgB;;;;;;;wBA4B9B,eAAe,gBAAgB;;wBAiB/B,WAAW,cAAc,OAAM,kBAAuB"}
@@ -0,0 +1,69 @@
1
+ /** A rule of dependency-cruiser (the `forbidden` list). The package does not depend on the types of dependency-cruiser. */
2
+ export interface Rule {
3
+ name: string;
4
+ severity: "error" | "warn" | "info" | "ignore";
5
+ comment?: string;
6
+ from: Record<string, unknown>;
7
+ to: Record<string, unknown>;
8
+ }
9
+ /** A dependency-cruiser configuration. */
10
+ export interface Config {
11
+ forbidden: Rule[];
12
+ options: Record<string, unknown>;
13
+ }
14
+ /** A package of the workspace. */
15
+ export interface WorkspacePackage {
16
+ /** The name in package.json. */
17
+ name: string;
18
+ /** The folder, relative to the root, with "/". */
19
+ dir: string;
20
+ private: boolean;
21
+ /** RegExp sources of the files that other packages can import. */
22
+ entries: string[];
23
+ }
24
+ export interface BoundaryOptions {
25
+ /**
26
+ * Globs of the package folders, for example `["packages/*"]`. The default is the `packages` list of
27
+ * pnpm-workspace.yaml, or `["packages/*"]` when the file does not exist.
28
+ */
29
+ packages?: string[];
30
+ /** The apps: the leaves of the graph, which no other package imports. "private" means each private package. */
31
+ apps?: "private" | string[];
32
+ /** A text before each comment, for example the decision record of the rules. */
33
+ reference?: string;
34
+ /** More rules, after the rules of the boundaries. */
35
+ forbidden?: Rule[];
36
+ /** More options of dependency-cruiser. They replace the default options with the same key. */
37
+ options?: Record<string, unknown>;
38
+ }
39
+ /** The `packages` list of a pnpm-workspace.yaml file. It reads only that list, with no YAML library. */
40
+ export declare function workspaceGlobs(yaml: string): string[];
41
+ /**
42
+ * The RegExp source of an entry target of a package. The extension can change, because
43
+ * dependency-cruiser resolves "./x.js" to the source file x.ts, and "*" of a subpath pattern matches
44
+ * each path.
45
+ */
46
+ export declare function entryPattern(dir: string, target: string): string;
47
+ /** The entries of a package.json: the files that other packages can import. */
48
+ export declare function packageEntries(dir: string, manifest: Record<string, unknown>): string[];
49
+ /** The packages of the workspace in the folder `root`. */
50
+ export declare function workspacePackages(root: string, globs?: string[]): WorkspacePackage[];
51
+ /** The rules of the boundaries for a list of packages. `boundaries()` reads the list from the workspace. */
52
+ export declare function boundaryRules(packages: WorkspacePackage[], opts?: Pick<BoundaryOptions, "apps" | "reference">): Rule[];
53
+ /**
54
+ * The parser of the TypeScript source. dependency-cruiser reads TypeScript with the TypeScript
55
+ * compiler of the repository only for TypeScript 2 to 6. With TypeScript 7 or no TypeScript, it reads
56
+ * TypeScript with swc when @swc/core is installed. Else it reads only JavaScript (acorn): that is
57
+ * enough for a check of built JavaScript.
58
+ */
59
+ export declare function parserOptions(root?: string): Record<string, unknown>;
60
+ /**
61
+ * The default options: the source of the packages, with type-only imports, resolved as Node resolves
62
+ * them. There is no `includeOnly`, because it also removes the imports that do not resolve, and the
63
+ * rule not-a-declared-export needs them. The "types" condition is not used: it resolves to a
64
+ * declaration file, and the analysis excludes declaration files, so a deep import does not show.
65
+ */
66
+ export declare function defaultOptions(root?: string): Record<string, unknown>;
67
+ /** The dependency-cruiser configuration of the boundaries for the workspace in the folder `root`. */
68
+ export declare function boundaries(root: string, opts?: BoundaryOptions): Config;
69
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";iBAiBiB;EACf;EACA;EACA;EACA,MAAM;EACN,IAAI;;;iBAIW;EACf,WAAW;EACX,SAAS;;;iBAIM;;EAEf;;EAEA;EACA;;EAEA;;iBAGe;;;;;EAKf;;EAEA;;EAEA;;EAEA,YAAY;;EAEZ,UAAU;;;wBAMI,eAAe;;;;;;wBAqEf,aAAa,aAAa;;wBAW1B,eAAe,aAAa,UAAU;;wBActC,kBAAkB,cAAc,mBAAmB;;wBA2BnD,cAAc,UAAU,oBAAoB,OAAM,KAAK,yCAA8C;;;;;;;wBA0DrG,cAAc,gBAAgB;;;;;;;wBA4B9B,eAAe,gBAAgB;;wBAiB/B,WAAW,cAAc,OAAM,kBAAuB"}
package/build/index.js ADDED
@@ -0,0 +1,261 @@
1
+ import { createRequire } from "node:module";
2
+ import { readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { join, posix } from "node:path";
4
+ // src/index.ts
5
+ /**
6
+ * The import boundaries of a workspace, as a dependency-cruiser configuration. Each package is a
7
+ * unit. Another package imports it only through an entry of its package.json (`exports`, `main`,
8
+ * `module`, `types`, `bin`). A relative path or a deep path into its folder is not an entry.
9
+ *
10
+ * A repository uses it from its `.dependency-cruiser.cjs`:
11
+ *
12
+ * ```js
13
+ * const { boundaries } = require("@mark1russell7/boundaries");
14
+ * module.exports = boundaries(__dirname, { apps: "private" });
15
+ * ```
16
+ */
17
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
18
+ /** The `packages` list of a pnpm-workspace.yaml file. It reads only that list, with no YAML library. */
19
+ function workspaceGlobs(yaml) {
20
+ const globs = [];
21
+ let inList = false;
22
+ for (const raw of yaml.split(/\r?\n/)) {
23
+ const hash = raw.indexOf(" #");
24
+ const line = (hash === -1 ? raw : raw.slice(0, hash)).trimEnd();
25
+ const trimmed = line.trimStart();
26
+ if (trimmed === "" || trimmed.startsWith("#")) continue;
27
+ if (/^packages\s*:/.test(line)) {
28
+ inList = true;
29
+ continue;
30
+ }
31
+ if (!inList) continue;
32
+ if (trimmed === line) break;
33
+ if (!trimmed.startsWith("-")) continue;
34
+ const item = trimmed.slice(1).trim().replace(/^["']/, "").replace(/["']$/, "");
35
+ if (item) globs.push(item);
36
+ }
37
+ return globs;
38
+ }
39
+ function isDir(path) {
40
+ try {
41
+ return statSync(path).isDirectory();
42
+ } catch {
43
+ return false;
44
+ }
45
+ }
46
+ /** The folders that a glob of pnpm-workspace.yaml gives: "a/b", "a/*" and "a/**". */
47
+ function expand(root, glob) {
48
+ const clean = glob.replace(/^\.\//, "").replace(/\/$/, "");
49
+ const star = clean.indexOf("*");
50
+ if (star === -1) return isDir(join(root, clean)) ? [clean] : [];
51
+ const base = clean.slice(0, star).replace(/\/$/, "");
52
+ const recursive = clean.slice(star).startsWith("**");
53
+ const found = [];
54
+ const walk = (dir, depth) => {
55
+ let entries;
56
+ try {
57
+ entries = readdirSync(join(root, dir), { withFileTypes: true });
58
+ } catch {
59
+ return;
60
+ }
61
+ for (const entry of entries) {
62
+ if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith(".")) continue;
63
+ const child = dir === "" ? entry.name : `${dir}/${entry.name}`;
64
+ found.push(child);
65
+ if (recursive && depth < 6) walk(child, depth + 1);
66
+ }
67
+ };
68
+ walk(base, 0);
69
+ return found;
70
+ }
71
+ /** The leaf strings of an `exports` value, with their subpath keys. */
72
+ function exportTargets(value, out = []) {
73
+ if (typeof value === "string") out.push(value);
74
+ else if (Array.isArray(value)) for (const item of value) exportTargets(item, out);
75
+ else if (value && typeof value === "object") for (const item of Object.values(value)) exportTargets(item, out);
76
+ return out;
77
+ }
78
+ /**
79
+ * The RegExp source of an entry target of a package. The extension can change, because
80
+ * dependency-cruiser resolves "./x.js" to the source file x.ts, and "*" of a subpath pattern matches
81
+ * each path.
82
+ */
83
+ function entryPattern(dir, target) {
84
+ return `^${posix.normalize(posix.join(dir, target.replace(/^\.\//, ""))).replace(/\.d\.[cm]?ts$|\.[cm]?[jt]sx?$/, "").split("*").map(escape).join(".*")}(${EXTENSIONS})?$`;
85
+ }
86
+ const EXTENSIONS = [
87
+ ".js",
88
+ ".mjs",
89
+ ".cjs",
90
+ ".jsx",
91
+ ".ts",
92
+ ".mts",
93
+ ".cts",
94
+ ".tsx",
95
+ ".d.ts",
96
+ ".d.mts",
97
+ ".d.cts"
98
+ ].map(escape).join("|");
99
+ /** The entries of a package.json: the files that other packages can import. */
100
+ function packageEntries(dir, manifest) {
101
+ const targets = exportTargets(manifest["exports"]);
102
+ for (const field of [
103
+ "main",
104
+ "module",
105
+ "types",
106
+ "typings"
107
+ ]) {
108
+ const value = manifest[field];
109
+ if (typeof value === "string") targets.push(value);
110
+ }
111
+ if (typeof manifest["bin"] === "string") targets.push(manifest["bin"]);
112
+ else if (manifest["bin"] && typeof manifest["bin"] === "object") targets.push(...exportTargets(manifest["bin"]));
113
+ if (targets.length === 0 && manifest["exports"] === void 0) targets.push("./index.js");
114
+ return [...new Set(targets.filter((t) => !t.endsWith(".json") || t === "./package.json").map((t) => entryPattern(dir, t)))];
115
+ }
116
+ /** The packages of the workspace in the folder `root`. */
117
+ function workspacePackages(root, globs) {
118
+ let list = globs;
119
+ if (!list) {
120
+ try {
121
+ list = workspaceGlobs(readFileSync(join(root, "pnpm-workspace.yaml"), "utf8"));
122
+ } catch {
123
+ list = [];
124
+ }
125
+ if (list.length === 0) list = ["packages/*"];
126
+ }
127
+ const excluded = list.filter((g) => g.startsWith("!")).flatMap((g) => expand(root, g.slice(1)));
128
+ const dirs = [...new Set(list.filter((g) => !g.startsWith("!")).flatMap((g) => expand(root, g)))].filter((d) => !excluded.includes(d));
129
+ const found = [];
130
+ for (const dir of dirs.sort()) {
131
+ let manifest;
132
+ try {
133
+ manifest = JSON.parse(readFileSync(join(root, dir, "package.json"), "utf8"));
134
+ } catch {
135
+ continue;
136
+ }
137
+ if (typeof manifest["name"] !== "string") continue;
138
+ found.push({
139
+ name: manifest["name"],
140
+ dir,
141
+ private: manifest["private"] === true,
142
+ entries: packageEntries(dir, manifest)
143
+ });
144
+ }
145
+ return found;
146
+ }
147
+ /** The rules of the boundaries for a list of packages. `boundaries()` reads the list from the workspace. */
148
+ function boundaryRules(packages, opts = {}) {
149
+ const why = (text) => opts.reference ? `${opts.reference} ${text}` : text;
150
+ const anyPackage = packages.map((p) => `^${escape(p.dir)}/`);
151
+ const rules = [];
152
+ for (const pkg of packages) {
153
+ const own = `^${escape(pkg.dir)}/`;
154
+ const others = anyPackage.filter((path) => path !== own);
155
+ if (others.length > 0) rules.push({
156
+ name: `relative-import-out-of-${slug(pkg.name)}`,
157
+ severity: "error",
158
+ comment: why(`A relative import leaves the package ${pkg.name}. Import the other package by its name, through an entry of its package.json.`),
159
+ from: { path: own },
160
+ to: {
161
+ path: others,
162
+ pathNot: own,
163
+ dependencyTypes: ["local"]
164
+ }
165
+ });
166
+ rules.push({
167
+ name: `deep-import-into-${slug(pkg.name)}`,
168
+ severity: "error",
169
+ comment: why(`An import reaches into the folder of ${pkg.name} at a file that is not an entry of its package.json (exports, main, module, types or bin). Import an entry, or add the file to the exports of ${pkg.name}.`),
170
+ from: { pathNot: own },
171
+ to: pkg.entries.length > 0 ? {
172
+ path: own,
173
+ pathNot: pkg.entries
174
+ } : { path: own }
175
+ });
176
+ }
177
+ const names = packages.map((p) => escape(p.name));
178
+ if (names.length > 0) rules.push({
179
+ name: "not-a-declared-export",
180
+ severity: "error",
181
+ comment: why("An import of a package of this workspace does not resolve. The path is not an entry of its exports, or the package is not built."),
182
+ from: {},
183
+ to: {
184
+ path: `^(${names.join("|")})(/|$)`,
185
+ couldNotResolve: true
186
+ }
187
+ });
188
+ const apps = opts.apps === "private" ? packages.filter((p) => p.private) : packages.filter((p) => (opts.apps ?? []).includes(p.name));
189
+ for (const app of apps) rules.push({
190
+ name: `import-of-the-app-${slug(app.name)}`,
191
+ severity: "error",
192
+ comment: why(`A package imports the app ${app.name}. An app is a leaf: no other package imports it. Move the shared code to a library package.`),
193
+ from: { pathNot: `^${escape(app.dir)}/` },
194
+ to: { path: `^${escape(app.dir)}/` }
195
+ });
196
+ return rules;
197
+ }
198
+ const slug = (name) => name.replace(/^@/, "").replace(/[^A-Za-z0-9]+/g, "-");
199
+ /**
200
+ * The parser of the TypeScript source. dependency-cruiser reads TypeScript with the TypeScript
201
+ * compiler of the repository only for TypeScript 2 to 6. With TypeScript 7 or no TypeScript, it reads
202
+ * TypeScript with swc when @swc/core is installed. Else it reads only JavaScript (acorn): that is
203
+ * enough for a check of built JavaScript.
204
+ */
205
+ function parserOptions(root) {
206
+ if (!root) return {};
207
+ const require = createRequire(join(root, "package.json"));
208
+ try {
209
+ const { version } = require("typescript/package.json");
210
+ if (Number(version.split(".")[0]) < 7) return { tsPreCompilationDeps: true };
211
+ } catch {}
212
+ for (const from of [require, createRequire(import.meta.url)]) try {
213
+ from.resolve("@swc/core");
214
+ return { parser: "swc" };
215
+ } catch {}
216
+ return {};
217
+ }
218
+ /**
219
+ * The default options: the source of the packages, with type-only imports, resolved as Node resolves
220
+ * them. There is no `includeOnly`, because it also removes the imports that do not resolve, and the
221
+ * rule not-a-declared-export needs them. The "types" condition is not used: it resolves to a
222
+ * declaration file, and the analysis excludes declaration files, so a deep import does not show.
223
+ */
224
+ function defaultOptions(root) {
225
+ return {
226
+ ...parserOptions(root),
227
+ exclude: { path: [
228
+ "(^|/)node_modules/",
229
+ "\\.(test|spec|e2e)\\.[cm]?[jt]sx?$",
230
+ "\\.d\\.[cm]?ts$",
231
+ "/(test|tests|e2e|__tests__|fixtures)/"
232
+ ] },
233
+ doNotFollow: { path: ["(^|/)node_modules/"] },
234
+ enhancedResolveOptions: {
235
+ exportsFields: ["exports"],
236
+ conditionNames: [
237
+ "import",
238
+ "require",
239
+ "node",
240
+ "default"
241
+ ],
242
+ mainFields: ["module", "main"]
243
+ },
244
+ skipAnalysisNotInRules: true
245
+ };
246
+ }
247
+ /** The dependency-cruiser configuration of the boundaries for the workspace in the folder `root`. */
248
+ function boundaries(root, opts = {}) {
249
+ const packages = workspacePackages(root, opts.packages);
250
+ const options = {
251
+ ...defaultOptions(root),
252
+ ...opts.options
253
+ };
254
+ return {
255
+ forbidden: [...boundaryRules(packages, opts), ...opts.forbidden ?? []],
256
+ options
257
+ };
258
+ }
259
+ export { boundaries, boundaryRules, defaultOptions, entryPattern, packageEntries, parserOptions, workspaceGlobs, workspacePackages };
260
+
261
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * The import boundaries of a workspace, as a dependency-cruiser configuration. Each package is a\n * unit. Another package imports it only through an entry of its package.json (`exports`, `main`,\n * `module`, `types`, `bin`). A relative path or a deep path into its folder is not an entry.\n *\n * A repository uses it from its `.dependency-cruiser.cjs`:\n *\n * ```js\n * const { boundaries } = require(\"@mark1russell7/boundaries\");\n * module.exports = boundaries(__dirname, { apps: \"private\" });\n * ```\n */\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, posix } from \"node:path\";\n\n/** A rule of dependency-cruiser (the `forbidden` list). The package does not depend on the types of dependency-cruiser. */\nexport interface Rule {\n name: string;\n severity: \"error\" | \"warn\" | \"info\" | \"ignore\";\n comment?: string;\n from: Record<string, unknown>;\n to: Record<string, unknown>;\n}\n\n/** A dependency-cruiser configuration. */\nexport interface Config {\n forbidden: Rule[];\n options: Record<string, unknown>;\n}\n\n/** A package of the workspace. */\nexport interface WorkspacePackage {\n /** The name in package.json. */\n name: string;\n /** The folder, relative to the root, with \"/\". */\n dir: string;\n private: boolean;\n /** RegExp sources of the files that other packages can import. */\n entries: string[];\n}\n\nexport interface BoundaryOptions {\n /**\n * Globs of the package folders, for example `[\"packages/*\"]`. The default is the `packages` list of\n * pnpm-workspace.yaml, or `[\"packages/*\"]` when the file does not exist.\n */\n packages?: string[];\n /** The apps: the leaves of the graph, which no other package imports. \"private\" means each private package. */\n apps?: \"private\" | string[];\n /** A text before each comment, for example the decision record of the rules. */\n reference?: string;\n /** More rules, after the rules of the boundaries. */\n forbidden?: Rule[];\n /** More options of dependency-cruiser. They replace the default options with the same key. */\n options?: Record<string, unknown>;\n}\n\nconst escape = (text: string): string => text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/** The `packages` list of a pnpm-workspace.yaml file. It reads only that list, with no YAML library. */\nexport function workspaceGlobs(yaml: string): string[] {\n const globs: string[] = [];\n let inList = false;\n // String operations, not one large RegExp: a RegExp with nested whitespace groups can be slow on some input.\n for (const raw of yaml.split(/\\r?\\n/)) {\n const hash = raw.indexOf(\" #\");\n const line = (hash === -1 ? raw : raw.slice(0, hash)).trimEnd();\n const trimmed = line.trimStart();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n if (/^packages\\s*:/.test(line)) {\n inList = true;\n continue;\n }\n if (!inList) continue;\n if (trimmed === line) break;\n if (!trimmed.startsWith(\"-\")) continue;\n const item = trimmed.slice(1).trim().replace(/^[\"']/, \"\").replace(/[\"']$/, \"\");\n if (item) globs.push(item);\n }\n return globs;\n}\n\nfunction isDir(path: string): boolean {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\n/** The folders that a glob of pnpm-workspace.yaml gives: \"a/b\", \"a/*\" and \"a/**\". */\nfunction expand(root: string, glob: string): string[] {\n const clean = glob.replace(/^\\.\\//, \"\").replace(/\\/$/, \"\");\n const star = clean.indexOf(\"*\");\n if (star === -1) return isDir(join(root, clean)) ? [clean] : [];\n const base = clean.slice(0, star).replace(/\\/$/, \"\");\n const recursive = clean.slice(star).startsWith(\"**\");\n const found: string[] = [];\n const walk = (dir: string, depth: number): void => {\n let entries;\n try {\n entries = readdirSync(join(root, dir), { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n const child = dir === \"\" ? entry.name : `${dir}/${entry.name}`;\n found.push(child);\n if (recursive && depth < 6) walk(child, depth + 1);\n }\n };\n walk(base, 0);\n return found;\n}\n\n/** The leaf strings of an `exports` value, with their subpath keys. */\nfunction exportTargets(value: unknown, out: string[] = []): string[] {\n if (typeof value === \"string\") out.push(value);\n else if (Array.isArray(value)) for (const item of value) exportTargets(item, out);\n else if (value && typeof value === \"object\") for (const item of Object.values(value)) exportTargets(item, out);\n return out;\n}\n\n/**\n * The RegExp source of an entry target of a package. The extension can change, because\n * dependency-cruiser resolves \"./x.js\" to the source file x.ts, and \"*\" of a subpath pattern matches\n * each path.\n */\nexport function entryPattern(dir: string, target: string): string {\n const path = posix.normalize(posix.join(dir, target.replace(/^\\.\\//, \"\")));\n const stem = path.replace(/\\.d\\.[cm]?ts$|\\.[cm]?[jt]sx?$/, \"\");\n const source = stem.split(\"*\").map(escape).join(\".*\");\n // A flat list, because dependency-cruiser refuses a RegExp with nested quantifiers (safe-regex).\n return `^${source}(${EXTENSIONS})?$`;\n}\n\nconst EXTENSIONS = [\".js\", \".mjs\", \".cjs\", \".jsx\", \".ts\", \".mts\", \".cts\", \".tsx\", \".d.ts\", \".d.mts\", \".d.cts\"].map(escape).join(\"|\");\n\n/** The entries of a package.json: the files that other packages can import. */\nexport function packageEntries(dir: string, manifest: Record<string, unknown>): string[] {\n const targets = exportTargets(manifest[\"exports\"]);\n for (const field of [\"main\", \"module\", \"types\", \"typings\"]) {\n const value = manifest[field];\n if (typeof value === \"string\") targets.push(value);\n }\n if (typeof manifest[\"bin\"] === \"string\") targets.push(manifest[\"bin\"]);\n else if (manifest[\"bin\"] && typeof manifest[\"bin\"] === \"object\") targets.push(...exportTargets(manifest[\"bin\"]));\n // With no entry field, Node resolves the package to index.js.\n if (targets.length === 0 && manifest[\"exports\"] === undefined) targets.push(\"./index.js\");\n return [...new Set(targets.filter((t) => !t.endsWith(\".json\") || t === \"./package.json\").map((t) => entryPattern(dir, t)))];\n}\n\n/** The packages of the workspace in the folder `root`. */\nexport function workspacePackages(root: string, globs?: string[]): WorkspacePackage[] {\n let list = globs;\n if (!list) {\n try {\n list = workspaceGlobs(readFileSync(join(root, \"pnpm-workspace.yaml\"), \"utf8\"));\n } catch {\n list = [];\n }\n if (list.length === 0) list = [\"packages/*\"];\n }\n const excluded = list.filter((g) => g.startsWith(\"!\")).flatMap((g) => expand(root, g.slice(1)));\n const dirs = [...new Set(list.filter((g) => !g.startsWith(\"!\")).flatMap((g) => expand(root, g)))].filter((d) => !excluded.includes(d));\n const found: WorkspacePackage[] = [];\n for (const dir of dirs.sort()) {\n let manifest: Record<string, unknown>;\n try {\n manifest = JSON.parse(readFileSync(join(root, dir, \"package.json\"), \"utf8\")) as Record<string, unknown>;\n } catch {\n continue;\n }\n if (typeof manifest[\"name\"] !== \"string\") continue;\n found.push({ name: manifest[\"name\"], dir, private: manifest[\"private\"] === true, entries: packageEntries(dir, manifest) });\n }\n return found;\n}\n\n/** The rules of the boundaries for a list of packages. `boundaries()` reads the list from the workspace. */\nexport function boundaryRules(packages: WorkspacePackage[], opts: Pick<BoundaryOptions, \"apps\" | \"reference\"> = {}): Rule[] {\n const why = (text: string): string => (opts.reference ? `${opts.reference} ${text}` : text);\n const anyPackage = packages.map((p) => `^${escape(p.dir)}/`);\n const rules: Rule[] = [];\n for (const pkg of packages) {\n const own = `^${escape(pkg.dir)}/`;\n const others = anyPackage.filter((path) => path !== own);\n if (others.length > 0) {\n rules.push({\n name: `relative-import-out-of-${slug(pkg.name)}`,\n severity: \"error\",\n comment: why(`A relative import leaves the package ${pkg.name}. Import the other package by its name, through an entry of its package.json.`),\n from: { path: own },\n to: { path: others, pathNot: own, dependencyTypes: [\"local\"] },\n });\n }\n rules.push({\n name: `deep-import-into-${slug(pkg.name)}`,\n severity: \"error\",\n comment: why(\n `An import reaches into the folder of ${pkg.name} at a file that is not an entry of its package.json (exports, main, module, types or bin). Import an entry, or add the file to the exports of ${pkg.name}.`,\n ),\n from: { pathNot: own },\n to: pkg.entries.length > 0 ? { path: own, pathNot: pkg.entries } : { path: own },\n });\n }\n const names = packages.map((p) => escape(p.name));\n if (names.length > 0) {\n rules.push({\n name: \"not-a-declared-export\",\n severity: \"error\",\n comment: why(\"An import of a package of this workspace does not resolve. The path is not an entry of its exports, or the package is not built.\"),\n from: {},\n to: { path: `^(${names.join(\"|\")})(/|$)`, couldNotResolve: true },\n });\n }\n const apps =\n opts.apps === \"private\" ? packages.filter((p) => p.private) : packages.filter((p) => (opts.apps ?? []).includes(p.name));\n for (const app of apps) {\n rules.push({\n name: `import-of-the-app-${slug(app.name)}`,\n severity: \"error\",\n comment: why(`A package imports the app ${app.name}. An app is a leaf: no other package imports it. Move the shared code to a library package.`),\n from: { pathNot: `^${escape(app.dir)}/` },\n to: { path: `^${escape(app.dir)}/` },\n });\n }\n return rules;\n}\n\nconst slug = (name: string): string => name.replace(/^@/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\");\n\n/**\n * The parser of the TypeScript source. dependency-cruiser reads TypeScript with the TypeScript\n * compiler of the repository only for TypeScript 2 to 6. With TypeScript 7 or no TypeScript, it reads\n * TypeScript with swc when @swc/core is installed. Else it reads only JavaScript (acorn): that is\n * enough for a check of built JavaScript.\n */\nexport function parserOptions(root?: string): Record<string, unknown> {\n if (!root) return {};\n const require = createRequire(join(root, \"package.json\"));\n try {\n const { version } = require(\"typescript/package.json\") as { version: string };\n // A type-only import is a boundary too. This option needs the TypeScript compiler.\n if (Number(version.split(\".\")[0]) < 7) return { tsPreCompilationDeps: true };\n } catch {\n // No TypeScript in the repository\n }\n // @swc/core from the repository, or next to this package (a peer dependency)\n for (const from of [require, createRequire(import.meta.url)]) {\n try {\n from.resolve(\"@swc/core\");\n return { parser: \"swc\" };\n } catch {\n // Not there\n }\n }\n return {};\n}\n\n/**\n * The default options: the source of the packages, with type-only imports, resolved as Node resolves\n * them. There is no `includeOnly`, because it also removes the imports that do not resolve, and the\n * rule not-a-declared-export needs them. The \"types\" condition is not used: it resolves to a\n * declaration file, and the analysis excludes declaration files, so a deep import does not show.\n */\nexport function defaultOptions(root?: string): Record<string, unknown> {\n return {\n ...parserOptions(root),\n exclude: {\n path: [\"(^|/)node_modules/\", \"\\\\.(test|spec|e2e)\\\\.[cm]?[jt]sx?$\", \"\\\\.d\\\\.[cm]?ts$\", \"/(test|tests|e2e|__tests__|fixtures)/\"],\n },\n doNotFollow: { path: [\"(^|/)node_modules/\"] },\n enhancedResolveOptions: {\n exportsFields: [\"exports\"],\n conditionNames: [\"import\", \"require\", \"node\", \"default\"],\n mainFields: [\"module\", \"main\"],\n },\n skipAnalysisNotInRules: true,\n };\n}\n\n/** The dependency-cruiser configuration of the boundaries for the workspace in the folder `root`. */\nexport function boundaries(root: string, opts: BoundaryOptions = {}): Config {\n const packages = workspacePackages(root, opts.packages);\n const options = { ...defaultOptions(root), ...opts.options };\n return {\n forbidden: [...boundaryRules(packages, opts), ...(opts.forbidden ?? [])],\n options,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA0DA,MAAM,UAAU,SAAyB,KAAK,QAAQ,uBAAuB,MAAM;;AAGnF,SAAgB,eAAe,MAAwB;CACrD,MAAM,QAAkB,CAAC;CACzB,IAAI,SAAS;CAEb,KAAK,MAAM,OAAO,KAAK,MAAM,OAAO,GAAG;EACrC,MAAM,OAAO,IAAI,QAAQ,IAAI;EAC7B,MAAM,QAAQ,SAAS,KAAK,MAAM,IAAI,MAAM,GAAG,IAAI,EAAA,CAAG,QAAQ;EAC9D,MAAM,UAAU,KAAK,UAAU;EAC/B,IAAI,YAAY,MAAM,QAAQ,WAAW,GAAG,GAAG;EAC/C,IAAI,gBAAgB,KAAK,IAAI,GAAG;GAC9B,SAAS;GACT;EACF;EACA,IAAI,CAAC,QAAQ;EACb,IAAI,YAAY,MAAM;EACtB,IAAI,CAAC,QAAQ,WAAW,GAAG,GAAG;EAC9B,MAAM,OAAO,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,QAAQ,SAAS,EAAE,CAAC,CAAC,QAAQ,SAAS,EAAE;EAC7E,IAAI,MAAM,MAAM,KAAK,IAAI;CAC3B;CACA,OAAO;AACT;AAEA,SAAS,MAAM,MAAuB;CACpC,IAAI;EACF,OAAO,SAAS,IAAI,CAAC,CAAC,YAAY;CACpC,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,SAAS,OAAO,MAAc,MAAwB;CACpD,MAAM,QAAQ,KAAK,QAAQ,SAAS,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE;CACzD,MAAM,OAAO,MAAM,QAAQ,GAAG;CAC9B,IAAI,SAAS,IAAI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ACF,KAAK,QAAQ,WAAW;EACxB,OAAO,EAAE,QAAQ,MAAM;CACzB,QAAQ,CAER;CAEF,OAAO,CAAC;AACV;;;;;;;AAQA,SAAgB,eAAe,MAAwC;CACrE,OAAO;EACL,GAAG,cAAc,IAAI;EACrB,SAAS,EACP,MAAM;GAAC;GAAsB;GAAsC;GAAmB;EAAuC,EAC/H;EACA,aAAa,EAAE,MAAM,CAAC,oBAAoB,EAAE;EAC5C,wBAAwB;GACtB,eAAe,CAAC,SAAS;GACzB,gBAAgB;IAAC;IAAU;IAAW;IAAQ;GAAS;GACvD,YAAY,CAAC,UAAU,MAAM;EAC/B;EACA,wBAAwB;CAC1B;AACF;;AAGA,SAAgB,WAAW,MAAc,OAAwB,CAAC,GAAW;CAC3E,MAAM,WAAW,kBAAkB,MAAM,KAAK,QAAQ;CACtD,MAAM,UAAU;EAAE,GAAG,eAAe,IAAI;EAAG,GAAG,KAAK;CAAQ;CAC3D,OAAO;EACL,WAAW,CAAC,GAAG,cAAc,UAAU,IAAI,GAAG,GAAI,KAAK,aAAa,CAAC,CAAE;EACvE;CACF;AACF"}
package/package.json CHANGED
@@ -1,13 +1,79 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package",
2
3
  "name": "@mark1russell7/boundaries",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "A placeholder that lets npm trust the release workflow of mark1russell7/template. Use a later version.",
4
+ "version": "0.1.0",
5
+ "description": "The import boundaries of a pnpm workspace as a dependency-cruiser configuration: each package is imported only through the entries of its package.json.",
6
+ "keywords": [
7
+ "dependency-cruiser",
8
+ "monorepo",
9
+ "pnpm",
10
+ "workspace",
11
+ "architecture",
12
+ "boundaries",
13
+ "exports",
14
+ "lint"
15
+ ],
16
+ "homepage": "https://github.com/mark1russell7/template/tree/main/packages/boundaries#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/mark1russell7/template/issues"
19
+ },
5
20
  "repository": {
6
21
  "type": "git",
7
- "url": "git+https://github.com/mark1russell7/template.git"
22
+ "url": "git+https://github.com/mark1russell7/template.git",
23
+ "directory": "packages/boundaries"
8
24
  },
9
25
  "license": "MIT",
26
+ "author": "Mark Russell (https://github.com/mark1russell7)",
27
+ "type": "module",
28
+ "main": "./build/index.js",
29
+ "files": [
30
+ "build"
31
+ ],
10
32
  "publishConfig": {
11
33
  "access": "public"
34
+ },
35
+ "engines": {
36
+ "node": ">=22"
37
+ },
38
+ "peerDependencies": {
39
+ "dependency-cruiser": "^17.0.0 || ^18.0.0",
40
+ "@swc/core": "^1.10.0"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "dependency-cruiser": {
44
+ "optional": true
45
+ },
46
+ "@swc/core": {
47
+ "optional": true
48
+ }
49
+ },
50
+ "devDependencies": {
51
+ "@mark1russell7/cue": "^1.0.2",
52
+ "@types/node": "^26.6.4",
53
+ "typescript": "^7.0.2",
54
+ "vitest": "^5.0.3",
55
+ "dependency-cruiser": "^18.7.0",
56
+ "tsdown": "^0.23.1",
57
+ "@swc/core": "^1.15.0"
58
+ },
59
+ "scripts": {
60
+ "build": "tsdown",
61
+ "test": "vitest run",
62
+ "test:watch": "vitest",
63
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
64
+ },
65
+ "types": "./build/index.d.ts",
66
+ "exports": {
67
+ ".": {
68
+ "import": {
69
+ "types": "./build/index.d.ts",
70
+ "default": "./build/index.js"
71
+ },
72
+ "require": {
73
+ "types": "./build/index.d.cts",
74
+ "default": "./build/index.cjs"
75
+ }
76
+ },
77
+ "./package.json": "./package.json"
12
78
  }
13
- }
79
+ }