@marktiderman/genesis-cli 1.1.0 → 1.2.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/dist/vite.js ADDED
@@ -0,0 +1,1092 @@
1
+ import * as path3 from 'path';
2
+ import { spawnSync } from 'child_process';
3
+ import { existsSync, readFileSync, statSync, readdirSync } from 'fs';
4
+ import { createRequire } from 'module';
5
+ import { pathToFileURL } from 'url';
6
+
7
+ // src/vite.ts
8
+ var BUILD_GUARD_ENV = "GENESIS_DOCTOR_BUILDING";
9
+ function buildCommands(root, config) {
10
+ if (config.build) return config.build;
11
+ const pkgFile = path3.join(root, "package.json");
12
+ const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
13
+ const pm = packageManager(root);
14
+ return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
15
+ }
16
+ function packageManager(root) {
17
+ let dir = path3.resolve(root);
18
+ for (; ; ) {
19
+ if (existsSync(path3.join(dir, "pnpm-lock.yaml"))) return "pnpm";
20
+ if (existsSync(path3.join(dir, "bun.lock")) || existsSync(path3.join(dir, "bun.lockb"))) return "bun";
21
+ if (existsSync(path3.join(dir, "yarn.lock"))) return "yarn";
22
+ if (existsSync(path3.join(dir, "package-lock.json"))) return "npm";
23
+ const parent = path3.dirname(dir);
24
+ if (parent === dir) return "npm";
25
+ dir = parent;
26
+ }
27
+ }
28
+ function runBuild(root, commands, quiet) {
29
+ if (process.env[BUILD_GUARD_ENV]) return null;
30
+ if (commands.length === 0) {
31
+ return { rule: "build", level: "warn", file: "package.json", message: "--build found nothing to run: add typecheck/build scripts or doctor.build" };
32
+ }
33
+ for (const command of commands) {
34
+ const r = spawnSync(command, {
35
+ cwd: root,
36
+ shell: true,
37
+ stdio: quiet ? "pipe" : "inherit",
38
+ env: { ...process.env, [BUILD_GUARD_ENV]: "1" }
39
+ });
40
+ if (r.status !== 0) {
41
+ const tail = quiet ? `
42
+ ${String(r.stderr ?? "").trim().split("\n").slice(-20).join("\n")}` : "";
43
+ return { rule: "build", file: command, message: `\`${command}\` failed (exit ${r.status ?? r.signal})${tail}` };
44
+ }
45
+ }
46
+ return null;
47
+ }
48
+ var DoctorConfigError = class extends Error {
49
+ name = "DoctorConfigError";
50
+ };
51
+ var STRING_LISTS = ["src", "extensions", "ignore", "tokenFiles", "ignoreTokenPrefixes", "localPrimitiveDirs", "build"];
52
+ var STRINGS = ["uiPackage", "rulesDoc"];
53
+ var KNOWN = /* @__PURE__ */ new Set([
54
+ ...STRING_LISTS,
55
+ ...STRINGS,
56
+ "themeCss",
57
+ "rawTags",
58
+ "forbiddenImports",
59
+ "rules",
60
+ "allow",
61
+ "patterns",
62
+ "plugins",
63
+ "$schema",
64
+ "$comment"
65
+ ]);
66
+ var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "off"]);
67
+ var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
68
+ function loadConfig(root, configPath) {
69
+ if (configPath) {
70
+ const file = path3.resolve(root, configPath);
71
+ if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
72
+ const json = readJson(file);
73
+ const block = path3.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
74
+ return { config: validateConfig(block ?? {}, file), file, dir: path3.dirname(file) };
75
+ }
76
+ const own = path3.join(root, "genesis.config.json");
77
+ if (existsSync(own)) {
78
+ return { config: validateConfig(readJson(own)?.doctor ?? {}, own), file: own, dir: root };
79
+ }
80
+ const pkg = path3.join(root, "package.json");
81
+ if (existsSync(pkg)) {
82
+ const block = readJson(pkg)?.genesis?.doctor;
83
+ if (block !== void 0) return { config: validateConfig(block, pkg), file: pkg, dir: root };
84
+ }
85
+ return { config: {}, file: null, dir: root };
86
+ }
87
+ function readJson(file) {
88
+ try {
89
+ return JSON.parse(readFileSync(file, "utf8"));
90
+ } catch (err) {
91
+ throw new DoctorConfigError(`${file} is not valid JSON: ${err.message}`);
92
+ }
93
+ }
94
+ function validateConfig(raw, source = "config") {
95
+ const fail = (msg) => {
96
+ throw new DoctorConfigError(`${source}: ${msg}`);
97
+ };
98
+ if (!isObject(raw)) fail("the doctor settings must be an object");
99
+ const c = raw;
100
+ for (const key of Object.keys(c)) if (!KNOWN.has(key)) fail(`unknown setting "${key}"`);
101
+ if (typeof c.themeCss === "string") c.themeCss = [c.themeCss];
102
+ if (c.themeCss !== void 0 && !isStringList(c.themeCss)) fail(`"themeCss" must be a path or a list of paths`);
103
+ for (const key of STRING_LISTS) {
104
+ if (c[key] !== void 0 && !isStringList(c[key])) fail(`"${key}" must be a list of strings`);
105
+ }
106
+ for (const key of STRINGS) {
107
+ if (c[key] !== void 0 && typeof c[key] !== "string") fail(`"${key}" must be a string`);
108
+ }
109
+ if (c.rawTags !== void 0) {
110
+ if (!isObject(c.rawTags)) fail(`"rawTags" must be an object`);
111
+ for (const [tag, v] of Object.entries(c.rawTags)) {
112
+ if (!/^[a-z][a-z0-9-]*$/.test(tag)) fail(`rawTags: "${tag}" is not an HTML tag name`);
113
+ if (v !== false && typeof v !== "string") fail(`rawTags.${tag} must be a component name or false`);
114
+ }
115
+ }
116
+ if (c.forbiddenImports !== void 0) {
117
+ if (!isObject(c.forbiddenImports)) fail(`"forbiddenImports" must be an object of pattern \u2192 message`);
118
+ for (const [re, msg] of Object.entries(c.forbiddenImports)) {
119
+ if (typeof msg !== "string") fail(`forbiddenImports["${re}"] must be a message string`);
120
+ checkRegExp(re, `forbiddenImports["${re}"]`, fail);
121
+ }
122
+ }
123
+ if (c.rules !== void 0) {
124
+ if (!isObject(c.rules)) fail(`"rules" must be an object of rule \u2192 level`);
125
+ for (const [rule, level] of Object.entries(c.rules)) {
126
+ if (!LEVELS.has(level)) fail(`rules.${rule} must be "error", "warn" or "off"`);
127
+ }
128
+ }
129
+ if (c.allow !== void 0) {
130
+ if (!Array.isArray(c.allow)) fail(`"allow" must be a list`);
131
+ c.allow.forEach((e, i) => {
132
+ if (!isObject(e)) return fail(`allow[${i}] must be an object`);
133
+ const entry = e;
134
+ if (typeof entry.rule !== "string" || !entry.rule) fail(`allow[${i}] needs a "rule"`);
135
+ if (typeof entry.reason !== "string" || !entry.reason.trim()) fail(`allow[${i}] (${entry.rule}) needs a "reason"`);
136
+ for (const k of ["file", "match"]) {
137
+ if (entry[k] !== void 0 && typeof entry[k] !== "string") fail(`allow[${i}].${k} must be a string`);
138
+ }
139
+ });
140
+ }
141
+ if (c.patterns !== void 0) {
142
+ if (!Array.isArray(c.patterns)) fail(`"patterns" must be a list`);
143
+ c.patterns.forEach((p, i) => {
144
+ if (!isObject(p)) return fail(`patterns[${i}] must be an object`);
145
+ const rule = p;
146
+ for (const k of Object.keys(rule)) if (!PATTERN_KEYS.has(k)) fail(`patterns[${i}]: unknown key "${k}"`);
147
+ if (typeof rule.id !== "string" || !rule.id) fail(`patterns[${i}] needs an "id"`);
148
+ for (const k of ["files", "exclude"]) {
149
+ if (rule[k] !== void 0 && !isStringList(rule[k])) fail(`patterns[${i}].${k} must be a list of globs`);
150
+ }
151
+ });
152
+ }
153
+ if (c.plugins !== void 0) {
154
+ const ok = Array.isArray(c.plugins) && c.plugins.every((p) => typeof p === "string" || Array.isArray(p) && p.length === 2 && typeof p[0] === "string");
155
+ if (!ok) fail(`"plugins" must be a list of module paths or [path, options] pairs`);
156
+ }
157
+ return c;
158
+ }
159
+ function checkRegExp(source, where, fail) {
160
+ try {
161
+ new RegExp(source);
162
+ } catch (err) {
163
+ fail(`${where} is not a valid regular expression: ${err.message}`);
164
+ }
165
+ }
166
+ function isObject(v) {
167
+ return typeof v === "object" && v !== null && !Array.isArray(v);
168
+ }
169
+ function isStringList(v) {
170
+ return Array.isArray(v) && v.every((x) => typeof x === "string");
171
+ }
172
+
173
+ // src/doctor/glob.ts
174
+ function globToRegExp(glob) {
175
+ let g = glob.trim().replace(/^\.\//, "");
176
+ if (g.endsWith("/")) g += "**";
177
+ let out = "";
178
+ for (let i = 0; i < g.length; i++) {
179
+ const ch = g[i];
180
+ if (ch === "*") {
181
+ if (g[i + 1] === "*") {
182
+ const slash = g[i + 2] === "/";
183
+ out += slash ? "(?:.*/)?" : ".*";
184
+ i += slash ? 2 : 1;
185
+ } else {
186
+ out += "[^/]*";
187
+ }
188
+ } else if (ch === "?") {
189
+ out += "[^/]";
190
+ } else {
191
+ out += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
192
+ }
193
+ }
194
+ return new RegExp(`^${out}$`);
195
+ }
196
+ function globMatcher(globs) {
197
+ const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
198
+ return (path10) => res.some((re) => re.test(path10));
199
+ }
200
+ var DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
201
+ var DESIGN_SYSTEM_PACKAGE = "@marktiderman/genesis-design-system";
202
+ var TAGS = ["button", "input", "textarea", "select", "label", "table", "dialog", "progress", "details", "summary"];
203
+ var TAG_ALIASES = { hr: "Separator" };
204
+ var NON_COMPONENT_SUFFIX = /(Props|Variant|Variants|Type|Types|Config|Context|Options|Status)$/;
205
+ var TAILWIND_PALETTE = [
206
+ "black",
207
+ "white",
208
+ "slate",
209
+ "gray",
210
+ "zinc",
211
+ "neutral",
212
+ "stone",
213
+ "red",
214
+ "orange",
215
+ "amber",
216
+ "yellow",
217
+ "lime",
218
+ "green",
219
+ "emerald",
220
+ "teal",
221
+ "cyan",
222
+ "sky",
223
+ "blue",
224
+ "indigo",
225
+ "violet",
226
+ "purple",
227
+ "fuchsia",
228
+ "pink",
229
+ "rose",
230
+ "taupe",
231
+ "mauve",
232
+ "mist",
233
+ "olive"
234
+ ];
235
+ function findPackageDir(from, name) {
236
+ let dir = path3.resolve(from);
237
+ for (; ; ) {
238
+ const candidate = path3.join(dir, "node_modules", name);
239
+ if (existsSync(path3.join(candidate, "package.json"))) return candidate;
240
+ const parent = path3.dirname(dir);
241
+ if (parent === dir) return null;
242
+ dir = parent;
243
+ }
244
+ }
245
+ function loadGenesis(root, config) {
246
+ const uiPackage = config.uiPackage ?? DEFAULT_UI_PACKAGE;
247
+ const uiDir = findPackageDir(root, uiPackage);
248
+ if (!uiDir) throw new DoctorConfigError(`${uiPackage} is not installed here. Install it, or set doctor.uiPackage.`);
249
+ const uiPkg = JSON.parse(readFileSync(path3.join(uiDir, "package.json"), "utf8"));
250
+ const typeEntries = /* @__PURE__ */ new Set();
251
+ const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
252
+ if (typeof mainTypes === "string") typeEntries.add(mainTypes);
253
+ for (const target of Object.values(uiPkg.exports ?? {})) {
254
+ const t = exportTypes(target);
255
+ if (typeof t === "string" && !t.includes("*")) typeEntries.add(t);
256
+ }
257
+ const exportNames = /* @__PURE__ */ new Set();
258
+ const reexportedPackages = /* @__PURE__ */ new Set();
259
+ let readAny = false;
260
+ for (const entry of typeEntries) {
261
+ const file = path3.join(uiDir, entry);
262
+ if (!existsSync(file)) continue;
263
+ readAny = true;
264
+ const dts = readFileSync(file, "utf8");
265
+ for (const name of parseExportNames(dts)) exportNames.add(name);
266
+ for (const m of dts.matchAll(/export\s+(?:type\s+)?(?:\{[^}]*\}|\*)\s*from\s*["']([^"'.][^"']*)["']/g)) {
267
+ reexportedPackages.add(packageName(m[1]));
268
+ }
269
+ }
270
+ if (!readAny) {
271
+ throw new DoctorConfigError(`${uiPackage} has no type declarations to read (is it built?). Looked for: ${[...typeEntries].join(", ") || "none"}`);
272
+ }
273
+ const valueDecls = /* @__PURE__ */ new Set();
274
+ const typeDecls = /* @__PURE__ */ new Set();
275
+ const declRoot = typeof mainTypes === "string" ? path3.dirname(path3.join(uiDir, mainTypes)) : uiDir;
276
+ const declFiles = walkDts(declRoot);
277
+ for (const pkg of reexportedPackages) {
278
+ const dir = findPackageDir(uiDir, pkg);
279
+ if (dir) walkDts(path3.join(dir, "dist"), declFiles);
280
+ }
281
+ for (const file of declFiles) {
282
+ const text = readFileSync(file, "utf8");
283
+ for (const m of text.matchAll(/\b(?:declare\s+)?(?:const|let|var|function|class|enum)\s+([A-Za-z_$][\w$]*)/g)) valueDecls.add(m[1]);
284
+ for (const m of text.matchAll(/\b(?:interface|type)\s+([A-Za-z_$][\w$]*)/g)) typeDecls.add(m[1]);
285
+ }
286
+ const isTypeOnly = (n) => typeDecls.has(n) && !valueDecls.has(n);
287
+ const values = new Set([...exportNames].filter((n) => !isTypeOnly(n)));
288
+ const components = [...values].filter((n) => /^[A-Z][A-Za-z0-9]*$/.test(n) && !(n.length > 2 && n === n.toUpperCase()) && !NON_COMPONENT_SUFFIX.test(n)).sort();
289
+ const tokens = /* @__PURE__ */ new Set();
290
+ const themeFiles = resolveThemeFiles(root, config, uiDir);
291
+ for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
292
+ const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
293
+ const rawTags = /* @__PURE__ */ new Map();
294
+ for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
295
+ for (const [tag, comp] of Object.entries(TAG_ALIASES)) if (values.has(comp)) rawTags.set(tag, comp);
296
+ for (const [tag, comp] of Object.entries(config.rawTags ?? {})) {
297
+ if (comp === false) rawTags.delete(tag);
298
+ else rawTags.set(tag, comp);
299
+ }
300
+ return {
301
+ uiPackage,
302
+ uiVersion: String(uiPkg.version ?? "unknown"),
303
+ exports: exportNames,
304
+ values,
305
+ components,
306
+ tokens,
307
+ rawTags,
308
+ palette: loadPalette(root)
309
+ };
310
+ }
311
+ function parseExportNames(dts) {
312
+ const names = [];
313
+ for (const m of dts.matchAll(/export\s+(?:type\s+)?\{([^}]*)\}/g)) {
314
+ for (const part of m[1].split(",")) {
315
+ const name = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/).pop()?.trim();
316
+ if (name && name !== "default") names.push(name);
317
+ }
318
+ }
319
+ for (const m of dts.matchAll(/export\s+(?:declare\s+)?(?:const|let|function|class|enum|interface|type)\s+([A-Za-z_$][\w$]*)/g)) {
320
+ names.push(m[1]);
321
+ }
322
+ return names;
323
+ }
324
+ function declaredTokens(css) {
325
+ return [...css.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)].map((m) => m[1]);
326
+ }
327
+ function packageName(specifier) {
328
+ const parts = specifier.split("/");
329
+ return parts.slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
330
+ }
331
+ function exportTypes(target) {
332
+ if (!target || typeof target !== "object") return void 0;
333
+ const t = target;
334
+ if (typeof t.types === "string") return t.types;
335
+ for (const key of ["import", "default", "require"]) {
336
+ const nested = exportTypes(t[key]);
337
+ if (nested) return nested;
338
+ }
339
+ return void 0;
340
+ }
341
+ function walkDts(dir, out = []) {
342
+ if (!existsSync(dir)) return out;
343
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
344
+ if (entry.name === "node_modules") continue;
345
+ const p = path3.join(dir, entry.name);
346
+ if (entry.isDirectory()) walkDts(p, out);
347
+ else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
348
+ }
349
+ return out;
350
+ }
351
+ function resolveThemeFiles(root, config, uiDir) {
352
+ if (config.themeCss) {
353
+ const specs = typeof config.themeCss === "string" ? [config.themeCss] : config.themeCss;
354
+ return specs.map((spec) => {
355
+ const file = resolveSpec(root, spec);
356
+ if (!file) throw new DoctorConfigError(`doctor.themeCss: cannot find ${spec}`);
357
+ return file;
358
+ });
359
+ }
360
+ const files = [];
361
+ const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
362
+ const themes = ds && path3.join(ds, "dist", "themes");
363
+ if (themes && existsSync(themes)) {
364
+ for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path3.join(themes, name));
365
+ }
366
+ if (files.length === 0) {
367
+ throw new DoctorConfigError(
368
+ `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
369
+ );
370
+ }
371
+ const uiStyles = path3.join(uiDir, "dist", "styles.css");
372
+ if (existsSync(uiStyles)) files.push(uiStyles);
373
+ return files;
374
+ }
375
+ function resolveSpec(root, spec) {
376
+ const local = path3.resolve(root, spec);
377
+ if (spec.startsWith(".") || path3.isAbsolute(spec)) return existsSync(local) ? local : null;
378
+ const parts = spec.split("/");
379
+ const nameLength = spec.startsWith("@") ? 2 : 1;
380
+ const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
381
+ if (dir) {
382
+ const file = path3.join(dir, ...parts.slice(nameLength));
383
+ if (existsSync(file) && statSync(file).isFile()) return file;
384
+ }
385
+ return existsSync(local) ? local : null;
386
+ }
387
+ function loadPalette(root) {
388
+ const names = new Set(TAILWIND_PALETTE);
389
+ try {
390
+ const req = createRequire(path3.join(root, "package.json"));
391
+ const colors = req("tailwindcss/colors");
392
+ for (const key of Object.keys(colors?.default ?? colors ?? {})) {
393
+ if (/^[a-z]+$/.test(key) && !["inherit", "current", "transparent"].includes(key)) names.add(key);
394
+ }
395
+ } catch {
396
+ }
397
+ return [...names].sort();
398
+ }
399
+
400
+ // ../../scripts/lib/color-literals.mjs
401
+ var LINE_COMMENT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".jsx", ".js", ".mjs", ".cjs", ".scss", ".less"]);
402
+ var HTML_ENTITY_RE = /&#\d+;/g;
403
+ function stripBlockComments(content, hasLineComments = true) {
404
+ let result = "";
405
+ let i = 0;
406
+ const len = content.length;
407
+ while (i < len) {
408
+ const ch = content[i];
409
+ const next = i + 1 < len ? content[i + 1] : "";
410
+ const prevIsColon = i > 0 && content[i - 1] === ":";
411
+ const prevIsBackslash = i > 0 && content[i - 1] === "\\";
412
+ if (ch === '"') {
413
+ result += ch;
414
+ i++;
415
+ while (i < len) {
416
+ const c = content[i];
417
+ result += c;
418
+ if (c === "\\" && i + 1 < len) {
419
+ result += content[i + 1];
420
+ i += 2;
421
+ } else if (c === '"') {
422
+ i++;
423
+ break;
424
+ } else {
425
+ i++;
426
+ }
427
+ }
428
+ continue;
429
+ }
430
+ if (ch === "'") {
431
+ result += ch;
432
+ i++;
433
+ while (i < len) {
434
+ const c = content[i];
435
+ result += c;
436
+ if (c === "\\" && i + 1 < len) {
437
+ result += content[i + 1];
438
+ i += 2;
439
+ } else if (c === "'") {
440
+ i++;
441
+ break;
442
+ } else {
443
+ i++;
444
+ }
445
+ }
446
+ continue;
447
+ }
448
+ if (ch === "`") {
449
+ result += ch;
450
+ i++;
451
+ while (i < len) {
452
+ const c = content[i];
453
+ result += c;
454
+ if (c === "\\" && i + 1 < len) {
455
+ result += content[i + 1];
456
+ i += 2;
457
+ } else if (c === "`") {
458
+ i++;
459
+ break;
460
+ } else {
461
+ i++;
462
+ }
463
+ }
464
+ continue;
465
+ }
466
+ if ((ch === "u" || ch === "U") && content.slice(i, i + 4).toLowerCase() === "url(" && !/[\w$]/.test(content[i - 1] ?? "")) {
467
+ result += content.slice(i, i + 4);
468
+ i += 4;
469
+ while (i < len && content[i] !== ")") {
470
+ const c = content[i];
471
+ if (c === '"' || c === "'") {
472
+ result += c;
473
+ i++;
474
+ while (i < len) {
475
+ const q = content[i];
476
+ result += q;
477
+ if (q === "\\" && i + 1 < len) {
478
+ result += content[i + 1];
479
+ i += 2;
480
+ } else if (q === c) {
481
+ i++;
482
+ break;
483
+ } else {
484
+ i++;
485
+ }
486
+ }
487
+ } else {
488
+ result += c;
489
+ i++;
490
+ }
491
+ }
492
+ if (i < len && content[i] === ")") {
493
+ result += ")";
494
+ i++;
495
+ }
496
+ continue;
497
+ }
498
+ if (hasLineComments && ch === "/" && next === "/" && !prevIsColon && !prevIsBackslash) {
499
+ let j = i + 2;
500
+ while (j < len && content[j] !== "\n") {
501
+ j++;
502
+ }
503
+ const commentLen = j - i;
504
+ const commentText = content.slice(i, i + commentLen);
505
+ result += commentText.replace(/[^\n]/g, " ");
506
+ i += commentLen;
507
+ continue;
508
+ }
509
+ if (ch === "/" && next === "*") {
510
+ let commentLen = 2;
511
+ let j = i + 2;
512
+ while (j < len) {
513
+ if (content[j] === "*" && j + 1 < len && content[j + 1] === "/") {
514
+ commentLen = j + 2 - i;
515
+ break;
516
+ }
517
+ j++;
518
+ }
519
+ const commentText = content.slice(i, i + commentLen);
520
+ result += commentText.replace(/[^\n]/g, " ");
521
+ i += commentLen;
522
+ continue;
523
+ }
524
+ result += ch;
525
+ i++;
526
+ }
527
+ return result;
528
+ }
529
+ var HEX_RE = /(^|[^\w&])#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b/g;
530
+ var HEX_LETTER_RE = /[a-fA-F]/;
531
+ var COLOR_FN_RE = /\b(rgba?|hsla?)\(\s*[\d.][^)\n]*\)?/gi;
532
+ function stripHtmlEntities(line) {
533
+ return line.replace(HTML_ENTITY_RE, "");
534
+ }
535
+ function findHexLiterals(line) {
536
+ const cleaned = stripHtmlEntities(line);
537
+ const matches = [];
538
+ let m;
539
+ HEX_RE.lastIndex = 0;
540
+ while ((m = HEX_RE.exec(cleaned)) !== null) {
541
+ const digits = m[2];
542
+ if (digits.length <= 4 && !HEX_LETTER_RE.test(digits)) continue;
543
+ const literal = `#${digits}`;
544
+ const idx = m.index + m[1].length;
545
+ matches.push({ literal, column: idx + 1 });
546
+ }
547
+ return matches;
548
+ }
549
+ function findColorFunctions(line) {
550
+ const cleaned = stripHtmlEntities(line);
551
+ const matches = [];
552
+ let m;
553
+ COLOR_FN_RE.lastIndex = 0;
554
+ while ((m = COLOR_FN_RE.exec(cleaned)) !== null) {
555
+ matches.push({ literal: m[0], column: m.index + 1 });
556
+ }
557
+ return matches;
558
+ }
559
+
560
+ // src/doctor/scan.ts
561
+ var DEFAULT_SRC = ["src"];
562
+ var DEFAULT_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".css"];
563
+ var DEFAULT_IGNORE = [
564
+ "**/*.d.ts",
565
+ "**/*.gen.*",
566
+ "**/*.test.*",
567
+ "**/*.spec.*",
568
+ "**/__tests__/**",
569
+ "**/__fixtures__/**",
570
+ "**/__mocks__/**"
571
+ ];
572
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
573
+ var MAX_FILE_BYTES = 2 * 1024 * 1024;
574
+ var toPosix = (p) => p.split(path3.sep).join("/");
575
+ function scanFiles(root, config) {
576
+ const extensions = new Set(config.extensions ?? DEFAULT_EXTENSIONS);
577
+ const ignored = globMatcher([...DEFAULT_IGNORE, ...config.ignore ?? []]);
578
+ const files = [];
579
+ const seen = /* @__PURE__ */ new Set();
580
+ const visit = (abs) => {
581
+ const rel = toPosix(path3.relative(root, abs));
582
+ if (seen.has(rel) || ignored(rel)) return;
583
+ const ext = path3.extname(abs);
584
+ if (!extensions.has(ext)) return;
585
+ if (statSync(abs).size > MAX_FILE_BYTES) return;
586
+ seen.add(rel);
587
+ const text = readFileSync(abs, "utf8");
588
+ files.push({ path: rel, absolutePath: abs, ext, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(ext)) });
589
+ };
590
+ const walk = (dir) => {
591
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
592
+ if (entry.isDirectory()) {
593
+ if (!SKIP_DIRS.has(entry.name)) walk(path3.join(dir, entry.name));
594
+ } else if (entry.isFile()) {
595
+ visit(path3.join(dir, entry.name));
596
+ }
597
+ }
598
+ };
599
+ for (const src of config.src ?? DEFAULT_SRC) {
600
+ const abs = path3.resolve(root, src);
601
+ if (!existsSync(abs)) continue;
602
+ if (statSync(abs).isDirectory()) walk(abs);
603
+ else visit(abs);
604
+ }
605
+ return files;
606
+ }
607
+ function lineAt(text, index) {
608
+ let line = 1;
609
+ for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
610
+ return line;
611
+ }
612
+
613
+ // src/doctor/patterns.ts
614
+ function parseRulesMarkdown(markdown) {
615
+ const rules = [];
616
+ let current = null;
617
+ for (const line of markdown.split("\n")) {
618
+ const heading = line.match(/^###\s+([A-Za-z0-9_-]+)\s*$/);
619
+ if (heading) {
620
+ current = { id: heading[1] };
621
+ rules.push(current);
622
+ continue;
623
+ }
624
+ if (/^#{1,2}\s/.test(line)) {
625
+ current = null;
626
+ continue;
627
+ }
628
+ const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message):\s*(.*)$/);
629
+ if (!current || !kv) continue;
630
+ const [, key, raw] = kv;
631
+ const value = raw.trim();
632
+ if (key === "files" || key === "exclude") current[key] = value.split(",").map((s) => s.trim()).filter(Boolean);
633
+ else if (key === "level") current.level = value;
634
+ else current[key] = value;
635
+ }
636
+ return rules;
637
+ }
638
+ function toRegExp(source, flags = "") {
639
+ if (source.startsWith("(?i)")) return new RegExp(source.slice(4), flags + "i");
640
+ return new RegExp(source, flags);
641
+ }
642
+ function compilePatternRules(rules, source) {
643
+ const ids = /* @__PURE__ */ new Set();
644
+ const out = [];
645
+ for (const rule of rules) {
646
+ if (ids.has(rule.id)) throw new DoctorConfigError(`${source}: rule "${rule.id}" is defined twice`);
647
+ ids.add(rule.id);
648
+ const level = rule.level ?? "error";
649
+ if (!["error", "warn", "guide"].includes(level)) {
650
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" has level "${level}" (use error, warn or guide)`);
651
+ }
652
+ if (level === "guide") continue;
653
+ if (!rule.files?.length) throw new DoctorConfigError(`${source}: rule "${rule.id}" needs "files" (or level: guide)`);
654
+ if (!rule.forbid && !rule.require && !rule.path) {
655
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" needs forbid, require or path (or level: guide)`);
656
+ }
657
+ try {
658
+ out.push({
659
+ rule,
660
+ level,
661
+ includes: globMatcher(rule.files),
662
+ excludes: globMatcher(rule.exclude),
663
+ forbid: rule.forbid ? toRegExp(rule.forbid, "m") : void 0,
664
+ require: rule.require ? toRegExp(rule.require, "m") : void 0,
665
+ path: rule.path ? toRegExp(rule.path) : void 0
666
+ });
667
+ } catch (err) {
668
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" has an invalid pattern: ${err.message}`);
669
+ }
670
+ }
671
+ return out;
672
+ }
673
+ function loadPatternRules(root, patterns, rulesDoc) {
674
+ const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
675
+ let all = compiled;
676
+ if (rulesDoc) {
677
+ const file = path3.resolve(root, rulesDoc);
678
+ if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
679
+ const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
680
+ const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
681
+ if (clash) throw new DoctorConfigError(`rule "${clash.rule.id}" is defined in both doctor.patterns and ${rulesDoc}`);
682
+ all = [...compiled, ...fromDoc];
683
+ }
684
+ if (all.length === 0) return null;
685
+ return {
686
+ count: all.length,
687
+ plugin: {
688
+ name: "patterns",
689
+ check(ctx) {
690
+ for (const r of all) {
691
+ const message = r.rule.message ?? "breaks a design rule";
692
+ for (const file of ctx.files) {
693
+ if (!r.includes(file.path) || r.excludes(file.path)) continue;
694
+ const report = (line) => ctx.report({ rule: r.rule.id, level: r.level, file: file.path, line, message });
695
+ if (r.path && !r.path.test(file.path)) report(0);
696
+ if (r.require && !r.require.test(file.code)) report(0);
697
+ if (r.forbid) {
698
+ const m = r.forbid.exec(file.code);
699
+ if (m) report(lineAt(file.code, m.index));
700
+ }
701
+ }
702
+ }
703
+ }
704
+ }
705
+ };
706
+ }
707
+ async function loadPlugins(specs, configDir) {
708
+ const plugins = [];
709
+ for (const spec of specs ?? []) {
710
+ const [id, options] = typeof spec === "string" ? [spec, void 0] : spec;
711
+ const file = resolvePlugin(id, configDir);
712
+ const url = `${pathToFileURL(file).href}?mtime=${statSync(file).mtimeMs}`;
713
+ let mod;
714
+ try {
715
+ mod = await import(url);
716
+ } catch (err) {
717
+ throw new DoctorConfigError(`doctor.plugins: could not load ${id}: ${err.message}`);
718
+ }
719
+ let value = mod.default;
720
+ if (typeof value === "function") value = await value(options);
721
+ const list = Array.isArray(value) ? value : [value];
722
+ for (const p of list) {
723
+ if (!p || typeof p !== "object" || typeof p.check !== "function" || typeof p.name !== "string") {
724
+ throw new DoctorConfigError(`doctor.plugins: ${id} must default-export { name, check(context) } (or an array, or a factory returning one)`);
725
+ }
726
+ plugins.push(p);
727
+ }
728
+ }
729
+ return plugins;
730
+ }
731
+ function resolvePlugin(id, configDir) {
732
+ try {
733
+ if (id.startsWith(".") || path3.isAbsolute(id)) return resolveFrom(path3.resolve(configDir, id), configDir);
734
+ return resolveFrom(id, configDir);
735
+ } catch {
736
+ throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
737
+ }
738
+ }
739
+ function resolveFrom(id, from) {
740
+ return createRequire(path3.join(from, "noop.js")).resolve(id);
741
+ }
742
+ var BUILTIN_RULES = [
743
+ "local-primitives",
744
+ "starter-leftover",
745
+ "forbidden-import",
746
+ "raw-tag",
747
+ "palette-color",
748
+ "arbitrary-color",
749
+ "raw-color",
750
+ "undefined-token",
751
+ "shadowed-export"
752
+ ];
753
+ var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
754
+ var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
755
+ var DEFAULT_IGNORE_TOKEN_PREFIXES = ["--tw-", "--radix-"];
756
+ var JSX_EXTS = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
757
+ var SCRIPT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
758
+ function importSpecifiers(file) {
759
+ const out = [];
760
+ const lines = file.code.split("\n");
761
+ const re = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|@import\s+)["']([^"']+)["']/g;
762
+ lines.forEach((text, i) => {
763
+ for (const m of text.matchAll(re)) out.push({ specifier: m[1], line: i + 1 });
764
+ });
765
+ return out;
766
+ }
767
+ function checkProjectLayout(ctx) {
768
+ for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
769
+ if (existsSync(path3.join(ctx.root, dir))) {
770
+ ctx.report({
771
+ rule: "local-primitives",
772
+ file: dir,
773
+ subject: dir,
774
+ message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} (or extend it upstream)`
775
+ });
776
+ }
777
+ }
778
+ for (const file of STARTER_LEFTOVERS) {
779
+ if (existsSync(path3.join(ctx.root, file))) {
780
+ ctx.report({
781
+ rule: "starter-leftover",
782
+ level: "warn",
783
+ file,
784
+ subject: file,
785
+ message: `is a starter leftover; Genesis ships cn and owns the components`
786
+ });
787
+ }
788
+ }
789
+ }
790
+ function checkImports(ctx) {
791
+ const ui = ctx.genesis.uiPackage;
792
+ const forbidden = [
793
+ [/^@radix-ui\//, `imports Radix directly; use the Genesis wrapper from ${ui}`],
794
+ [/^(?:[@~#]\/|\.{1,2}\/)(?:.*\/)?components\/ui(?:\/|$)/, `imports a local UI primitive; use ${ui}`],
795
+ [/^[@~#]\/lib\/utils$/, `imports the starter's utils; use cn from ${ui}`],
796
+ ...Object.entries(ctx.config.forbiddenImports ?? {}).map(([re, msg]) => [new RegExp(re), msg])
797
+ ];
798
+ for (const file of ctx.files) {
799
+ if (!SCRIPT_EXTS.has(file.ext)) continue;
800
+ for (const { specifier, line } of importSpecifiers(file)) {
801
+ const hit = forbidden.find(([re]) => re.test(specifier));
802
+ if (hit) ctx.report({ rule: "forbidden-import", file: file.path, line, subject: specifier, message: `${hit[1]} ('${specifier}')` });
803
+ }
804
+ }
805
+ }
806
+ function checkRawTags(ctx) {
807
+ const tags = [...ctx.genesis.rawTags].map(([tag, component]) => [tag, component, new RegExp(`<${tag}(?=[\\s>/]|$)`)]);
808
+ if (tags.length === 0) return;
809
+ for (const file of ctx.files) {
810
+ if (!JSX_EXTS.has(file.ext)) continue;
811
+ file.code.split("\n").forEach((text, i) => {
812
+ for (const [tag, component, re] of tags) {
813
+ if (re.test(text)) {
814
+ ctx.report({ rule: "raw-tag", file: file.path, line: i + 1, subject: tag, message: `renders a raw <${tag}>; use Genesis ${component}` });
815
+ }
816
+ }
817
+ });
818
+ }
819
+ }
820
+ var COLOR_UTILITIES = "bg|text|border(?:-[xytrbls])?|ring|ring-offset|fill|stroke|from|to|via|outline|divide|decoration|shadow|accent|caret|placeholder";
821
+ var ARBITRARY_COLOR_RE = /(?<![\w-])[a-z][a-z-]*-\[(?:#|(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb|color)\()[^\]]*\]/g;
822
+ function checkColors(ctx) {
823
+ const palette = new RegExp(
824
+ `(?<![\\w-])(?:${COLOR_UTILITIES})-(?:${ctx.genesis.palette.join("|")})(?:-\\d{2,3})?(?:\\/\\d{1,3})?(?![\\w-])`,
825
+ "g"
826
+ );
827
+ for (const file of ctx.files) {
828
+ file.code.split("\n").forEach((text, i) => {
829
+ const line = i + 1;
830
+ for (const m of text.matchAll(palette)) {
831
+ ctx.report({ rule: "palette-color", file: file.path, line, subject: m[0], message: `uses the literal palette color '${m[0]}'; use a semantic token (bg-primary, text-muted-foreground, \u2026)` });
832
+ }
833
+ const arbitrary = [];
834
+ for (const m of text.matchAll(ARBITRARY_COLOR_RE)) {
835
+ arbitrary.push([m.index, m.index + m[0].length]);
836
+ ctx.report({ rule: "arbitrary-color", file: file.path, line, subject: m[0], message: `uses the arbitrary color '${m[0]}'; define it as a brand token first` });
837
+ }
838
+ for (const hit of [...findHexLiterals(text), ...findColorFunctions(text)]) {
839
+ const at = hit.column - 1;
840
+ if (arbitrary.some(([a, b]) => at >= a && at < b)) continue;
841
+ ctx.report({ rule: "raw-color", file: file.path, line, subject: hit.literal, message: `hardcodes the color ${hit.literal}; color values come from Genesis tokens` });
842
+ }
843
+ });
844
+ }
845
+ }
846
+ function checkTokens(ctx) {
847
+ const defined = new Set(ctx.genesis.tokens);
848
+ const isTokenFile = ctx.config.tokenFiles ? globMatcher(ctx.config.tokenFiles) : (p) => p.endsWith(".css");
849
+ for (const file of ctx.files) {
850
+ if (isTokenFile(file.path)) for (const t of declaredTokens(file.code)) defined.add(t);
851
+ for (const m of file.code.matchAll(/["'](--[A-Za-z0-9_-]+)["']\s*:/g)) defined.add(m[1]);
852
+ }
853
+ for (const pattern of ctx.config.tokenFiles ?? []) {
854
+ if (/[*?]/.test(pattern)) continue;
855
+ const abs = path3.join(ctx.root, pattern);
856
+ if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
857
+ for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
858
+ }
859
+ }
860
+ const ignorePrefixes = ctx.config.ignoreTokenPrefixes ?? DEFAULT_IGNORE_TOKEN_PREFIXES;
861
+ for (const file of ctx.files) {
862
+ file.code.split("\n").forEach((text, i) => {
863
+ for (const m of text.matchAll(/var\(\s*(--[A-Za-z0-9_-]+)/g)) {
864
+ const token = m[1];
865
+ if (defined.has(token) || ignorePrefixes.some((p) => token.startsWith(p))) continue;
866
+ ctx.report({ rule: "undefined-token", file: file.path, line: i + 1, subject: token, message: `references the undefined token ${token}; define it in Genesis or the brand` });
867
+ }
868
+ });
869
+ }
870
+ }
871
+ function checkShadowedExports(ctx) {
872
+ const re = /\bexport\s+(?:default\s+)?(?:declare\s+)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([A-Z][\w$]*)/g;
873
+ for (const file of ctx.files) {
874
+ if (!SCRIPT_EXTS.has(file.ext)) continue;
875
+ file.code.split("\n").forEach((text, i) => {
876
+ for (const m of text.matchAll(re)) {
877
+ if (!ctx.genesis.values.has(m[1])) continue;
878
+ ctx.report({ rule: "shadowed-export", file: file.path, line: i + 1, subject: m[1], message: `shadows the Genesis export '${m[1]}'; reuse or extend Genesis ${m[1]}` });
879
+ }
880
+ });
881
+ }
882
+ }
883
+ function unusedComponents(ctx) {
884
+ const used = /* @__PURE__ */ new Set();
885
+ const pkg = ctx.genesis.uiPackage.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
886
+ const re = new RegExp(`\\b(?:import|export)\\s+(?:type\\s+)?(?:[\\w$]+\\s*,\\s*)?\\{([^}]*)\\}\\s*from\\s*["']${pkg}(?:/[^"']*)?["']`, "g");
887
+ for (const file of ctx.files) {
888
+ for (const m of file.code.matchAll(re)) {
889
+ for (const part of m[1].split(",")) {
890
+ const name = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/)[0]?.trim();
891
+ if (name) used.add(name);
892
+ }
893
+ }
894
+ }
895
+ return ctx.genesis.components.filter((c) => !used.has(c));
896
+ }
897
+
898
+ // src/doctor/index.ts
899
+ async function runDoctor(options = {}) {
900
+ const root = path3.resolve(options.root ?? process.cwd());
901
+ const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
902
+ const config = loaded.config;
903
+ const genesis = options.genesis ?? loadGenesis(root, config);
904
+ const files = scanFiles(root, config);
905
+ const patterns = loadPatternRules(root, config.patterns, config.rulesDoc);
906
+ const plugins = await loadPlugins(config.plugins, loaded.dir);
907
+ const builtinIds = new Set(BUILTIN_RULES);
908
+ for (const p of config.patterns ?? []) {
909
+ if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
910
+ }
911
+ const raw = [];
912
+ const ctx = { root, files, genesis, config, report: (f) => raw.push(f) };
913
+ const builtins = [
914
+ { name: "layout", check: checkProjectLayout },
915
+ { name: "imports", check: checkImports },
916
+ { name: "raw-tags", check: checkRawTags },
917
+ { name: "colors", check: checkColors },
918
+ { name: "tokens", check: checkTokens },
919
+ { name: "shadowed-exports", check: checkShadowedExports }
920
+ ];
921
+ for (const plugin of [...builtins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
922
+ try {
923
+ await plugin.check(ctx);
924
+ } catch (err) {
925
+ if (err instanceof DoctorConfigError) throw err;
926
+ raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
927
+ }
928
+ }
929
+ if (options.build) {
930
+ const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
931
+ if (failure) raw.push(failure);
932
+ }
933
+ const findings = applyConfig(raw, config);
934
+ const errors = findings.filter((f) => f.level === "error").length;
935
+ const warnings = findings.length - errors;
936
+ return {
937
+ ok: errors === 0 && !(options.strict && warnings > 0),
938
+ root,
939
+ genesis,
940
+ findings,
941
+ unused: unusedComponents(ctx),
942
+ ruleCount: (patterns?.count ?? 0) + plugins.length,
943
+ errors,
944
+ warnings
945
+ };
946
+ }
947
+ function applyConfig(raw, config) {
948
+ const allow = (config.allow ?? []).map((entry) => ({ entry, file: entry.file ? globToRegExp(entry.file) : null, used: false }));
949
+ const out = [];
950
+ for (const input of raw) {
951
+ const setting = config.rules?.[input.rule];
952
+ if (setting === "off") continue;
953
+ const finding = {
954
+ rule: input.rule,
955
+ level: setting ?? input.level ?? "error",
956
+ file: input.file,
957
+ line: input.line ?? 0,
958
+ message: input.message,
959
+ ...input.subject !== void 0 ? { subject: input.subject } : {}
960
+ };
961
+ const exception = allow.find(
962
+ (a) => a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
963
+ );
964
+ if (exception) {
965
+ exception.used = true;
966
+ continue;
967
+ }
968
+ out.push(finding);
969
+ }
970
+ const staleLevel = config.rules?.["stale-exception"];
971
+ for (const a of allow) {
972
+ if (staleLevel === "off" || a.used || config.rules?.[a.entry.rule] === "off") continue;
973
+ out.push({
974
+ rule: "stale-exception",
975
+ level: staleLevel ?? "warn",
976
+ file: a.entry.file ?? "genesis config",
977
+ line: 0,
978
+ subject: a.entry.rule,
979
+ message: `the allow entry for ${a.entry.rule}${a.entry.match ? ` (${a.entry.match})` : ""} no longer matches anything; remove it`
980
+ });
981
+ }
982
+ return out.sort((x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule));
983
+ }
984
+ function formatReport(result) {
985
+ const g = result.genesis;
986
+ const lines = [
987
+ `Genesis doctor: ${g.uiPackage}@${g.uiVersion}, ${g.components.length} components, ${g.tokens.size} tokens, ${result.ruleCount} app rules; raw tags checked: ${[...g.rawTags.keys()].join(", ") || "none"}`
988
+ ];
989
+ for (const f of result.findings) {
990
+ lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
991
+ }
992
+ lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
993
+ lines.push(result.ok ? `PASS (${result.warnings} warnings)` : `FAIL (${result.errors} errors, ${result.warnings} warnings)`);
994
+ return lines.join("\n");
995
+ }
996
+
997
+ // src/vite.ts
998
+ var formatProblems = (result, withWarnings = false) => result.findings.filter((f) => f.level === "error" || withWarnings).map((f) => `${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`).join("\n");
999
+ function genesisDoctor(options = {}) {
1000
+ let root = options.root ?? process.cwd();
1001
+ return [
1002
+ {
1003
+ name: "genesis-doctor:build",
1004
+ apply: "build",
1005
+ configResolved(config) {
1006
+ root = options.root ?? config.root;
1007
+ },
1008
+ async buildStart() {
1009
+ const result = await runDoctor({ root, configPath: options.configPath, strict: options.strict });
1010
+ if (!result.ok) this.error(`Genesis doctor found problems:
1011
+ ${formatProblems(result, options.strict)}`);
1012
+ if (result.warnings > 0) this.warn(formatReport(result));
1013
+ }
1014
+ },
1015
+ {
1016
+ name: "genesis-doctor:serve",
1017
+ apply: "serve",
1018
+ configResolved(config) {
1019
+ root = options.root ?? config.root;
1020
+ },
1021
+ configureServer(server) {
1022
+ let genesis;
1023
+ let timer;
1024
+ let failing = false;
1025
+ let lastError = null;
1026
+ const showError = (message) => {
1027
+ lastError = message;
1028
+ failing = true;
1029
+ server.config.logger.error(message, { timestamp: true });
1030
+ server.ws.send({ type: "error", err: { message, stack: "", plugin: "genesis-doctor" } });
1031
+ };
1032
+ let running = false;
1033
+ let again = false;
1034
+ const check = async () => {
1035
+ if (running) {
1036
+ again = true;
1037
+ return;
1038
+ }
1039
+ running = true;
1040
+ try {
1041
+ genesis ??= loadGenesis(root, loadConfig(root, options.configPath).config);
1042
+ const result = await runDoctor({ root, configPath: options.configPath, genesis });
1043
+ if (result.errors > 0) {
1044
+ showError(`Genesis doctor found problems:
1045
+ ${formatProblems(result)}`);
1046
+ } else if (failing) {
1047
+ failing = false;
1048
+ lastError = null;
1049
+ server.config.logger.info("Genesis doctor: all clear", { timestamp: true });
1050
+ server.ws.send({ type: "full-reload" });
1051
+ }
1052
+ } catch (err) {
1053
+ showError(`Genesis doctor could not run: ${err.message}`);
1054
+ } finally {
1055
+ running = false;
1056
+ if (again) {
1057
+ again = false;
1058
+ void check();
1059
+ }
1060
+ }
1061
+ };
1062
+ const explicit = /* @__PURE__ */ new Set([path3.join(root, "genesis.config.json"), ...options.configPath ? [path3.resolve(root, options.configPath)] : []]);
1063
+ try {
1064
+ const { config } = loadConfig(root, options.configPath);
1065
+ if (config.rulesDoc) explicit.add(path3.resolve(root, config.rulesDoc));
1066
+ } catch {
1067
+ }
1068
+ const schedule = (file) => {
1069
+ if (!explicit.has(path3.resolve(file))) {
1070
+ const rel = path3.relative(root, file).split(path3.sep).join("/");
1071
+ if (rel.startsWith("..") || rel.includes("node_modules/")) return;
1072
+ }
1073
+ clearTimeout(timer);
1074
+ timer = setTimeout(() => void check(), options.debounceMs ?? 300);
1075
+ };
1076
+ server.watcher.add([...explicit]);
1077
+ server.watcher.on("change", schedule);
1078
+ server.watcher.on("add", schedule);
1079
+ server.watcher.on("unlink", schedule);
1080
+ server.ws.on("connection", () => {
1081
+ if (lastError) server.ws.send({ type: "error", err: { message: lastError, stack: "", plugin: "genesis-doctor" } });
1082
+ });
1083
+ server.httpServer?.once("listening", () => void check());
1084
+ if (!server.httpServer) void check();
1085
+ }
1086
+ }
1087
+ ];
1088
+ }
1089
+
1090
+ export { genesisDoctor };
1091
+ //# sourceMappingURL=vite.js.map
1092
+ //# sourceMappingURL=vite.js.map