@widgetic/dev-tools 0.1.0 → 0.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,78 @@
1
+ /**
2
+ * Types for the link-doctor's rules (`check-links.mjs`). Hand-written,
3
+ * dependency-free — same rules as `frontend-layout.d.mts` beside it.
4
+ */
5
+
6
+ /** One problem the link-doctor found in a Frontend checkout. */
7
+ export interface LinkProblem {
8
+ /** The rule that caught it. */
9
+ kind: 'dangling link' | 'outside checkout' | 'missing dist' | 'dead name';
10
+ /** The package directory under `Frontend/` that owns the broken promise. */
11
+ pkg: string;
12
+ /** What is broken, package-relative. */
13
+ detail: string;
14
+ /** The action that repairs it. */
15
+ fix: string;
16
+ }
17
+
18
+ /** The result of scanning one checkout. */
19
+ export interface LinkProblems {
20
+ /** Every package directory found under the root, sorted. */
21
+ packages: string[];
22
+ /** Everything broken, grouped by package in discovery order. */
23
+ problems: LinkProblem[];
24
+ }
25
+
26
+ /**
27
+ * Manifest-relative values that promise a file on disk: the classic entry
28
+ * fields plus every non-glob string leaf of `exports`. Source-first `.ts`
29
+ * contracts are skipped; `.d.ts` build artifacts are not.
30
+ */
31
+ export declare function promisedFiles(manifest: Record<string, unknown>): string[];
32
+
33
+ /**
34
+ * Dead-name hits in one file's text, word-bounded on both sides —
35
+ * `prompt-chat-messages-scroll` does not match, `../prompt-chat/src/lib` does.
36
+ */
37
+ export declare function deadNameHits(text: string): string[];
38
+
39
+ /**
40
+ * Symlinked `@widgetic/*` entries under one package's node_modules, plus one
41
+ * nested level. A dangling link's target is `null`.
42
+ */
43
+ export declare function widgeticLinks(
44
+ pkgDir: string
45
+ ): { linkPath: string; target: string | null }[];
46
+
47
+ /** Options for {@link collectLinkProblems}. */
48
+ export interface CollectLinkProblemsOptions {
49
+ /**
50
+ * Per-package dead-name file exemptions, keyed by package directory,
51
+ * valued at checkout-relative paths. Defaults to
52
+ * `DEFAULT_EXEMPT_FILES`; the fixture suite overrides this to prove the
53
+ * tables are honored.
54
+ */
55
+ exemptFiles?: Record<string, string[]>;
56
+ }
57
+
58
+ /**
59
+ * Collect every broken sibling promise under a Frontend checkout: dangling
60
+ * `@widgetic/*` symlinks, links that escape the checkout, manifest-promised
61
+ * files that do not exist, and live references to dead checkout names.
62
+ */
63
+ export declare function collectLinkProblems(
64
+ frontendRoot: string,
65
+ options?: CollectLinkProblemsOptions
66
+ ): LinkProblems;
67
+
68
+ /** The dead checkout names and their canonical replacements. */
69
+ export declare const DEAD_CHECKOUT_NAMES: Record<string, string>;
70
+
71
+ /**
72
+ * Packages the dead-name rule skips entirely — the reporter and its docs name
73
+ * the renames as data. Links and dist promises are still checked for these.
74
+ */
75
+ export declare const EXEMPT_DEADNAME_PACKAGES: readonly string[];
76
+
77
+ /** Per-package dead-name file exemptions, keyed by package directory. */
78
+ export declare const DEFAULT_EXEMPT_FILES: Record<string, string[]>;
@@ -0,0 +1,349 @@
1
+ /**
2
+ * The link-doctor's rules, as data. The CLI in `bin/check-links.mjs` formats and
3
+ * exits; this module decides what is broken.
4
+ *
5
+ * Everything here is injectable-root pure: `collectLinkProblems(frontendRoot)`
6
+ * takes the `Frontend/` checkout root and returns the problems found under it,
7
+ * which is what lets the fixture suite in `test/` build a throwaway checkout,
8
+ * break it on purpose, and assert on the result without spawning the CLI.
9
+ *
10
+ * Zero dependencies, plain ESM with hand-written JSDoc types — same rules as
11
+ * `frontend-layout.mjs` beside it.
12
+ */
13
+
14
+ import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
15
+ import { join, relative } from 'node:path';
16
+
17
+ /**
18
+ * Checkout directories that no longer exist but are known to linger in configs,
19
+ * imports and CSS classnames. Keyed by the dead name; valued at the canonical
20
+ * replacement so the message can say what to migrate to. Every entry here is a
21
+ * rename that actually happened and actually left residue behind.
22
+ */
23
+ export const DEAD_CHECKOUT_NAMES = {
24
+ 'props-editor': '@widgetic/editor (the props-editor checkout was renamed to editor/)',
25
+ 'prompt-chat': '@widgetic/chat (the prompt-chat checkout was renamed to chat/)'
26
+ };
27
+
28
+ /**
29
+ * Packages the dead-name rule skips entirely. `dev-tools` is the reporter: its
30
+ * alias tables, this check's own data and its docs exist to *name* the renames
31
+ * (`props-editor` → `editor`, `prompt-chat` → `chat`), and flagging the
32
+ * reporter for knowing its history would be self-defeating. Its links and
33
+ * dist promises are still checked like any other package.
34
+ */
35
+ export const EXEMPT_DEADNAME_PACKAGES = ['dev-tools'];
36
+
37
+ /**
38
+ * Per-package file exemptions for the dead-name rule, keyed by package
39
+ * directory, valued at checkout-relative paths. Every entry is a claim that the
40
+ * reference is deliberate — kept narrow, and worded so a reviewer can verify it.
41
+ * The rule scans everything else, so a new dead reference cannot hide behind an
42
+ * old exemption.
43
+ */
44
+ export const DEFAULT_EXEMPT_FILES = {
45
+ // Deprecated rollback path (its own header says so): resolvePackageLib tries
46
+ // the pre-rename candidates first but guards every one with existsSync and
47
+ // falls through to node_modules. Fix its chat fallback if the embed build is
48
+ // ever revived — do not copy this pattern.
49
+ site: ['scripts/build-creator-embed.mjs'],
50
+ // The PropsEditor component styles its consumers through a live
51
+ // `:global(.props-editor …)` wrapper classname that predates the checkout
52
+ // rename — an identifier the code sets and the standalone shell consumes,
53
+ // not a path. Renaming it is a coordinated product change, not a cleanup.
54
+ editor: ['src/lib/components/editors/PropsEditor.svelte']
55
+ };
56
+
57
+ /** Suffixes of files worth dead-name-scanning. CSS is deliberately absent:
58
+ * the editor package's own component *is* styled through a `.props-editor`
59
+ * classname that predates the checkout rename — a selector the code sets and
60
+ * the app consumes — so matching dead names inside stylesheets flags live
61
+ * identifiers. A CSS-only dead checkout path has not occurred yet; add the
62
+ * suffix back with that distinction handled if one ever does. */
63
+ const SCANNABLE_SUFFIXES = [
64
+ '.ts',
65
+ '.tsx',
66
+ '.mts',
67
+ '.cts',
68
+ '.js',
69
+ '.mjs',
70
+ '.cjs',
71
+ '.jsx',
72
+ '.svelte',
73
+ '.html',
74
+ '.json',
75
+ '.md'
76
+ ];
77
+
78
+ /** Basenames never worth scanning — dependency state and lock metadata. */
79
+ const SKIP_BASENAMES = new Set(['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']);
80
+
81
+ /** Directories never traversed: VCS state, generated output, archives. */
82
+ const SKIP_DIRS = new Set([
83
+ '.git',
84
+ '.svelte-kit',
85
+ 'node_modules',
86
+ 'dist',
87
+ 'build',
88
+ '.output',
89
+ 'coverage',
90
+ // The dunder convention here is for archives: `__docs`, `__specs`. They are
91
+ // history — guides written when the old names were current — and a rename
92
+ // does not reach back and rewrite its own documentation.
93
+ '__docs',
94
+ '__docs__',
95
+ '__specs',
96
+ '__specs__'
97
+ ]);
98
+
99
+ /**
100
+ * Comment lines are stripped from source scanning by prefix, not by parsing:
101
+ * a rename's documentation lives in comments (every dead name in the tree was
102
+ * introduced by a rename comment at least once), while a dead *path* has to be
103
+ * in code or a string to resolve.
104
+ */
105
+ const COMMENT_LINE_PREFIXES = ['//', '*', '/*', '<!--'];
106
+
107
+ /**
108
+ * Manifest-relative values that promise a file on disk: the classic entry
109
+ * fields plus every string leaf of `exports`. Glob patterns are skipped (a
110
+ * pattern cannot be missing the way a file can) and so are `.ts` values (a
111
+ * source-first export is a deliberate contract, not a build artifact).
112
+ *
113
+ * @param {Record<string, unknown>} manifest A parsed package.json.
114
+ * @returns {string[]} Manifest-relative paths, deduplicated, in declaration order.
115
+ */
116
+ export function promisedFiles(manifest) {
117
+ const values = [];
118
+ const push = (value) => {
119
+ if (typeof value !== 'string') return;
120
+ if (!value.startsWith('./')) return;
121
+ if (value.includes('*')) return;
122
+ // Skip source-first `.ts` contracts — but not `.d.ts`, which is a build
123
+ // artifact like any other and exactly as missing when nobody built it.
124
+ if (value.endsWith('.ts') && !/\.d\.(mts|cts|ts)$/.test(value)) return;
125
+ values.push(value);
126
+ };
127
+ for (const field of ['main', 'module', 'svelte', 'types']) push(manifest[field]);
128
+ const walk = (node) => {
129
+ if (typeof node === 'string') push(node);
130
+ else if (node && typeof node === 'object') for (const child of Object.values(node)) walk(child);
131
+ };
132
+ walk(manifest.exports);
133
+ return [...new Set(values)];
134
+ }
135
+
136
+ /**
137
+ * Dead-name hits in one file's text. Word-bounded on both sides so
138
+ * `prompt-chat-messages-scroll` (a live classname in the chat package) does not
139
+ * match `prompt-chat`, while a bare specifier, glob or `.env` path does.
140
+ *
141
+ * @param {string} text The file's contents.
142
+ * @returns {string[]} Dead names present, in declaration order.
143
+ */
144
+ export function deadNameHits(text) {
145
+ const hits = [];
146
+ for (const name of Object.keys(DEAD_CHECKOUT_NAMES)) {
147
+ const pattern = new RegExp(`(?<![\\w-])${name}(?![\\w-])`);
148
+ if (pattern.test(text)) hits.push(name);
149
+ }
150
+ return hits;
151
+ }
152
+
153
+ /** One reported problem: what kind, where, and the fix that repairs it. */
154
+ /**
155
+ * @typedef {Object} LinkProblem
156
+ * @property {'dangling link' | 'outside checkout' | 'missing dist' | 'dead name'} kind
157
+ * @property {string} pkg The package directory under Frontend/.
158
+ * @property {string} detail What is broken, package-relative.
159
+ * @property {string} fix The action that repairs it.
160
+ */
161
+
162
+ /**
163
+ * Symlinked `@widgetic/*` entries under one package's node_modules, plus one
164
+ * nested level (bundled/workspace deps). A dangling link's target resolves to
165
+ * `null` — `realpathSync` throws on exactly the condition being checked.
166
+ *
167
+ * @param {string} pkgDir The package checkout root.
168
+ * @returns {{linkPath: string, target: string | null}[]}
169
+ */
170
+ export function widgeticLinks(pkgDir) {
171
+ const links = [];
172
+ const scopes = [join(pkgDir, 'node_modules', '@widgetic')];
173
+ const nm = join(pkgDir, 'node_modules');
174
+ if (existsSync(nm)) {
175
+ for (const entry of readdirSync(nm, { withFileTypes: true })) {
176
+ if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === '@widgetic') continue;
177
+ const nested = join(nm, entry.name, 'node_modules', '@widgetic');
178
+ if (existsSync(nested)) scopes.push(nested);
179
+ }
180
+ }
181
+ for (const scope of scopes) {
182
+ if (!existsSync(scope)) continue;
183
+ for (const entry of readdirSync(scope, { withFileTypes: true })) {
184
+ const linkPath = join(scope, entry.name);
185
+ let target = null;
186
+ try {
187
+ target = realpathSync(linkPath);
188
+ } catch {
189
+ // Dangling — the finding itself.
190
+ }
191
+ links.push({ linkPath, target });
192
+ }
193
+ }
194
+ return links;
195
+ }
196
+
197
+ /**
198
+ * Recursively collect scannable files under dir, honoring the skip lists.
199
+ *
200
+ * @param {string} dir Directory to walk.
201
+ * @param {string[]} out Accumulator.
202
+ * @returns {string[]}
203
+ */
204
+ function scannableFiles(dir, out = []) {
205
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
206
+ if (entry.name.startsWith('.') || SKIP_BASENAMES.has(entry.name)) continue;
207
+ const full = join(dir, entry.name);
208
+ if (entry.isDirectory()) {
209
+ if (!SKIP_DIRS.has(entry.name)) scannableFiles(full, out);
210
+ } else if (SCANNABLE_SUFFIXES.some((suffix) => entry.name.endsWith(suffix))) {
211
+ out.push(full);
212
+ }
213
+ }
214
+ return out;
215
+ }
216
+
217
+ /**
218
+ * Whether a file is exempt from the dead-name rule in this checkout.
219
+ *
220
+ * @param {string} pkgDir The package root.
221
+ * @param {string} file Absolute file path.
222
+ * @param {string} frontendRoot The checkout root, for package-relative keys.
223
+ * @param {Record<string, string[]>} exemptFiles Package → relative paths.
224
+ */
225
+ function isExemptFile(pkgDir, file, frontendRoot, exemptFiles) {
226
+ const pkg = relative(frontendRoot, pkgDir);
227
+ const rel = relative(pkgDir, file);
228
+ return (exemptFiles[pkg] ?? []).includes(rel);
229
+ }
230
+
231
+ /**
232
+ * Collect every broken sibling promise under a Frontend checkout.
233
+ *
234
+ * @param {string} frontendRoot The `Frontend/` checkout root.
235
+ * @param {{exemptFiles?: Record<string, string[]>}} [options]
236
+ * Overrides for the exemption tables — the fixture suite uses this to prove
237
+ * the tables themselves are honored.
238
+ * @returns {{packages: string[], problems: LinkProblem[]}}
239
+ */
240
+ export function collectLinkProblems(frontendRoot, options = {}) {
241
+ const exemptFiles = options.exemptFiles ?? DEFAULT_EXEMPT_FILES;
242
+ // Canonicalize before any comparison: realpath resolves symlinks in the root
243
+ // itself (macOS reports /var/... as /private/var/...), and a link target
244
+ // compared against an unresolved root would be misread as outside the
245
+ // checkout even when it lives inside it.
246
+ try {
247
+ frontendRoot = realpathSync(frontendRoot);
248
+ } catch {
249
+ // A root that cannot be resolved gets reported by the caller's own
250
+ // existence checks; readdirSync below fails loudly enough.
251
+ }
252
+ /** @type {LinkProblem[]} */
253
+ const problems = [];
254
+
255
+ const packages = readdirSync(frontendRoot, { withFileTypes: true })
256
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
257
+ .map((entry) => entry.name)
258
+ .filter((name) => existsSync(join(frontendRoot, name, 'package.json')))
259
+ .sort();
260
+
261
+ for (const pkg of packages) {
262
+ const pkgDir = join(frontendRoot, pkg);
263
+ let manifest;
264
+ try {
265
+ manifest = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8'));
266
+ } catch (error) {
267
+ problems.push({
268
+ kind: 'missing dist',
269
+ pkg,
270
+ detail: `package.json is not readable JSON (${error instanceof Error ? error.message : String(error)})`,
271
+ fix: 'repair the manifest — nothing downstream of it can be trusted while it does not parse'
272
+ });
273
+ continue;
274
+ }
275
+
276
+ // Rule 1 — every @widgetic symlink resolves, and into this checkout.
277
+ for (const { linkPath, target } of widgeticLinks(pkgDir)) {
278
+ const rel = relative(pkgDir, linkPath);
279
+ if (!target) {
280
+ problems.push({
281
+ kind: 'dangling link',
282
+ pkg,
283
+ detail: `${rel} resolves to nothing`,
284
+ fix: 'relink it (npm run ldt, or recreate the symlink) after confirming the sibling checkout exists'
285
+ });
286
+ continue;
287
+ }
288
+ if (!existsSync(target)) {
289
+ problems.push({
290
+ kind: 'dangling link',
291
+ pkg,
292
+ detail: `${rel} → ${target} does not exist`,
293
+ fix: 'relink it (npm run ldt, or recreate the symlink) after confirming the sibling checkout exists'
294
+ });
295
+ continue;
296
+ }
297
+ if (!target.startsWith(frontendRoot)) {
298
+ problems.push({
299
+ kind: 'outside checkout',
300
+ pkg,
301
+ detail: `${rel} → ${relative(frontendRoot, target)} (outside the checkout)`,
302
+ fix: 'remove the link and relink to the sibling checkout — a foreign copy shadows the sibling and looks installed'
303
+ });
304
+ }
305
+ }
306
+
307
+ // Rule 2 — every manifest-promised file exists.
308
+ for (const promised of promisedFiles(manifest)) {
309
+ if (existsSync(join(pkgDir, promised))) continue;
310
+ problems.push({
311
+ kind: 'missing dist',
312
+ pkg,
313
+ detail: `manifest promises ${promised} but the file does not exist`,
314
+ fix: 'build the package, or delete the stale export if the output is gone for good'
315
+ });
316
+ }
317
+
318
+ // Rule 3 — no references to dead checkout names.
319
+ if (EXEMPT_DEADNAME_PACKAGES.includes(pkg)) continue;
320
+ for (const file of scannableFiles(pkgDir)) {
321
+ if (isExemptFile(pkgDir, file, frontendRoot, exemptFiles)) continue;
322
+ const text = readFileSync(file, 'utf8');
323
+ const isSource = /\.(ts|tsx|mts|cts|js|mjs|cjs|jsx|svelte)$/.test(file);
324
+ const lines = text.split('\n');
325
+ // Comment-prefix stripping applies to source files only: a dead path
326
+ // has to be in code or a string to resolve, while documentation of the
327
+ // renames lives in comments and must stay scannable-exempt. Markdown,
328
+ // json and html are scanned whole.
329
+ const scanned = isSource
330
+ ? lines
331
+ .filter((line) => {
332
+ const trimmed = line.trimStart();
333
+ return !COMMENT_LINE_PREFIXES.some((prefix) => trimmed.startsWith(prefix));
334
+ })
335
+ .join('\n')
336
+ : text;
337
+ for (const name of deadNameHits(scanned)) {
338
+ problems.push({
339
+ kind: 'dead name',
340
+ pkg,
341
+ detail: `${relative(pkgDir, file)} references "${name}" — a checkout that no longer exists`,
342
+ fix: `migrate to ${DEAD_CHECKOUT_NAMES[name]}; delete the reference if nothing consumes it`
343
+ });
344
+ }
345
+ }
346
+ }
347
+
348
+ return { packages, problems };
349
+ }
@@ -60,7 +60,9 @@ export const SIBLING_PACKAGES = {
60
60
  */
61
61
  subpaths: {
62
62
  styles: 'styles/global.css',
63
- previews: 'components/previews',
63
+ // `previews` (→ components/previews) was removed: the directory no
64
+ // longer exists and no consumer imports it — the alias every table
65
+ // used to carry resolved nothing. Re-add only with a live path.
64
66
  'shad-editor': 'shad-editor',
65
67
  components: 'components',
66
68
  icons: 'icons',
@@ -0,0 +1,193 @@
1
+ /**
2
+ * The lockfile-peers rule, as data — the CLI in `bin/check-design-system-peers.mjs`
3
+ * formats and exits, this module decides what is broken.
4
+ *
5
+ * `@widgetic/design-system` has exactly two sibling-app consumers that resolve
6
+ * it from the registry — `canvas` and `file-browser` — and a range alone cannot
7
+ * keep them coordinated: both declare `^0.5.12`, nothing forces the two
8
+ * lockfiles to move together, and when 0.5.14 published, canvas's lockfile
9
+ * refreshed to it while file-browser's kept promising 0.5.12. Nothing failed —
10
+ * both resolutions satisfy the same range — but the two consumers now pin
11
+ * different component trees, so a shared screen renders with two different
12
+ * designs depending on which app hosts it, and nobody would ever connect the
13
+ * symptom to the split. The fix is the same discipline the README contract
14
+ * enforces for publish prose: the bump lands as one coordinated change, and a
15
+ * machine check fails when it does not.
16
+ *
17
+ * Two rules:
18
+ *
19
+ * version-divergence the peers' lockfiles must resolve the *same*
20
+ * design-system version. "Both satisfy the range" is not
21
+ * the bar; the bar is the same bar.
22
+ *
23
+ * stale-manifest each peer's manifest range must admit the version the
24
+ * design-system checkout carries. This fires when a
25
+ * release leaves the declared range (a 0.6.0 across a
26
+ * `^0.5.12`); npm's caret semantics silently admit
27
+ * every minor, so the range alone can never force the
28
+ * bump.
29
+ *
30
+ * checkout-sync the peers' lockfiles must resolve the version the
31
+ * design-system checkout carries. This is the rule
32
+ * that fires at *every* publish — a version bump in the
33
+ * checkout goes red in both peers until the coordinated
34
+ * lockfile refresh lands, because a caret range would
35
+ * otherwise admit the new version and nothing would
36
+ * force anyone to move.
37
+ *
38
+ * Zero dependencies, plain ESM, injectable-root pure: every function takes the
39
+ * `Frontend/` checkout root, so the fixture suite builds a throwaway checkout,
40
+ * breaks it on purpose, and asserts on the result without touching the real
41
+ * one.
42
+ */
43
+
44
+ /** The package whose coordination is guarded, unscoped and scoped. */
45
+ export const PACKAGE = 'design-system';
46
+ export const SCOPED = `@widgetic/${PACKAGE}`;
47
+
48
+ /** The sibling apps that resolve the package from the registry, as lockfile pairs. */
49
+ export const PEERS = ['canvas', 'file-browser'];
50
+
51
+ /** The checkout whose version the peers' ranges must admit. */
52
+ export const SOURCE_PACKAGE = 'design-system';
53
+
54
+ import { satisfies } from './semver-lite.mjs';
55
+
56
+ /** Minimal JSON reader that returns `null` instead of throwing. */
57
+ export function readJson(path) {
58
+ try {
59
+ return JSON.parse(readFile(path));
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ import { readFileSync as readFile } from 'node:fs';
66
+
67
+ /**
68
+ * The design-system version one peer's lockfile resolves, or `undefined`.
69
+ *
70
+ * @param {string} root The Frontend checkout root.
71
+ * @param {string} pkg The peer's directory name.
72
+ * @returns {string | undefined}
73
+ */
74
+ export function lockResolved(root, pkg) {
75
+ const lock = readJson(`${root}/${pkg}/package-lock.json`);
76
+ return lock?.packages?.[`node_modules/${SCOPED}`]?.version;
77
+ }
78
+
79
+ /**
80
+ * The design-system range one peer's manifest admits, or `undefined` when the
81
+ * manifest does not declare the dependency at all.
82
+ *
83
+ * @param {string} root The Frontend checkout root.
84
+ * @param {string} pkg The peer's directory name.
85
+ * @returns {string | undefined}
86
+ */
87
+ export function admittedRange(root, pkg) {
88
+ const manifest = readJson(`${root}/${pkg}/package.json`);
89
+ const deps = manifest?.dependencies ?? {};
90
+ return deps[SCOPED];
91
+ }
92
+
93
+ /**
94
+ * The version the design-system checkout itself carries.
95
+ *
96
+ * @param {string} root The Frontend checkout root.
97
+ * @returns {string | undefined}
98
+ */
99
+ export function checkoutVersion(root) {
100
+ return readJson(`${root}/${SOURCE_PACKAGE}/package.json`)?.version;
101
+ }
102
+
103
+ /**
104
+ * Find every lockfile-peers violation under `root`.
105
+ *
106
+ * @param {string} root The Frontend checkout root.
107
+ * @returns {{ kind: 'unreadable' | 'unresolved' | 'version-divergence' | 'stale-manifest' | 'checkout-sync', pkg: string, detail: string, fix: string }[]}
108
+ */
109
+ export function collectPeersProblems(root) {
110
+ const problems = [];
111
+ const resolved = new Map();
112
+
113
+ for (const pkg of PEERS) {
114
+ const lock = readJson(`${root}/${pkg}/package-lock.json`);
115
+ if (!lock) {
116
+ problems.push({
117
+ kind: 'unreadable',
118
+ pkg,
119
+ detail: 'no readable package-lock.json',
120
+ fix: `run npm install in ${pkg}/ so the lockfile exists`
121
+ });
122
+ continue;
123
+ }
124
+ const version = lockResolved(root, pkg);
125
+ if (!version) {
126
+ problems.push({
127
+ kind: 'unresolved',
128
+ pkg,
129
+ detail: `the lockfile has no node_modules/${SCOPED} entry`,
130
+ fix: `run npm install in ${pkg}/ so ${SCOPED} resolves into the lockfile`
131
+ });
132
+ continue;
133
+ }
134
+ resolved.set(pkg, version);
135
+ }
136
+
137
+ // Divergence needs at least two healthy resolutions to compare.
138
+ const versions = [...new Set(resolved.values())];
139
+ if (versions.length > 1) {
140
+ const detail = PEERS.filter((p) => resolved.has(p))
141
+ .map((p) => `${p} ${resolved.get(p)}`)
142
+ .join(', ');
143
+ problems.push({
144
+ kind: 'version-divergence',
145
+ pkg: PEERS.join(' + '),
146
+ detail: `the peers' lockfiles resolve different ${SCOPED} versions: ${detail}`,
147
+ fix: `bump/refresh both lockfiles as one coordinated change — run npm update ${SCOPED} in each peer, land them as one commit pair`
148
+ });
149
+ }
150
+
151
+ const checkout = checkoutVersion(root);
152
+ if (checkout) {
153
+ for (const pkg of PEERS) {
154
+ const version = resolved.get(pkg);
155
+ if (version && version !== checkout) {
156
+ problems.push({
157
+ kind: 'checkout-sync',
158
+ pkg,
159
+ detail: `the design-system checkout carries ${checkout} but ${pkg}'s lockfile resolves ${version}`,
160
+ fix: `run npm update ${SCOPED} in ${pkg}/ and land both peers' lockfiles as one coordinated commit with the design-system release`
161
+ });
162
+ }
163
+ const range = admittedRange(root, pkg);
164
+ if (range === undefined) continue;
165
+ if (!satisfies(checkout, range)) {
166
+ problems.push({
167
+ kind: 'stale-manifest',
168
+ pkg,
169
+ detail: `the manifest range ${range} does not admit the design-system checkout version ${checkout}`,
170
+ fix: `bump ${SCOPED} in ${pkg}/package.json to admit ${checkout} and refresh its lockfile — together with the other peer`
171
+ });
172
+ }
173
+ }
174
+ }
175
+
176
+ return problems;
177
+ }
178
+
179
+ /**
180
+ * Render problems the way the other dev-tools checks do: one indented
181
+ * finding with its fix, ready to paste into a terminal.
182
+ *
183
+ * @param {ReturnType<typeof collectPeersProblems>} problems
184
+ * @returns {string}
185
+ */
186
+ export function formatPeersProblems(problems) {
187
+ return problems
188
+ .map(
189
+ ({ kind, pkg, detail, fix }) =>
190
+ ` ${pkg}: ${kind}\n ${detail}\n → ${fix}`
191
+ )
192
+ .join('\n');
193
+ }