@marktiderman/genesis-cli 1.24.0 → 1.26.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/cli.js CHANGED
@@ -1029,6 +1029,7 @@ var init_migrations = __esm({
1029
1029
  var config_exports = {};
1030
1030
  __export(config_exports, {
1031
1031
  DoctorConfigError: () => DoctorConfigError,
1032
+ EXTENSION_REASON_MIN: () => EXTENSION_REASON_MIN,
1032
1033
  GenesisConfigError: () => GenesisConfigError,
1033
1034
  META_RULES: () => META_RULES,
1034
1035
  PRIVACY_DATA_TYPES: () => PRIVACY_DATA_TYPES,
@@ -1264,6 +1265,30 @@ function validateConfig(raw, source = "config") {
1264
1265
  }
1265
1266
  });
1266
1267
  }
1268
+ if (c.extend !== void 0) {
1269
+ if (!Array.isArray(c.extend)) fail(`"extend" must be a list of { rule, file, buildsOn, reason, upstream? }`);
1270
+ const seen = /* @__PURE__ */ new Set();
1271
+ c.extend.forEach((e, i) => {
1272
+ const where2 = `extend[${i}]`;
1273
+ if (!isObject2(e)) return fail(`${where2} must be an object`);
1274
+ for (const k of Object.keys(e)) if (!EXTENSION_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: ${[...EXTENSION_KEYS].join(", ")})`);
1275
+ for (const k of ["rule", "file", "buildsOn", "reason"]) if (typeof e[k] !== "string" || !e[k].trim()) fail(`${where2} needs "${k}"`);
1276
+ const { rule, file, buildsOn, reason } = e;
1277
+ if (META_RULES.has(rule) || CONFIG_RULES.has(rule)) fail(`${where2} can't extend ${rule}: it is about the config, not the app's code`);
1278
+ if (!rule.includes("/")) fail(`${where2} can't extend ${rule}: only package rules declare extension points (a built-in rule's findings are fixed, or recorded as allow debt)`);
1279
+ if (/[*?[\]{}]/.test(file)) fail(`${where2}.file must be one file, not a glob: each extension is reviewed on its own`);
1280
+ e.file = appPath2(file, `${where2}.file`, fail);
1281
+ if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(buildsOn)) fail(`${where2}.buildsOn must name a Genesis export, or a part of one ("FormBuilder", "ResourceView.slots")`);
1282
+ const text = reason.trim();
1283
+ if (text.length < EXTENSION_REASON_MIN.chars || text.split(/\s+/).length < EXTENSION_REASON_MIN.words) {
1284
+ fail(`${where2} (${rule}) needs a reason of at least ${EXTENSION_REASON_MIN.words} words and ${EXTENSION_REASON_MIN.chars} characters: why the rule's primitive doesn't fit this file`);
1285
+ }
1286
+ if (e.upstream !== void 0 && (typeof e.upstream !== "string" || !e.upstream.trim())) fail(`${where2}.upstream must be a link to the gap's write-up`);
1287
+ const key2 = `${rule}\0${e.file}`;
1288
+ if (seen.has(key2)) fail(`${where2} extends ${rule} in ${e.file} twice`);
1289
+ seen.add(key2);
1290
+ });
1291
+ }
1267
1292
  if (c.patterns !== void 0) {
1268
1293
  if (!Array.isArray(c.patterns)) fail(`"patterns" must be a list`);
1269
1294
  c.patterns.forEach((p, i) => {
@@ -1346,7 +1371,7 @@ function isObject2(v) {
1346
1371
  function isStringList(v) {
1347
1372
  return Array.isArray(v) && v.every((x) => typeof x === "string");
1348
1373
  }
1349
- var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, ENVIRONMENT_KEYS, STRING_LISTS, STRINGS, KNOWN, LEVELS, META_RULES, PATTERN_KEYS, PACKAGE_RULE_KEYS, CONTRACT_KEYS, PACKS, PACK_KEYS, PLAIN_FOLDER, PRIVACY_KEYS, DATA_USE_KEYS, LINK_KEYS, HOST;
1374
+ var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, ENVIRONMENT_KEYS, STRING_LISTS, STRINGS, KNOWN, LEVELS, META_RULES, CONFIG_RULES, EXTENSION_KEYS, EXTENSION_REASON_MIN, PATTERN_KEYS, PACKAGE_RULE_KEYS, CONTRACT_KEYS, PACKS, PACK_KEYS, PLAIN_FOLDER, PRIVACY_KEYS, DATA_USE_KEYS, LINK_KEYS, HOST;
1350
1375
  var init_config = __esm({
1351
1376
  "src/doctor/config.ts"() {
1352
1377
  GenesisConfigError = class extends Error {
@@ -1411,6 +1436,7 @@ var init_config = __esm({
1411
1436
  "forbiddenImports",
1412
1437
  "rules",
1413
1438
  "allow",
1439
+ "extend",
1414
1440
  "patterns",
1415
1441
  "plugins",
1416
1442
  "packs",
@@ -1425,7 +1451,10 @@ var init_config = __esm({
1425
1451
  "$comment"
1426
1452
  ]);
1427
1453
  LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
1428
- META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
1454
+ META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped", "extension-invalid"]);
1455
+ CONFIG_RULES = /* @__PURE__ */ new Set(["stale-exception", "stale-extension", "package-rule-override"]);
1456
+ EXTENSION_KEYS = /* @__PURE__ */ new Set(["rule", "file", "buildsOn", "reason", "upstream"]);
1457
+ EXTENSION_REASON_MIN = { chars: 40, words: 6 };
1429
1458
  PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
1430
1459
  PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
1431
1460
  CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
@@ -1554,7 +1583,9 @@ function loadGenesis(root, config) {
1554
1583
  const { dir: uiDir, exports: exportNames, values, components } = pkg;
1555
1584
  const tokens = /* @__PURE__ */ new Set();
1556
1585
  const themeFiles = resolveThemeFiles(root, config, uiDir);
1557
- for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
1586
+ const themeCss = themeFiles.map((file) => readFileSync(file, "utf8"));
1587
+ for (const css of themeCss) for (const t of declaredTokens(css)) tokens.add(t);
1588
+ const colorTokens = colorRoles(themeCss);
1558
1589
  const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
1559
1590
  const rawTags = /* @__PURE__ */ new Map();
1560
1591
  for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
@@ -1570,6 +1601,8 @@ function loadGenesis(root, config) {
1570
1601
  values,
1571
1602
  components,
1572
1603
  tokens,
1604
+ colorTokens,
1605
+ ...themeParts(root) ? { themeParts: themeParts(root) } : {},
1573
1606
  rawTags,
1574
1607
  palette: loadPalette(root),
1575
1608
  companions: loadCompanions(root, config, uiPackage)
@@ -1669,6 +1702,47 @@ function parseExportNames(dts) {
1669
1702
  }
1670
1703
  return names;
1671
1704
  }
1705
+ function colorRoles(sheets) {
1706
+ const declared = /* @__PURE__ */ new Map();
1707
+ for (const css of sheets) {
1708
+ for (const m of css.matchAll(/(--[A-Za-z0-9_-]+)\s*:\s*([^;{}]+);/g)) {
1709
+ const list = declared.get(m[1]) ?? [];
1710
+ list.push(m[2].trim());
1711
+ declared.set(m[1], list);
1712
+ }
1713
+ }
1714
+ const roles = /* @__PURE__ */ new Set();
1715
+ for (const [name, values] of declared) if (values.some((v) => COLOUR_VALUE.test(v))) roles.add(name);
1716
+ for (let pass = 0; pass < 4; pass++) {
1717
+ for (const [name, values] of declared) {
1718
+ if (roles.has(name)) continue;
1719
+ if (values.some((v) => [...v.matchAll(/var\(\s*(--[A-Za-z0-9_-]+)/g)].some((r) => roles.has(r[1])))) roles.add(name);
1720
+ }
1721
+ }
1722
+ return roles;
1723
+ }
1724
+ function themeParts(root) {
1725
+ const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
1726
+ if (!ds) return null;
1727
+ if (partsCache.has(ds)) return partsCache.get(ds);
1728
+ let found = null;
1729
+ const dist = path30.join(ds, "dist");
1730
+ try {
1731
+ for (const name of existsSync(dist) ? readdirSync(dist) : []) {
1732
+ if (!name.endsWith(".js")) continue;
1733
+ const code = readFileSync(path30.join(dist, name), "utf8");
1734
+ const at = code.indexOf("THEME_PARTS = Object.freeze([");
1735
+ if (at === -1) continue;
1736
+ const body = code.slice(at, code.indexOf("]);", at));
1737
+ found = [...body.matchAll(/\bp\(\s*"([a-z][a-z0-9-]*)"/g)].map((m) => m[1]);
1738
+ break;
1739
+ }
1740
+ } catch {
1741
+ found = null;
1742
+ }
1743
+ partsCache.set(ds, found);
1744
+ return found;
1745
+ }
1672
1746
  function declaredTokens(css) {
1673
1747
  return [...css.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)].map((m) => m[1]);
1674
1748
  }
@@ -1808,7 +1882,7 @@ function loadPalette(root) {
1808
1882
  }
1809
1883
  return [...names].sort();
1810
1884
  }
1811
- var DEFAULT_UI_PACKAGE, NATIVE_UI_PACKAGE, DESIGN_SYSTEM_PACKAGE, DEFAULT_COMPONENT_PACKAGES, TAGS, TAG_ALIASES, NON_COMPONENT_SUFFIX, TAILWIND_PALETTE, TS_SOURCE, isTsSource;
1885
+ var DEFAULT_UI_PACKAGE, NATIVE_UI_PACKAGE, DESIGN_SYSTEM_PACKAGE, DEFAULT_COMPONENT_PACKAGES, TAGS, TAG_ALIASES, NON_COMPONENT_SUFFIX, TAILWIND_PALETTE, COLOUR_VALUE, partsCache, TS_SOURCE, isTsSource;
1812
1886
  var init_genesis = __esm({
1813
1887
  "src/doctor/genesis.ts"() {
1814
1888
  init_pm();
@@ -1850,6 +1924,8 @@ var init_genesis = __esm({
1850
1924
  "mist",
1851
1925
  "olive"
1852
1926
  ];
1927
+ COLOUR_VALUE = /^(?:-?[\d.]+(?:deg)?\s+[\d.]+%\s+[\d.]+%(?:\s*\/\s*[\d.]+%?)?|#[0-9a-f]{3,8}|(?:hsla?|rgba?|oklch|oklab|lab|lch|color)\(.*\))$/i;
1928
+ partsCache = /* @__PURE__ */ new Map();
1853
1929
  TS_SOURCE = /\.(?:[cm]?tsx?)$/;
1854
1930
  isTsSource = (v) => typeof v === "string" && TS_SOURCE.test(v) && !/\.d\.[cm]?ts$/.test(v);
1855
1931
  }
@@ -2090,6 +2166,9 @@ function scanFiles(root, config) {
2090
2166
  for (const pkg of local) walk4(pkg.dir);
2091
2167
  return files;
2092
2168
  }
2169
+ function withText(file, text) {
2170
+ return { ...file, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(file.ext)) };
2171
+ }
2093
2172
  function lineAt(text, index) {
2094
2173
  let line = 1;
2095
2174
  for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
@@ -3256,7 +3335,7 @@ var init_comments = __esm({
3256
3335
  "src/introspect/comments.ts"() {
3257
3336
  MARKER = "@genesis";
3258
3337
  TABLE_KEYS = { label: "string", labelField: "string", description: "string", noun: "string", nounPlural: "string", key: "key" };
3259
- FIELD_KEYS = { label: "string", description: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
3338
+ FIELD_KEYS = { label: "string", description: "string", control: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
3260
3339
  CommentSettingsError = class extends Error {
3261
3340
  };
3262
3341
  }
@@ -3615,7 +3694,8 @@ function field(column, indent) {
3615
3694
  const description = column.settings?.description ?? column.description;
3616
3695
  if (label) parts.push(`label: ${quote(label)}`);
3617
3696
  if (description) parts.push(`description: ${quote(description)}`);
3618
- if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
3697
+ if (column.settings?.control) parts.push(`control: ${quote(column.settings.control)}`);
3698
+ else if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
3619
3699
  if (column.settings?.readonly) parts.push("readOnly: true");
3620
3700
  if (column.settings?.sensitive) parts.push("sensitive: true");
3621
3701
  return `${indent}{ ${parts.join(", ")} },`;
@@ -4037,7 +4117,7 @@ function checkProjectLayout(ctx) {
4037
4117
  rule: "local-primitives",
4038
4118
  file: dir,
4039
4119
  subject: dir,
4040
- message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} (or extend it upstream)`
4120
+ message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} for those, and keep the app's own components in another folder`
4041
4121
  });
4042
4122
  }
4043
4123
  }
@@ -4250,6 +4330,10 @@ var init_rules = __esm({
4250
4330
  "ratchet-skipped",
4251
4331
  "allow-grew",
4252
4332
  "rules-weakened",
4333
+ "extension-added",
4334
+ // declared extensions (extensions.ts)
4335
+ "stale-extension",
4336
+ "extension-invalid",
4253
4337
  // agent guide (primitives.ts)
4254
4338
  "agent-guide-stale",
4255
4339
  // supabase pack: contracts (contracts.ts)
@@ -4259,7 +4343,11 @@ var init_rules = __esm({
4259
4343
  // an app whose database files live in another app (database.ts)
4260
4344
  "database-elsewhere",
4261
4345
  // the app's eslint config loads Genesis's lint rules (eslint-config.ts)
4262
- "genesis-eslint-config"
4346
+ "genesis-eslint-config",
4347
+ // custom views and app parts (custom-views.ts)
4348
+ "app-part-colors",
4349
+ "app-part-name",
4350
+ "custom-view-states"
4263
4351
  ];
4264
4352
  DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
4265
4353
  STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -4382,6 +4470,33 @@ function readSource(abs) {
4382
4470
  return null;
4383
4471
  }
4384
4472
  }
4473
+ function blankStrings(code) {
4474
+ if (lastBlanked?.source === code) return lastBlanked.blanked;
4475
+ const out = code.split("");
4476
+ for (let i = 0; i < code.length; i++) {
4477
+ const ch = code[i];
4478
+ if (ch !== '"' && ch !== "'" && ch !== "`") continue;
4479
+ let j = i - 1;
4480
+ while (j >= 0 && /[ \t]/.test(code[j])) j--;
4481
+ const before = j >= 0 ? code[j] : "\n";
4482
+ const word = /[\w$]/.test(before) ? /(?:^|[^\w$])(return|case|typeof|in|of|yield|await)$/.test(code.slice(Math.max(0, j - 8), j + 1)) : false;
4483
+ if (/[\w$)\]]/.test(before) && !word) continue;
4484
+ let k = i + 1;
4485
+ for (; k < code.length; k++) {
4486
+ const c = code[k];
4487
+ if (c === "\\") {
4488
+ k++;
4489
+ continue;
4490
+ }
4491
+ if (c === ch) break;
4492
+ if (c === "\n" && ch !== "`") break;
4493
+ }
4494
+ for (let x = i + 1; x < k && x < code.length; x++) if (code[x] !== "\n") out[x] = " ";
4495
+ i = k;
4496
+ }
4497
+ lastBlanked = { source: code, blanked: out.join("") };
4498
+ return lastBlanked.blanked;
4499
+ }
4385
4500
  function tagEnd(code, start) {
4386
4501
  let depth = 0;
4387
4502
  let quote2 = null;
@@ -4403,7 +4518,8 @@ function tagEnd(code, start) {
4403
4518
  }
4404
4519
  return { end: code.length, selfClosing: false };
4405
4520
  }
4406
- function openElementsAt(code, index, track) {
4521
+ function openElementsAt(source, index, track) {
4522
+ const code = blankStrings(source);
4407
4523
  const open = [];
4408
4524
  const re = /<(\/?)([A-Z][\w.]*)(?=[\s>/])/g;
4409
4525
  for (let m = re.exec(code); m && m.index < index; m = re.exec(code)) {
@@ -4442,12 +4558,13 @@ function namedImportsFrom(code, pkg) {
4442
4558
  }
4443
4559
  return out;
4444
4560
  }
4445
- var SCRIPT_EXTS2, JSX_EXTS2, RESOLVE_EXTS;
4561
+ var SCRIPT_EXTS2, JSX_EXTS2, RESOLVE_EXTS, lastBlanked;
4446
4562
  var init_source = __esm({
4447
4563
  "src/doctor/source.ts"() {
4448
4564
  SCRIPT_EXTS2 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
4449
4565
  JSX_EXTS2 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
4450
4566
  RESOLVE_EXTS = [".tsx", ".ts", ".jsx", ".js"];
4567
+ lastBlanked = null;
4451
4568
  }
4452
4569
  });
4453
4570
  function nativePackage(ctx) {
@@ -5383,6 +5500,9 @@ function validatePrefer(raw, where2, fail, unknownKey) {
5383
5500
  if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
5384
5501
  if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
5385
5502
  for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
5503
+ if (raw.extensible !== void 0 && !(isStringList2(raw.extensible) && raw.extensible.every((n) => /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(n)))) {
5504
+ fail(`${at}.extensible must be a list of export names, or parts of one ("ResourceView.slots")`);
5505
+ }
5386
5506
  if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
5387
5507
  const forbid = raw.forbid;
5388
5508
  for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
@@ -5395,6 +5515,7 @@ function validatePrefer(raw, where2, fail, unknownKey) {
5395
5515
  const unless = raw.unless;
5396
5516
  for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
5397
5517
  if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
5518
+ if (unless.inside !== void 0 && !(isStringList2(unless.inside) && unless.inside.every((n) => /^[A-Z][\w.]*$/.test(n)))) fail(`${at}.unless.inside must be a list of component names`);
5398
5519
  if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
5399
5520
  }
5400
5521
  return raw;
@@ -5510,6 +5631,7 @@ function compile(rule, setting, routes) {
5510
5631
  imports: (rule.forbid.imports ?? []).map(specMatcher),
5511
5632
  ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
5512
5633
  unlessRenders: new Set(rule.unless?.renders ?? []),
5634
+ unlessInside: new Set(rule.unless?.inside ?? []),
5513
5635
  ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
5514
5636
  };
5515
5637
  }
@@ -5518,7 +5640,7 @@ function messageFor(rule, found) {
5518
5640
  const docs = rule.docs ? ` See ${rule.docs}` : "";
5519
5641
  return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
5520
5642
  }
5521
- function wrappersIn(file, elements, c) {
5643
+ function wrappersIn(file, elements, names, accept) {
5522
5644
  const out = /* @__PURE__ */ new Map();
5523
5645
  const decls = [...file.code.matchAll(TOP_LEVEL)];
5524
5646
  const listed = /* @__PURE__ */ new Map();
@@ -5531,12 +5653,12 @@ function wrappersIn(file, elements, c) {
5531
5653
  for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
5532
5654
  decls.forEach((d, i) => {
5533
5655
  const name = d[3];
5534
- if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
5656
+ if (!/^[A-Z]/.test(name) || names.has(name)) return;
5535
5657
  const end = decls[i + 1]?.index ?? file.code.length;
5536
- const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
5537
- if (!hit) return;
5538
- const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
5539
- for (const n of names) out.set(n, hit[1]);
5658
+ const hit = elements.find((m) => m.index > d.index && m.index < end && names.has(m[1]));
5659
+ if (!hit || accept && !accept(d.index, end)) return;
5660
+ const exported = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
5661
+ for (const n of exported) out.set(n, hit[1]);
5540
5662
  });
5541
5663
  return out;
5542
5664
  }
@@ -5544,6 +5666,32 @@ function runPrefer(ctx, c) {
5544
5666
  const own = c.rule.packageDir;
5545
5667
  const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
5546
5668
  const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
5669
+ const scanned = new Map(ctx.files.map((f) => [f.absolutePath, f]));
5670
+ const importedBy = /* @__PURE__ */ new Map();
5671
+ const importsOf = (file) => {
5672
+ if (!importedBy.has(file)) importedBy.set(file, localImportedNames(ctx.root, file));
5673
+ return importedBy.get(file);
5674
+ };
5675
+ const builders = /* @__PURE__ */ new Map();
5676
+ const buildersIn = (abs) => {
5677
+ if (!builders.has(abs)) {
5678
+ const target = scanned.get(abs) ?? readSource(abs);
5679
+ const code = target ? "ext" in target ? target.code : stripBlockComments(target.code, true) : "";
5680
+ const childrenInside = (start, end) => [...code.slice(start, end).matchAll(CHILDREN)].some((m) => openElementsAt(code, start + m.index, (n) => c.unlessInside.has(n)).length > 0);
5681
+ builders.set(abs, code ? wrappersIn({ code }, [...code.matchAll(ELEMENT)], c.unlessInside, childrenInside) : /* @__PURE__ */ new Map());
5682
+ }
5683
+ return builders.get(abs);
5684
+ };
5685
+ const nestedInBuilder = (file, index) => {
5686
+ if (!c.unlessInside.size) return false;
5687
+ const imported = importsOf(file);
5688
+ const isBuilder = (name) => {
5689
+ if (c.unlessInside.has(name)) return true;
5690
+ const from = name.includes(".") ? void 0 : imported.get(name);
5691
+ return from !== void 0 && buildersIn(from.file).has(from.name);
5692
+ };
5693
+ return openElementsAt(file.code, index, isBuilder).length > 0;
5694
+ };
5547
5695
  const wrappers = /* @__PURE__ */ new Map();
5548
5696
  const renderedBy = /* @__PURE__ */ new Map();
5549
5697
  for (const file of checked) {
@@ -5551,16 +5699,17 @@ function runPrefer(ctx, c) {
5551
5699
  const elements = [...file.code.matchAll(ELEMENT)];
5552
5700
  renderedBy.set(file, elements);
5553
5701
  if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
5554
- const found = wrappersIn(file, elements, c);
5702
+ const found = wrappersIn(file, elements, c.jsx);
5555
5703
  if (found.size) wrappers.set(file.absolutePath, found);
5556
5704
  }
5557
5705
  for (const file of checked) {
5558
5706
  const elements = renderedBy.get(file) ?? [];
5559
5707
  if (exempt(file, elements.map((m) => m[1]))) continue;
5560
5708
  const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
5561
- const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
5709
+ const imported = wrappers.size && elements.length ? importsOf(file) : null;
5562
5710
  for (const m of elements) {
5563
5711
  const name = m[1];
5712
+ if (nestedInBuilder(file, m.index)) continue;
5564
5713
  if (c.jsx.has(name)) {
5565
5714
  report(lineAt(file.code, m.index), name, `renders <${name}>`);
5566
5715
  continue;
@@ -5577,6 +5726,7 @@ function runPrefer(ctx, c) {
5577
5726
  if (c.pattern) {
5578
5727
  c.pattern.lastIndex = 0;
5579
5728
  for (const m of file.code.matchAll(c.pattern)) {
5729
+ if (nestedInBuilder(file, m.index)) continue;
5580
5730
  const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
5581
5731
  report(lineAt(file.code, m.index), text, `has ${text}`);
5582
5732
  }
@@ -5641,7 +5791,7 @@ function unknownPackageRuleSettings(config, packages, reported) {
5641
5791
  function packageRuleIds(packages) {
5642
5792
  return new Set(preferRules(packages).map((r) => r.ruleId));
5643
5793
  }
5644
- var PackageDeclarationError, GENESIS, ID, LEVELS2, PREFER_KEYS, FORBID_KEYS, UNLESS_KEYS, PRIMITIVE_KEYS, DECLARATION_KEYS, SCRIPT_GLOBS, isObject3, isStringList2, discoveryCache, specMatcher, JSX, ELEMENT, SCRIPT, TOP_LEVEL, EXPORT_LIST, EXPORT_DEFAULT_NAME, isNative;
5794
+ var PackageDeclarationError, GENESIS, ID, LEVELS2, PREFER_KEYS, FORBID_KEYS, UNLESS_KEYS, PRIMITIVE_KEYS, DECLARATION_KEYS, SCRIPT_GLOBS, isObject3, isStringList2, discoveryCache, specMatcher, JSX, ELEMENT, SCRIPT, CHILDREN, TOP_LEVEL, EXPORT_LIST, EXPORT_DEFAULT_NAME, isNative;
5645
5795
  var init_package_rules = __esm({
5646
5796
  "src/doctor/package-rules.ts"() {
5647
5797
  init_discover();
@@ -5653,6 +5803,7 @@ var init_package_rules = __esm({
5653
5803
  init_routes();
5654
5804
  init_scan();
5655
5805
  init_source();
5806
+ init_color_literals();
5656
5807
  init_rules();
5657
5808
  PackageDeclarationError = class extends Error {
5658
5809
  name = "PackageDeclarationError";
@@ -5660,9 +5811,9 @@ var init_package_rules = __esm({
5660
5811
  GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
5661
5812
  ID = /^[a-z0-9][a-z0-9-]*$/;
5662
5813
  LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
5663
- PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
5814
+ PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly", "extensible"]);
5664
5815
  FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
5665
- UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
5816
+ UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "inside", "pattern"]);
5666
5817
  PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
5667
5818
  DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "catalog", "primitives", "plugin", "$comment"]);
5668
5819
  SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
@@ -5673,6 +5824,7 @@ var init_package_rules = __esm({
5673
5824
  JSX = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
5674
5825
  ELEMENT = /(?<![\w$.])<([A-Z][\w.]*)(?=[\s>/<])/g;
5675
5826
  SCRIPT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
5827
+ CHILDREN = /\{\s*(?:props\.)?children\s*\}/g;
5676
5828
  TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
5677
5829
  EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
5678
5830
  EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
@@ -7955,6 +8107,80 @@ var init_api_usage = __esm({
7955
8107
  };
7956
8108
  }
7957
8109
  });
8110
+
8111
+ // src/doctor/custom-views.ts
8112
+ function checkAppParts(ctx) {
8113
+ const roles = ctx.genesis.colorTokens;
8114
+ const genesisParts = new Set(ctx.genesis.themeParts ?? []);
8115
+ const overlays = markedOverlays(ctx);
8116
+ for (const file of ctx.files) {
8117
+ if (!JSX_EXTS4.has(file.ext) && file.ext !== ".ts" && file.ext !== ".js") continue;
8118
+ if (insideOverlayOf(overlays, file, ctx.genesis.uiPackage)) continue;
8119
+ const code = file.code;
8120
+ if (JSX_EXTS4.has(file.ext)) {
8121
+ for (const m of code.matchAll(/\bdata-slot\s*=\s*(?:\{\s*)?["'`]([^"'`$]+)["'`]/g)) {
8122
+ const name = m[1];
8123
+ if (name.startsWith("app-")) continue;
8124
+ const clash = genesisParts.has(name);
8125
+ ctx.report({
8126
+ rule: "app-part-name",
8127
+ level: "warn",
8128
+ file: file.path,
8129
+ line: lineAt(code, m.index ?? 0),
8130
+ subject: name,
8131
+ message: clash ? `marks an app element data-slot="${name}", which is a Genesis part (THEME_PARTS): every app style's rules for it would hit this element too. Name the app's own part "app-${name}"` : `marks an app element data-slot="${name}"; name the app's own part "app-${name}", so it never collides with a Genesis part (docs/adr/0018-app-brands-styles-themes.md)`
8132
+ });
8133
+ }
8134
+ }
8135
+ if (roles && roles.size && (CUSTOM_VIEW.test(code) || APP_PART.test(code))) {
8136
+ const seen = /* @__PURE__ */ new Set();
8137
+ const check = (value, at) => {
8138
+ for (const v of value.matchAll(VARIABLE)) {
8139
+ const name = v[1];
8140
+ if (roles.has(name)) continue;
8141
+ const line = lineAt(code, at);
8142
+ if (seen.has(`${line}:${name}`)) continue;
8143
+ seen.add(`${line}:${name}`);
8144
+ ctx.report({
8145
+ rule: "app-part-colors",
8146
+ level: "warn",
8147
+ file: file.path,
8148
+ line,
8149
+ subject: name,
8150
+ message: `colours a custom view or app part with ${name}, which isn't a colour role; take colours from roles only (hsl(var(--primary)), bg-primary, text-muted-foreground) so the app brand and dark mode reach it`
8151
+ });
8152
+ }
8153
+ };
8154
+ for (const m of code.matchAll(COLOUR_KEY)) check(m[3], m.index ?? 0);
8155
+ for (const m of code.matchAll(COLOUR_UTILITY)) check(m[1], m.index ?? 0);
8156
+ }
8157
+ if (JSX_EXTS4.has(file.ext) && CUSTOM_VIEW.test(code)) {
8158
+ for (const m of code.matchAll(/\bstatus\s*[!=]={1,2}\s*["'`](loading|empty|error)["'`]/g)) {
8159
+ ctx.report({
8160
+ rule: "custom-view-states",
8161
+ level: "warn",
8162
+ file: file.path,
8163
+ line: lineAt(code, m.index ?? 0),
8164
+ subject: m[1],
8165
+ message: `draws a custom view's own ${m[1]} state; <CustomView> draws loading, empty and error in the app's style (pass its loading, empty or error prop to replace one) (docs/adr/0019-custom-views.md)`
8166
+ });
8167
+ }
8168
+ }
8169
+ }
8170
+ }
8171
+ var JSX_EXTS4, CUSTOM_VIEW, APP_PART, COLOUR_KEY, COLOUR_UTILITY, VARIABLE;
8172
+ var init_custom_views = __esm({
8173
+ "src/doctor/custom-views.ts"() {
8174
+ init_scan();
8175
+ init_overlays();
8176
+ JSX_EXTS4 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
8177
+ CUSTOM_VIEW = /<CustomView\b|\buseCustomView\s*[<(]/;
8178
+ APP_PART = /data-slot\s*=\s*\{?\s*["'`]app-/;
8179
+ COLOUR_KEY = /\b(color|background(?:Color)?|border(?:Top|Right|Bottom|Left|Block|Inline)?(?:Color)?|outline(?:Color)?|textDecorationColor|caretColor|accentColor|fill|stroke|columnRuleColor|boxShadow)\s*:\s*(["'`])([^"'`]*)\2/g;
8180
+ COLOUR_UTILITY = /(?<![\w-])(?:bg|text|border(?:-[xytrbls])?|ring|ring-offset|fill|stroke|from|to|via|outline|divide|decoration|shadow|accent|caret|placeholder)-\[([^\]]*var\(--[^\]]*)\]/g;
8181
+ VARIABLE = /var\(\s*(--[A-Za-z0-9_-]+)/g;
8182
+ }
8183
+ });
7958
8184
  function specifierParts(spec) {
7959
8185
  return spec.trim().replace(/^type\s+/, "").split(/\s+as\s+/).map((part) => part.trim());
7960
8186
  }
@@ -8073,20 +8299,41 @@ function git3(root, args) {
8073
8299
  return r.status === 0 ? r.stdout : null;
8074
8300
  }
8075
8301
  function changedSince(root, base) {
8076
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
8302
+ const mergeBase = mergeBaseOf2(root, base);
8077
8303
  if (!mergeBase) return null;
8078
8304
  const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
8079
8305
  const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
8080
8306
  if (committed === null || untracked === null) return null;
8081
8307
  return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
8082
8308
  }
8309
+ function originsSince(root, base) {
8310
+ const out = /* @__PURE__ */ new Map();
8311
+ const mergeBase = mergeBaseOf2(root, base);
8312
+ if (!mergeBase) return out;
8313
+ const diff = git3(root, ["diff", "-z", "-M", "--name-status", "--relative", mergeBase, "--"]);
8314
+ if (diff === null) return out;
8315
+ const parts = diff.split("\0");
8316
+ for (let i = 0; i < parts.length; ) {
8317
+ const status = parts[i++] ?? "";
8318
+ if (!status) continue;
8319
+ if (status.startsWith("R") || status.startsWith("C")) {
8320
+ const from = parts[i++];
8321
+ const to = parts[i++];
8322
+ if (status.startsWith("R")) out.set(to, from);
8323
+ } else i++;
8324
+ }
8325
+ return out;
8326
+ }
8327
+ function mergeBaseOf2(root, base) {
8328
+ return git3(root, ["merge-base", base, "HEAD"])?.trim() || null;
8329
+ }
8083
8330
  function showAt(dir, rev, file) {
8084
8331
  const at = `${rev}:./${file}`;
8085
8332
  if (git3(dir, ["cat-file", "-e", at]) === null) return void 0;
8086
8333
  return git3(dir, ["show", at]);
8087
8334
  }
8088
8335
  function configAtBase(root, base, explicitFile) {
8089
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
8336
+ const mergeBase = mergeBaseOf2(root, base);
8090
8337
  if (!mergeBase) return null;
8091
8338
  const candidates = explicitFile ? [{ dir: path30.dirname(explicitFile), file: path30.basename(explicitFile), explicit: true }] : [
8092
8339
  { dir: root, file: "genesis.config.json", explicit: false },
@@ -8107,7 +8354,12 @@ function configAtBase(root, base, explicitFile) {
8107
8354
  continue;
8108
8355
  }
8109
8356
  const b = objectOr(block);
8110
- return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
8357
+ return {
8358
+ allow: Array.isArray(b.allow) ? b.allow : [],
8359
+ extend: Array.isArray(b.extend) ? b.extend : [],
8360
+ rules: objectOr(b.rules),
8361
+ packageRules: objectOr(b.packageRules)
8362
+ };
8111
8363
  }
8112
8364
  return "absent";
8113
8365
  }
@@ -8120,6 +8372,16 @@ function allowGrew(allow, before, base) {
8120
8372
  message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
8121
8373
  }));
8122
8374
  }
8375
+ function extensionsAdded(extend, before, base) {
8376
+ const had = new Set(before.map((e) => `${e.rule}\0${e.file}\0${e.buildsOn}`));
8377
+ return extend.filter((e) => !had.has(`${e.rule}\0${e.file}\0${e.buildsOn}`)).map((e) => ({
8378
+ rule: "extension-added",
8379
+ level: "info",
8380
+ file: e.file,
8381
+ subject: e.rule,
8382
+ message: `extends ${e.rule} since ${base}, building on ${e.buildsOn}: "${e.reason}"${e.upstream ? ` (upstream: ${e.upstream})` : ""}; the pull request's review accepts it, and it covers only the findings the file has now`
8383
+ }));
8384
+ }
8123
8385
  function rulesWeakened(config, before, base) {
8124
8386
  const out = [];
8125
8387
  const levelIn = (c, rule) => c.rules?.[rule] ?? c.packageRules?.[rule]?.level;
@@ -8147,18 +8409,63 @@ function touched(file, changed) {
8147
8409
  for (const c of changed) if (c.startsWith(prefix)) return true;
8148
8410
  return false;
8149
8411
  }
8412
+ function isRatcheted(rule, config, newOnly) {
8413
+ return !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
8414
+ }
8415
+ function countFindings(findings) {
8416
+ const counts = /* @__PURE__ */ new Map();
8417
+ for (const f of findings) counts.set(countKey(f.file, f.rule), (counts.get(countKey(f.file, f.rule)) ?? 0) + 1);
8418
+ return counts;
8419
+ }
8150
8420
  function applyRatchet(findings, options) {
8151
- const { config, newOnly, changed, base, isAppPath } = options;
8152
- const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
8421
+ const { config, newOnly, changed, base, isAppPath, baseCounts, existedAtBase } = options;
8422
+ const originOf = options.originOf ?? ((f) => f);
8423
+ const counts = countFindings(findings.map((f) => ({ file: originOf(f.file), rule: f.rule })));
8153
8424
  return findings.map((f) => {
8154
- if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
8155
- return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
8425
+ if (f.level === "info" || !isRatcheted(f.rule, config, newOnly) || !isAppPath(f.file)) return f;
8426
+ if (!touched(f.file, changed)) return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
8427
+ const origin = originOf(f.file);
8428
+ if (!baseCounts || !existedAtBase?.(origin)) return f;
8429
+ const now = counts.get(countKey(origin, f.rule)) ?? 0;
8430
+ const was = baseCounts.get(countKey(origin, f.rule)) ?? 0;
8431
+ const where2 = origin === f.file ? "this file" : `the files from ${origin}`;
8432
+ if (now > was) return { ...f, message: `${f.message} (${now} ${f.rule} findings in ${where2}, ${was} at the merge base with ${base}: don't add to the debt)` };
8433
+ return { ...f, level: "info", message: `${f.message} (ratcheted: ${now} in ${where2}, ${was} at the merge base with ${base})` };
8156
8434
  });
8157
8435
  }
8158
- var objectOr, allowKey, RANK, NEVER_RATCHETED;
8436
+ function snapshotAtBase(root, base, files, changed, originOf = (f) => f) {
8437
+ const mergeBase = mergeBaseOf2(root, base);
8438
+ if (!mergeBase) return null;
8439
+ const out = [];
8440
+ const seen = /* @__PURE__ */ new Set();
8441
+ for (const f of files) {
8442
+ if (!changed.has(f.path)) {
8443
+ if (!seen.has(f.path)) out.push(f);
8444
+ seen.add(f.path);
8445
+ continue;
8446
+ }
8447
+ const origin = originOf(f.path);
8448
+ if (seen.has(origin)) continue;
8449
+ seen.add(origin);
8450
+ const text = showAt(root, mergeBase, origin);
8451
+ if (text === null) return null;
8452
+ if (text !== void 0) out.push(withText({ ...f, path: origin, absolutePath: path30.join(root, origin) }, text));
8453
+ }
8454
+ const cache2 = /* @__PURE__ */ new Map();
8455
+ return {
8456
+ mergeBase,
8457
+ files: out,
8458
+ existed(file) {
8459
+ if (!cache2.has(file)) cache2.set(file, git3(root, ["cat-file", "-e", `${mergeBase}:./${file}`]) !== null);
8460
+ return cache2.get(file);
8461
+ }
8462
+ };
8463
+ }
8464
+ var objectOr, allowKey, RANK, NEVER_RATCHETED, countKey;
8159
8465
  var init_ratchet = __esm({
8160
8466
  "src/doctor/ratchet.ts"() {
8161
8467
  init_config();
8468
+ init_scan();
8162
8469
  objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
8163
8470
  allowKey = (a) => `${a.rule}\0${a.file ?? ""}\0${a.match ?? ""}`;
8164
8471
  RANK = { off: 0, info: 1, warn: 2, error: 3 };
@@ -8171,8 +8478,127 @@ var init_ratchet = __esm({
8171
8478
  "plugin-error",
8172
8479
  "build",
8173
8480
  "agent-guide-stale",
8174
- "contracts-stale"
8481
+ "contracts-stale",
8482
+ "stale-extension",
8483
+ "extension-added"
8175
8484
  ]);
8485
+ countKey = (file, rule) => `${file}\0${rule}`;
8486
+ }
8487
+ });
8488
+
8489
+ // src/doctor/extensions.ts
8490
+ function pointProblem(entry, packages) {
8491
+ const rule = preferRules(packages).find((r) => r.ruleId === entry.rule);
8492
+ if (!rule?.extensible?.length) return `${entry.rule} declares no extension points, so it can't be extended (debt goes in allow, and is fixed)`;
8493
+ if (!rule.extensible.includes(entry.buildsOn)) return `${entry.buildsOn} isn't one of ${entry.rule}'s extension points (${rule.extensible.join(", ")})`;
8494
+ return null;
8495
+ }
8496
+ function extensionProblem(entry, ctx) {
8497
+ const point = pointProblem(entry, ctx.packages);
8498
+ if (point) return point;
8499
+ const name = entry.buildsOn.split(".")[0];
8500
+ const replaces = preferRules(ctx.packages).find((r) => r.forbid.jsx?.includes(name));
8501
+ if (replaces) return `${name} is what ${replaces.ruleId} replaces (use ${replaces.use}); a legacy component can't be built on`;
8502
+ const flagged = ctx.raw.find((f) => f.file === entry.file && f.subject === name);
8503
+ if (flagged) return `${name} is flagged in this file by ${flagged.rule}; build on a current Genesis primitive`;
8504
+ const file = ctx.files.find((f) => f.path === entry.file);
8505
+ if (!file) return `${entry.file} isn't one of the files the doctor scans`;
8506
+ const imported = genesisNamedImports(file.code).some((i) => i.names.includes(name));
8507
+ if (!imported) return `${entry.file} doesn't import ${name} from a Genesis package; buildsOn names the extension point the file uses`;
8508
+ if (!usesPoint(blankStrings(file.code), entry.buildsOn)) {
8509
+ const prop = entry.buildsOn.split(".")[1];
8510
+ return prop ? `${entry.file} doesn't pass ${prop} to <${name}>; an extension point is one the file uses` : `${entry.file} imports ${name} but doesn't render or call it; an extension point is one the file uses`;
8511
+ }
8512
+ return null;
8513
+ }
8514
+ function usesPoint(code, point) {
8515
+ const [name, prop] = point.split(".");
8516
+ const n = escape2(name);
8517
+ if (!prop) return new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])|(?<![\\w$.])${n}\\s*(?:<[^>()]*>)?\\s*\\(`).test(code);
8518
+ for (const m of code.matchAll(new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])`, "g"))) {
8519
+ const { end } = tagEnd(code, m.index);
8520
+ if (new RegExp(`(?<![\\w$.])${escape2(prop)}\\s*=`).test(code.slice(m.index, end))) return true;
8521
+ }
8522
+ return false;
8523
+ }
8524
+ function applyExtensions(findings, ctx) {
8525
+ const entries = ctx.config.extend ?? [];
8526
+ if (!entries.length) return findings;
8527
+ const staleLevel = ctx.config.rules?.["stale-extension"];
8528
+ const covered = /* @__PURE__ */ new Set();
8529
+ const grew = /* @__PURE__ */ new Map();
8530
+ const out = [];
8531
+ const invalid = (entry, problem) => out.push({ rule: "extension-invalid", level: "error", file: entry.file, line: 0, subject: entry.rule, message: `the extension of ${entry.rule} isn't accepted: ${problem}` });
8532
+ for (const entry of entries) {
8533
+ if (ctx.config.rules?.[entry.rule] === "off" || ctx.config.packageRules?.[entry.rule]?.level === "off") continue;
8534
+ const point = pointProblem(entry, ctx.packages);
8535
+ if (point) {
8536
+ invalid(entry, point);
8537
+ continue;
8538
+ }
8539
+ const hits = findings.filter((f) => f.rule === entry.rule && f.file === entry.file);
8540
+ if (!hits.length) {
8541
+ if (staleLevel === "off") continue;
8542
+ out.push({
8543
+ rule: "stale-extension",
8544
+ level: staleLevel ?? "warn",
8545
+ file: entry.file,
8546
+ line: 0,
8547
+ subject: entry.rule,
8548
+ message: `the extension of ${entry.rule} (building on ${entry.buildsOn}) no longer matches a finding in this file; remove it from doctor.extend`
8549
+ });
8550
+ continue;
8551
+ }
8552
+ const problem = extensionProblem(entry, ctx);
8553
+ if (problem) {
8554
+ invalid(entry, problem);
8555
+ continue;
8556
+ }
8557
+ const limit = ctx.limit?.(entry);
8558
+ if (limit !== void 0 && hits.length > limit) {
8559
+ for (const h of hits) grew.set(h, `${h.message} (the extension of ${entry.rule} here covers the ${limit} at the merge base; this file now has ${hits.length}, so they all count)`);
8560
+ continue;
8561
+ }
8562
+ for (const h of hits) covered.add(h);
8563
+ }
8564
+ const kept = findings.filter((f) => !covered.has(f)).map((f) => grew.has(f) ? { ...f, message: grew.get(f) } : f);
8565
+ return [...kept, ...out].sort(byPlace);
8566
+ }
8567
+ function dedupeFindings(findings) {
8568
+ const groups = /* @__PURE__ */ new Map();
8569
+ const order = [];
8570
+ for (const f of findings) {
8571
+ if (f.subject === void 0 || !f.line) {
8572
+ order.push([f]);
8573
+ continue;
8574
+ }
8575
+ const key2 = `${f.file}\0${f.line}\0${f.subject}`;
8576
+ const list = groups.get(key2) ?? [];
8577
+ const group = list.find((g) => !g.some((x) => x.rule === f.rule));
8578
+ if (group) group.push(f);
8579
+ else {
8580
+ const fresh = [f];
8581
+ list.push(fresh);
8582
+ groups.set(key2, list);
8583
+ order.push(fresh);
8584
+ }
8585
+ }
8586
+ return order.map((group) => {
8587
+ if (group.length === 1) return group[0];
8588
+ const primary = group.reduce((a, b) => RANK2[b.level] > RANK2[a.level] ? b : a);
8589
+ const rules = [primary.rule, ...group.filter((g) => g !== primary).map((g) => g.rule)];
8590
+ return { ...primary, rules, message: `${primary.message} (also ${rules.slice(1).join(", ")})` };
8591
+ });
8592
+ }
8593
+ var escape2, byPlace, RANK2;
8594
+ var init_extensions = __esm({
8595
+ "src/doctor/extensions.ts"() {
8596
+ init_stability();
8597
+ init_source();
8598
+ init_package_rules();
8599
+ escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8600
+ byPlace = (x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule);
8601
+ RANK2 = { info: 0, warn: 1, error: 2 };
8176
8602
  }
8177
8603
  });
8178
8604
  function pathTaken(file) {
@@ -8453,7 +8879,7 @@ var init_primitives = __esm({
8453
8879
  CORE = [
8454
8880
  {
8455
8881
  need: "anything, before building it",
8456
- use: 'search what exists: `genesis features find <term>`, this catalog, and the "Available but unused" list in `genesis doctor --verbose`',
8882
+ use: 'search what exists: `genesis features find <term>`, this catalog, and the "Available but unused" list in `genesis doctor --verbose`. Check the install is current first (`genesis upgrade --dry-run`): an old one hides pieces that exist',
8457
8883
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
8458
8884
  from: "genesis-cli"
8459
8885
  },
@@ -8478,9 +8904,15 @@ var init_primitives = __esm({
8478
8904
  rule: "raw-color",
8479
8905
  from: "genesis-cli"
8480
8906
  },
8907
+ {
8908
+ need: "a Genesis piece that is close but doesn't quite fit",
8909
+ use: "extend it: a prop, a variant, a slot, or your own component that wraps it; never a parallel copy beside it",
8910
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
8911
+ from: "genesis-cli"
8912
+ },
8481
8913
  {
8482
8914
  need: "something no primitive covers",
8483
- use: "write the gap up for Genesis (an issue or a proposal) first, then invent in the app, on Genesis primitives",
8915
+ use: "invent it in the app, on Genesis tokens and primitives; Genesis asks for no write-up first. You may add it to `docs/genesis-upstream.md` (`genesis upstream`) if you think Genesis should have it",
8484
8916
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
8485
8917
  from: "genesis-cli"
8486
8918
  }
@@ -8492,10 +8924,12 @@ var init_primitives = __esm({
8492
8924
  AGENTS_END = "<!-- genesis-primitives:end -->";
8493
8925
  RULES = [
8494
8926
  `Use the Genesis primitive for the need first: reuse, then extend, then invent (G1 to G6 in ${GENESIS_DOCS}/FRAMEWORK.md).`,
8927
+ "Before deciding Genesis lacks a piece, look at all of it (the catalog below, `genesis features find <term>`) and check the installed packages are current (`genesis upgrade --dry-run`). An old install hides pieces that exist; upgrade before building around a gap that is already closed.",
8495
8928
  "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
8496
8929
  "A list screen is a view (`defineView`) rendered by `ResourceView`; a record view is `RecordView`; on the phone, `NativeResourceView`.",
8497
8930
  "Screens never call the database client (`supabase.from`, `.rpc`) directly: reads go through a view or a named data function, writes through the resource's provider rules.",
8498
- "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
8931
+ "When a Genesis piece is close and does the same job, extend it: a prop, a variant, a slot, or your own component that wraps it. Never build a parallel copy beside it.",
8932
+ "When no Genesis piece does the job, invent it in the app: your own screens and components, on Genesis tokens and primitives. Genesis asks for no write-up or approval first (your app's own design review still applies); you may add it to `docs/genesis-upstream.md` if you think Genesis should have it.",
8499
8933
  "Run `genesis doctor` before you finish; it enforces these rules."
8500
8934
  ];
8501
8935
  GUIDE_SEARCH_LEVELS = 4;
@@ -9570,12 +10004,15 @@ __export(doctor_exports, {
9570
10004
  agentGuideState: () => agentGuideState,
9571
10005
  agentHooksState: () => agentHooksState,
9572
10006
  agentRules: () => agentRules,
10007
+ applyExtensions: () => applyExtensions,
9573
10008
  builtinChecks: () => builtinChecks,
9574
10009
  catalogTable: () => catalogTable,
9575
10010
  changedSince: () => changedSince,
9576
10011
  clearPackageRulesCache: () => clearPackageRulesCache,
10012
+ dedupeFindings: () => dedupeFindings,
9577
10013
  defineDoctorPlugin: () => defineDoctorPlugin,
9578
10014
  discoverPackages: () => discoverPackages,
10015
+ extensionProblem: () => extensionProblem,
9579
10016
  findPackageDir: () => findPackageDir,
9580
10017
  formatPrimitives: () => formatPrimitives,
9581
10018
  formatReport: () => formatReport,
@@ -9632,14 +10069,8 @@ async function runDoctor(options = {}) {
9632
10069
  }
9633
10070
  const raw = [];
9634
10071
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
9635
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
9636
- try {
9637
- await plugin.check(ctx);
9638
- } catch (err) {
9639
- if (err instanceof DoctorConfigError) throw err;
9640
- raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
9641
- }
9642
- }
10072
+ const appChecks = [...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins];
10073
+ await runChecks(ctx, [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...appChecks]);
9643
10074
  if (options.build) {
9644
10075
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
9645
10076
  if (failure) raw.push(failure);
@@ -9649,30 +10080,57 @@ async function runDoctor(options = {}) {
9649
10080
  let changed = null;
9650
10081
  let skipped = false;
9651
10082
  const ratchetNeeded = newOnly.size > RATCHETED_BY_DEFAULT.length || raw.some((f) => RATCHETED_BY_DEFAULT.includes(f.rule));
9652
- if (options.base && (ratchetNeeded || config.ratchet)) {
10083
+ if (options.base && (ratchetNeeded || config.ratchet || config.extend?.length)) {
9653
10084
  changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
9654
10085
  skipped ||= !changed;
9655
10086
  }
9656
10087
  const configFile = "file" in loaded ? loaded.file : null;
9657
- const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
10088
+ const guarded = (config.allow?.length ?? 0) + (config.extend?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
9658
10089
  let configSkipped = false;
10090
+ let baseExtend = [];
9659
10091
  if (options.base && configFile) {
9660
10092
  const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
10093
+ if (before && before !== "absent") baseExtend = before.extend;
10094
+ if (before === "absent") raw.push(...extensionsAdded(config.extend ?? [], [], options.base));
9661
10095
  if (before && before !== "absent") {
9662
10096
  raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
9663
10097
  raw.push(...rulesWeakened(config, before, options.base));
10098
+ raw.push(...extensionsAdded(config.extend ?? [], before.extend, options.base));
9664
10099
  }
9665
10100
  configSkipped = !before && guarded;
9666
10101
  }
9667
10102
  if (skipped || configSkipped) {
9668
10103
  raw.push(
9669
- configSkipped ? { rule: "ratchet-skipped", level: "error", file: "genesis config", message: `couldn't compare allow, rules and packageRules against ${options.base} (not a git repository, or the ref isn't fetched; in CI check out with fetch-depth: 0)` } : { rule: "ratchet-skipped", level: "warn", file: "genesis config", message: `couldn't compare against ${options.base} (not a git repository, or the ref isn't fetched); every rule ran at its full level` }
10104
+ configSkipped ? { rule: "ratchet-skipped", level: "error", file: "genesis config", message: `couldn't compare allow, extend, rules and packageRules against ${options.base} (not a git repository, or the ref isn't fetched; in CI check out with fetch-depth: 0)` } : { rule: "ratchet-skipped", level: "warn", file: "genesis config", message: `couldn't compare against ${options.base} (not a git repository, or the ref isn't fetched); every rule ran at its full level` }
9670
10105
  );
9671
10106
  }
9672
- let findings = applyConfig(raw, config, packageRuleIds(packages));
10107
+ const packageIds = packageRuleIds(packages);
10108
+ const extensionCtx = { config, files, packages, raw };
10109
+ const configured = applyConfig(raw, config, packageIds);
10110
+ let findings = applyExtensions(configured, extensionCtx);
9673
10111
  if (options.base && changed) {
9674
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path30.join(root, f)) });
9675
- }
10112
+ const isAppPath = (f) => existsSync(path30.join(root, f));
10113
+ const origins = options.changedFiles ? /* @__PURE__ */ new Map() : originsSince(root, options.base);
10114
+ const originOf = (f) => origins.get(f) ?? f;
10115
+ const dueRules = new Set(findings.filter((f) => f.level !== "info" && isRatcheted(f.rule, config, newOnly) && isAppPath(f.file) && touched(f.file, changed)).map((f) => f.rule));
10116
+ const heldExtensions = (config.extend ?? []).filter((e) => touched(e.file, changed) && baseExtend.some((b) => b.rule === e.rule && (b.file === e.file || b.file === originOf(e.file))));
10117
+ for (const e of heldExtensions) dueRules.add(e.rule);
10118
+ const snapshot = dueRules.size ? snapshotAtBase(root, options.base, files, changed, originOf) : null;
10119
+ let baseCounts;
10120
+ if (snapshot) {
10121
+ const before = [];
10122
+ await runChecks({ ...ctx, files: snapshot.files, report: (f) => before.push(f) }, baseChecks(dueRules, packageIds, packagePlugins, () => [...builtinChecks(config, { contracts: false, figma: false }), ...appChecks]));
10123
+ baseCounts = countFindings(applyConfig(before, config, packageIds));
10124
+ if (heldExtensions.length) {
10125
+ const counts = baseCounts;
10126
+ const held = new Set(heldExtensions);
10127
+ findings = applyExtensions(configured, { ...extensionCtx, limit: (e) => held.has(e) ? counts.get(countKey(originOf(e.file), e.rule)) ?? 0 : void 0 });
10128
+ }
10129
+ }
10130
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath, originOf, ...snapshot && baseCounts ? { baseCounts, existedAtBase: snapshot.existed } : {} });
10131
+ }
10132
+ findings = dedupeFindings(findings);
10133
+ const extensionsNew = (config.extend ?? []).filter((e) => findings.some((f) => f.rule === "extension-added" && f.file === e.file && f.subject === e.rule));
9676
10134
  const errors = findings.filter((f) => f.level === "error").length;
9677
10135
  const warnings = findings.filter((f) => f.level === "warn").length;
9678
10136
  const infos = findings.length - errors - warnings;
@@ -9686,9 +10144,24 @@ async function runDoctor(options = {}) {
9686
10144
  primitives: primitivesSummary(packages),
9687
10145
  errors,
9688
10146
  warnings,
9689
- infos
10147
+ infos,
10148
+ ...extensionsNew.length ? { extensionsAdded: extensionsNew } : {}
9690
10149
  };
9691
10150
  }
10151
+ function baseChecks(rules, preferIds, packagePlugins, all) {
10152
+ if ([...rules].every((r) => preferIds.has(r))) return packagePlugins.filter((p) => p.name === "package-rules");
10153
+ return all();
10154
+ }
10155
+ async function runChecks(ctx, checks) {
10156
+ for (const plugin of checks) {
10157
+ try {
10158
+ await plugin.check(ctx);
10159
+ } catch (err) {
10160
+ if (err instanceof DoctorConfigError) throw err;
10161
+ ctx.report({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
10162
+ }
10163
+ }
10164
+ }
9692
10165
  function builtinChecks(config, options = {}) {
9693
10166
  const packs = {
9694
10167
  native: { name: "native", check: checkNativePack },
@@ -9713,6 +10186,7 @@ function builtinChecks(config, options = {}) {
9713
10186
  { name: "resource-view-trees", check: checkTreeViews },
9714
10187
  { name: "studio-server-imports", check: checkStudioServerImports },
9715
10188
  { name: "removed-scope-names", check: checkRemovedScopeNames },
10189
+ { name: "app-parts", check: checkAppParts },
9716
10190
  { name: "stability-imports", check: checkStabilityImports },
9717
10191
  { name: "agent-guide", check: (ctx) => {
9718
10192
  checkAgentGuide(ctx);
@@ -9782,10 +10256,14 @@ function formatReport(result, options = {}) {
9782
10256
  `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"}`
9783
10257
  ];
9784
10258
  for (const f of result.findings) {
9785
- lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
10259
+ lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${(f.rules ?? [f.rule]).join(", ")}] ${f.message}`);
9786
10260
  }
9787
10261
  lines.push(options.verbose ? `Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}` : `Available but unused: ${result.unused.length} (genesis doctor --verbose lists them)`);
9788
10262
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
10263
+ if (result.extensionsAdded?.length) {
10264
+ lines.push(`Extensions added on this branch (${result.extensionsAdded.length}); the pull request's review accepts each:`);
10265
+ for (const e of result.extensionsAdded) lines.push(` ${e.file} [${e.rule}] builds on ${e.buildsOn}: ${e.reason}${e.upstream ? ` (upstream: ${e.upstream})` : ""}`);
10266
+ }
9789
10267
  const info = result.infos ? `, ${result.infos} info` : "";
9790
10268
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
9791
10269
  return lines.join("\n");
@@ -9799,7 +10277,8 @@ function toJson(result) {
9799
10277
  infos: result.infos,
9800
10278
  findings: result.findings,
9801
10279
  unused: result.unused,
9802
- primitives: result.primitives
10280
+ primitives: result.primitives,
10281
+ ...result.extensionsAdded ? { extensionsAdded: result.extensionsAdded } : {}
9803
10282
  };
9804
10283
  }
9805
10284
  function genesisSummary(g) {
@@ -9831,9 +10310,11 @@ var init_doctor = __esm({
9831
10310
  init_structure();
9832
10311
  init_dates();
9833
10312
  init_api_usage();
10313
+ init_custom_views();
9834
10314
  init_stability();
9835
10315
  init_package_rules();
9836
10316
  init_ratchet();
10317
+ init_extensions();
9837
10318
  init_contracts();
9838
10319
  init_primitives();
9839
10320
  init_agent_hooks();
@@ -9857,6 +10338,7 @@ var init_doctor = __esm({
9857
10338
  init_package_rules();
9858
10339
  init_primitives();
9859
10340
  init_ratchet();
10341
+ init_extensions();
9860
10342
  init_contracts();
9861
10343
  init_agent_hooks();
9862
10344
  RATCHETED_BY_DEFAULT = ["deprecated-import", "genesis-eslint-config"];