@greenharness/greenrack-cli 0.0.0-reserved → 7.0.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.
Files changed (125) hide show
  1. package/README.md +334 -1
  2. package/agents/design-system-lookup.md +59 -0
  3. package/dist/bin.d.ts +3 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +145 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/catalog.d.ts +13 -0
  8. package/dist/catalog.d.ts.map +1 -0
  9. package/dist/catalog.js +67 -0
  10. package/dist/catalog.js.map +1 -0
  11. package/dist/commands/context.d.ts +17 -0
  12. package/dist/commands/context.d.ts.map +1 -0
  13. package/dist/commands/context.js +110 -0
  14. package/dist/commands/context.js.map +1 -0
  15. package/dist/commands/doctor.d.ts +75 -0
  16. package/dist/commands/doctor.d.ts.map +1 -0
  17. package/dist/commands/doctor.js +1008 -0
  18. package/dist/commands/doctor.js.map +1 -0
  19. package/dist/commands/hook.d.ts +10 -0
  20. package/dist/commands/hook.d.ts.map +1 -0
  21. package/dist/commands/hook.js +323 -0
  22. package/dist/commands/hook.js.map +1 -0
  23. package/dist/commands/list.d.ts +4 -0
  24. package/dist/commands/list.d.ts.map +1 -0
  25. package/dist/commands/list.js +59 -0
  26. package/dist/commands/list.js.map +1 -0
  27. package/dist/commands/lookup.d.ts +13 -0
  28. package/dist/commands/lookup.d.ts.map +1 -0
  29. package/dist/commands/lookup.js +66 -0
  30. package/dist/commands/lookup.js.map +1 -0
  31. package/dist/commands/manifest.d.ts +5 -0
  32. package/dist/commands/manifest.d.ts.map +1 -0
  33. package/dist/commands/manifest.js +33 -0
  34. package/dist/commands/manifest.js.map +1 -0
  35. package/dist/commands/mcp.d.ts +159 -0
  36. package/dist/commands/mcp.d.ts.map +1 -0
  37. package/dist/commands/mcp.js +235 -0
  38. package/dist/commands/mcp.js.map +1 -0
  39. package/dist/commands/mockup.d.ts +80 -0
  40. package/dist/commands/mockup.d.ts.map +1 -0
  41. package/dist/commands/mockup.js +714 -0
  42. package/dist/commands/mockup.js.map +1 -0
  43. package/dist/commands/skill.d.ts +15 -0
  44. package/dist/commands/skill.d.ts.map +1 -0
  45. package/dist/commands/skill.js +398 -0
  46. package/dist/commands/skill.js.map +1 -0
  47. package/dist/disambiguation.d.ts +24 -0
  48. package/dist/disambiguation.d.ts.map +1 -0
  49. package/dist/disambiguation.js +56 -0
  50. package/dist/disambiguation.js.map +1 -0
  51. package/dist/extension-pointer.d.ts +7 -0
  52. package/dist/extension-pointer.d.ts.map +1 -0
  53. package/dist/extension-pointer.js +30 -0
  54. package/dist/extension-pointer.js.map +1 -0
  55. package/dist/format.d.ts +19 -0
  56. package/dist/format.d.ts.map +1 -0
  57. package/dist/format.js +213 -0
  58. package/dist/format.js.map +1 -0
  59. package/dist/hook-script.d.ts +73 -0
  60. package/dist/hook-script.d.ts.map +1 -0
  61. package/dist/hook-script.js +165 -0
  62. package/dist/hook-script.js.map +1 -0
  63. package/dist/index.d.ts +7 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +6 -0
  66. package/dist/index.js.map +1 -0
  67. package/dist/legacy-names.d.ts +26 -0
  68. package/dist/legacy-names.d.ts.map +1 -0
  69. package/dist/legacy-names.js +26 -0
  70. package/dist/legacy-names.js.map +1 -0
  71. package/dist/manifest.d.ts +51 -0
  72. package/dist/manifest.d.ts.map +1 -0
  73. package/dist/manifest.js +229 -0
  74. package/dist/manifest.js.map +1 -0
  75. package/dist/registry-types.d.ts +106 -0
  76. package/dist/registry-types.d.ts.map +1 -0
  77. package/dist/registry-types.js +2 -0
  78. package/dist/registry-types.js.map +1 -0
  79. package/dist/registry.d.ts +52 -0
  80. package/dist/registry.d.ts.map +1 -0
  81. package/dist/registry.js +95 -0
  82. package/dist/registry.js.map +1 -0
  83. package/dist/scan.d.ts +19 -0
  84. package/dist/scan.d.ts.map +1 -0
  85. package/dist/scan.js +29 -0
  86. package/dist/scan.js.map +1 -0
  87. package/dist/search.d.ts +16 -0
  88. package/dist/search.d.ts.map +1 -0
  89. package/dist/search.js +75 -0
  90. package/dist/search.js.map +1 -0
  91. package/dist/skill-template.d.ts +24 -0
  92. package/dist/skill-template.d.ts.map +1 -0
  93. package/dist/skill-template.js +140 -0
  94. package/dist/skill-template.js.map +1 -0
  95. package/greenharness.toml +38 -0
  96. package/package.json +76 -4
  97. package/registry.json +12893 -0
  98. package/skills/colors/LICENSE +21 -0
  99. package/skills/colors/NOTICE.md +36 -0
  100. package/skills/colors/SKILL.md +101 -0
  101. package/skills/colors/color-formats.md +90 -0
  102. package/skills/colors/color-usage.md +109 -0
  103. package/skills/colors/contrast.md +70 -0
  104. package/skills/colors/palette-generation.md +108 -0
  105. package/skills/colors/palette-structure.md +72 -0
  106. package/skills/colors/token-naming.md +99 -0
  107. package/skills/greenrack-mockup/SKILL.md +115 -0
  108. package/skills/typography/LICENSE +21 -0
  109. package/skills/typography/NOTICE.md +36 -0
  110. package/skills/typography/SKILL.md +171 -0
  111. package/skills/typography/choosing-fonts.md +53 -0
  112. package/skills/typography/css-cheat-sheet.md +67 -0
  113. package/skills/typography/details-and-accessibility.md +84 -0
  114. package/skills/typography/spacing-and-sizing.md +87 -0
  115. package/skills/typography/variable-fonts-and-opentype.md +100 -0
  116. package/skills/typography/wrapping-and-punctuation.md +23 -0
  117. package/skills/ui/LICENSE +21 -0
  118. package/skills/ui/NOTICE.md +38 -0
  119. package/skills/ui/SKILL.md +141 -0
  120. package/skills/ui/animations.md +170 -0
  121. package/skills/ui/enter-exit.md +157 -0
  122. package/skills/ui/icon-transitions.md +72 -0
  123. package/skills/ui/icons.md +105 -0
  124. package/skills/ui/performance.md +63 -0
  125. package/skills/ui/surfaces.md +166 -0
@@ -0,0 +1,1008 @@
1
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
3
+ import { cliVersion } from './manifest.js';
4
+ import { lineOf, maskComments } from '../scan.js';
5
+ import { LEGACY_CLI_PACKAGE, LEGACY_CSS_VARIABLE_PREFIX, LEGACY_DATA_ATTRIBUTE_PREFIX, LEGACY_PROSE_LAYER, LEGACY_TOKENS_PACKAGE, LEGACY_UI_PACKAGE, } from '../legacy-names.js';
6
+ const GREENRACK_SCOPE = {
7
+ kind: 'greenrack',
8
+ ui: '@greenharness/greenrack-ui',
9
+ tokens: '@greenharness/greenrack-tokens',
10
+ cli: '@greenharness/greenrack-cli',
11
+ proseLayer: 'gr-prose',
12
+ cssVariablePrefix: '--gr-',
13
+ dataAttributePrefix: 'data-gr',
14
+ };
15
+ const LEGACY_SCOPE = {
16
+ kind: 'legacy',
17
+ ui: LEGACY_UI_PACKAGE,
18
+ tokens: LEGACY_TOKENS_PACKAGE,
19
+ cli: LEGACY_CLI_PACKAGE,
20
+ proseLayer: LEGACY_PROSE_LAYER,
21
+ cssVariablePrefix: LEGACY_CSS_VARIABLE_PREFIX,
22
+ dataAttributePrefix: LEGACY_DATA_ATTRIBUTE_PREFIX,
23
+ };
24
+ /** New scope first: an app that depends on both is checked as the new one. */
25
+ export const SCOPES = [GREENRACK_SCOPE, LEGACY_SCOPE];
26
+ const PRIORITIES = ['priority1', 'priority2', 'priority3', 'priority4', 'priority5'];
27
+ const LAYER_STATEMENT = `@layer reset, ${PRIORITIES.join(', ')};`;
28
+ const dsCss = (scope) => `${scope.ui}/dist/index.css`;
29
+ /** Layers each design-system stylesheet of a scope declares, in declaration order. */
30
+ function dsSheets(scope) {
31
+ return {
32
+ [dsCss(scope)]: ['reset', scope.proseLayer, ...PRIORITIES],
33
+ [`${scope.ui}/reset.css`]: ['reset'],
34
+ [`${scope.ui}/strict.css`]: ['reset', scope.proseLayer, ...PRIORITIES],
35
+ };
36
+ }
37
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\/-]/g, '\\$&');
38
+ /** `@scope/name` as source text, also as inside a regex literal (`@scope\/name`). */
39
+ function packageMention(name) {
40
+ return new RegExp(`${name
41
+ .split('/')
42
+ .map(escapeRegExp)
43
+ .join(String.raw `\\?/`)}(?![\\w-])`);
44
+ }
45
+ /** `from '<tokens>/tokens/…'`: a deep import of a token module. */
46
+ function tokensDeepImport(scope) {
47
+ return new RegExp(String.raw `\bfrom\s*(['"])${escapeRegExp(scope.tokens)}/tokens/[^'"\n]+\1`);
48
+ }
49
+ /** Build config that can carry StyleX / react-strict-dom options. */
50
+ const CONFIG_FILE = /^(?:(?:vite|vitest|babel|postcss)(?:\.[\w-]+)*\.[cm]?[jt]s|\.babelrc(?:\.[cm]?js|\.json)?|[\w-]+\.babel\.[cm]?[jt]s)$/;
51
+ /** App entry modules, most specific first. */
52
+ const ENTRIES = [
53
+ 'app/root.tsx',
54
+ 'app/root.jsx',
55
+ 'src/main.tsx',
56
+ 'src/main.jsx',
57
+ 'src/main.ts',
58
+ 'src/index.tsx',
59
+ 'src/index.jsx',
60
+ 'src/root.tsx',
61
+ ];
62
+ /**
63
+ * Elements the design system renders. A zero padding/margin on one of these
64
+ * (or on `*`) outside a layer beats the component's own spacing.
65
+ */
66
+ const COMPONENT_ELEMENTS = new Set([
67
+ 'a',
68
+ 'button',
69
+ 'div',
70
+ 'fieldset',
71
+ 'form',
72
+ 'h1',
73
+ 'h2',
74
+ 'h3',
75
+ 'h4',
76
+ 'h5',
77
+ 'h6',
78
+ 'header',
79
+ 'footer',
80
+ 'input',
81
+ 'label',
82
+ 'legend',
83
+ 'li',
84
+ 'main',
85
+ 'nav',
86
+ 'ol',
87
+ 'p',
88
+ 'section',
89
+ 'select',
90
+ 'span',
91
+ 'table',
92
+ 'td',
93
+ 'textarea',
94
+ 'th',
95
+ 'ul',
96
+ ]);
97
+ const ZERO_SPACING = /(?:^|[;{\s])((?:padding|margin)(?:-(?:top|right|bottom|left|block|inline)(?:-(?:start|end))?)?)\s*:\s*0(?:px|rem|em)?\s*(?:!important\s*)?(?=;|$)/g;
98
+ /** True when the root, a workspace package or a package one directory down depends on either scope's UI package. */
99
+ export function isGreenrackConsumer(root) {
100
+ return consumerPackages(resolve(root)).length > 0;
101
+ }
102
+ export function runDoctor(options = {}) {
103
+ const root = resolve(options.cwd ?? process.cwd());
104
+ const packages = consumerPackages(root);
105
+ if (packages.length === 0) {
106
+ return {
107
+ text: options.session ? '' : 'not a greenrack consumer',
108
+ data: { ok: true, findings: [], checked: [], skipped: [], packages: [], scopes: [] },
109
+ };
110
+ }
111
+ const findings = [];
112
+ const checked = [];
113
+ const rel = (path) => relative(root, path) || '.';
114
+ const skipped = [];
115
+ for (const { dir, pkg, scope } of packages) {
116
+ findings.push(...checkPackage(dir, pkg, scope, rel, checked, skipped));
117
+ }
118
+ return report(findings, checked, packages.map(({ dir }) => rel(dir)), [...new Set(packages.map(({ scope }) => scope.ui))], options.session === true, skipped);
119
+ }
120
+ /** Every check, for one package that depends on its scope's UI package. */
121
+ function checkPackage(dir, pkg, scope, rel, checked, skipped) {
122
+ const findings = [];
123
+ let unlayeredExtraction = false;
124
+ const configs = [];
125
+ const names = readdirSync(dir)
126
+ .filter((entry) => CONFIG_FILE.test(entry))
127
+ .sort();
128
+ // A config may keep its StyleX options in a module it imports
129
+ // (`vite.config.ts` → `./vite-stylex.ts`). Read those too, one level deep,
130
+ // or moving the options out of the config silently blinds every check below.
131
+ for (const name of [...names]) {
132
+ const source = readText(join(dir, name));
133
+ if (source === null)
134
+ continue;
135
+ for (const imported of relativeImports(dir, source)) {
136
+ if (!names.includes(imported))
137
+ names.push(imported);
138
+ }
139
+ }
140
+ for (const name of names) {
141
+ const source = readText(join(dir, name));
142
+ if (source === null)
143
+ continue;
144
+ const file = rel(join(dir, name));
145
+ checked.push(file);
146
+ configs.push({ file, source });
147
+ findings.push(...checkRuntimeInjection(file, source, scope));
148
+ const extraction = checkExtraction(file, source, scope);
149
+ if (extraction) {
150
+ unlayeredExtraction = true;
151
+ findings.push(extraction);
152
+ }
153
+ }
154
+ const tokens = checkTokensCompiled(dir, configs, rel, scope);
155
+ if (tokens)
156
+ findings.push(tokens);
157
+ const media = checkMediaVar(dir, names, rel, scope);
158
+ findings.push(...media.findings);
159
+ if (media.skipped) {
160
+ skipped.push(`${rel(dir) === '.' ? '' : `${rel(dir)}: `}media-var (no fresh build)`);
161
+ }
162
+ else {
163
+ checked.push(...media.checked);
164
+ }
165
+ const entry = ENTRIES.map((path) => join(dir, path)).find((path) => existsSync(path));
166
+ if (entry !== undefined) {
167
+ checked.push(rel(entry));
168
+ findings.push(...checkStylesheets(dir, entry, rel, checked, unlayeredExtraction, scope));
169
+ }
170
+ else if (!isLibrary(pkg)) {
171
+ // A library (it publishes main/exports) has no entry by design: its
172
+ // consumers load the stylesheet, and doctor checks them.
173
+ findings.push({
174
+ rule: 'css-imported',
175
+ severity: 'warn',
176
+ file: rel(dir),
177
+ message: `No app entry found (looked for ${ENTRIES.join(', ')}), so the stylesheet wiring was not checked.`,
178
+ fix: `Import '${dsCss(scope)}' in the module that renders the app.`,
179
+ });
180
+ }
181
+ const skew = uiVersionSkew(dir, [scope]);
182
+ if (skew) {
183
+ findings.push({
184
+ rule: 'version-skew',
185
+ severity: 'warn',
186
+ file: rel(join(dir, 'package.json')),
187
+ message: `${skew.ui} is ${skew.installed}, but this CLI documents and checks ${skew.own}.`,
188
+ fix: `npx -y ${skew.cli}@${skew.installed} doctor, or upgrade ${skew.ui}.`,
189
+ });
190
+ }
191
+ findings.push(...checkLegacyNames(dir, scope, rel));
192
+ return findings;
193
+ }
194
+ /**
195
+ * The packages under `root` that depend on @greenharness/greenrack-ui. The hook runs at
196
+ * the repo root, which in a workspace (or an app kept in web/) is not the
197
+ * package that renders anything: follow the workspace globs, and without
198
+ * any, look one directory down.
199
+ */
200
+ function consumerPackages(root) {
201
+ const rootPkg = readPackage(root);
202
+ const dirs = [root];
203
+ const patterns = workspacePatterns(root, rootPkg);
204
+ for (const pattern of patterns)
205
+ dirs.push(...expandWorkspace(root, pattern));
206
+ if (patterns.length === 0 && !(rootPkg && scopeOf(rootPkg))) {
207
+ dirs.push(...childDirs(root));
208
+ }
209
+ const out = [];
210
+ for (const dir of new Set(dirs)) {
211
+ const pkg = readPackage(dir);
212
+ const scope = pkg ? scopeOf(pkg) : null;
213
+ if (pkg && scope)
214
+ out.push({ dir, pkg, scope });
215
+ }
216
+ return out;
217
+ }
218
+ function readPackage(dir) {
219
+ const raw = readText(join(dir, 'package.json'));
220
+ return raw === null ? null : parsePackage(raw);
221
+ }
222
+ /** npm/yarn `workspaces` and pnpm-workspace.yaml `packages`, negations dropped. */
223
+ function workspacePatterns(root, pkg) {
224
+ const field = pkg?.workspaces;
225
+ const fromPkg = Array.isArray(field)
226
+ ? field
227
+ : Array.isArray(field?.packages)
228
+ ? field.packages
229
+ : [];
230
+ const yaml = readText(join(root, 'pnpm-workspace.yaml')) ?? '';
231
+ const block = /^packages:\s*\n((?:[ \t]+-.*\n?|[ \t]*#.*\n?|[ \t]*\n)*)/m.exec(yaml)?.[1] ?? '';
232
+ const fromYaml = [...block.matchAll(/^[ \t]+-\s*['"]?([^'"#\n]+?)['"]?\s*(?:#.*)?$/gm)].map((match) => match[1]);
233
+ return [...fromPkg, ...fromYaml].filter((pattern) => typeof pattern === 'string' && !pattern.startsWith('!'));
234
+ }
235
+ /** `apps/*` and `apps/**` list apps' subdirectories; anything else is a path. */
236
+ function expandWorkspace(root, pattern) {
237
+ const glob = /^(.*?)\/\*\*?$/.exec(pattern.replace(/\/$/, ''));
238
+ return glob ? childDirs(join(root, glob[1])) : [join(root, pattern)];
239
+ }
240
+ function childDirs(dir) {
241
+ try {
242
+ return readdirSync(dir, { withFileTypes: true })
243
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules')
244
+ .map((entry) => join(dir, entry.name))
245
+ .sort();
246
+ }
247
+ catch {
248
+ return [];
249
+ }
250
+ }
251
+ /** Source modules a config can import by a relative path. */
252
+ const MODULE_EXT = ['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'];
253
+ const RELATIVE_IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*)(['"])(\.\/[^'"\n]+)\1/g;
254
+ /**
255
+ * Files in `dir` that a config imports by `./relative` path: the modules a
256
+ * split config keeps its build options in. Siblings only — a config that
257
+ * reaches into `../` or a subdirectory is importing app code, not options.
258
+ */
259
+ function relativeImports(dir, source) {
260
+ const found = [];
261
+ for (const match of maskComments(source, { line: true }).matchAll(RELATIVE_IMPORT)) {
262
+ const spec = match[2].slice(2);
263
+ if (spec.includes('/'))
264
+ continue;
265
+ const candidates = MODULE_EXT.some((ext) => spec.endsWith(ext))
266
+ ? [spec, ...MODULE_EXT.map((ext) => spec.replace(/\.[cm]?js$/, ext))]
267
+ : MODULE_EXT.map((ext) => spec + ext);
268
+ const hit = candidates.find((name) => existsSync(join(dir, name)));
269
+ if (hit && !/\.(?:test|spec|d)\./.test(hit) && !found.includes(hit))
270
+ found.push(hit);
271
+ }
272
+ return found;
273
+ }
274
+ function readText(path) {
275
+ try {
276
+ return readFileSync(path, 'utf8');
277
+ }
278
+ catch {
279
+ return null;
280
+ }
281
+ }
282
+ function parsePackage(raw) {
283
+ try {
284
+ return JSON.parse(raw);
285
+ }
286
+ catch {
287
+ return {};
288
+ }
289
+ }
290
+ /** The scope whose UI package the package depends on, or null when it uses neither. */
291
+ function scopeOf(pkg) {
292
+ return (SCOPES.find((scope) => ['dependencies', 'devDependencies', 'peerDependencies'].some((field) => pkg[field]?.[scope.ui] !== undefined)) ?? null);
293
+ }
294
+ function isLibrary(pkg) {
295
+ return pkg.exports !== undefined || pkg.main !== undefined || pkg.module !== undefined;
296
+ }
297
+ /**
298
+ * The installed UI package's version when it differs from this CLI's: the
299
+ * given scope's, or either scope's when none is given. The package's exports
300
+ * map does not expose ./package.json, so require() cannot read it: walk up
301
+ * node_modules the way resolution does and read the file. A workspace link
302
+ * (the design system's own checkout) resolves outside any node_modules: its
303
+ * version is the source's, with no release to skew against.
304
+ */
305
+ export function uiVersionSkew(cwd, scopes) {
306
+ const own = cliVersion();
307
+ for (let dir = resolve(cwd);; dir = dirname(dir)) {
308
+ for (const { ui, cli } of scopes) {
309
+ const manifest = join(dir, 'node_modules', ...ui.split('/'), 'package.json');
310
+ if (!existsSync(manifest))
311
+ continue;
312
+ try {
313
+ if (!realpathSync(manifest).includes(`${sep}node_modules${sep}`))
314
+ return null;
315
+ const installed = JSON.parse(readFileSync(manifest, 'utf8')).version;
316
+ return installed && own !== '0.0.0' && installed !== own ? { own, installed, ui, cli } : null;
317
+ }
318
+ catch {
319
+ return null;
320
+ }
321
+ }
322
+ if (dirname(dir) === dir)
323
+ return null;
324
+ }
325
+ }
326
+ function checkRuntimeInjection(file, source, scope) {
327
+ const masked = maskComments(source, { line: true });
328
+ const out = [];
329
+ const name = basename(file);
330
+ for (const match of masked.matchAll(/\bruntimeInjection\s*:\s*([^,}\n]+)/g)) {
331
+ const value = match[1].trim();
332
+ if (/^false\b/.test(value))
333
+ continue;
334
+ const literal = /^(?:true\b|['"`])/.test(value);
335
+ // Test runners render into jsdom, where nothing is laid out: injection
336
+ // there changes no pixel anyone sees, but it is one copy-paste from the
337
+ // app config, so it is still worth a warning.
338
+ const testOnly = name.startsWith('vitest.');
339
+ out.push({
340
+ rule: 'runtime-injection',
341
+ severity: literal && !testOnly ? 'error' : 'warn',
342
+ file,
343
+ line: lineOf(source, match.index),
344
+ message: `${literal
345
+ ? `runtimeInjection: ${value}`
346
+ : `runtimeInjection is computed (${value}), and may be on`}${testOnly ? ' (test config only)' : ''} — StyleX then injects react-strict-dom's element reset (padding: 0, margin: 0) into an unlayered <style> at import time. Unlayered rules beat every @layer rule, so it flattens the spacing of every ${scope.ui} component.`,
347
+ fix: `Set runtimeInjection: false and extract the rules at build time instead: react-strict-dom/postcss-plugin in postcss.config, plus a CSS file containing @react-strict-dom; imported after '${dsCss(scope)}'.`,
348
+ });
349
+ }
350
+ return out;
351
+ }
352
+ function checkExtraction(file, source, scope) {
353
+ if (!basename(file).startsWith('postcss.config'))
354
+ return null;
355
+ const masked = maskComments(source, { line: true });
356
+ const match = /\buseCSSLayers\s*:\s*false\b/.exec(masked);
357
+ if (!match)
358
+ return null;
359
+ return {
360
+ rule: 'layered-extraction',
361
+ severity: 'error',
362
+ file,
363
+ line: lineOf(source, match.index),
364
+ message: "useCSSLayers: false emits this app's StyleX rules unlayered — including react-strict-dom's element reset (padding: 0) — and unlayered rules beat the design system's layered component styles.",
365
+ fix: `Remove useCSSLayers (it defaults to true) so the extracted rules land in the same priority layers as ${scope.ui}.`,
366
+ };
367
+ }
368
+ /**
369
+ * A StyleX compiler referenced from build config. react-strict-dom's preset
370
+ * counts: it bundles @stylexjs/babel-plugin.
371
+ */
372
+ const STYLEX_COMPILER = /(['"])(?:@stylexjs\/(?:babel-plugin|unplugin|rollup-plugin)|vite-plugin-stylex|@stylex-extend\/[\w-]+|react-strict-dom\/babel-preset)(?:\/[\w./-]*)?\1/;
373
+ /** `noExternal: [...]`, `: true`, `: /re/` or `: 'pkg'`. */
374
+ const NO_EXTERNAL = /\bnoExternal\s*:\s*(?:\[[^\]]*\]|true\b|\/(?:\\.|[^/\n])+\/[a-z]*|(['"`])[^'"`\n]*\1)/g;
375
+ /** `noExternal: someList` — the list is declared elsewhere. */
376
+ const NO_EXTERNAL_IDENT = /\bnoExternal\s*:\s*([A-Za-z_$][\w$]*)\b(?!\s*[.([])/g;
377
+ /** The shorthand `{noExternal}` / `{…, noExternal, …}`: a binding named noExternal. */
378
+ const NO_EXTERNAL_SHORTHAND = /[{,]\s*(noExternal)\s*(?=[,}])/g;
379
+ /** A value a noExternal binding can hold that doctor can read. */
380
+ const LIST_VALUE = String.raw `(\[[^\]]*\]|true\b|false\b|\/(?:\\.|[^/\n])+\/[a-z]*|(['"\x60])[^'"\x60\n]*\3)`;
381
+ const NAMED_IMPORT = /\bimport\s*(?:type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\2/g;
382
+ function declarationOf(name, file, masked) {
383
+ const decl = new RegExp(String.raw `\b(?:const|let|var)\s+(${name.replace(/\$/g, '\\$')})\b[^=;\n]*=\s*` + LIST_VALUE);
384
+ const match = decl.exec(masked);
385
+ if (!match)
386
+ return null;
387
+ return { file, index: match.index, length: match[0].length, value: match[2] };
388
+ }
389
+ /**
390
+ * Resolve the binding a `noExternal` refers to: a const in the same config, or
391
+ * one a sibling module exports and the config imports by name.
392
+ */
393
+ function resolveList(name, config, dir, maskedOf) {
394
+ const local = declarationOf(name, config.file, config.masked);
395
+ if (local)
396
+ return local;
397
+ for (const match of config.masked.matchAll(NAMED_IMPORT)) {
398
+ const specifier = match[3];
399
+ if (!specifier.startsWith('./') && !specifier.startsWith('../'))
400
+ continue;
401
+ for (const part of match[1].split(',')) {
402
+ const [imported, as] = part
403
+ .trim()
404
+ .replace(/^type\s+/, '')
405
+ .split(/\s+as\s+/);
406
+ if ((as ?? imported)?.trim() !== name || !imported)
407
+ continue;
408
+ const base = join(dirname(config.file), specifier);
409
+ const candidates = MODULE_EXT.some((ext) => base.endsWith(ext))
410
+ ? [base, ...MODULE_EXT.map((ext) => base.replace(/\.[cm]?js$/, ext))]
411
+ : MODULE_EXT.map((ext) => base + ext);
412
+ for (const candidate of candidates) {
413
+ const masked = maskedOf(candidate);
414
+ if (masked === null)
415
+ continue;
416
+ return declarationOf(imported.trim(), candidate, masked);
417
+ }
418
+ return null;
419
+ }
420
+ }
421
+ return null;
422
+ }
423
+ const SSR_CONFIG = /\bssr\s*:|['"]@react-router\/dev\/vite['"]|['"]@remix-run\/dev['"]/;
424
+ const STYLEX_CREATE = /\b(?:css|stylex)\.create\s*\(/;
425
+ const STYLEX_ERROR = 'Could not resolve the path to the imported file. Please ensure the theme file has a .stylex.js or .stylex.ts extension';
426
+ /**
427
+ * `@greenharness/greenrack-tokens/tokens/*.css` resolves to the package's uncompiled
428
+ * `src/tokens/*.css.ts` (react-strict-dom `css.defineVars`), which only
429
+ * react-strict-dom's babel preset turns into StyleX theme variables. An app
430
+ * that compiles its own code with StyleX but routes nothing of
431
+ * @greenharness/greenrack-tokens through that preset cannot use the tokens in css.create.
432
+ *
433
+ * Conservative: any vite/babel config text naming @greenharness/greenrack-tokens outside
434
+ * `noExternal` counts as routing it. An error only with evidence — a source file that
435
+ * deep-imports the tokens and calls css.create, whose build fails today;
436
+ * otherwise a warning, since the design system's own rules tell the next
437
+ * edit to write exactly that import.
438
+ */
439
+ function checkTokensCompiled(dir, configs, rel, scope) {
440
+ const tokensMention = packageMention(scope.tokens);
441
+ // The bundle's build only: vitest runs its own transform, and a postcss
442
+ // extraction `include` that names the tokens (duro-app's does) collects
443
+ // their rules without compiling the module the bundle imports.
444
+ const build = configs.filter(({ file }) => !/^(?:vitest|postcss)\./.test(basename(file)));
445
+ // Comment-masked text per config; `outside` is the same with every
446
+ // noExternal list (inline or declared) blanked, so naming the tokens in a
447
+ // list never counts as routing them through Babel.
448
+ const masked = new Map(build.map(({ file, source }) => [file, maskComments(source, { line: true })]));
449
+ const outside = new Map(masked);
450
+ const blankOut = (file, index, length) => {
451
+ const text = outside.get(file);
452
+ if (text === undefined)
453
+ return;
454
+ outside.set(file, text.slice(0, index) + ' '.repeat(length) + text.slice(index + length));
455
+ };
456
+ const maskedOf = (file) => {
457
+ const known = masked.get(file);
458
+ if (known !== undefined)
459
+ return known;
460
+ // `file` is relative to the checked root, like every config's name.
461
+ const source = readText(join(dir, relative(rel(dir), file)));
462
+ return source === null ? null : maskComments(source, { line: true });
463
+ };
464
+ const listsTokens = (value) => value === 'true' || tokensMention.test(value);
465
+ let stylex = null;
466
+ let ssr = false;
467
+ let ssrExternal = false;
468
+ const unresolved = [];
469
+ for (const { file, source } of build) {
470
+ const text = masked.get(file);
471
+ for (const list of text.matchAll(NO_EXTERNAL)) {
472
+ if (listsTokens(list[0].replace(/^\bnoExternal\s*:\s*/, '')))
473
+ ssrExternal = true;
474
+ blankOut(file, list.index, list[0].length);
475
+ }
476
+ // `import {noExternal} from …` is a binding, not a use of one.
477
+ const uses = text.replace(NAMED_IMPORT, (statement) => ' '.repeat(statement.length));
478
+ const refs = [
479
+ ...[...uses.matchAll(NO_EXTERNAL_IDENT)].map((m) => ({ name: m[1], index: m.index })),
480
+ ...[...uses.matchAll(NO_EXTERNAL_SHORTHAND)].map((m) => ({ name: m[1], index: m.index })),
481
+ ].filter(({ name }) => !['true', 'false', 'undefined', 'null'].includes(name));
482
+ for (const { name, index } of refs) {
483
+ const declared = resolveList(name, { file, masked: text }, dir, maskedOf);
484
+ if (!declared) {
485
+ unresolved.push({ name, file, line: lineOf(source, index) });
486
+ continue;
487
+ }
488
+ if (listsTokens(declared.value))
489
+ ssrExternal = true;
490
+ blankOut(declared.file, declared.index, declared.length);
491
+ }
492
+ if (/^vite\./.test(basename(file)) && SSR_CONFIG.test(text))
493
+ ssr = true;
494
+ const compiler = STYLEX_COMPILER.exec(text);
495
+ if (compiler && !stylex)
496
+ stylex = { file, line: lineOf(source, compiler.index) };
497
+ }
498
+ if (!stylex)
499
+ return null;
500
+ const routed = [...outside.values()].some((text) => tokensMention.test(text));
501
+ const ssrGap = ssr && !ssrExternal;
502
+ if (routed && !ssrGap)
503
+ return null;
504
+ // The only gap is SSR inlining, and a list doctor could not read may close
505
+ // it: say what could not be verified instead of failing.
506
+ const opaque = unresolved[0];
507
+ if (routed && opaque) {
508
+ return {
509
+ rule: 'tokens-compiled',
510
+ severity: 'warn',
511
+ file: opaque.file,
512
+ line: opaque.line,
513
+ message: `ssr.noExternal is \`${opaque.name}\` in ${opaque.file}:${opaque.line}, which doctor cannot resolve to a list, so it cannot verify that SSR inlines ${scope.tokens} (without it, css.defineVars throws at runtime).`,
514
+ fix: `Make sure '${scope.tokens}' is in \`${opaque.name}\`, or declare noExternal inline in ${opaque.file}.`,
515
+ };
516
+ }
517
+ const evidence = tokensInCreate(dir, scope);
518
+ const where = evidence ? `${rel(evidence.path)}:${evidence.line}` : null;
519
+ const cause = routed
520
+ ? `${stylex.file} routes ${scope.tokens} through Babel, but this app renders on the server and ssr.noExternal does not list it: SSR loads the tokens from node_modules as native ESM, bypassing that rule, and css.defineVars throws at runtime.`
521
+ : `${stylex.file} compiles the app with StyleX, but nothing compiles ${scope.tokens}' sources: ${scope.tokens}/tokens/*.css resolves to uncompiled src/tokens/*.css.ts (react-strict-dom css.defineVars), which only react-strict-dom/babel-preset turns into StyleX theme variables. css.create then cannot import them — StyleX fails with "${STYLEX_ERROR}".`;
522
+ return {
523
+ rule: 'tokens-compiled',
524
+ severity: evidence ? 'error' : 'warn',
525
+ file: stylex.file,
526
+ line: stylex.line,
527
+ message: `${cause} ${where
528
+ ? `${where} imports one into css.create.`
529
+ : 'Latent until a file imports a token into css.create — the import the design system prescribes; the barrel import apps fall back on is forbidden.'}`,
530
+ fix: routed
531
+ ? `Add '${scope.tokens}' (with 'react-strict-dom') to ssr.noExternal in ${stylex.file}.`
532
+ : `Compile node_modules/${scope.tokens} with react-strict-dom/babel-preset, as duro-app's vite.config.ts does — babel({filter: /node_modules\\/${scope.tokens.split('/').join('\\/')}\\/.*\\.[jt]sx?$/, babelConfig: {presets: ['@babel/preset-typescript', ['react-strict-dom/babel-preset', {platform: 'web', rootDir: process.cwd()}]]}}) from vite-plugin-babel, ahead of the app's StyleX pass — and add '${scope.tokens}' to ssr.noExternal if the app renders on the server.`,
533
+ };
534
+ }
535
+ /** Sources under app/ and src/ scanned for tokens evidence, at most. */
536
+ const SOURCE_SCAN_LIMIT = 5000;
537
+ /** The first app source that deep-imports @greenharness/greenrack-tokens and calls css.create. */
538
+ function tokensInCreate(dir, scope) {
539
+ const deepImport = tokensDeepImport(scope);
540
+ const stack = ['src', 'app'].map((name) => join(dir, name));
541
+ let budget = SOURCE_SCAN_LIMIT;
542
+ while (stack.length > 0 && budget > 0) {
543
+ const current = stack.pop();
544
+ let entries;
545
+ try {
546
+ entries = readdirSync(current, { withFileTypes: true });
547
+ }
548
+ catch {
549
+ continue;
550
+ }
551
+ const dirs = [];
552
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
553
+ if (entry.name.startsWith('.') || entry.name === 'node_modules')
554
+ continue;
555
+ const path = join(current, entry.name);
556
+ if (entry.isDirectory()) {
557
+ dirs.push(path);
558
+ continue;
559
+ }
560
+ if (!/\.[cm]?[jt]sx?$/.test(entry.name) || /\.native\./.test(entry.name))
561
+ continue;
562
+ if (--budget < 0)
563
+ break;
564
+ const source = readText(path);
565
+ if (source === null)
566
+ continue;
567
+ const masked = maskComments(source, { line: true });
568
+ const deep = deepImport.exec(masked);
569
+ if (deep && STYLEX_CREATE.test(masked))
570
+ return { path, line: lineOf(source, deep.index) };
571
+ }
572
+ // Depth-first, alphabetical: the first match is stable across runs.
573
+ stack.push(...dirs.reverse());
574
+ }
575
+ return null;
576
+ }
577
+ /** Build output directories `media-var` reads. */
578
+ const BUILD_DIRS = ['build', 'dist'];
579
+ /** An `@media` prelude, up to its block. */
580
+ const MEDIA_RULE = /@media\b([^{;]*)\{/g;
581
+ /** Text cut to about `max` characters, for one-line minified CSS. */
582
+ const clip = (text, max = 80) => text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
583
+ const errorCode = (error) => error?.code ?? 'unknown';
584
+ /**
585
+ * `statSync(path).mtimeMs`, or null when the path is gone (ENOENT: it
586
+ * vanished between listing and stat). Any other failure is recorded in
587
+ * `unreadable` and also returns null.
588
+ */
589
+ function mtimeOf(path, unreadable) {
590
+ try {
591
+ return statSync(path).mtimeMs;
592
+ }
593
+ catch (error) {
594
+ if (errorCode(error) !== 'ENOENT')
595
+ unreadable.push({ path, code: errorCode(error) });
596
+ return null;
597
+ }
598
+ }
599
+ /**
600
+ * The newest modification time among the package's build config and its
601
+ * sources (app/, src/), scanned up to SOURCE_SCAN_LIMIT files.
602
+ */
603
+ function newestInput(dir, configs, unreadable) {
604
+ let newest = 0;
605
+ const seen = (path) => {
606
+ const mtime = mtimeOf(path, unreadable);
607
+ if (mtime !== null)
608
+ newest = Math.max(newest, mtime);
609
+ };
610
+ for (const name of [...configs, 'package.json'])
611
+ seen(join(dir, name));
612
+ walkFiles(['src', 'app'].map((name) => join(dir, name)), (name) => /\.[cm]?[jt]sx?$|\.css$/.test(name), seen, unreadable);
613
+ return newest;
614
+ }
615
+ /**
616
+ * Depth-first over `roots`, calling `visit` on each matching file, capped. A
617
+ * root that does not exist (ENOENT) or is not a directory (ENOTDIR) is
618
+ * skipped; a directory that cannot be read for any other reason is recorded
619
+ * in `unreadable`.
620
+ */
621
+ function walkFiles(roots, matches, visit, unreadable) {
622
+ const stack = [...roots].reverse();
623
+ let budget = SOURCE_SCAN_LIMIT;
624
+ while (stack.length > 0 && budget > 0) {
625
+ const current = stack.pop();
626
+ let entries;
627
+ try {
628
+ entries = readdirSync(current, { withFileTypes: true });
629
+ }
630
+ catch (error) {
631
+ const code = errorCode(error);
632
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
633
+ unreadable.push({ path: current, code });
634
+ continue;
635
+ }
636
+ const dirs = [];
637
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
638
+ if (entry.name.startsWith('.') || entry.name === 'node_modules')
639
+ continue;
640
+ const path = join(current, entry.name);
641
+ if (entry.isDirectory())
642
+ dirs.push(path);
643
+ else if (matches(entry.name)) {
644
+ if (--budget < 0)
645
+ return;
646
+ visit(path);
647
+ }
648
+ }
649
+ stack.push(...dirs.reverse());
650
+ }
651
+ }
652
+ /**
653
+ * A media query cannot read a custom property: `@media (max-width:
654
+ * var(--x))` never matches, so the rules inside never apply. It happens when
655
+ * `@greenharness/greenrack-tokens/tokens/breakpoints.css.ts` reaches the CSS without the
656
+ * StyleX/RSD compile that turns its consts into px. Reads built CSS only, and
657
+ * only output newer than every config and source file: stale output says
658
+ * nothing about the code as it is. `skipped` when there is no fresh build;
659
+ * a path it could not read is a warning, never silently left out.
660
+ */
661
+ function checkMediaVar(dir, configs, rel, scope) {
662
+ const unreadable = [];
663
+ const newest = newestInput(dir, configs, unreadable);
664
+ const fresh = [];
665
+ walkFiles(BUILD_DIRS.map((name) => join(dir, name)), (name) => name.endsWith('.css'), (path) => {
666
+ const mtime = mtimeOf(path, unreadable);
667
+ if (mtime !== null && mtime > newest)
668
+ fresh.push(path);
669
+ }, unreadable);
670
+ // What could not be read is said, not silently left out of the check.
671
+ const findings = unreadable.map(({ path, code }) => ({
672
+ rule: 'media-var',
673
+ severity: 'warn',
674
+ file: rel(path),
675
+ message: `${rel(path)} could not be read (${code}), so media-var did not check it or what it holds.`,
676
+ fix: `Make ${rel(path)} readable by the user running doctor, or remove it.`,
677
+ }));
678
+ if (fresh.length === 0)
679
+ return { checked: [], findings, skipped: true };
680
+ for (const path of fresh) {
681
+ const source = readText(path);
682
+ if (source === null)
683
+ continue;
684
+ const css = maskComments(source, { line: false });
685
+ const broken = [...css.matchAll(MEDIA_RULE)].filter((m) => m[1].includes('var(--'));
686
+ const first = broken[0];
687
+ if (!first)
688
+ continue;
689
+ const query = clip(`@media${first[1].replace(/\s+/g, ' ').trimEnd()}`);
690
+ const more = broken.length > 1 ? ` (and ${broken.length - 1} more)` : '';
691
+ findings.push({
692
+ rule: 'media-var',
693
+ severity: 'error',
694
+ file: rel(path),
695
+ line: lineOf(source, first.index),
696
+ message: `${query}${more} compares against a CSS variable, which a media query cannot read: it never matches, so the rules inside never apply.`,
697
+ fix: `compile \`${scope.tokens}/tokens/breakpoints.css.ts\` through the StyleX/RSD babel step, rebuild, re-run \`npx -y ${scope.cli} doctor\``,
698
+ });
699
+ }
700
+ return { checked: fresh.map(rel), findings, skipped: false };
701
+ }
702
+ function checkStylesheets(root, entry, rel, checked, unlayeredExtraction, scope) {
703
+ const walk = {
704
+ root,
705
+ rel,
706
+ checked,
707
+ unlayeredExtraction,
708
+ layers: new Map(),
709
+ findings: [],
710
+ seen: new Set(),
711
+ dsImported: false,
712
+ scope,
713
+ sheets: dsSheets(scope),
714
+ };
715
+ const source = readText(entry) ?? '';
716
+ for (const imp of cssImports(source)) {
717
+ visit(walk, imp.specifier, dirname(entry), { file: rel(entry), line: imp.line }, false);
718
+ }
719
+ if (!walk.dsImported) {
720
+ walk.findings.unshift({
721
+ rule: 'css-imported',
722
+ severity: 'error',
723
+ file: rel(entry),
724
+ message: `${rel(entry)} never imports '${dsCss(scope)}'. ${scope.ui}'s JavaScript does not load its stylesheet, so every component renders unstyled.`,
725
+ fix: `Add import '${dsCss(scope)}' to ${rel(entry)}, before the app's own CSS.`,
726
+ });
727
+ return walk.findings;
728
+ }
729
+ const order = [...walk.layers.keys()];
730
+ const reset = order.indexOf('reset');
731
+ const firstPriority = order.findIndex((name) => PRIORITIES.includes(name));
732
+ if (reset > firstPriority && firstPriority >= 0) {
733
+ const origin = walk.layers.get(order[firstPriority]);
734
+ walk.findings.unshift({
735
+ rule: 'css-load-order',
736
+ severity: 'error',
737
+ file: origin.file,
738
+ line: origin.line,
739
+ message: `${origin.file} declares StyleX's priority layers before 'reset'. The first declaration fixes layer order for the whole page, so the design system's reset (* { padding: 0; margin: 0 }) now outranks every component style.`,
740
+ fix: `Import '${dsCss(scope)}' before ${origin.file}, or start ${origin.file} with ${LAYER_STATEMENT}`,
741
+ });
742
+ }
743
+ return walk.findings;
744
+ }
745
+ /** Stylesheet imports of a JS/TS module, in source order. */
746
+ function cssImports(source) {
747
+ const masked = maskComments(source, { line: true });
748
+ const out = [];
749
+ for (const match of masked.matchAll(/^[ \t]*import\s+(?:([\w$*{}\s,]+?)\s+from\s+)?(['"])([^'"\n]+)\2/gm)) {
750
+ const [, clause, , specifier] = match;
751
+ if (!/\.css(?:\?[\w&=-]*)?$/.test(specifier))
752
+ continue;
753
+ // `import {spacing} from '@greenharness/greenrack-tokens/tokens/spacing.css'` is a
754
+ // .css.ts module, not a stylesheet — only side-effect and ?url imports
755
+ // put CSS on the page.
756
+ if (clause !== undefined && !specifier.includes('?'))
757
+ continue;
758
+ out.push({ specifier: specifier.replace(/\?.*$/, ''), line: lineOf(source, match.index) });
759
+ }
760
+ return out;
761
+ }
762
+ function resolveSheet(walk, specifier, fromDir) {
763
+ const candidates = specifier.startsWith('.')
764
+ ? [resolve(fromDir, specifier)]
765
+ : specifier.startsWith('~/')
766
+ ? ['app', 'src'].map((dir) => join(walk.root, dir, specifier.slice(2)))
767
+ : specifier.startsWith('/')
768
+ ? [join(walk.root, specifier)]
769
+ : [];
770
+ return candidates.find((path) => existsSync(path)) ?? null;
771
+ }
772
+ function declare(walk, names, origin) {
773
+ for (const name of names)
774
+ if (!walk.layers.has(name))
775
+ walk.layers.set(name, origin);
776
+ }
777
+ /** One stylesheet import: record the layers it declares and scan app CSS. */
778
+ function visit(walk, specifier, fromDir, origin, layered) {
779
+ const ds = walk.sheets[specifier];
780
+ if (ds) {
781
+ if (specifier === dsCss(walk.scope))
782
+ walk.dsImported = true;
783
+ if (!layered)
784
+ declare(walk, ds, { file: specifier, line: 0 });
785
+ return;
786
+ }
787
+ const path = resolveSheet(walk, specifier, fromDir);
788
+ if (path === null || walk.seen.has(path))
789
+ return;
790
+ walk.seen.add(path);
791
+ const file = walk.rel(path);
792
+ walk.checked.push(file);
793
+ scanSheet(walk, path, file, layered);
794
+ }
795
+ /**
796
+ * Walks a stylesheet's blocks in order: top-level layer declarations
797
+ * (statements, blocks, `@react-strict-dom;`, `@import … layer()`), and zero
798
+ * spacing on component elements outside any layer.
799
+ */
800
+ function scanSheet(walk, path, file, layered) {
801
+ const source = readText(path) ?? '';
802
+ const css = maskComments(source, { line: false });
803
+ const stack = [];
804
+ const insideLayer = () => layered || stack.some((block) => block.kind === 'layer');
805
+ let pos = 0;
806
+ for (const boundary of css.matchAll(/[{};]/g)) {
807
+ const at = boundary.index;
808
+ const prelude = css.slice(pos, at).trim();
809
+ const preludeAt = at - css.slice(pos, at).trimStart().length;
810
+ pos = at + 1;
811
+ const origin = { file, line: lineOf(source, preludeAt) };
812
+ const topLevel = !insideLayer() && stack.every((block) => block.kind !== 'rule');
813
+ if (boundary[0] === '{') {
814
+ if (prelude.startsWith('@layer')) {
815
+ const name = prelude.slice('@layer'.length).trim();
816
+ if (topLevel && name)
817
+ declare(walk, [name], origin);
818
+ stack.push({ kind: 'layer' });
819
+ }
820
+ else if (prelude.startsWith('@')) {
821
+ stack.push({ kind: 'at' });
822
+ }
823
+ else {
824
+ stack.push({ kind: 'rule', selector: prelude, body: at + 1 });
825
+ }
826
+ }
827
+ else if (boundary[0] === '}') {
828
+ const block = stack.pop();
829
+ if (block?.kind === 'rule' && !insideLayer()) {
830
+ const body = css.slice(block.body, at);
831
+ const selector = block.selector ?? '';
832
+ if (targetsComponents(selector)) {
833
+ for (const decl of body.matchAll(ZERO_SPACING)) {
834
+ walk.findings.push({
835
+ rule: 'unlayered-reset',
836
+ severity: 'warn',
837
+ file,
838
+ line: lineOf(source, (block.body ?? 0) + decl.index),
839
+ message: `'${selector.replace(/\s+/g, ' ')} { ${decl[1]}: 0 }' sits outside any @layer, so it beats the spacing ${walk.scope.ui} components set in their layers.`,
840
+ fix: `Wrap the rule in @layer reset { … } — the design system's reset layer, which component styles already outrank.`,
841
+ });
842
+ }
843
+ }
844
+ }
845
+ }
846
+ else if (topLevel) {
847
+ if (prelude.startsWith('@layer')) {
848
+ const names = prelude
849
+ .slice('@layer'.length)
850
+ .split(',')
851
+ .map((name) => name.trim())
852
+ .filter(Boolean);
853
+ declare(walk, names, origin);
854
+ }
855
+ else if (prelude === '@react-strict-dom') {
856
+ // Extracted with layers (the default), this directive expands to
857
+ // StyleX's priority layers; unlayered, layered-extraction reports it.
858
+ if (!walk.unlayeredExtraction)
859
+ declare(walk, PRIORITIES, origin);
860
+ }
861
+ else if (prelude.startsWith('@import')) {
862
+ const target = /@import\s+(?:url\(\s*)?(['"])([^'"]+)\1/.exec(prelude);
863
+ if (target) {
864
+ const layer = /\blayer\(\s*([\w.-]+)\s*\)/.exec(prelude);
865
+ if (layer)
866
+ declare(walk, [layer[1]], origin);
867
+ visit(walk, target[2], dirname(path), origin, layer !== null || /\blayer\b/.test(prelude));
868
+ }
869
+ }
870
+ }
871
+ }
872
+ }
873
+ /** Whether any selector in a list is `*` or a bare element the DS renders. */
874
+ function targetsComponents(selectorList) {
875
+ return selectorList.split(',').some((selector) => {
876
+ const bare = selector.trim().replace(/::?[\w-]+(?:\([^)]*\))?/g, '');
877
+ return bare === '*' || COMPONENT_ELEMENTS.has(bare);
878
+ });
879
+ }
880
+ /** What each kind of error does to the app, for the session block's first line. */
881
+ const CONSEQUENCE = {
882
+ 'runtime-injection': 'components render with their spacing flattened',
883
+ 'layered-extraction': 'components render with their spacing flattened',
884
+ 'css-imported': 'components render with their spacing flattened',
885
+ 'css-load-order': 'components render with their spacing flattened',
886
+ 'unlayered-reset': 'components render with their spacing flattened',
887
+ 'version-skew': 'the CLI checks a different version than the one installed',
888
+ 'tokens-compiled': 'css.create cannot use the design tokens',
889
+ 'media-var': 'breakpoint media queries never match',
890
+ 'legacy-names': 'the app still reads names the old scope published',
891
+ };
892
+ /** The old CSS names an app's own stylesheet may still carry, with the names that replace them. */
893
+ const LEGACY_CSS_NAME = new RegExp(`${escapeRegExp(LEGACY_SCOPE.cssVariablePrefix)}[\\w-]+|${escapeRegExp(LEGACY_SCOPE.dataAttributePrefix)}[\\w-]*|${escapeRegExp(LEGACY_SCOPE.proseLayer)}`, 'g');
894
+ function renamedCssName(name) {
895
+ const from = LEGACY_SCOPE;
896
+ const to = GREENRACK_SCOPE;
897
+ if (name.startsWith(from.cssVariablePrefix)) {
898
+ return `${to.cssVariablePrefix}${name.slice(from.cssVariablePrefix.length)}`;
899
+ }
900
+ if (name.startsWith(from.dataAttributePrefix)) {
901
+ return `${to.dataAttributePrefix}${name.slice(from.dataAttributePrefix.length)}`;
902
+ }
903
+ return to.proseLayer;
904
+ }
905
+ /** How many leftover names are reported one by one, before `… and N more`. */
906
+ const LEGACY_NAME_LIMIT = 10;
907
+ /**
908
+ * Old CSS names in the app's own stylesheets (the old variable prefix, data attribute prefix and
909
+ * prose layer), each with its new name: the first LEGACY_NAME_LIMIT, then
910
+ * one line counting the rest.
911
+ */
912
+ function checkLegacyNames(dir, scope, rel) {
913
+ const found = [];
914
+ walkFiles(['src', 'app'].map((name) => join(dir, name)), (name) => name.endsWith('.css'), (path) => {
915
+ const source = readText(path);
916
+ if (source === null)
917
+ return;
918
+ for (const match of maskComments(source, { line: false }).matchAll(LEGACY_CSS_NAME)) {
919
+ const renamed = renamedCssName(match[0]);
920
+ found.push({
921
+ rule: 'legacy-names',
922
+ severity: 'warn',
923
+ file: rel(path),
924
+ line: lineOf(source, match.index),
925
+ message: `${match[0]} is the old name; the new name is ${renamed}.`,
926
+ fix: `Rename ${match[0]} to ${renamed}.`,
927
+ });
928
+ }
929
+ }, []);
930
+ if (found.length === 0)
931
+ return found;
932
+ // On the old scope these names are still right: one line says what to do on the move.
933
+ if (scope.kind === 'legacy') {
934
+ return [
935
+ {
936
+ rule: 'legacy-names',
937
+ severity: 'warn',
938
+ file: rel(dir),
939
+ message: `${found.length} old CSS name(s) in the app's own stylesheets, right for ${scope.ui}.`,
940
+ fix: `Rename them (${LEGACY_SCOPE.cssVariablePrefix}* to ${GREENRACK_SCOPE.cssVariablePrefix}*) when the app moves to ${GREENRACK_SCOPE.ui}.`,
941
+ },
942
+ ];
943
+ }
944
+ if (found.length <= LEGACY_NAME_LIMIT)
945
+ return found;
946
+ return [
947
+ ...found.slice(0, LEGACY_NAME_LIMIT),
948
+ {
949
+ rule: 'legacy-names',
950
+ severity: 'warn',
951
+ file: rel(dir),
952
+ message: `… and ${found.length - LEGACY_NAME_LIMIT} more`,
953
+ fix: 'Rename them the same way.',
954
+ },
955
+ ];
956
+ }
957
+ function report(findings, checked, packages, scopes, session, skipped = []) {
958
+ const errors = findings.filter((finding) => finding.severity === 'error');
959
+ const warnings = findings.filter((finding) => finding.severity === 'warn');
960
+ const summary = { ok: errors.length === 0, findings, checked, skipped, packages, scopes };
961
+ const scopeNames = scopes.join(' + ');
962
+ const recheck = SCOPES.filter(({ ui }) => scopes.includes(ui)).map(({ cli }) => `npx -y ${cli} doctor`);
963
+ const where = (finding) => finding.line ? `${finding.file}:${finding.line}` : finding.file;
964
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
965
+ if (session) {
966
+ if (findings.length === 0)
967
+ return { text: '', data: summary };
968
+ const effects = [...new Set(errors.map((finding) => CONSEQUENCE[finding.rule]))];
969
+ return {
970
+ text: [
971
+ errors.length > 0
972
+ ? `GREENRACK DOCTOR — ${plural(errors.length, 'error')} in ${scopeNames}`
973
+ : `GREENRACK DOCTOR — ${plural(warnings.length, 'warning')} in ${scopeNames}`,
974
+ errors.length > 0
975
+ ? `This repo's setup: ${effects.join('; ')} until fixed. Fix before any styling work:`
976
+ : "Warnings about this repo's setup:",
977
+ ...findings.map((finding) => `- [${finding.severity}] ${finding.rule} at ${where(finding)}: ${finding.message} Fix: ${finding.fix}`),
978
+ `Re-check with: ${recheck.join(' or ')}`,
979
+ ].join('\n'),
980
+ data: summary,
981
+ };
982
+ }
983
+ const tail = [
984
+ ` checked: ${checked.join(', ')}`,
985
+ ...(skipped.length > 0 ? [` skipped: ${skipped.join(', ')}`] : []),
986
+ ];
987
+ if (findings.length === 0) {
988
+ return {
989
+ text: [`greenrack doctor — ${scopeNames}`, ' no problems found', ...tail].join('\n'),
990
+ data: summary,
991
+ };
992
+ }
993
+ return {
994
+ text: [
995
+ `greenrack doctor: ${errors.length} error(s), ${warnings.length} warning(s)`,
996
+ ` scope: ${scopeNames}`,
997
+ ...findings.flatMap((finding) => [
998
+ ` ${finding.severity.padEnd(5)} ${finding.rule.padEnd(18)} ${where(finding)}`,
999
+ ` ${finding.message}`,
1000
+ ` fix: ${finding.fix}`,
1001
+ ]),
1002
+ ...tail,
1003
+ ].join('\n'),
1004
+ data: summary,
1005
+ exitCode: errors.length > 0 ? 1 : undefined,
1006
+ };
1007
+ }
1008
+ //# sourceMappingURL=doctor.js.map