@marktiderman/genesis-cli 1.1.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +189 -4
- package/dist/cli.js +1286 -26
- package/dist/cli.js.map +1 -1
- package/dist/doctor.d.ts +232 -0
- package/dist/doctor.js +1021 -0
- package/dist/doctor.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1004 -9
- package/dist/index.js.map +1 -1
- package/dist/vite.d.ts +15 -0
- package/dist/vite.js +1092 -0
- package/dist/vite.js.map +1 -0
- package/package.json +22 -3
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { execFileSync, spawnSync } from 'child_process';
|
|
3
|
+
import { existsSync, readFileSync, statSync, readdirSync } from 'fs';
|
|
4
|
+
import * as path3 from 'path';
|
|
2
5
|
import { createRequire } from 'module';
|
|
6
|
+
import { pathToFileURL } from 'url';
|
|
7
|
+
import { createJiti } from 'jiti';
|
|
8
|
+
import { buildFeatureOutputs, checkFeatureOutputs, summarizeCheck } from '@marktiderman/genesis-features/node';
|
|
9
|
+
import { findFeatures } from '@marktiderman/genesis-features';
|
|
3
10
|
import { studioSetupSql } from '@marktiderman/genesis-studio-server';
|
|
4
11
|
import { Command } from 'commander';
|
|
5
12
|
import * as fs from 'fs/promises';
|
|
6
|
-
import * as path from 'path';
|
|
7
13
|
|
|
8
14
|
var __defProp = Object.defineProperty;
|
|
9
15
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
@@ -31,15 +37,15 @@ function parse(comment, keys, where) {
|
|
|
31
37
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
32
38
|
throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
|
|
33
39
|
}
|
|
34
|
-
const
|
|
40
|
+
const settings2 = {};
|
|
35
41
|
for (const [key, v] of Object.entries(value)) {
|
|
36
42
|
if (!keys.includes(key)) {
|
|
37
43
|
throw new CommentSettingsError(`${where}: unknown ${MARKER} setting "${key}". Allowed: ${keys.join(", ")}.`);
|
|
38
44
|
}
|
|
39
45
|
if (typeof v !== "string") throw new CommentSettingsError(`${where}: ${MARKER} "${key}" must be a string.`);
|
|
40
|
-
|
|
46
|
+
settings2[key] = v;
|
|
41
47
|
}
|
|
42
|
-
return { ...description ? { description } : {}, ...Object.keys(
|
|
48
|
+
return { ...description ? { description } : {}, ...Object.keys(settings2).length ? { settings: settings2 } : {} };
|
|
43
49
|
}
|
|
44
50
|
function parseTableComment(comment, table) {
|
|
45
51
|
return parse(comment, TABLE_KEYS, table);
|
|
@@ -329,6 +335,1210 @@ var init_introspect = __esm({
|
|
|
329
335
|
init_comments();
|
|
330
336
|
}
|
|
331
337
|
});
|
|
338
|
+
function buildCommands(root, config) {
|
|
339
|
+
if (config.build) return config.build;
|
|
340
|
+
const pkgFile = path3.join(root, "package.json");
|
|
341
|
+
const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
|
|
342
|
+
const pm = packageManager(root);
|
|
343
|
+
return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
|
|
344
|
+
}
|
|
345
|
+
function packageManager(root) {
|
|
346
|
+
let dir = path3.resolve(root);
|
|
347
|
+
for (; ; ) {
|
|
348
|
+
if (existsSync(path3.join(dir, "pnpm-lock.yaml"))) return "pnpm";
|
|
349
|
+
if (existsSync(path3.join(dir, "bun.lock")) || existsSync(path3.join(dir, "bun.lockb"))) return "bun";
|
|
350
|
+
if (existsSync(path3.join(dir, "yarn.lock"))) return "yarn";
|
|
351
|
+
if (existsSync(path3.join(dir, "package-lock.json"))) return "npm";
|
|
352
|
+
const parent = path3.dirname(dir);
|
|
353
|
+
if (parent === dir) return "npm";
|
|
354
|
+
dir = parent;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
function runBuild(root, commands, quiet) {
|
|
358
|
+
if (process.env[BUILD_GUARD_ENV]) return null;
|
|
359
|
+
if (commands.length === 0) {
|
|
360
|
+
return { rule: "build", level: "warn", file: "package.json", message: "--build found nothing to run: add typecheck/build scripts or doctor.build" };
|
|
361
|
+
}
|
|
362
|
+
for (const command of commands) {
|
|
363
|
+
const r = spawnSync(command, {
|
|
364
|
+
cwd: root,
|
|
365
|
+
shell: true,
|
|
366
|
+
stdio: quiet ? "pipe" : "inherit",
|
|
367
|
+
env: { ...process.env, [BUILD_GUARD_ENV]: "1" }
|
|
368
|
+
});
|
|
369
|
+
if (r.status !== 0) {
|
|
370
|
+
const tail = quiet ? `
|
|
371
|
+
${String(r.stderr ?? "").trim().split("\n").slice(-20).join("\n")}` : "";
|
|
372
|
+
return { rule: "build", file: command, message: `\`${command}\` failed (exit ${r.status ?? r.signal})${tail}` };
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
var BUILD_GUARD_ENV;
|
|
378
|
+
var init_build = __esm({
|
|
379
|
+
"src/doctor/build.ts"() {
|
|
380
|
+
BUILD_GUARD_ENV = "GENESIS_DOCTOR_BUILDING";
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
function loadConfig(root, configPath) {
|
|
384
|
+
if (configPath) {
|
|
385
|
+
const file = path3.resolve(root, configPath);
|
|
386
|
+
if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
|
|
387
|
+
const json = readJson(file);
|
|
388
|
+
const block = path3.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
|
|
389
|
+
return { config: validateConfig(block ?? {}, file), file, dir: path3.dirname(file) };
|
|
390
|
+
}
|
|
391
|
+
const own = path3.join(root, "genesis.config.json");
|
|
392
|
+
if (existsSync(own)) {
|
|
393
|
+
return { config: validateConfig(readJson(own)?.doctor ?? {}, own), file: own, dir: root };
|
|
394
|
+
}
|
|
395
|
+
const pkg = path3.join(root, "package.json");
|
|
396
|
+
if (existsSync(pkg)) {
|
|
397
|
+
const block = readJson(pkg)?.genesis?.doctor;
|
|
398
|
+
if (block !== void 0) return { config: validateConfig(block, pkg), file: pkg, dir: root };
|
|
399
|
+
}
|
|
400
|
+
return { config: {}, file: null, dir: root };
|
|
401
|
+
}
|
|
402
|
+
function readJson(file) {
|
|
403
|
+
try {
|
|
404
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
405
|
+
} catch (err) {
|
|
406
|
+
throw new DoctorConfigError(`${file} is not valid JSON: ${err.message}`);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
function validateConfig(raw, source = "config") {
|
|
410
|
+
const fail = (msg) => {
|
|
411
|
+
throw new DoctorConfigError(`${source}: ${msg}`);
|
|
412
|
+
};
|
|
413
|
+
if (!isObject(raw)) fail("the doctor settings must be an object");
|
|
414
|
+
const c = raw;
|
|
415
|
+
for (const key of Object.keys(c)) if (!KNOWN.has(key)) fail(`unknown setting "${key}"`);
|
|
416
|
+
if (typeof c.themeCss === "string") c.themeCss = [c.themeCss];
|
|
417
|
+
if (c.themeCss !== void 0 && !isStringList(c.themeCss)) fail(`"themeCss" must be a path or a list of paths`);
|
|
418
|
+
for (const key of STRING_LISTS) {
|
|
419
|
+
if (c[key] !== void 0 && !isStringList(c[key])) fail(`"${key}" must be a list of strings`);
|
|
420
|
+
}
|
|
421
|
+
for (const key of STRINGS) {
|
|
422
|
+
if (c[key] !== void 0 && typeof c[key] !== "string") fail(`"${key}" must be a string`);
|
|
423
|
+
}
|
|
424
|
+
if (c.rawTags !== void 0) {
|
|
425
|
+
if (!isObject(c.rawTags)) fail(`"rawTags" must be an object`);
|
|
426
|
+
for (const [tag, v] of Object.entries(c.rawTags)) {
|
|
427
|
+
if (!/^[a-z][a-z0-9-]*$/.test(tag)) fail(`rawTags: "${tag}" is not an HTML tag name`);
|
|
428
|
+
if (v !== false && typeof v !== "string") fail(`rawTags.${tag} must be a component name or false`);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
if (c.forbiddenImports !== void 0) {
|
|
432
|
+
if (!isObject(c.forbiddenImports)) fail(`"forbiddenImports" must be an object of pattern \u2192 message`);
|
|
433
|
+
for (const [re, msg] of Object.entries(c.forbiddenImports)) {
|
|
434
|
+
if (typeof msg !== "string") fail(`forbiddenImports["${re}"] must be a message string`);
|
|
435
|
+
checkRegExp(re, `forbiddenImports["${re}"]`, fail);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (c.rules !== void 0) {
|
|
439
|
+
if (!isObject(c.rules)) fail(`"rules" must be an object of rule \u2192 level`);
|
|
440
|
+
for (const [rule, level] of Object.entries(c.rules)) {
|
|
441
|
+
if (!LEVELS.has(level)) fail(`rules.${rule} must be "error", "warn" or "off"`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (c.allow !== void 0) {
|
|
445
|
+
if (!Array.isArray(c.allow)) fail(`"allow" must be a list`);
|
|
446
|
+
c.allow.forEach((e, i) => {
|
|
447
|
+
if (!isObject(e)) return fail(`allow[${i}] must be an object`);
|
|
448
|
+
const entry = e;
|
|
449
|
+
if (typeof entry.rule !== "string" || !entry.rule) fail(`allow[${i}] needs a "rule"`);
|
|
450
|
+
if (typeof entry.reason !== "string" || !entry.reason.trim()) fail(`allow[${i}] (${entry.rule}) needs a "reason"`);
|
|
451
|
+
for (const k of ["file", "match"]) {
|
|
452
|
+
if (entry[k] !== void 0 && typeof entry[k] !== "string") fail(`allow[${i}].${k} must be a string`);
|
|
453
|
+
}
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
if (c.patterns !== void 0) {
|
|
457
|
+
if (!Array.isArray(c.patterns)) fail(`"patterns" must be a list`);
|
|
458
|
+
c.patterns.forEach((p, i) => {
|
|
459
|
+
if (!isObject(p)) return fail(`patterns[${i}] must be an object`);
|
|
460
|
+
const rule = p;
|
|
461
|
+
for (const k of Object.keys(rule)) if (!PATTERN_KEYS.has(k)) fail(`patterns[${i}]: unknown key "${k}"`);
|
|
462
|
+
if (typeof rule.id !== "string" || !rule.id) fail(`patterns[${i}] needs an "id"`);
|
|
463
|
+
for (const k of ["files", "exclude"]) {
|
|
464
|
+
if (rule[k] !== void 0 && !isStringList(rule[k])) fail(`patterns[${i}].${k} must be a list of globs`);
|
|
465
|
+
}
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
if (c.plugins !== void 0) {
|
|
469
|
+
const ok = Array.isArray(c.plugins) && c.plugins.every((p) => typeof p === "string" || Array.isArray(p) && p.length === 2 && typeof p[0] === "string");
|
|
470
|
+
if (!ok) fail(`"plugins" must be a list of module paths or [path, options] pairs`);
|
|
471
|
+
}
|
|
472
|
+
return c;
|
|
473
|
+
}
|
|
474
|
+
function checkRegExp(source, where, fail) {
|
|
475
|
+
try {
|
|
476
|
+
new RegExp(source);
|
|
477
|
+
} catch (err) {
|
|
478
|
+
fail(`${where} is not a valid regular expression: ${err.message}`);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
function isObject(v) {
|
|
482
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
483
|
+
}
|
|
484
|
+
function isStringList(v) {
|
|
485
|
+
return Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
486
|
+
}
|
|
487
|
+
var DoctorConfigError, STRING_LISTS, STRINGS, KNOWN, LEVELS, PATTERN_KEYS;
|
|
488
|
+
var init_config = __esm({
|
|
489
|
+
"src/doctor/config.ts"() {
|
|
490
|
+
DoctorConfigError = class extends Error {
|
|
491
|
+
name = "DoctorConfigError";
|
|
492
|
+
};
|
|
493
|
+
STRING_LISTS = ["src", "extensions", "ignore", "tokenFiles", "ignoreTokenPrefixes", "localPrimitiveDirs", "build"];
|
|
494
|
+
STRINGS = ["uiPackage", "rulesDoc"];
|
|
495
|
+
KNOWN = /* @__PURE__ */ new Set([
|
|
496
|
+
...STRING_LISTS,
|
|
497
|
+
...STRINGS,
|
|
498
|
+
"themeCss",
|
|
499
|
+
"rawTags",
|
|
500
|
+
"forbiddenImports",
|
|
501
|
+
"rules",
|
|
502
|
+
"allow",
|
|
503
|
+
"patterns",
|
|
504
|
+
"plugins",
|
|
505
|
+
"$schema",
|
|
506
|
+
"$comment"
|
|
507
|
+
]);
|
|
508
|
+
LEVELS = /* @__PURE__ */ new Set(["error", "warn", "off"]);
|
|
509
|
+
PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
// src/doctor/glob.ts
|
|
514
|
+
function globToRegExp(glob) {
|
|
515
|
+
let g = glob.trim().replace(/^\.\//, "");
|
|
516
|
+
if (g.endsWith("/")) g += "**";
|
|
517
|
+
let out = "";
|
|
518
|
+
for (let i = 0; i < g.length; i++) {
|
|
519
|
+
const ch = g[i];
|
|
520
|
+
if (ch === "*") {
|
|
521
|
+
if (g[i + 1] === "*") {
|
|
522
|
+
const slash = g[i + 2] === "/";
|
|
523
|
+
out += slash ? "(?:.*/)?" : ".*";
|
|
524
|
+
i += slash ? 2 : 1;
|
|
525
|
+
} else {
|
|
526
|
+
out += "[^/]*";
|
|
527
|
+
}
|
|
528
|
+
} else if (ch === "?") {
|
|
529
|
+
out += "[^/]";
|
|
530
|
+
} else {
|
|
531
|
+
out += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
return new RegExp(`^${out}$`);
|
|
535
|
+
}
|
|
536
|
+
function globMatcher(globs) {
|
|
537
|
+
const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
|
|
538
|
+
return (path11) => res.some((re) => re.test(path11));
|
|
539
|
+
}
|
|
540
|
+
var init_glob = __esm({
|
|
541
|
+
"src/doctor/glob.ts"() {
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
function findPackageDir(from, name) {
|
|
545
|
+
let dir = path3.resolve(from);
|
|
546
|
+
for (; ; ) {
|
|
547
|
+
const candidate = path3.join(dir, "node_modules", name);
|
|
548
|
+
if (existsSync(path3.join(candidate, "package.json"))) return candidate;
|
|
549
|
+
const parent = path3.dirname(dir);
|
|
550
|
+
if (parent === dir) return null;
|
|
551
|
+
dir = parent;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function loadGenesis(root, config) {
|
|
555
|
+
const uiPackage = config.uiPackage ?? DEFAULT_UI_PACKAGE;
|
|
556
|
+
const uiDir = findPackageDir(root, uiPackage);
|
|
557
|
+
if (!uiDir) throw new DoctorConfigError(`${uiPackage} is not installed here. Install it, or set doctor.uiPackage.`);
|
|
558
|
+
const uiPkg = JSON.parse(readFileSync(path3.join(uiDir, "package.json"), "utf8"));
|
|
559
|
+
const typeEntries = /* @__PURE__ */ new Set();
|
|
560
|
+
const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
|
|
561
|
+
if (typeof mainTypes === "string") typeEntries.add(mainTypes);
|
|
562
|
+
for (const target of Object.values(uiPkg.exports ?? {})) {
|
|
563
|
+
const t = exportTypes(target);
|
|
564
|
+
if (typeof t === "string" && !t.includes("*")) typeEntries.add(t);
|
|
565
|
+
}
|
|
566
|
+
const exportNames = /* @__PURE__ */ new Set();
|
|
567
|
+
const reexportedPackages = /* @__PURE__ */ new Set();
|
|
568
|
+
let readAny = false;
|
|
569
|
+
for (const entry of typeEntries) {
|
|
570
|
+
const file = path3.join(uiDir, entry);
|
|
571
|
+
if (!existsSync(file)) continue;
|
|
572
|
+
readAny = true;
|
|
573
|
+
const dts = readFileSync(file, "utf8");
|
|
574
|
+
for (const name of parseExportNames(dts)) exportNames.add(name);
|
|
575
|
+
for (const m of dts.matchAll(/export\s+(?:type\s+)?(?:\{[^}]*\}|\*)\s*from\s*["']([^"'.][^"']*)["']/g)) {
|
|
576
|
+
reexportedPackages.add(packageName(m[1]));
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
if (!readAny) {
|
|
580
|
+
throw new DoctorConfigError(`${uiPackage} has no type declarations to read (is it built?). Looked for: ${[...typeEntries].join(", ") || "none"}`);
|
|
581
|
+
}
|
|
582
|
+
const valueDecls = /* @__PURE__ */ new Set();
|
|
583
|
+
const typeDecls = /* @__PURE__ */ new Set();
|
|
584
|
+
const declRoot = typeof mainTypes === "string" ? path3.dirname(path3.join(uiDir, mainTypes)) : uiDir;
|
|
585
|
+
const declFiles = walkDts(declRoot);
|
|
586
|
+
for (const pkg of reexportedPackages) {
|
|
587
|
+
const dir = findPackageDir(uiDir, pkg);
|
|
588
|
+
if (dir) walkDts(path3.join(dir, "dist"), declFiles);
|
|
589
|
+
}
|
|
590
|
+
for (const file of declFiles) {
|
|
591
|
+
const text = readFileSync(file, "utf8");
|
|
592
|
+
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]);
|
|
593
|
+
for (const m of text.matchAll(/\b(?:interface|type)\s+([A-Za-z_$][\w$]*)/g)) typeDecls.add(m[1]);
|
|
594
|
+
}
|
|
595
|
+
const isTypeOnly = (n) => typeDecls.has(n) && !valueDecls.has(n);
|
|
596
|
+
const values = new Set([...exportNames].filter((n) => !isTypeOnly(n)));
|
|
597
|
+
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();
|
|
598
|
+
const tokens = /* @__PURE__ */ new Set();
|
|
599
|
+
const themeFiles = resolveThemeFiles(root, config, uiDir);
|
|
600
|
+
for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
|
|
601
|
+
const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
|
|
602
|
+
const rawTags = /* @__PURE__ */ new Map();
|
|
603
|
+
for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
|
|
604
|
+
for (const [tag, comp] of Object.entries(TAG_ALIASES)) if (values.has(comp)) rawTags.set(tag, comp);
|
|
605
|
+
for (const [tag, comp] of Object.entries(config.rawTags ?? {})) {
|
|
606
|
+
if (comp === false) rawTags.delete(tag);
|
|
607
|
+
else rawTags.set(tag, comp);
|
|
608
|
+
}
|
|
609
|
+
return {
|
|
610
|
+
uiPackage,
|
|
611
|
+
uiVersion: String(uiPkg.version ?? "unknown"),
|
|
612
|
+
exports: exportNames,
|
|
613
|
+
values,
|
|
614
|
+
components,
|
|
615
|
+
tokens,
|
|
616
|
+
rawTags,
|
|
617
|
+
palette: loadPalette(root)
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
function parseExportNames(dts) {
|
|
621
|
+
const names = [];
|
|
622
|
+
for (const m of dts.matchAll(/export\s+(?:type\s+)?\{([^}]*)\}/g)) {
|
|
623
|
+
for (const part of m[1].split(",")) {
|
|
624
|
+
const name = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/).pop()?.trim();
|
|
625
|
+
if (name && name !== "default") names.push(name);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
for (const m of dts.matchAll(/export\s+(?:declare\s+)?(?:const|let|function|class|enum|interface|type)\s+([A-Za-z_$][\w$]*)/g)) {
|
|
629
|
+
names.push(m[1]);
|
|
630
|
+
}
|
|
631
|
+
return names;
|
|
632
|
+
}
|
|
633
|
+
function declaredTokens(css) {
|
|
634
|
+
return [...css.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)].map((m) => m[1]);
|
|
635
|
+
}
|
|
636
|
+
function packageName(specifier) {
|
|
637
|
+
const parts = specifier.split("/");
|
|
638
|
+
return parts.slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
|
|
639
|
+
}
|
|
640
|
+
function exportTypes(target) {
|
|
641
|
+
if (!target || typeof target !== "object") return void 0;
|
|
642
|
+
const t = target;
|
|
643
|
+
if (typeof t.types === "string") return t.types;
|
|
644
|
+
for (const key of ["import", "default", "require"]) {
|
|
645
|
+
const nested = exportTypes(t[key]);
|
|
646
|
+
if (nested) return nested;
|
|
647
|
+
}
|
|
648
|
+
return void 0;
|
|
649
|
+
}
|
|
650
|
+
function walkDts(dir, out = []) {
|
|
651
|
+
if (!existsSync(dir)) return out;
|
|
652
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
653
|
+
if (entry.name === "node_modules") continue;
|
|
654
|
+
const p = path3.join(dir, entry.name);
|
|
655
|
+
if (entry.isDirectory()) walkDts(p, out);
|
|
656
|
+
else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
|
|
657
|
+
}
|
|
658
|
+
return out;
|
|
659
|
+
}
|
|
660
|
+
function resolveThemeFiles(root, config, uiDir) {
|
|
661
|
+
if (config.themeCss) {
|
|
662
|
+
const specs = typeof config.themeCss === "string" ? [config.themeCss] : config.themeCss;
|
|
663
|
+
return specs.map((spec) => {
|
|
664
|
+
const file = resolveSpec(root, spec);
|
|
665
|
+
if (!file) throw new DoctorConfigError(`doctor.themeCss: cannot find ${spec}`);
|
|
666
|
+
return file;
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
const files = [];
|
|
670
|
+
const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
|
|
671
|
+
const themes = ds && path3.join(ds, "dist", "themes");
|
|
672
|
+
if (themes && existsSync(themes)) {
|
|
673
|
+
for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path3.join(themes, name));
|
|
674
|
+
}
|
|
675
|
+
if (files.length === 0) {
|
|
676
|
+
throw new DoctorConfigError(
|
|
677
|
+
`No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
|
|
678
|
+
);
|
|
679
|
+
}
|
|
680
|
+
const uiStyles = path3.join(uiDir, "dist", "styles.css");
|
|
681
|
+
if (existsSync(uiStyles)) files.push(uiStyles);
|
|
682
|
+
return files;
|
|
683
|
+
}
|
|
684
|
+
function resolveSpec(root, spec) {
|
|
685
|
+
const local = path3.resolve(root, spec);
|
|
686
|
+
if (spec.startsWith(".") || path3.isAbsolute(spec)) return existsSync(local) ? local : null;
|
|
687
|
+
const parts = spec.split("/");
|
|
688
|
+
const nameLength = spec.startsWith("@") ? 2 : 1;
|
|
689
|
+
const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
|
|
690
|
+
if (dir) {
|
|
691
|
+
const file = path3.join(dir, ...parts.slice(nameLength));
|
|
692
|
+
if (existsSync(file) && statSync(file).isFile()) return file;
|
|
693
|
+
}
|
|
694
|
+
return existsSync(local) ? local : null;
|
|
695
|
+
}
|
|
696
|
+
function loadPalette(root) {
|
|
697
|
+
const names = new Set(TAILWIND_PALETTE);
|
|
698
|
+
try {
|
|
699
|
+
const req = createRequire(path3.join(root, "package.json"));
|
|
700
|
+
const colors = req("tailwindcss/colors");
|
|
701
|
+
for (const key of Object.keys(colors?.default ?? colors ?? {})) {
|
|
702
|
+
if (/^[a-z]+$/.test(key) && !["inherit", "current", "transparent"].includes(key)) names.add(key);
|
|
703
|
+
}
|
|
704
|
+
} catch {
|
|
705
|
+
}
|
|
706
|
+
return [...names].sort();
|
|
707
|
+
}
|
|
708
|
+
var DEFAULT_UI_PACKAGE, DESIGN_SYSTEM_PACKAGE, TAGS, TAG_ALIASES, NON_COMPONENT_SUFFIX, TAILWIND_PALETTE;
|
|
709
|
+
var init_genesis = __esm({
|
|
710
|
+
"src/doctor/genesis.ts"() {
|
|
711
|
+
init_config();
|
|
712
|
+
DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
|
|
713
|
+
DESIGN_SYSTEM_PACKAGE = "@marktiderman/genesis-design-system";
|
|
714
|
+
TAGS = ["button", "input", "textarea", "select", "label", "table", "dialog", "progress", "details", "summary"];
|
|
715
|
+
TAG_ALIASES = { hr: "Separator" };
|
|
716
|
+
NON_COMPONENT_SUFFIX = /(Props|Variant|Variants|Type|Types|Config|Context|Options|Status)$/;
|
|
717
|
+
TAILWIND_PALETTE = [
|
|
718
|
+
"black",
|
|
719
|
+
"white",
|
|
720
|
+
"slate",
|
|
721
|
+
"gray",
|
|
722
|
+
"zinc",
|
|
723
|
+
"neutral",
|
|
724
|
+
"stone",
|
|
725
|
+
"red",
|
|
726
|
+
"orange",
|
|
727
|
+
"amber",
|
|
728
|
+
"yellow",
|
|
729
|
+
"lime",
|
|
730
|
+
"green",
|
|
731
|
+
"emerald",
|
|
732
|
+
"teal",
|
|
733
|
+
"cyan",
|
|
734
|
+
"sky",
|
|
735
|
+
"blue",
|
|
736
|
+
"indigo",
|
|
737
|
+
"violet",
|
|
738
|
+
"purple",
|
|
739
|
+
"fuchsia",
|
|
740
|
+
"pink",
|
|
741
|
+
"rose",
|
|
742
|
+
"taupe",
|
|
743
|
+
"mauve",
|
|
744
|
+
"mist",
|
|
745
|
+
"olive"
|
|
746
|
+
];
|
|
747
|
+
}
|
|
748
|
+
});
|
|
749
|
+
|
|
750
|
+
// ../../scripts/lib/color-literals.mjs
|
|
751
|
+
function stripBlockComments(content, hasLineComments = true) {
|
|
752
|
+
let result = "";
|
|
753
|
+
let i = 0;
|
|
754
|
+
const len = content.length;
|
|
755
|
+
while (i < len) {
|
|
756
|
+
const ch = content[i];
|
|
757
|
+
const next = i + 1 < len ? content[i + 1] : "";
|
|
758
|
+
const prevIsColon = i > 0 && content[i - 1] === ":";
|
|
759
|
+
const prevIsBackslash = i > 0 && content[i - 1] === "\\";
|
|
760
|
+
if (ch === '"') {
|
|
761
|
+
result += ch;
|
|
762
|
+
i++;
|
|
763
|
+
while (i < len) {
|
|
764
|
+
const c = content[i];
|
|
765
|
+
result += c;
|
|
766
|
+
if (c === "\\" && i + 1 < len) {
|
|
767
|
+
result += content[i + 1];
|
|
768
|
+
i += 2;
|
|
769
|
+
} else if (c === '"') {
|
|
770
|
+
i++;
|
|
771
|
+
break;
|
|
772
|
+
} else {
|
|
773
|
+
i++;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
continue;
|
|
777
|
+
}
|
|
778
|
+
if (ch === "'") {
|
|
779
|
+
result += ch;
|
|
780
|
+
i++;
|
|
781
|
+
while (i < len) {
|
|
782
|
+
const c = content[i];
|
|
783
|
+
result += c;
|
|
784
|
+
if (c === "\\" && i + 1 < len) {
|
|
785
|
+
result += content[i + 1];
|
|
786
|
+
i += 2;
|
|
787
|
+
} else if (c === "'") {
|
|
788
|
+
i++;
|
|
789
|
+
break;
|
|
790
|
+
} else {
|
|
791
|
+
i++;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
if (ch === "`") {
|
|
797
|
+
result += ch;
|
|
798
|
+
i++;
|
|
799
|
+
while (i < len) {
|
|
800
|
+
const c = content[i];
|
|
801
|
+
result += c;
|
|
802
|
+
if (c === "\\" && i + 1 < len) {
|
|
803
|
+
result += content[i + 1];
|
|
804
|
+
i += 2;
|
|
805
|
+
} else if (c === "`") {
|
|
806
|
+
i++;
|
|
807
|
+
break;
|
|
808
|
+
} else {
|
|
809
|
+
i++;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
if ((ch === "u" || ch === "U") && content.slice(i, i + 4).toLowerCase() === "url(" && !/[\w$]/.test(content[i - 1] ?? "")) {
|
|
815
|
+
result += content.slice(i, i + 4);
|
|
816
|
+
i += 4;
|
|
817
|
+
while (i < len && content[i] !== ")") {
|
|
818
|
+
const c = content[i];
|
|
819
|
+
if (c === '"' || c === "'") {
|
|
820
|
+
result += c;
|
|
821
|
+
i++;
|
|
822
|
+
while (i < len) {
|
|
823
|
+
const q = content[i];
|
|
824
|
+
result += q;
|
|
825
|
+
if (q === "\\" && i + 1 < len) {
|
|
826
|
+
result += content[i + 1];
|
|
827
|
+
i += 2;
|
|
828
|
+
} else if (q === c) {
|
|
829
|
+
i++;
|
|
830
|
+
break;
|
|
831
|
+
} else {
|
|
832
|
+
i++;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
} else {
|
|
836
|
+
result += c;
|
|
837
|
+
i++;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
if (i < len && content[i] === ")") {
|
|
841
|
+
result += ")";
|
|
842
|
+
i++;
|
|
843
|
+
}
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
if (hasLineComments && ch === "/" && next === "/" && !prevIsColon && !prevIsBackslash) {
|
|
847
|
+
let j = i + 2;
|
|
848
|
+
while (j < len && content[j] !== "\n") {
|
|
849
|
+
j++;
|
|
850
|
+
}
|
|
851
|
+
const commentLen = j - i;
|
|
852
|
+
const commentText = content.slice(i, i + commentLen);
|
|
853
|
+
result += commentText.replace(/[^\n]/g, " ");
|
|
854
|
+
i += commentLen;
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
if (ch === "/" && next === "*") {
|
|
858
|
+
let commentLen = 2;
|
|
859
|
+
let j = i + 2;
|
|
860
|
+
while (j < len) {
|
|
861
|
+
if (content[j] === "*" && j + 1 < len && content[j + 1] === "/") {
|
|
862
|
+
commentLen = j + 2 - i;
|
|
863
|
+
break;
|
|
864
|
+
}
|
|
865
|
+
j++;
|
|
866
|
+
}
|
|
867
|
+
const commentText = content.slice(i, i + commentLen);
|
|
868
|
+
result += commentText.replace(/[^\n]/g, " ");
|
|
869
|
+
i += commentLen;
|
|
870
|
+
continue;
|
|
871
|
+
}
|
|
872
|
+
result += ch;
|
|
873
|
+
i++;
|
|
874
|
+
}
|
|
875
|
+
return result;
|
|
876
|
+
}
|
|
877
|
+
function stripHtmlEntities(line) {
|
|
878
|
+
return line.replace(HTML_ENTITY_RE, "");
|
|
879
|
+
}
|
|
880
|
+
function findHexLiterals(line) {
|
|
881
|
+
const cleaned = stripHtmlEntities(line);
|
|
882
|
+
const matches = [];
|
|
883
|
+
let m;
|
|
884
|
+
HEX_RE.lastIndex = 0;
|
|
885
|
+
while ((m = HEX_RE.exec(cleaned)) !== null) {
|
|
886
|
+
const digits = m[2];
|
|
887
|
+
if (digits.length <= 4 && !HEX_LETTER_RE.test(digits)) continue;
|
|
888
|
+
const literal = `#${digits}`;
|
|
889
|
+
const idx = m.index + m[1].length;
|
|
890
|
+
matches.push({ literal, column: idx + 1 });
|
|
891
|
+
}
|
|
892
|
+
return matches;
|
|
893
|
+
}
|
|
894
|
+
function findColorFunctions(line) {
|
|
895
|
+
const cleaned = stripHtmlEntities(line);
|
|
896
|
+
const matches = [];
|
|
897
|
+
let m;
|
|
898
|
+
COLOR_FN_RE.lastIndex = 0;
|
|
899
|
+
while ((m = COLOR_FN_RE.exec(cleaned)) !== null) {
|
|
900
|
+
matches.push({ literal: m[0], column: m.index + 1 });
|
|
901
|
+
}
|
|
902
|
+
return matches;
|
|
903
|
+
}
|
|
904
|
+
var LINE_COMMENT_EXTS, HTML_ENTITY_RE, HEX_RE, HEX_LETTER_RE, COLOR_FN_RE;
|
|
905
|
+
var init_color_literals = __esm({
|
|
906
|
+
"../../scripts/lib/color-literals.mjs"() {
|
|
907
|
+
LINE_COMMENT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".jsx", ".js", ".mjs", ".cjs", ".scss", ".less"]);
|
|
908
|
+
HTML_ENTITY_RE = /&#\d+;/g;
|
|
909
|
+
HEX_RE = /(^|[^\w&])#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b/g;
|
|
910
|
+
HEX_LETTER_RE = /[a-fA-F]/;
|
|
911
|
+
COLOR_FN_RE = /\b(rgba?|hsla?)\(\s*[\d.][^)\n]*\)?/gi;
|
|
912
|
+
}
|
|
913
|
+
});
|
|
914
|
+
function scanFiles(root, config) {
|
|
915
|
+
const extensions = new Set(config.extensions ?? DEFAULT_EXTENSIONS);
|
|
916
|
+
const ignored = globMatcher([...DEFAULT_IGNORE, ...config.ignore ?? []]);
|
|
917
|
+
const files = [];
|
|
918
|
+
const seen = /* @__PURE__ */ new Set();
|
|
919
|
+
const visit = (abs) => {
|
|
920
|
+
const rel = toPosix(path3.relative(root, abs));
|
|
921
|
+
if (seen.has(rel) || ignored(rel)) return;
|
|
922
|
+
const ext = path3.extname(abs);
|
|
923
|
+
if (!extensions.has(ext)) return;
|
|
924
|
+
if (statSync(abs).size > MAX_FILE_BYTES) return;
|
|
925
|
+
seen.add(rel);
|
|
926
|
+
const text = readFileSync(abs, "utf8");
|
|
927
|
+
files.push({ path: rel, absolutePath: abs, ext, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(ext)) });
|
|
928
|
+
};
|
|
929
|
+
const walk = (dir) => {
|
|
930
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
931
|
+
if (entry.isDirectory()) {
|
|
932
|
+
if (!SKIP_DIRS.has(entry.name)) walk(path3.join(dir, entry.name));
|
|
933
|
+
} else if (entry.isFile()) {
|
|
934
|
+
visit(path3.join(dir, entry.name));
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
};
|
|
938
|
+
for (const src of config.src ?? DEFAULT_SRC) {
|
|
939
|
+
const abs = path3.resolve(root, src);
|
|
940
|
+
if (!existsSync(abs)) continue;
|
|
941
|
+
if (statSync(abs).isDirectory()) walk(abs);
|
|
942
|
+
else visit(abs);
|
|
943
|
+
}
|
|
944
|
+
return files;
|
|
945
|
+
}
|
|
946
|
+
function lineAt(text, index) {
|
|
947
|
+
let line = 1;
|
|
948
|
+
for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
|
|
949
|
+
return line;
|
|
950
|
+
}
|
|
951
|
+
var DEFAULT_SRC, DEFAULT_EXTENSIONS, DEFAULT_IGNORE, SKIP_DIRS, MAX_FILE_BYTES, toPosix;
|
|
952
|
+
var init_scan = __esm({
|
|
953
|
+
"src/doctor/scan.ts"() {
|
|
954
|
+
init_color_literals();
|
|
955
|
+
init_glob();
|
|
956
|
+
DEFAULT_SRC = ["src"];
|
|
957
|
+
DEFAULT_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".css"];
|
|
958
|
+
DEFAULT_IGNORE = [
|
|
959
|
+
"**/*.d.ts",
|
|
960
|
+
"**/*.gen.*",
|
|
961
|
+
"**/*.test.*",
|
|
962
|
+
"**/*.spec.*",
|
|
963
|
+
"**/__tests__/**",
|
|
964
|
+
"**/__fixtures__/**",
|
|
965
|
+
"**/__mocks__/**"
|
|
966
|
+
];
|
|
967
|
+
SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
|
|
968
|
+
MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
969
|
+
toPosix = (p) => p.split(path3.sep).join("/");
|
|
970
|
+
}
|
|
971
|
+
});
|
|
972
|
+
function parseRulesMarkdown(markdown) {
|
|
973
|
+
const rules = [];
|
|
974
|
+
let current = null;
|
|
975
|
+
for (const line of markdown.split("\n")) {
|
|
976
|
+
const heading = line.match(/^###\s+([A-Za-z0-9_-]+)\s*$/);
|
|
977
|
+
if (heading) {
|
|
978
|
+
current = { id: heading[1] };
|
|
979
|
+
rules.push(current);
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
982
|
+
if (/^#{1,2}\s/.test(line)) {
|
|
983
|
+
current = null;
|
|
984
|
+
continue;
|
|
985
|
+
}
|
|
986
|
+
const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message):\s*(.*)$/);
|
|
987
|
+
if (!current || !kv) continue;
|
|
988
|
+
const [, key, raw] = kv;
|
|
989
|
+
const value = raw.trim();
|
|
990
|
+
if (key === "files" || key === "exclude") current[key] = value.split(",").map((s) => s.trim()).filter(Boolean);
|
|
991
|
+
else if (key === "level") current.level = value;
|
|
992
|
+
else current[key] = value;
|
|
993
|
+
}
|
|
994
|
+
return rules;
|
|
995
|
+
}
|
|
996
|
+
function toRegExp(source, flags = "") {
|
|
997
|
+
if (source.startsWith("(?i)")) return new RegExp(source.slice(4), flags + "i");
|
|
998
|
+
return new RegExp(source, flags);
|
|
999
|
+
}
|
|
1000
|
+
function compilePatternRules(rules, source) {
|
|
1001
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1002
|
+
const out = [];
|
|
1003
|
+
for (const rule of rules) {
|
|
1004
|
+
if (ids.has(rule.id)) throw new DoctorConfigError(`${source}: rule "${rule.id}" is defined twice`);
|
|
1005
|
+
ids.add(rule.id);
|
|
1006
|
+
const level = rule.level ?? "error";
|
|
1007
|
+
if (!["error", "warn", "guide"].includes(level)) {
|
|
1008
|
+
throw new DoctorConfigError(`${source}: rule "${rule.id}" has level "${level}" (use error, warn or guide)`);
|
|
1009
|
+
}
|
|
1010
|
+
if (level === "guide") continue;
|
|
1011
|
+
if (!rule.files?.length) throw new DoctorConfigError(`${source}: rule "${rule.id}" needs "files" (or level: guide)`);
|
|
1012
|
+
if (!rule.forbid && !rule.require && !rule.path) {
|
|
1013
|
+
throw new DoctorConfigError(`${source}: rule "${rule.id}" needs forbid, require or path (or level: guide)`);
|
|
1014
|
+
}
|
|
1015
|
+
try {
|
|
1016
|
+
out.push({
|
|
1017
|
+
rule,
|
|
1018
|
+
level,
|
|
1019
|
+
includes: globMatcher(rule.files),
|
|
1020
|
+
excludes: globMatcher(rule.exclude),
|
|
1021
|
+
forbid: rule.forbid ? toRegExp(rule.forbid, "m") : void 0,
|
|
1022
|
+
require: rule.require ? toRegExp(rule.require, "m") : void 0,
|
|
1023
|
+
path: rule.path ? toRegExp(rule.path) : void 0
|
|
1024
|
+
});
|
|
1025
|
+
} catch (err) {
|
|
1026
|
+
throw new DoctorConfigError(`${source}: rule "${rule.id}" has an invalid pattern: ${err.message}`);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
return out;
|
|
1030
|
+
}
|
|
1031
|
+
function loadPatternRules(root, patterns, rulesDoc) {
|
|
1032
|
+
const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
|
|
1033
|
+
let all = compiled;
|
|
1034
|
+
if (rulesDoc) {
|
|
1035
|
+
const file = path3.resolve(root, rulesDoc);
|
|
1036
|
+
if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
|
|
1037
|
+
const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
|
|
1038
|
+
const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
|
|
1039
|
+
if (clash) throw new DoctorConfigError(`rule "${clash.rule.id}" is defined in both doctor.patterns and ${rulesDoc}`);
|
|
1040
|
+
all = [...compiled, ...fromDoc];
|
|
1041
|
+
}
|
|
1042
|
+
if (all.length === 0) return null;
|
|
1043
|
+
return {
|
|
1044
|
+
count: all.length,
|
|
1045
|
+
plugin: {
|
|
1046
|
+
name: "patterns",
|
|
1047
|
+
check(ctx) {
|
|
1048
|
+
for (const r of all) {
|
|
1049
|
+
const message = r.rule.message ?? "breaks a design rule";
|
|
1050
|
+
for (const file of ctx.files) {
|
|
1051
|
+
if (!r.includes(file.path) || r.excludes(file.path)) continue;
|
|
1052
|
+
const report = (line) => ctx.report({ rule: r.rule.id, level: r.level, file: file.path, line, message });
|
|
1053
|
+
if (r.path && !r.path.test(file.path)) report(0);
|
|
1054
|
+
if (r.require && !r.require.test(file.code)) report(0);
|
|
1055
|
+
if (r.forbid) {
|
|
1056
|
+
const m = r.forbid.exec(file.code);
|
|
1057
|
+
if (m) report(lineAt(file.code, m.index));
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
var init_patterns = __esm({
|
|
1066
|
+
"src/doctor/patterns.ts"() {
|
|
1067
|
+
init_config();
|
|
1068
|
+
init_glob();
|
|
1069
|
+
init_scan();
|
|
1070
|
+
}
|
|
1071
|
+
});
|
|
1072
|
+
function defineDoctorPlugin(plugin) {
|
|
1073
|
+
return plugin;
|
|
1074
|
+
}
|
|
1075
|
+
async function loadPlugins(specs, configDir) {
|
|
1076
|
+
const plugins = [];
|
|
1077
|
+
for (const spec of specs ?? []) {
|
|
1078
|
+
const [id, options] = typeof spec === "string" ? [spec, void 0] : spec;
|
|
1079
|
+
const file = resolvePlugin(id, configDir);
|
|
1080
|
+
const url = `${pathToFileURL(file).href}?mtime=${statSync(file).mtimeMs}`;
|
|
1081
|
+
let mod;
|
|
1082
|
+
try {
|
|
1083
|
+
mod = await import(url);
|
|
1084
|
+
} catch (err) {
|
|
1085
|
+
throw new DoctorConfigError(`doctor.plugins: could not load ${id}: ${err.message}`);
|
|
1086
|
+
}
|
|
1087
|
+
let value = mod.default;
|
|
1088
|
+
if (typeof value === "function") value = await value(options);
|
|
1089
|
+
const list = Array.isArray(value) ? value : [value];
|
|
1090
|
+
for (const p of list) {
|
|
1091
|
+
if (!p || typeof p !== "object" || typeof p.check !== "function" || typeof p.name !== "string") {
|
|
1092
|
+
throw new DoctorConfigError(`doctor.plugins: ${id} must default-export { name, check(context) } (or an array, or a factory returning one)`);
|
|
1093
|
+
}
|
|
1094
|
+
plugins.push(p);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
return plugins;
|
|
1098
|
+
}
|
|
1099
|
+
function resolvePlugin(id, configDir) {
|
|
1100
|
+
try {
|
|
1101
|
+
if (id.startsWith(".") || path3.isAbsolute(id)) return resolveFrom(path3.resolve(configDir, id), configDir);
|
|
1102
|
+
return resolveFrom(id, configDir);
|
|
1103
|
+
} catch {
|
|
1104
|
+
throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
function resolveFrom(id, from) {
|
|
1108
|
+
return createRequire(path3.join(from, "noop.js")).resolve(id);
|
|
1109
|
+
}
|
|
1110
|
+
var init_plugins = __esm({
|
|
1111
|
+
"src/doctor/plugins.ts"() {
|
|
1112
|
+
init_config();
|
|
1113
|
+
}
|
|
1114
|
+
});
|
|
1115
|
+
function importSpecifiers(file) {
|
|
1116
|
+
const out = [];
|
|
1117
|
+
const lines = file.code.split("\n");
|
|
1118
|
+
const re = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|@import\s+)["']([^"']+)["']/g;
|
|
1119
|
+
lines.forEach((text, i) => {
|
|
1120
|
+
for (const m of text.matchAll(re)) out.push({ specifier: m[1], line: i + 1 });
|
|
1121
|
+
});
|
|
1122
|
+
return out;
|
|
1123
|
+
}
|
|
1124
|
+
function checkProjectLayout(ctx) {
|
|
1125
|
+
for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
|
|
1126
|
+
if (existsSync(path3.join(ctx.root, dir))) {
|
|
1127
|
+
ctx.report({
|
|
1128
|
+
rule: "local-primitives",
|
|
1129
|
+
file: dir,
|
|
1130
|
+
subject: dir,
|
|
1131
|
+
message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} (or extend it upstream)`
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
for (const file of STARTER_LEFTOVERS) {
|
|
1136
|
+
if (existsSync(path3.join(ctx.root, file))) {
|
|
1137
|
+
ctx.report({
|
|
1138
|
+
rule: "starter-leftover",
|
|
1139
|
+
level: "warn",
|
|
1140
|
+
file,
|
|
1141
|
+
subject: file,
|
|
1142
|
+
message: `is a starter leftover; Genesis ships cn and owns the components`
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
function checkImports(ctx) {
|
|
1148
|
+
const ui = ctx.genesis.uiPackage;
|
|
1149
|
+
const forbidden = [
|
|
1150
|
+
[/^@radix-ui\//, `imports Radix directly; use the Genesis wrapper from ${ui}`],
|
|
1151
|
+
[/^(?:[@~#]\/|\.{1,2}\/)(?:.*\/)?components\/ui(?:\/|$)/, `imports a local UI primitive; use ${ui}`],
|
|
1152
|
+
[/^[@~#]\/lib\/utils$/, `imports the starter's utils; use cn from ${ui}`],
|
|
1153
|
+
...Object.entries(ctx.config.forbiddenImports ?? {}).map(([re, msg]) => [new RegExp(re), msg])
|
|
1154
|
+
];
|
|
1155
|
+
for (const file of ctx.files) {
|
|
1156
|
+
if (!SCRIPT_EXTS.has(file.ext)) continue;
|
|
1157
|
+
for (const { specifier, line } of importSpecifiers(file)) {
|
|
1158
|
+
const hit = forbidden.find(([re]) => re.test(specifier));
|
|
1159
|
+
if (hit) ctx.report({ rule: "forbidden-import", file: file.path, line, subject: specifier, message: `${hit[1]} ('${specifier}')` });
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
function checkRawTags(ctx) {
|
|
1164
|
+
const tags = [...ctx.genesis.rawTags].map(([tag, component]) => [tag, component, new RegExp(`<${tag}(?=[\\s>/]|$)`)]);
|
|
1165
|
+
if (tags.length === 0) return;
|
|
1166
|
+
for (const file of ctx.files) {
|
|
1167
|
+
if (!JSX_EXTS.has(file.ext)) continue;
|
|
1168
|
+
file.code.split("\n").forEach((text, i) => {
|
|
1169
|
+
for (const [tag, component, re] of tags) {
|
|
1170
|
+
if (re.test(text)) {
|
|
1171
|
+
ctx.report({ rule: "raw-tag", file: file.path, line: i + 1, subject: tag, message: `renders a raw <${tag}>; use Genesis ${component}` });
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
function checkColors(ctx) {
|
|
1178
|
+
const palette = new RegExp(
|
|
1179
|
+
`(?<![\\w-])(?:${COLOR_UTILITIES})-(?:${ctx.genesis.palette.join("|")})(?:-\\d{2,3})?(?:\\/\\d{1,3})?(?![\\w-])`,
|
|
1180
|
+
"g"
|
|
1181
|
+
);
|
|
1182
|
+
for (const file of ctx.files) {
|
|
1183
|
+
file.code.split("\n").forEach((text, i) => {
|
|
1184
|
+
const line = i + 1;
|
|
1185
|
+
for (const m of text.matchAll(palette)) {
|
|
1186
|
+
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)` });
|
|
1187
|
+
}
|
|
1188
|
+
const arbitrary = [];
|
|
1189
|
+
for (const m of text.matchAll(ARBITRARY_COLOR_RE)) {
|
|
1190
|
+
arbitrary.push([m.index, m.index + m[0].length]);
|
|
1191
|
+
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` });
|
|
1192
|
+
}
|
|
1193
|
+
for (const hit of [...findHexLiterals(text), ...findColorFunctions(text)]) {
|
|
1194
|
+
const at = hit.column - 1;
|
|
1195
|
+
if (arbitrary.some(([a, b]) => at >= a && at < b)) continue;
|
|
1196
|
+
ctx.report({ rule: "raw-color", file: file.path, line, subject: hit.literal, message: `hardcodes the color ${hit.literal}; color values come from Genesis tokens` });
|
|
1197
|
+
}
|
|
1198
|
+
});
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
function checkTokens(ctx) {
|
|
1202
|
+
const defined = new Set(ctx.genesis.tokens);
|
|
1203
|
+
const isTokenFile = ctx.config.tokenFiles ? globMatcher(ctx.config.tokenFiles) : (p) => p.endsWith(".css");
|
|
1204
|
+
for (const file of ctx.files) {
|
|
1205
|
+
if (isTokenFile(file.path)) for (const t of declaredTokens(file.code)) defined.add(t);
|
|
1206
|
+
for (const m of file.code.matchAll(/["'](--[A-Za-z0-9_-]+)["']\s*:/g)) defined.add(m[1]);
|
|
1207
|
+
}
|
|
1208
|
+
for (const pattern of ctx.config.tokenFiles ?? []) {
|
|
1209
|
+
if (/[*?]/.test(pattern)) continue;
|
|
1210
|
+
const abs = path3.join(ctx.root, pattern);
|
|
1211
|
+
if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
|
|
1212
|
+
for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
const ignorePrefixes = ctx.config.ignoreTokenPrefixes ?? DEFAULT_IGNORE_TOKEN_PREFIXES;
|
|
1216
|
+
for (const file of ctx.files) {
|
|
1217
|
+
file.code.split("\n").forEach((text, i) => {
|
|
1218
|
+
for (const m of text.matchAll(/var\(\s*(--[A-Za-z0-9_-]+)/g)) {
|
|
1219
|
+
const token = m[1];
|
|
1220
|
+
if (defined.has(token) || ignorePrefixes.some((p) => token.startsWith(p))) continue;
|
|
1221
|
+
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` });
|
|
1222
|
+
}
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
function checkShadowedExports(ctx) {
|
|
1227
|
+
const re = /\bexport\s+(?:default\s+)?(?:declare\s+)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([A-Z][\w$]*)/g;
|
|
1228
|
+
for (const file of ctx.files) {
|
|
1229
|
+
if (!SCRIPT_EXTS.has(file.ext)) continue;
|
|
1230
|
+
file.code.split("\n").forEach((text, i) => {
|
|
1231
|
+
for (const m of text.matchAll(re)) {
|
|
1232
|
+
if (!ctx.genesis.values.has(m[1])) continue;
|
|
1233
|
+
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]}` });
|
|
1234
|
+
}
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
function unusedComponents(ctx) {
|
|
1239
|
+
const used = /* @__PURE__ */ new Set();
|
|
1240
|
+
const pkg = ctx.genesis.uiPackage.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
|
|
1241
|
+
const re = new RegExp(`\\b(?:import|export)\\s+(?:type\\s+)?(?:[\\w$]+\\s*,\\s*)?\\{([^}]*)\\}\\s*from\\s*["']${pkg}(?:/[^"']*)?["']`, "g");
|
|
1242
|
+
for (const file of ctx.files) {
|
|
1243
|
+
for (const m of file.code.matchAll(re)) {
|
|
1244
|
+
for (const part of m[1].split(",")) {
|
|
1245
|
+
const name = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/)[0]?.trim();
|
|
1246
|
+
if (name) used.add(name);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
return ctx.genesis.components.filter((c) => !used.has(c));
|
|
1251
|
+
}
|
|
1252
|
+
var BUILTIN_RULES, DEFAULT_LOCAL_PRIMITIVE_DIRS, STARTER_LEFTOVERS, DEFAULT_IGNORE_TOKEN_PREFIXES, JSX_EXTS, SCRIPT_EXTS, COLOR_UTILITIES, ARBITRARY_COLOR_RE;
|
|
1253
|
+
var init_rules = __esm({
|
|
1254
|
+
"src/doctor/rules.ts"() {
|
|
1255
|
+
init_color_literals();
|
|
1256
|
+
init_glob();
|
|
1257
|
+
init_genesis();
|
|
1258
|
+
BUILTIN_RULES = [
|
|
1259
|
+
"local-primitives",
|
|
1260
|
+
"starter-leftover",
|
|
1261
|
+
"forbidden-import",
|
|
1262
|
+
"raw-tag",
|
|
1263
|
+
"palette-color",
|
|
1264
|
+
"arbitrary-color",
|
|
1265
|
+
"raw-color",
|
|
1266
|
+
"undefined-token",
|
|
1267
|
+
"shadowed-export"
|
|
1268
|
+
];
|
|
1269
|
+
DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
|
|
1270
|
+
STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
|
|
1271
|
+
DEFAULT_IGNORE_TOKEN_PREFIXES = ["--tw-", "--radix-"];
|
|
1272
|
+
JSX_EXTS = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
|
|
1273
|
+
SCRIPT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
|
|
1274
|
+
COLOR_UTILITIES = "bg|text|border(?:-[xytrbls])?|ring|ring-offset|fill|stroke|from|to|via|outline|divide|decoration|shadow|accent|caret|placeholder";
|
|
1275
|
+
ARBITRARY_COLOR_RE = /(?<![\w-])[a-z][a-z-]*-\[(?:#|(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb|color)\()[^\]]*\]/g;
|
|
1276
|
+
}
|
|
1277
|
+
});
|
|
1278
|
+
|
|
1279
|
+
// src/doctor/index.ts
|
|
1280
|
+
var doctor_exports = {};
|
|
1281
|
+
__export(doctor_exports, {
|
|
1282
|
+
BUILTIN_RULES: () => BUILTIN_RULES,
|
|
1283
|
+
DoctorConfigError: () => DoctorConfigError,
|
|
1284
|
+
defineDoctorPlugin: () => defineDoctorPlugin,
|
|
1285
|
+
findPackageDir: () => findPackageDir,
|
|
1286
|
+
formatReport: () => formatReport,
|
|
1287
|
+
genesisSummary: () => genesisSummary,
|
|
1288
|
+
globToRegExp: () => globToRegExp,
|
|
1289
|
+
loadConfig: () => loadConfig,
|
|
1290
|
+
loadGenesis: () => loadGenesis,
|
|
1291
|
+
parseExportNames: () => parseExportNames,
|
|
1292
|
+
parseRulesMarkdown: () => parseRulesMarkdown,
|
|
1293
|
+
runDoctor: () => runDoctor,
|
|
1294
|
+
toJson: () => toJson,
|
|
1295
|
+
validateConfig: () => validateConfig
|
|
1296
|
+
});
|
|
1297
|
+
async function runDoctor(options = {}) {
|
|
1298
|
+
const root = path3.resolve(options.root ?? process.cwd());
|
|
1299
|
+
const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
|
|
1300
|
+
const config = loaded.config;
|
|
1301
|
+
const genesis = options.genesis ?? loadGenesis(root, config);
|
|
1302
|
+
const files = scanFiles(root, config);
|
|
1303
|
+
const patterns = loadPatternRules(root, config.patterns, config.rulesDoc);
|
|
1304
|
+
const plugins = await loadPlugins(config.plugins, loaded.dir);
|
|
1305
|
+
const builtinIds = new Set(BUILTIN_RULES);
|
|
1306
|
+
for (const p of config.patterns ?? []) {
|
|
1307
|
+
if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
|
|
1308
|
+
}
|
|
1309
|
+
const raw = [];
|
|
1310
|
+
const ctx = { root, files, genesis, config, report: (f) => raw.push(f) };
|
|
1311
|
+
const builtins = [
|
|
1312
|
+
{ name: "layout", check: checkProjectLayout },
|
|
1313
|
+
{ name: "imports", check: checkImports },
|
|
1314
|
+
{ name: "raw-tags", check: checkRawTags },
|
|
1315
|
+
{ name: "colors", check: checkColors },
|
|
1316
|
+
{ name: "tokens", check: checkTokens },
|
|
1317
|
+
{ name: "shadowed-exports", check: checkShadowedExports }
|
|
1318
|
+
];
|
|
1319
|
+
for (const plugin of [...builtins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
|
|
1320
|
+
try {
|
|
1321
|
+
await plugin.check(ctx);
|
|
1322
|
+
} catch (err) {
|
|
1323
|
+
if (err instanceof DoctorConfigError) throw err;
|
|
1324
|
+
raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
if (options.build) {
|
|
1328
|
+
const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
|
|
1329
|
+
if (failure) raw.push(failure);
|
|
1330
|
+
}
|
|
1331
|
+
const findings = applyConfig(raw, config);
|
|
1332
|
+
const errors = findings.filter((f) => f.level === "error").length;
|
|
1333
|
+
const warnings = findings.length - errors;
|
|
1334
|
+
return {
|
|
1335
|
+
ok: errors === 0 && !(options.strict && warnings > 0),
|
|
1336
|
+
root,
|
|
1337
|
+
genesis,
|
|
1338
|
+
findings,
|
|
1339
|
+
unused: unusedComponents(ctx),
|
|
1340
|
+
ruleCount: (patterns?.count ?? 0) + plugins.length,
|
|
1341
|
+
errors,
|
|
1342
|
+
warnings
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
function applyConfig(raw, config) {
|
|
1346
|
+
const allow = (config.allow ?? []).map((entry) => ({ entry, file: entry.file ? globToRegExp(entry.file) : null, used: false }));
|
|
1347
|
+
const out = [];
|
|
1348
|
+
for (const input of raw) {
|
|
1349
|
+
const setting = config.rules?.[input.rule];
|
|
1350
|
+
if (setting === "off") continue;
|
|
1351
|
+
const finding = {
|
|
1352
|
+
rule: input.rule,
|
|
1353
|
+
level: setting ?? input.level ?? "error",
|
|
1354
|
+
file: input.file,
|
|
1355
|
+
line: input.line ?? 0,
|
|
1356
|
+
message: input.message,
|
|
1357
|
+
...input.subject !== void 0 ? { subject: input.subject } : {}
|
|
1358
|
+
};
|
|
1359
|
+
const exception = allow.find(
|
|
1360
|
+
(a) => a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
|
|
1361
|
+
);
|
|
1362
|
+
if (exception) {
|
|
1363
|
+
exception.used = true;
|
|
1364
|
+
continue;
|
|
1365
|
+
}
|
|
1366
|
+
out.push(finding);
|
|
1367
|
+
}
|
|
1368
|
+
const staleLevel = config.rules?.["stale-exception"];
|
|
1369
|
+
for (const a of allow) {
|
|
1370
|
+
if (staleLevel === "off" || a.used || config.rules?.[a.entry.rule] === "off") continue;
|
|
1371
|
+
out.push({
|
|
1372
|
+
rule: "stale-exception",
|
|
1373
|
+
level: staleLevel ?? "warn",
|
|
1374
|
+
file: a.entry.file ?? "genesis config",
|
|
1375
|
+
line: 0,
|
|
1376
|
+
subject: a.entry.rule,
|
|
1377
|
+
message: `the allow entry for ${a.entry.rule}${a.entry.match ? ` (${a.entry.match})` : ""} no longer matches anything; remove it`
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
return out.sort((x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule));
|
|
1381
|
+
}
|
|
1382
|
+
function formatReport(result) {
|
|
1383
|
+
const g = result.genesis;
|
|
1384
|
+
const lines = [
|
|
1385
|
+
`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"}`
|
|
1386
|
+
];
|
|
1387
|
+
for (const f of result.findings) {
|
|
1388
|
+
lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
|
|
1389
|
+
}
|
|
1390
|
+
lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
|
|
1391
|
+
lines.push(result.ok ? `PASS (${result.warnings} warnings)` : `FAIL (${result.errors} errors, ${result.warnings} warnings)`);
|
|
1392
|
+
return lines.join("\n");
|
|
1393
|
+
}
|
|
1394
|
+
function toJson(result) {
|
|
1395
|
+
return {
|
|
1396
|
+
ok: result.ok,
|
|
1397
|
+
genesis: `${result.genesis.uiPackage}@${result.genesis.uiVersion}`,
|
|
1398
|
+
errors: result.errors,
|
|
1399
|
+
warnings: result.warnings,
|
|
1400
|
+
findings: result.findings,
|
|
1401
|
+
unused: result.unused
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
function genesisSummary(g) {
|
|
1405
|
+
return {
|
|
1406
|
+
package: `${g.uiPackage}@${g.uiVersion}`,
|
|
1407
|
+
components: g.components,
|
|
1408
|
+
tokens: [...g.tokens].sort(),
|
|
1409
|
+
rawTags: Object.fromEntries(g.rawTags),
|
|
1410
|
+
palette: g.palette
|
|
1411
|
+
};
|
|
1412
|
+
}
|
|
1413
|
+
var init_doctor = __esm({
|
|
1414
|
+
"src/doctor/index.ts"() {
|
|
1415
|
+
init_build();
|
|
1416
|
+
init_config();
|
|
1417
|
+
init_glob();
|
|
1418
|
+
init_genesis();
|
|
1419
|
+
init_patterns();
|
|
1420
|
+
init_plugins();
|
|
1421
|
+
init_rules();
|
|
1422
|
+
init_scan();
|
|
1423
|
+
init_config();
|
|
1424
|
+
init_genesis();
|
|
1425
|
+
init_patterns();
|
|
1426
|
+
init_plugins();
|
|
1427
|
+
init_rules();
|
|
1428
|
+
init_glob();
|
|
1429
|
+
}
|
|
1430
|
+
});
|
|
1431
|
+
|
|
1432
|
+
// src/features.ts
|
|
1433
|
+
var features_exports = {};
|
|
1434
|
+
__export(features_exports, {
|
|
1435
|
+
formatFeature: () => formatFeature,
|
|
1436
|
+
gatherPrEvidence: () => gatherPrEvidence,
|
|
1437
|
+
loadRegistry: () => loadRegistry,
|
|
1438
|
+
runFeaturesBuild: () => runFeaturesBuild,
|
|
1439
|
+
runFeaturesCheck: () => runFeaturesCheck,
|
|
1440
|
+
runFeaturesFind: () => runFeaturesFind
|
|
1441
|
+
});
|
|
1442
|
+
function isObject2(value) {
|
|
1443
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1444
|
+
}
|
|
1445
|
+
function settings(root, options) {
|
|
1446
|
+
let fromPackage = {};
|
|
1447
|
+
try {
|
|
1448
|
+
const pkg = JSON.parse(readFileSync(path3.join(root, "package.json"), "utf-8"));
|
|
1449
|
+
if (isObject2(pkg.genesisFeatures)) fromPackage = pkg.genesisFeatures;
|
|
1450
|
+
} catch {
|
|
1451
|
+
}
|
|
1452
|
+
const given = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== void 0));
|
|
1453
|
+
return { ...fromPackage, ...given };
|
|
1454
|
+
}
|
|
1455
|
+
async function loadRegistry(input) {
|
|
1456
|
+
const root = path3.resolve(input.dir);
|
|
1457
|
+
const options = settings(root, input);
|
|
1458
|
+
const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path3.join(root, p)));
|
|
1459
|
+
if (!registry || !existsSync(path3.join(root, registry))) {
|
|
1460
|
+
throw new Error(`No feature registry found. Looked for ${options.registry ?? DEFAULT_REGISTRIES.join(" and ")}; pass --registry.`);
|
|
1461
|
+
}
|
|
1462
|
+
const jiti = createJiti(path3.join(root, "package.json"), { moduleCache: false });
|
|
1463
|
+
const load = async (file) => await jiti.import(path3.join(root, file));
|
|
1464
|
+
const mod = await load(registry);
|
|
1465
|
+
const features2 = mod.features ?? mod.default;
|
|
1466
|
+
if (!isObject2(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
|
|
1467
|
+
const flags = options.flagsFile ? (await load(options.flagsFile)).flags : mod.flags;
|
|
1468
|
+
if (flags !== void 0 && !isObject2(flags)) {
|
|
1469
|
+
throw new Error(`${options.flagsFile ?? registry}'s \`flags\` export must be an object (from defineFlags).`);
|
|
1470
|
+
}
|
|
1471
|
+
const { dir: _dir, registry: _registry, flagsFile: _flagsFile, prs: _prs, gh: _gh, ...rest } = options;
|
|
1472
|
+
const project = {
|
|
1473
|
+
...rest,
|
|
1474
|
+
root,
|
|
1475
|
+
source: options.source ?? registry.split(path3.sep).join("/"),
|
|
1476
|
+
features: features2,
|
|
1477
|
+
flags
|
|
1478
|
+
};
|
|
1479
|
+
return project;
|
|
1480
|
+
}
|
|
1481
|
+
async function runFeaturesBuild(options) {
|
|
1482
|
+
return buildFeatureOutputs(await loadRegistry(options));
|
|
1483
|
+
}
|
|
1484
|
+
function ghFailure(error) {
|
|
1485
|
+
const e = error;
|
|
1486
|
+
if (e?.code === "ENOENT") return "gh is not installed";
|
|
1487
|
+
if (e?.code === "ETIMEDOUT" || e?.signal === "SIGTERM") return "gh timed out";
|
|
1488
|
+
const stderr = e?.stderr?.toString().trim();
|
|
1489
|
+
return (stderr || String(error instanceof Error ? error.message : error)).split("\n")[0];
|
|
1490
|
+
}
|
|
1491
|
+
function gatherPrEvidence(project, gh = runGh) {
|
|
1492
|
+
const prs = {};
|
|
1493
|
+
const names = Object.entries(project.features).filter(([, f]) => f.status === "planned").flatMap(([id, f]) => [id, ...f.aliases ?? []]);
|
|
1494
|
+
for (let i = 0; i < names.length; i += LABELS_PER_SEARCH) {
|
|
1495
|
+
const batch = names.slice(i, i + LABELS_PER_SEARCH);
|
|
1496
|
+
const search = `label:${batch.map((n) => `"feature:${n}"`).join(",")}`;
|
|
1497
|
+
try {
|
|
1498
|
+
const out = gh(["pr", "list", "--state", "merged", "--search", search, "--limit", "1000", "--json", "number,title,labels"], project.root);
|
|
1499
|
+
for (const { number, title, labels } of JSON.parse(out)) {
|
|
1500
|
+
for (const { name: label } of labels) {
|
|
1501
|
+
const name = label.startsWith("feature:") ? label.slice("feature:".length) : null;
|
|
1502
|
+
if (name && batch.includes(name)) (prs[name] ??= []).push({ number, title });
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
} catch (error) {
|
|
1506
|
+
return { prs, warning: `--prs: couldn't read merged PRs with gh (${ghFailure(error)}), so only changesets were checked for shipped work` };
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
return { prs };
|
|
1510
|
+
}
|
|
1511
|
+
async function runFeaturesCheck(options) {
|
|
1512
|
+
const project = await loadRegistry(options);
|
|
1513
|
+
const evidence = options.prs ? gatherPrEvidence(project, options.gh) : void 0;
|
|
1514
|
+
const result = checkFeatureOutputs({ ...project, evidence: evidence && { prs: evidence.prs } });
|
|
1515
|
+
let summary = summarizeCheck(result, project.features);
|
|
1516
|
+
if (evidence?.warning) {
|
|
1517
|
+
result.warnings.push(evidence.warning);
|
|
1518
|
+
summary = `${summarizeCheck(result, project.features)}
|
|
1519
|
+
- ${evidence.warning}.`;
|
|
1520
|
+
}
|
|
1521
|
+
return { ...result, summary };
|
|
1522
|
+
}
|
|
1523
|
+
async function runFeaturesFind(options, term) {
|
|
1524
|
+
const project = await loadRegistry(options);
|
|
1525
|
+
return findFeatures(project.features, term, project.flags);
|
|
1526
|
+
}
|
|
1527
|
+
function formatFeature(r) {
|
|
1528
|
+
const lines = [`${r.id} \u2014 ${r.name} [${r.status}${r.horizon ? `, ${r.horizon}` : ""}] (${r.owner})`, ` ${r.summary}`];
|
|
1529
|
+
if (r.links?.code?.length) lines.push(` code: ${r.links.code.join(", ")}`);
|
|
1530
|
+
if (r.flags.length) lines.push(` flags: ${r.flags.join(", ")}`);
|
|
1531
|
+
if (r.claimedBy) lines.push(` being built by ${r.claimedBy}`);
|
|
1532
|
+
return lines.join("\n");
|
|
1533
|
+
}
|
|
1534
|
+
var DEFAULT_REGISTRIES, runGh, LABELS_PER_SEARCH;
|
|
1535
|
+
var init_features = __esm({
|
|
1536
|
+
"src/features.ts"() {
|
|
1537
|
+
DEFAULT_REGISTRIES = ["src/features.ts", "features.ts"];
|
|
1538
|
+
runGh = (args, cwd) => execFileSync("gh", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 15e3 });
|
|
1539
|
+
LABELS_PER_SEARCH = 10;
|
|
1540
|
+
}
|
|
1541
|
+
});
|
|
332
1542
|
|
|
333
1543
|
// src/studio/wire-route.ts
|
|
334
1544
|
function routeTags(source) {
|
|
@@ -366,8 +1576,8 @@ function routeTags(source) {
|
|
|
366
1576
|
}
|
|
367
1577
|
function wireStudioRoute(source, route, pageImportPath) {
|
|
368
1578
|
const tags = routeTags(source);
|
|
369
|
-
const
|
|
370
|
-
const existing = tags.find((t) => new RegExp(`path=["'](/?${
|
|
1579
|
+
const relative2 = route.replace(/^\//, "");
|
|
1580
|
+
const existing = tags.find((t) => new RegExp(`path=["'](/?${relative2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
|
|
371
1581
|
if (existing) {
|
|
372
1582
|
return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
|
|
373
1583
|
}
|
|
@@ -375,17 +1585,17 @@ function wireStudioRoute(source, route, pageImportPath) {
|
|
|
375
1585
|
const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
|
|
376
1586
|
if (roots.length !== 1) {
|
|
377
1587
|
return {
|
|
378
|
-
skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${
|
|
1588
|
+
skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative2}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
|
|
379
1589
|
};
|
|
380
1590
|
}
|
|
381
1591
|
const layout = roots[0];
|
|
382
1592
|
const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
|
|
383
|
-
if (base && !
|
|
1593
|
+
if (base && !relative2.startsWith(`${base}/`)) {
|
|
384
1594
|
return {
|
|
385
1595
|
skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
|
|
386
1596
|
};
|
|
387
1597
|
}
|
|
388
|
-
const childPath = base ?
|
|
1598
|
+
const childPath = base ? relative2.slice(base.length + 1) : relative2;
|
|
389
1599
|
const guard = GUARD.exec(source)?.[1];
|
|
390
1600
|
const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
|
|
391
1601
|
const before = source.slice(0, layout.close);
|
|
@@ -814,9 +2024,9 @@ async function runScaffold(opts, fs2) {
|
|
|
814
2024
|
function joinPath(...parts) {
|
|
815
2025
|
return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
|
|
816
2026
|
}
|
|
817
|
-
function dirname(
|
|
818
|
-
const idx =
|
|
819
|
-
return idx === -1 ? "." :
|
|
2027
|
+
function dirname(path11) {
|
|
2028
|
+
const idx = path11.lastIndexOf("/");
|
|
2029
|
+
return idx === -1 ? "." : path11.slice(0, idx);
|
|
820
2030
|
}
|
|
821
2031
|
function brandPackageJson(consumer, genesisVersion) {
|
|
822
2032
|
return JSON.stringify(
|
|
@@ -1128,7 +2338,7 @@ program.command("introspect").description("Write a checked-in contract (resource
|
|
|
1128
2338
|
source = `Postgres (${schemas.join(", ")})`;
|
|
1129
2339
|
}
|
|
1130
2340
|
const content = emitContracts2(tables, { source });
|
|
1131
|
-
const target =
|
|
2341
|
+
const target = path3.resolve(opts.out);
|
|
1132
2342
|
if (opts.check) {
|
|
1133
2343
|
const current = await fs.readFile(target, "utf-8").catch(() => null);
|
|
1134
2344
|
if (current !== content) {
|
|
@@ -1141,27 +2351,77 @@ program.command("introspect").description("Write a checked-in contract (resource
|
|
|
1141
2351
|
await fs.writeFile(target, content, "utf-8");
|
|
1142
2352
|
console.log(`\u2714 Wrote ${opts.out}: ${tables.length} tables.`);
|
|
1143
2353
|
});
|
|
2354
|
+
program.command("doctor").description("Check this app against the installed Genesis: components, tokens, imports, colors, plus the app's own rules").option("--strict", "Fail on warnings too", false).option("--json", "Print the report as JSON", false).option("--build", "Also run the app's typecheck and build (doctor.build, or its typecheck/build scripts)", false).option("-c, --config <path>", 'Config file (default: genesis.config.json, then package.json "genesis")').option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--print-genesis", "Print the components, tokens and raw tags read from Genesis, and exit", false).action(async (opts) => {
|
|
2355
|
+
const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
|
|
2356
|
+
const root = path3.resolve(opts.dir);
|
|
2357
|
+
try {
|
|
2358
|
+
if (opts.printGenesis) {
|
|
2359
|
+
const { config } = doctor.loadConfig(root, opts.config);
|
|
2360
|
+
console.log(JSON.stringify(doctor.genesisSummary(doctor.loadGenesis(root, config)), null, 2));
|
|
2361
|
+
return;
|
|
2362
|
+
}
|
|
2363
|
+
const result = await doctor.runDoctor({ root, configPath: opts.config, strict: opts.strict, build: opts.build, quietBuild: opts.json });
|
|
2364
|
+
console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result));
|
|
2365
|
+
process.exitCode = result.ok ? 0 : 1;
|
|
2366
|
+
} catch (err) {
|
|
2367
|
+
if (!(err instanceof doctor.DoctorConfigError)) throw err;
|
|
2368
|
+
if (opts.json) console.log(JSON.stringify({ ok: false, error: err.message }, null, 2));
|
|
2369
|
+
else console.error(`\u2717 ${err.message}`);
|
|
2370
|
+
process.exitCode = 2;
|
|
2371
|
+
}
|
|
2372
|
+
});
|
|
2373
|
+
var features = program.command("features").description('The feature registry: one typed features.ts, everything else generated from it. Settings: package.json "genesisFeatures"');
|
|
2374
|
+
function featureOptions(command) {
|
|
2375
|
+
return command.option("-d, --dir <dir>", "The repo root", process.cwd()).option("-r, --registry <file>", "The registry (default: src/features.ts, then features.ts)").option("--flags-file <file>", "A flags file exporting `flags` (default: the registry's own `flags` export)").option("--agents <file>", "The AGENTS.md that holds the pointer block (default AGENTS.md)").option("--json <file>", "The JSON copy, also the record of every id (default features.json)").option("--command <text>", "How people run this CLI here, named in generated files (default `genesis features`)");
|
|
2376
|
+
}
|
|
2377
|
+
featureOptions(features.command("build").description("Write the AGENTS.md block, features.json, flags.json, the skill and the marketing block")).action(
|
|
2378
|
+
async (opts) => {
|
|
2379
|
+
const { runFeaturesBuild: runFeaturesBuild2 } = await Promise.resolve().then(() => (init_features(), features_exports));
|
|
2380
|
+
const changed = await runFeaturesBuild2(opts);
|
|
2381
|
+
console.log(changed.length ? changed.map((f) => `~ ${f}`).join("\n") : "\u2714 Generated feature files are up to date.");
|
|
2382
|
+
}
|
|
2383
|
+
);
|
|
2384
|
+
featureOptions(features.command("check").description("Errors fail (stale output, missing code paths, flag rules, removed ids, bad tags); warnings don't")).option("--labels <list>", "The PR's labels, comma-separated, to check feature:<id> labels").option("--prs", "Also read merged PRs labelled feature:<id> with gh, to warn about planned features that shipped", false).option("--summary", "Print a short summary and always exit 0 (for a SessionStart hook)", false).action(async (opts) => {
|
|
2385
|
+
const { runFeaturesCheck: runFeaturesCheck2 } = await Promise.resolve().then(() => (init_features(), features_exports));
|
|
2386
|
+
const { summary, labels, ...rest } = opts;
|
|
2387
|
+
const result = await runFeaturesCheck2({ ...rest, labels: labels?.split(",").map((l) => l.trim()).filter(Boolean) });
|
|
2388
|
+
if (summary) {
|
|
2389
|
+
console.log(result.summary);
|
|
2390
|
+
return;
|
|
2391
|
+
}
|
|
2392
|
+
for (const warning of result.warnings) console.warn(`! ${warning}`);
|
|
2393
|
+
for (const error of result.errors) console.error(`\u2717 ${error}`);
|
|
2394
|
+
if (result.ok) console.log(`\u2714 The feature registry and the repo agree${result.warnings.length ? ` (${result.warnings.length} warning${result.warnings.length === 1 ? "" : "s"})` : ""}.`);
|
|
2395
|
+
process.exitCode = result.ok ? 0 : 1;
|
|
2396
|
+
});
|
|
2397
|
+
featureOptions(features.command("find").description("Search features by id, alias, name, summary, flag or code path").argument("<term>", "What to look for")).action(
|
|
2398
|
+
async (term, opts) => {
|
|
2399
|
+
const { runFeaturesFind: runFeaturesFind2, formatFeature: formatFeature2 } = await Promise.resolve().then(() => (init_features(), features_exports));
|
|
2400
|
+
const hits = await runFeaturesFind2(opts, term);
|
|
2401
|
+
console.log(hits.length ? hits.map(formatFeature2).join("\n\n") : `No feature matches "${term}". If this is new work, add it to the registry first.`);
|
|
2402
|
+
}
|
|
2403
|
+
);
|
|
1144
2404
|
var studio = program.command("studio").description("The Genesis Data Studio");
|
|
1145
2405
|
studio.command("init").description("Turn the Data Studio on in this app: a server for every table, a page, and one migration to review").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--host <host>", "next, tanstack-start or supabase-function (default: detected)").option("--route <path>", "Where the page lives", "/admin/data").option("--login-role <name>", "The studio's database login", "genesis_studio_login").option("--force", "Overwrite files that already exist", false).action(async (opts) => {
|
|
1146
2406
|
const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
|
|
1147
|
-
const root =
|
|
1148
|
-
const packageJson = JSON.parse(await fs.readFile(
|
|
1149
|
-
const
|
|
2407
|
+
const root = path3.resolve(opts.dir);
|
|
2408
|
+
const packageJson = JSON.parse(await fs.readFile(path3.join(root, "package.json"), "utf-8").catch(() => "{}"));
|
|
2409
|
+
const existsSync8 = (await import('fs')).existsSync;
|
|
1150
2410
|
const readSync = (await import('fs')).readFileSync;
|
|
1151
|
-
const
|
|
2411
|
+
const readdirSync3 = (await import('fs')).readdirSync;
|
|
1152
2412
|
if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
|
|
1153
2413
|
throw new Error("--host must be next, tanstack-start or supabase-function.");
|
|
1154
2414
|
}
|
|
1155
2415
|
const plan = planStudioInit2(
|
|
1156
2416
|
{
|
|
1157
2417
|
packageJson,
|
|
1158
|
-
exists: (p) =>
|
|
1159
|
-
read: (p) =>
|
|
2418
|
+
exists: (p) => existsSync8(path3.join(root, p)),
|
|
2419
|
+
read: (p) => existsSync8(path3.join(root, p)) ? readSync(path3.join(root, p), "utf-8") : null,
|
|
1160
2420
|
timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
|
|
1161
2421
|
listDeep: (p) => {
|
|
1162
2422
|
const out = [];
|
|
1163
2423
|
const walk = (rel) => {
|
|
1164
|
-
for (const entry of
|
|
2424
|
+
for (const entry of readdirSync3(path3.join(root, rel), { withFileTypes: true })) {
|
|
1165
2425
|
const child = `${rel}/${entry.name}`;
|
|
1166
2426
|
if (entry.isDirectory()) walk(child);
|
|
1167
2427
|
else out.push(child);
|
|
@@ -1175,7 +2435,7 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
|
|
|
1175
2435
|
},
|
|
1176
2436
|
list: (p) => {
|
|
1177
2437
|
try {
|
|
1178
|
-
return
|
|
2438
|
+
return readdirSync3(path3.join(root, p));
|
|
1179
2439
|
} catch {
|
|
1180
2440
|
return [];
|
|
1181
2441
|
}
|
|
@@ -1184,8 +2444,8 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
|
|
|
1184
2444
|
{ host: opts.host, route: opts.route, loginRole: opts.loginRole }
|
|
1185
2445
|
);
|
|
1186
2446
|
for (const file of plan.files) {
|
|
1187
|
-
const target =
|
|
1188
|
-
await fs.mkdir(
|
|
2447
|
+
const target = path3.join(root, file.path);
|
|
2448
|
+
await fs.mkdir(path3.dirname(target), { recursive: true });
|
|
1189
2449
|
if (file.edit) {
|
|
1190
2450
|
await fs.writeFile(target, file.content, "utf-8");
|
|
1191
2451
|
console.log(`~ ${file.path} (${file.edit})`);
|
|
@@ -1196,14 +2456,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
|
|
|
1196
2456
|
console.log(`+ ${file.path} (appended)`);
|
|
1197
2457
|
continue;
|
|
1198
2458
|
}
|
|
1199
|
-
if (
|
|
2459
|
+
if (existsSync8(target) && !opts.force) {
|
|
1200
2460
|
console.log(`= ${file.path} exists; left as it is (--force to replace)`);
|
|
1201
2461
|
continue;
|
|
1202
2462
|
}
|
|
1203
2463
|
await fs.writeFile(target, file.content, "utf-8");
|
|
1204
2464
|
console.log(`+ ${file.path}`);
|
|
1205
2465
|
}
|
|
1206
|
-
const pm =
|
|
2466
|
+
const pm = existsSync8(path3.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync8(path3.join(root, "yarn.lock")) ? "yarn add" : existsSync8(path3.join(root, "bun.lock")) || existsSync8(path3.join(root, "bun.lockb")) ? "bun add" : "npm install";
|
|
1207
2467
|
console.log("");
|
|
1208
2468
|
console.log(`\u2714 The Data Studio is set up for ${{ next: "Next.js", "tanstack-start": "TanStack Start", "supabase-function": "a Supabase Edge Function" }[plan.host]}. To finish:`);
|
|
1209
2469
|
console.log(` 1. ${pm} ${plan.install.join(" ")}`);
|
|
@@ -1256,7 +2516,7 @@ function redactUrl(location) {
|
|
|
1256
2516
|
const url = new URL(location);
|
|
1257
2517
|
return `${url.origin}${url.pathname}`;
|
|
1258
2518
|
} catch {
|
|
1259
|
-
return
|
|
2519
|
+
return path3.basename(location);
|
|
1260
2520
|
}
|
|
1261
2521
|
}
|
|
1262
2522
|
//# sourceMappingURL=cli.js.map
|