@vwala/tooling-config 1.2.0 → 1.3.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,369 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The package-manifest half of the packaging convention: a shared package
4
+ * declares its entry points in `exports`, one explicit subpath each, and
5
+ * nothing else claims to be an entry point. Biome reasons about syntax and
6
+ * never opens a `package.json`, so this cannot be a lint rule.
7
+ *
8
+ * Scope is two rules, not one, because "must have an exports map" and "the
9
+ * exports map must be well formed" are different questions:
10
+ *
11
+ * - Only `packages/**` has to *have* an `exports` map and a scoped name. An
12
+ * app under `apps/` is bundled by Next or Expo and imported by nobody, so an
13
+ * entry-point map would be ceremony; the workspace root is not a package.
14
+ * - *Any* manifest that declares `exports` has its shape checked, wherever it
15
+ * lives. If you wrote an entry-point map, it has to be one — which is also
16
+ * what lets this package check its own root manifest.
17
+ *
18
+ * Detection is by path rather than by `private`, because `private` does not
19
+ * separate the two: an app and an internal package are both routinely private.
20
+ * `packages/` is a mandated layout, so the prefix enforces a documented rule
21
+ * instead of guessing. It is a prefix rather than `packages/*\/`, because the
22
+ * layout nests a category: `packages/<tooling|modules|platform>/<name>/`.
23
+ *
24
+ * Severity follows age, like check-naming, because an exports map is a
25
+ * published contract: migrating one means updating every importer and cannot be
26
+ * a drive-by. The difference from check-naming is `--diff-filter=AM` rather
27
+ * than `A` — a filename can only be wrong the day it is created, while a
28
+ * manifest field can be wrong at any edit, and the commonest real breakage is a
29
+ * typo in a subpath added to a manifest that already existed.
30
+ *
31
+ * A target counts as resolved when it is a file on disk, and is skipped when
32
+ * git ignores it. That is how `"./dist/button.js"` passes in a compiled package
33
+ * before `turbo build` has ever run. The trade is that build output nobody
34
+ * added to .gitignore reads as a broken path, which is the safer mistake.
35
+ * Resolution is a stat rather than a lookup in the tracked file list, so a new
36
+ * package whose sources are written but not yet `git add`ed does not report
37
+ * every one of its own targets as dangling.
38
+ *
39
+ * Deliberately not checked: whether `"."` exists — a feature's `index.ts` is
40
+ * its documented public boundary, so a package exporting only `"."` is obeying
41
+ * a convention rather than breaking one, and whether a package should have one
42
+ * entry point or five is a review judgement rather than a pattern; whether a
43
+ * target is a barrel, for the same reason; the `@vwala/<category>-<name>`
44
+ * prefix, which belongs to the monorepo-structure convention and would break a
45
+ * consumer with a different org; and `"./test-support"` exports, which
46
+ * check-test-layout explicitly sanctions.
47
+ *
48
+ * Wire this into a repository's own check script and run it from the repository
49
+ * root. Set EXPORTS_BASE_REF when the default branch is not `origin/main`; when
50
+ * it cannot be resolved, nothing counts as changed and the script degrades to
51
+ * warnings only.
52
+ *
53
+ * See: .agents/skills/vwala-conventions/references/monorepo-structure.md
54
+ * .agents/skills/turborepo/references/best-practices/packages.md
55
+ */
56
+ import { execFileSync } from "node:child_process";
57
+ import { readFileSync, statSync } from "node:fs";
58
+ import path from "node:path";
59
+
60
+ const BASE_REF = process.env.EXPORTS_BASE_REF ?? "origin/main";
61
+
62
+ const MANIFEST = /(^|\/)package\.json$/;
63
+ const LIBRARY_MANIFEST = /^packages\//;
64
+ // A manifest under one of these is test data — a consumer testing a package
65
+ // generator commits fixture manifests — not a workspace package.
66
+ const FIXTURE_MANIFEST =
67
+ /\/(__tests__|__fixtures__|test-support|node_modules)\//;
68
+ const IGNORED_PREFIXES = [".agents/", ".claude/"];
69
+
70
+ // npm names are lowercase; the scope is what stops `ui` colliding with an
71
+ // unrelated package on the public registry.
72
+ const SCOPED_NAME = /^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/;
73
+ // "." or "./anything" — an exports key. Rejects the condition names that belong
74
+ // one level down ("types", "default", "import") and any "../" escape.
75
+ const SUBPATH = /^\.(\/.+)?$/;
76
+ const LEGACY_FIELDS = ["main", "module", "types", "typings"];
77
+
78
+ const trackedFiles = git(["ls-files"]);
79
+ const untrackedFiles = git(["ls-files", "--others", "--exclude-standard"]);
80
+ const changedFiles = new Set([...untrackedFiles, ...changedSinceBaseRef()]);
81
+
82
+ const errors = [];
83
+ const warnings = [];
84
+
85
+ const manifests = [];
86
+ for (const file of [...trackedFiles, ...untrackedFiles]) {
87
+ if (
88
+ !MANIFEST.test(file) ||
89
+ FIXTURE_MANIFEST.test(file) ||
90
+ IGNORED_PREFIXES.some((prefix) => file.startsWith(prefix))
91
+ ) {
92
+ continue;
93
+ }
94
+ const isChanged = changedFiles.has(file);
95
+ let manifest;
96
+ try {
97
+ manifest = JSON.parse(readFileSync(file, "utf8"));
98
+ } catch {
99
+ // Reported rather than thrown, so one unparseable manifest does not hide
100
+ // every other violation in the repository.
101
+ report({
102
+ isChanged,
103
+ violation: `${file}\n Not valid JSON, so the exports map cannot be checked.`,
104
+ });
105
+ continue;
106
+ }
107
+ manifests.push({
108
+ file,
109
+ directory: path.posix.dirname(file),
110
+ isChanged,
111
+ manifest,
112
+ });
113
+ }
114
+
115
+ const ignoredTargets = resolveIgnored(manifests);
116
+
117
+ for (const { file, directory, isChanged, manifest } of manifests) {
118
+ const isLibrary = LIBRARY_MANIFEST.test(file);
119
+ const exportsField = manifest.exports;
120
+
121
+ if (isLibrary) {
122
+ if (exportsField === undefined) {
123
+ report({
124
+ isChanged,
125
+ violation: `${file}\n No "exports" field. A shared package names its entry points explicitly: "exports": { "./button": "./src/button.tsx" }.`,
126
+ });
127
+ }
128
+ if (typeof manifest.name !== "string") {
129
+ report({
130
+ isChanged,
131
+ violation: `${file}\n Package name is missing. Use a lowercase "@<org>/<name>" — a bare name collides with the public npm registry.`,
132
+ });
133
+ } else if (!SCOPED_NAME.test(manifest.name)) {
134
+ report({
135
+ isChanged,
136
+ violation: `${file}\n Package name "${manifest.name}" is not scoped. Use a lowercase "@<org>/<name>" — a bare name collides with the public npm registry.`,
137
+ });
138
+ }
139
+ }
140
+
141
+ if (exportsField === undefined) {
142
+ continue;
143
+ }
144
+
145
+ for (const field of LEGACY_FIELDS) {
146
+ if (manifest[field] === undefined) {
147
+ continue;
148
+ }
149
+ // `types` gets its own sentence, because the fix is to move it rather than
150
+ // to delete it.
151
+ report({
152
+ isChanged,
153
+ violation:
154
+ field === "types" || field === "typings"
155
+ ? `${file}\n "${field}" alongside "exports". Modern TypeScript resolution reads types out of "exports" and ignores the top-level field, so it only ever goes stale — put "types" inside each subpath's condition object instead.`
156
+ : `${file}\n "${field}" alongside "exports". Node and TypeScript resolve through "exports" and ignore "${field}", so it only ever goes stale — delete it.`,
157
+ });
158
+ }
159
+
160
+ if (!isSubpathMap(exportsField)) {
161
+ report({
162
+ isChanged,
163
+ violation: `${file}\n "exports" is a single target, not a subpath map. Name each entry point — "exports": { "./button": "./src/button.tsx" } — so an importer reaches one file rather than a barrel.`,
164
+ });
165
+ continue;
166
+ }
167
+
168
+ const conditionKeys = Object.keys(exportsField).filter(
169
+ (key) => !SUBPATH.test(key),
170
+ );
171
+ if (conditionKeys.length > 0) {
172
+ report({
173
+ isChanged,
174
+ violation: `${file}\n "exports" keys ${quoteList(conditionKeys)} are conditions, not subpaths. Conditions nest one level down, under a "." or "./<name>" key.`,
175
+ });
176
+ }
177
+
178
+ for (const subpath of Object.keys(exportsField)) {
179
+ if (subpath.includes("*")) {
180
+ report({
181
+ isChanged,
182
+ violation: `${file}\n Wildcard subpath "${subpath}". Enumerate the entry points — a pattern re-opens the whole package and leaves nothing to check against the files on disk.`,
183
+ });
184
+ }
185
+ }
186
+
187
+ for (const { subpath, value, resolved } of exportTargets({
188
+ directory,
189
+ manifest,
190
+ })) {
191
+ if (resolved === undefined) {
192
+ report({
193
+ isChanged,
194
+ violation: `${file}\n "${subpath}" points at "${value}". An "exports" target is a path inside the package and starts with "./".`,
195
+ });
196
+ continue;
197
+ }
198
+ if (isFile(resolved) || ignoredTargets.has(resolved)) {
199
+ continue;
200
+ }
201
+ report({
202
+ isChanged,
203
+ violation: `${file}\n "${subpath}" points at "${value}", which does not resolve to a file and is not git-ignored. Fix the path — or, if it is build output, let .gitignore cover it so the check knows to skip it.`,
204
+ });
205
+ }
206
+ }
207
+
208
+ if (warnings.length > 0) {
209
+ console.warn(
210
+ `\n ! ${warnings.length} exports violation(s) in unchanged manifests — fix when you next touch them:\n`,
211
+ );
212
+ for (const warning of warnings) {
213
+ console.warn(` ${warning}\n`);
214
+ }
215
+ }
216
+
217
+ if (errors.length > 0) {
218
+ console.error(
219
+ `\n ✖ ${errors.length} exports violation(s) in changed manifests:\n`,
220
+ );
221
+ for (const error of errors) {
222
+ console.error(` ${error}\n`);
223
+ }
224
+ process.exit(1);
225
+ }
226
+
227
+ console.log(" ✔ no exports violations in changed manifests");
228
+
229
+ function report({ isChanged, violation }) {
230
+ if (isChanged) {
231
+ errors.push(violation);
232
+ } else {
233
+ warnings.push(violation);
234
+ }
235
+ }
236
+
237
+ function isSubpathMap(exportsField) {
238
+ return (
239
+ typeof exportsField === "object" &&
240
+ exportsField !== null &&
241
+ !Array.isArray(exportsField)
242
+ );
243
+ }
244
+
245
+ /**
246
+ * Every target a manifest's `exports` map points at, paired with the repository
247
+ * path it resolves to. A wildcard subpath is skipped: its target cannot be
248
+ * resolved, and the wildcard itself is already reported.
249
+ */
250
+ function exportTargets({ directory, manifest }) {
251
+ const exportsField = manifest.exports;
252
+ if (!isSubpathMap(exportsField)) {
253
+ return [];
254
+ }
255
+ const targets = [];
256
+ for (const [subpath, target] of Object.entries(exportsField)) {
257
+ if (!SUBPATH.test(subpath) || subpath.includes("*")) {
258
+ continue;
259
+ }
260
+ for (const value of flattenTargets(target)) {
261
+ targets.push({
262
+ subpath,
263
+ value,
264
+ resolved: value.startsWith("./")
265
+ ? path.posix.join(directory, value)
266
+ : undefined,
267
+ });
268
+ }
269
+ }
270
+ return targets;
271
+ }
272
+
273
+ /**
274
+ * The three legal target shapes — a string, a fallback array, and a condition
275
+ * object — flattened to the paths they can resolve to. `null` yields nothing,
276
+ * because it deliberately blocks a subpath rather than naming a file.
277
+ */
278
+ function flattenTargets(target) {
279
+ if (typeof target === "string") {
280
+ return [target];
281
+ }
282
+ if (Array.isArray(target)) {
283
+ return target.flatMap(flattenTargets);
284
+ }
285
+ if (target !== null && typeof target === "object") {
286
+ return Object.values(target).flatMap(flattenTargets);
287
+ }
288
+ return [];
289
+ }
290
+
291
+ /**
292
+ * Which unresolved targets git ignores, in one call rather than one process per
293
+ * target. `git check-ignore` exits 1 when nothing matches, which is the clean
294
+ * case here, so the status is read off the thrown error the way check-test-layout
295
+ * reads `git grep`'s.
296
+ */
297
+ function resolveIgnored(manifestList) {
298
+ const candidates = [
299
+ ...new Set(
300
+ manifestList
301
+ .flatMap(exportTargets)
302
+ .filter(({ resolved }) => resolved !== undefined && !isFile(resolved))
303
+ .map(({ resolved }) => resolved),
304
+ ),
305
+ ];
306
+ if (candidates.length === 0) {
307
+ return new Set();
308
+ }
309
+ try {
310
+ return toSet(
311
+ execFileSync("git", ["check-ignore", "--stdin"], {
312
+ encoding: "utf8",
313
+ input: `${candidates.join("\n")}\n`,
314
+ maxBuffer: 1024 * 1024 * 64,
315
+ }),
316
+ );
317
+ } catch (error) {
318
+ if (error.status !== 1) {
319
+ throw error;
320
+ }
321
+ return toSet(error.stdout ?? "");
322
+ }
323
+ }
324
+
325
+ function toSet(output) {
326
+ return new Set(output.split("\n").filter(Boolean));
327
+ }
328
+
329
+ function isFile(file) {
330
+ try {
331
+ return statSync(file).isFile();
332
+ } catch {
333
+ return false;
334
+ }
335
+ }
336
+
337
+ function quoteList(values) {
338
+ return values.map((value) => `"${value}"`).join(", ");
339
+ }
340
+
341
+ /**
342
+ * Diffs the merge base against the working tree rather than against HEAD, so
343
+ * manifests edited but not yet committed are held to the same standard as the
344
+ * ones already on the branch.
345
+ */
346
+ function changedSinceBaseRef() {
347
+ let mergeBase;
348
+ try {
349
+ mergeBase = execFileSync("git", ["merge-base", BASE_REF, "HEAD"], {
350
+ encoding: "utf8",
351
+ stdio: ["ignore", "pipe", "ignore"],
352
+ }).trim();
353
+ } catch {
354
+ console.warn(
355
+ ` ! Cannot resolve ${BASE_REF} — reporting every violation as a warning.`,
356
+ );
357
+ return [];
358
+ }
359
+ return git(["diff", "--diff-filter=AM", "--name-only", mergeBase]);
360
+ }
361
+
362
+ function git(args) {
363
+ return execFileSync("git", args, {
364
+ encoding: "utf8",
365
+ maxBuffer: 1024 * 1024 * 64,
366
+ })
367
+ .split("\n")
368
+ .filter(Boolean);
369
+ }