@marktiderman/genesis-cli 1.24.0 → 1.25.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/index.js CHANGED
@@ -1534,6 +1534,7 @@ var KNOWN = /* @__PURE__ */ new Set([
1534
1534
  "forbiddenImports",
1535
1535
  "rules",
1536
1536
  "allow",
1537
+ "extend",
1537
1538
  "patterns",
1538
1539
  "plugins",
1539
1540
  "packs",
@@ -1548,7 +1549,10 @@ var KNOWN = /* @__PURE__ */ new Set([
1548
1549
  "$comment"
1549
1550
  ]);
1550
1551
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
1551
- var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
1552
+ var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped", "extension-invalid"]);
1553
+ var CONFIG_RULES = /* @__PURE__ */ new Set(["stale-exception", "stale-extension", "package-rule-override"]);
1554
+ var EXTENSION_KEYS = /* @__PURE__ */ new Set(["rule", "file", "buildsOn", "reason", "upstream"]);
1555
+ var EXTENSION_REASON_MIN = { chars: 40, words: 6 };
1552
1556
  var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
1553
1557
  var PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
1554
1558
  var CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
@@ -1759,6 +1763,30 @@ function validateConfig(raw, source = "config") {
1759
1763
  }
1760
1764
  });
1761
1765
  }
1766
+ if (c.extend !== void 0) {
1767
+ if (!Array.isArray(c.extend)) fail(`"extend" must be a list of { rule, file, buildsOn, reason, upstream? }`);
1768
+ const seen = /* @__PURE__ */ new Set();
1769
+ c.extend.forEach((e, i) => {
1770
+ const where2 = `extend[${i}]`;
1771
+ if (!isObject(e)) return fail(`${where2} must be an object`);
1772
+ for (const k of Object.keys(e)) if (!EXTENSION_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: ${[...EXTENSION_KEYS].join(", ")})`);
1773
+ for (const k of ["rule", "file", "buildsOn", "reason"]) if (typeof e[k] !== "string" || !e[k].trim()) fail(`${where2} needs "${k}"`);
1774
+ const { rule, file, buildsOn, reason } = e;
1775
+ 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`);
1776
+ 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)`);
1777
+ if (/[*?[\]{}]/.test(file)) fail(`${where2}.file must be one file, not a glob: each extension is reviewed on its own`);
1778
+ e.file = appPath(file, `${where2}.file`, fail);
1779
+ 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")`);
1780
+ const text = reason.trim();
1781
+ if (text.length < EXTENSION_REASON_MIN.chars || text.split(/\s+/).length < EXTENSION_REASON_MIN.words) {
1782
+ 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`);
1783
+ }
1784
+ 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`);
1785
+ const key2 = `${rule}\0${e.file}`;
1786
+ if (seen.has(key2)) fail(`${where2} extends ${rule} in ${e.file} twice`);
1787
+ seen.add(key2);
1788
+ });
1789
+ }
1762
1790
  if (c.patterns !== void 0) {
1763
1791
  if (!Array.isArray(c.patterns)) fail(`"patterns" must be a list`);
1764
1792
  c.patterns.forEach((p, i) => {
@@ -2452,6 +2480,9 @@ function scanFiles(root, config) {
2452
2480
  for (const pkg of local) walk3(pkg.dir);
2453
2481
  return files;
2454
2482
  }
2483
+ function withText(file, text) {
2484
+ return { ...file, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(file.ext)) };
2485
+ }
2455
2486
  function lineAt(text, index) {
2456
2487
  let line = 1;
2457
2488
  for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
@@ -3449,6 +3480,10 @@ var BUILTIN_RULES = [
3449
3480
  "ratchet-skipped",
3450
3481
  "allow-grew",
3451
3482
  "rules-weakened",
3483
+ "extension-added",
3484
+ // declared extensions (extensions.ts)
3485
+ "stale-extension",
3486
+ "extension-invalid",
3452
3487
  // agent guide (primitives.ts)
3453
3488
  "agent-guide-stale",
3454
3489
  // supabase pack: contracts (contracts.ts)
@@ -3737,6 +3772,34 @@ function readSource(abs) {
3737
3772
  return null;
3738
3773
  }
3739
3774
  }
3775
+ var lastBlanked = null;
3776
+ function blankStrings(code) {
3777
+ if (lastBlanked?.source === code) return lastBlanked.blanked;
3778
+ const out = code.split("");
3779
+ for (let i = 0; i < code.length; i++) {
3780
+ const ch = code[i];
3781
+ if (ch !== '"' && ch !== "'" && ch !== "`") continue;
3782
+ let j = i - 1;
3783
+ while (j >= 0 && /[ \t]/.test(code[j])) j--;
3784
+ const before = j >= 0 ? code[j] : "\n";
3785
+ const word = /[\w$]/.test(before) ? /(?:^|[^\w$])(return|case|typeof|in|of|yield|await)$/.test(code.slice(Math.max(0, j - 8), j + 1)) : false;
3786
+ if (/[\w$)\]]/.test(before) && !word) continue;
3787
+ let k = i + 1;
3788
+ for (; k < code.length; k++) {
3789
+ const c = code[k];
3790
+ if (c === "\\") {
3791
+ k++;
3792
+ continue;
3793
+ }
3794
+ if (c === ch) break;
3795
+ if (c === "\n" && ch !== "`") break;
3796
+ }
3797
+ for (let x = i + 1; x < k && x < code.length; x++) if (code[x] !== "\n") out[x] = " ";
3798
+ i = k;
3799
+ }
3800
+ lastBlanked = { source: code, blanked: out.join("") };
3801
+ return lastBlanked.blanked;
3802
+ }
3740
3803
  function tagEnd(code, start) {
3741
3804
  let depth = 0;
3742
3805
  let quote2 = null;
@@ -3758,7 +3821,8 @@ function tagEnd(code, start) {
3758
3821
  }
3759
3822
  return { end: code.length, selfClosing: false };
3760
3823
  }
3761
- function openElementsAt(code, index, track) {
3824
+ function openElementsAt(source, index, track) {
3825
+ const code = blankStrings(source);
3762
3826
  const open = [];
3763
3827
  const re = /<(\/?)([A-Z][\w.]*)(?=[\s>/])/g;
3764
3828
  for (let m = re.exec(code); m && m.index < index; m = re.exec(code)) {
@@ -4610,9 +4674,9 @@ var PackageDeclarationError = class extends Error {
4610
4674
  var GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
4611
4675
  var ID = /^[a-z0-9][a-z0-9-]*$/;
4612
4676
  var LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
4613
- var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
4677
+ var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly", "extensible"]);
4614
4678
  var FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
4615
- var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
4679
+ var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "inside", "pattern"]);
4616
4680
  var PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
4617
4681
  var DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "catalog", "primitives", "plugin", "$comment"]);
4618
4682
  var SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
@@ -4721,6 +4785,9 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4721
4785
  if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
4722
4786
  if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
4723
4787
  for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
4788
+ if (raw.extensible !== void 0 && !(isStringList2(raw.extensible) && raw.extensible.every((n) => /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(n)))) {
4789
+ fail(`${at}.extensible must be a list of export names, or parts of one ("ResourceView.slots")`);
4790
+ }
4724
4791
  if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
4725
4792
  const forbid = raw.forbid;
4726
4793
  for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
@@ -4733,6 +4800,7 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4733
4800
  const unless = raw.unless;
4734
4801
  for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
4735
4802
  if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
4803
+ 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`);
4736
4804
  if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
4737
4805
  }
4738
4806
  return raw;
@@ -4847,6 +4915,7 @@ function compile(rule, setting, routes) {
4847
4915
  imports: (rule.forbid.imports ?? []).map(specMatcher),
4848
4916
  ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
4849
4917
  unlessRenders: new Set(rule.unless?.renders ?? []),
4918
+ unlessInside: new Set(rule.unless?.inside ?? []),
4850
4919
  ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
4851
4920
  };
4852
4921
  }
@@ -4858,10 +4927,11 @@ function messageFor(rule, found) {
4858
4927
  const docs = rule.docs ? ` See ${rule.docs}` : "";
4859
4928
  return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
4860
4929
  }
4930
+ var CHILDREN = /\{\s*(?:props\.)?children\s*\}/g;
4861
4931
  var TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
4862
4932
  var EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
4863
4933
  var EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
4864
- function wrappersIn(file, elements, c) {
4934
+ function wrappersIn(file, elements, names, accept) {
4865
4935
  const out = /* @__PURE__ */ new Map();
4866
4936
  const decls = [...file.code.matchAll(TOP_LEVEL)];
4867
4937
  const listed = /* @__PURE__ */ new Map();
@@ -4874,12 +4944,12 @@ function wrappersIn(file, elements, c) {
4874
4944
  for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
4875
4945
  decls.forEach((d, i) => {
4876
4946
  const name = d[3];
4877
- if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
4947
+ if (!/^[A-Z]/.test(name) || names.has(name)) return;
4878
4948
  const end = decls[i + 1]?.index ?? file.code.length;
4879
- const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
4880
- if (!hit) return;
4881
- const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4882
- for (const n of names) out.set(n, hit[1]);
4949
+ const hit = elements.find((m) => m.index > d.index && m.index < end && names.has(m[1]));
4950
+ if (!hit || accept && !accept(d.index, end)) return;
4951
+ const exported = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4952
+ for (const n of exported) out.set(n, hit[1]);
4883
4953
  });
4884
4954
  return out;
4885
4955
  }
@@ -4887,6 +4957,32 @@ function runPrefer(ctx, c) {
4887
4957
  const own = c.rule.packageDir;
4888
4958
  const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
4889
4959
  const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
4960
+ const scanned = new Map(ctx.files.map((f) => [f.absolutePath, f]));
4961
+ const importedBy = /* @__PURE__ */ new Map();
4962
+ const importsOf = (file) => {
4963
+ if (!importedBy.has(file)) importedBy.set(file, localImportedNames(ctx.root, file));
4964
+ return importedBy.get(file);
4965
+ };
4966
+ const builders = /* @__PURE__ */ new Map();
4967
+ const buildersIn = (abs) => {
4968
+ if (!builders.has(abs)) {
4969
+ const target = scanned.get(abs) ?? readSource(abs);
4970
+ const code = target ? "ext" in target ? target.code : stripBlockComments(target.code, true) : "";
4971
+ const childrenInside = (start, end) => [...code.slice(start, end).matchAll(CHILDREN)].some((m) => openElementsAt(code, start + m.index, (n) => c.unlessInside.has(n)).length > 0);
4972
+ builders.set(abs, code ? wrappersIn({ code }, [...code.matchAll(ELEMENT)], c.unlessInside, childrenInside) : /* @__PURE__ */ new Map());
4973
+ }
4974
+ return builders.get(abs);
4975
+ };
4976
+ const nestedInBuilder = (file, index) => {
4977
+ if (!c.unlessInside.size) return false;
4978
+ const imported = importsOf(file);
4979
+ const isBuilder = (name) => {
4980
+ if (c.unlessInside.has(name)) return true;
4981
+ const from = name.includes(".") ? void 0 : imported.get(name);
4982
+ return from !== void 0 && buildersIn(from.file).has(from.name);
4983
+ };
4984
+ return openElementsAt(file.code, index, isBuilder).length > 0;
4985
+ };
4890
4986
  const wrappers = /* @__PURE__ */ new Map();
4891
4987
  const renderedBy = /* @__PURE__ */ new Map();
4892
4988
  for (const file of checked) {
@@ -4894,16 +4990,17 @@ function runPrefer(ctx, c) {
4894
4990
  const elements = [...file.code.matchAll(ELEMENT)];
4895
4991
  renderedBy.set(file, elements);
4896
4992
  if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
4897
- const found = wrappersIn(file, elements, c);
4993
+ const found = wrappersIn(file, elements, c.jsx);
4898
4994
  if (found.size) wrappers.set(file.absolutePath, found);
4899
4995
  }
4900
4996
  for (const file of checked) {
4901
4997
  const elements = renderedBy.get(file) ?? [];
4902
4998
  if (exempt(file, elements.map((m) => m[1]))) continue;
4903
4999
  const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
4904
- const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
5000
+ const imported = wrappers.size && elements.length ? importsOf(file) : null;
4905
5001
  for (const m of elements) {
4906
5002
  const name = m[1];
5003
+ if (nestedInBuilder(file, m.index)) continue;
4907
5004
  if (c.jsx.has(name)) {
4908
5005
  report(lineAt(file.code, m.index), name, `renders <${name}>`);
4909
5006
  continue;
@@ -4920,6 +5017,7 @@ function runPrefer(ctx, c) {
4920
5017
  if (c.pattern) {
4921
5018
  c.pattern.lastIndex = 0;
4922
5019
  for (const m of file.code.matchAll(c.pattern)) {
5020
+ if (nestedInBuilder(file, m.index)) continue;
4923
5021
  const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
4924
5022
  report(lineAt(file.code, m.index), text, `has ${text}`);
4925
5023
  }
@@ -6715,13 +6813,34 @@ function git3(root, args) {
6715
6813
  return r.status === 0 ? r.stdout : null;
6716
6814
  }
6717
6815
  function changedSince(root, base) {
6718
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6816
+ const mergeBase = mergeBaseOf2(root, base);
6719
6817
  if (!mergeBase) return null;
6720
6818
  const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
6721
6819
  const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
6722
6820
  if (committed === null || untracked === null) return null;
6723
6821
  return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
6724
6822
  }
6823
+ function originsSince(root, base) {
6824
+ const out = /* @__PURE__ */ new Map();
6825
+ const mergeBase = mergeBaseOf2(root, base);
6826
+ if (!mergeBase) return out;
6827
+ const diff = git3(root, ["diff", "-z", "-M", "--name-status", "--relative", mergeBase, "--"]);
6828
+ if (diff === null) return out;
6829
+ const parts = diff.split("\0");
6830
+ for (let i = 0; i < parts.length; ) {
6831
+ const status = parts[i++] ?? "";
6832
+ if (!status) continue;
6833
+ if (status.startsWith("R") || status.startsWith("C")) {
6834
+ const from = parts[i++];
6835
+ const to = parts[i++];
6836
+ if (status.startsWith("R")) out.set(to, from);
6837
+ } else i++;
6838
+ }
6839
+ return out;
6840
+ }
6841
+ function mergeBaseOf2(root, base) {
6842
+ return git3(root, ["merge-base", base, "HEAD"])?.trim() || null;
6843
+ }
6725
6844
  var objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
6726
6845
  function showAt(dir, rev, file) {
6727
6846
  const at = `${rev}:./${file}`;
@@ -6729,7 +6848,7 @@ function showAt(dir, rev, file) {
6729
6848
  return git3(dir, ["show", at]);
6730
6849
  }
6731
6850
  function configAtBase(root, base, explicitFile) {
6732
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6851
+ const mergeBase = mergeBaseOf2(root, base);
6733
6852
  if (!mergeBase) return null;
6734
6853
  const candidates = explicitFile ? [{ dir: path21.dirname(explicitFile), file: path21.basename(explicitFile), explicit: true }] : [
6735
6854
  { dir: root, file: "genesis.config.json", explicit: false },
@@ -6750,7 +6869,12 @@ function configAtBase(root, base, explicitFile) {
6750
6869
  continue;
6751
6870
  }
6752
6871
  const b = objectOr(block);
6753
- return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
6872
+ return {
6873
+ allow: Array.isArray(b.allow) ? b.allow : [],
6874
+ extend: Array.isArray(b.extend) ? b.extend : [],
6875
+ rules: objectOr(b.rules),
6876
+ packageRules: objectOr(b.packageRules)
6877
+ };
6754
6878
  }
6755
6879
  return "absent";
6756
6880
  }
@@ -6764,6 +6888,16 @@ function allowGrew(allow, before, base) {
6764
6888
  message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
6765
6889
  }));
6766
6890
  }
6891
+ function extensionsAdded(extend, before, base) {
6892
+ const had = new Set(before.map((e) => `${e.rule}\0${e.file}\0${e.buildsOn}`));
6893
+ return extend.filter((e) => !had.has(`${e.rule}\0${e.file}\0${e.buildsOn}`)).map((e) => ({
6894
+ rule: "extension-added",
6895
+ level: "info",
6896
+ file: e.file,
6897
+ subject: e.rule,
6898
+ 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`
6899
+ }));
6900
+ }
6767
6901
  var RANK = { off: 0, info: 1, warn: 2, error: 3 };
6768
6902
  function rulesWeakened(config, before, base) {
6769
6903
  const out = [];
@@ -6801,14 +6935,169 @@ var NEVER_RATCHETED = /* @__PURE__ */ new Set([
6801
6935
  "plugin-error",
6802
6936
  "build",
6803
6937
  "agent-guide-stale",
6804
- "contracts-stale"
6938
+ "contracts-stale",
6939
+ "stale-extension",
6940
+ "extension-added"
6805
6941
  ]);
6942
+ function isRatcheted(rule, config, newOnly) {
6943
+ return !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6944
+ }
6945
+ var countKey = (file, rule) => `${file}\0${rule}`;
6946
+ function countFindings(findings) {
6947
+ const counts = /* @__PURE__ */ new Map();
6948
+ for (const f of findings) counts.set(countKey(f.file, f.rule), (counts.get(countKey(f.file, f.rule)) ?? 0) + 1);
6949
+ return counts;
6950
+ }
6806
6951
  function applyRatchet(findings, options) {
6807
- const { config, newOnly, changed, base, isAppPath } = options;
6808
- const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6952
+ const { config, newOnly, changed, base, isAppPath, baseCounts, existedAtBase } = options;
6953
+ const originOf = options.originOf ?? ((f) => f);
6954
+ const counts = countFindings(findings.map((f) => ({ file: originOf(f.file), rule: f.rule })));
6809
6955
  return findings.map((f) => {
6810
- if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
6811
- return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6956
+ if (f.level === "info" || !isRatcheted(f.rule, config, newOnly) || !isAppPath(f.file)) return f;
6957
+ if (!touched(f.file, changed)) return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6958
+ const origin = originOf(f.file);
6959
+ if (!baseCounts || !existedAtBase?.(origin)) return f;
6960
+ const now = counts.get(countKey(origin, f.rule)) ?? 0;
6961
+ const was = baseCounts.get(countKey(origin, f.rule)) ?? 0;
6962
+ const where2 = origin === f.file ? "this file" : `the files from ${origin}`;
6963
+ 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)` };
6964
+ return { ...f, level: "info", message: `${f.message} (ratcheted: ${now} in ${where2}, ${was} at the merge base with ${base})` };
6965
+ });
6966
+ }
6967
+ function snapshotAtBase(root, base, files, changed, originOf = (f) => f) {
6968
+ const mergeBase = mergeBaseOf2(root, base);
6969
+ if (!mergeBase) return null;
6970
+ const out = [];
6971
+ const seen = /* @__PURE__ */ new Set();
6972
+ for (const f of files) {
6973
+ if (!changed.has(f.path)) {
6974
+ if (!seen.has(f.path)) out.push(f);
6975
+ seen.add(f.path);
6976
+ continue;
6977
+ }
6978
+ const origin = originOf(f.path);
6979
+ if (seen.has(origin)) continue;
6980
+ seen.add(origin);
6981
+ const text = showAt(root, mergeBase, origin);
6982
+ if (text === null) return null;
6983
+ if (text !== void 0) out.push(withText({ ...f, path: origin, absolutePath: path21.join(root, origin) }, text));
6984
+ }
6985
+ const cache2 = /* @__PURE__ */ new Map();
6986
+ return {
6987
+ mergeBase,
6988
+ files: out,
6989
+ existed(file) {
6990
+ if (!cache2.has(file)) cache2.set(file, git3(root, ["cat-file", "-e", `${mergeBase}:./${file}`]) !== null);
6991
+ return cache2.get(file);
6992
+ }
6993
+ };
6994
+ }
6995
+
6996
+ // src/doctor/extensions.ts
6997
+ function pointProblem(entry, packages) {
6998
+ const rule = preferRules(packages).find((r) => r.ruleId === entry.rule);
6999
+ if (!rule?.extensible?.length) return `${entry.rule} declares no extension points, so it can't be extended (debt goes in allow, and is fixed)`;
7000
+ if (!rule.extensible.includes(entry.buildsOn)) return `${entry.buildsOn} isn't one of ${entry.rule}'s extension points (${rule.extensible.join(", ")})`;
7001
+ return null;
7002
+ }
7003
+ function extensionProblem(entry, ctx) {
7004
+ const point = pointProblem(entry, ctx.packages);
7005
+ if (point) return point;
7006
+ const name = entry.buildsOn.split(".")[0];
7007
+ const replaces = preferRules(ctx.packages).find((r) => r.forbid.jsx?.includes(name));
7008
+ if (replaces) return `${name} is what ${replaces.ruleId} replaces (use ${replaces.use}); a legacy component can't be built on`;
7009
+ const flagged = ctx.raw.find((f) => f.file === entry.file && f.subject === name);
7010
+ if (flagged) return `${name} is flagged in this file by ${flagged.rule}; build on a current Genesis primitive`;
7011
+ const file = ctx.files.find((f) => f.path === entry.file);
7012
+ if (!file) return `${entry.file} isn't one of the files the doctor scans`;
7013
+ const imported = genesisNamedImports(file.code).some((i) => i.names.includes(name));
7014
+ if (!imported) return `${entry.file} doesn't import ${name} from a Genesis package; buildsOn names the extension point the file uses`;
7015
+ if (!usesPoint(blankStrings(file.code), entry.buildsOn)) {
7016
+ const prop = entry.buildsOn.split(".")[1];
7017
+ 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`;
7018
+ }
7019
+ return null;
7020
+ }
7021
+ var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7022
+ function usesPoint(code, point) {
7023
+ const [name, prop] = point.split(".");
7024
+ const n = escape2(name);
7025
+ if (!prop) return new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])|(?<![\\w$.])${n}\\s*(?:<[^>()]*>)?\\s*\\(`).test(code);
7026
+ for (const m of code.matchAll(new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])`, "g"))) {
7027
+ const { end } = tagEnd(code, m.index);
7028
+ if (new RegExp(`(?<![\\w$.])${escape2(prop)}\\s*=`).test(code.slice(m.index, end))) return true;
7029
+ }
7030
+ return false;
7031
+ }
7032
+ function applyExtensions(findings, ctx) {
7033
+ const entries = ctx.config.extend ?? [];
7034
+ if (!entries.length) return findings;
7035
+ const staleLevel = ctx.config.rules?.["stale-extension"];
7036
+ const covered = /* @__PURE__ */ new Set();
7037
+ const grew = /* @__PURE__ */ new Map();
7038
+ const out = [];
7039
+ 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}` });
7040
+ for (const entry of entries) {
7041
+ if (ctx.config.rules?.[entry.rule] === "off" || ctx.config.packageRules?.[entry.rule]?.level === "off") continue;
7042
+ const point = pointProblem(entry, ctx.packages);
7043
+ if (point) {
7044
+ invalid(entry, point);
7045
+ continue;
7046
+ }
7047
+ const hits = findings.filter((f) => f.rule === entry.rule && f.file === entry.file);
7048
+ if (!hits.length) {
7049
+ if (staleLevel === "off") continue;
7050
+ out.push({
7051
+ rule: "stale-extension",
7052
+ level: staleLevel ?? "warn",
7053
+ file: entry.file,
7054
+ line: 0,
7055
+ subject: entry.rule,
7056
+ message: `the extension of ${entry.rule} (building on ${entry.buildsOn}) no longer matches a finding in this file; remove it from doctor.extend`
7057
+ });
7058
+ continue;
7059
+ }
7060
+ const problem = extensionProblem(entry, ctx);
7061
+ if (problem) {
7062
+ invalid(entry, problem);
7063
+ continue;
7064
+ }
7065
+ const limit = ctx.limit?.(entry);
7066
+ if (limit !== void 0 && hits.length > limit) {
7067
+ 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)`);
7068
+ continue;
7069
+ }
7070
+ for (const h of hits) covered.add(h);
7071
+ }
7072
+ const kept = findings.filter((f) => !covered.has(f)).map((f) => grew.has(f) ? { ...f, message: grew.get(f) } : f);
7073
+ return [...kept, ...out].sort(byPlace);
7074
+ }
7075
+ var byPlace = (x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule);
7076
+ var RANK2 = { info: 0, warn: 1, error: 2 };
7077
+ function dedupeFindings(findings) {
7078
+ const groups = /* @__PURE__ */ new Map();
7079
+ const order = [];
7080
+ for (const f of findings) {
7081
+ if (f.subject === void 0 || !f.line) {
7082
+ order.push([f]);
7083
+ continue;
7084
+ }
7085
+ const key2 = `${f.file}\0${f.line}\0${f.subject}`;
7086
+ const list = groups.get(key2) ?? [];
7087
+ const group = list.find((g) => !g.some((x) => x.rule === f.rule));
7088
+ if (group) group.push(f);
7089
+ else {
7090
+ const fresh = [f];
7091
+ list.push(fresh);
7092
+ groups.set(key2, list);
7093
+ order.push(fresh);
7094
+ }
7095
+ }
7096
+ return order.map((group) => {
7097
+ if (group.length === 1) return group[0];
7098
+ const primary = group.reduce((a, b) => RANK2[b.level] > RANK2[a.level] ? b : a);
7099
+ const rules = [primary.rule, ...group.filter((g) => g !== primary).map((g) => g.rule)];
7100
+ return { ...primary, rules, message: `${primary.message} (also ${rules.slice(1).join(", ")})` };
6812
7101
  });
6813
7102
  }
6814
7103
  var DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
@@ -8002,14 +8291,8 @@ async function runDoctor(options = {}) {
8002
8291
  }
8003
8292
  const raw = [];
8004
8293
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
8005
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
8006
- try {
8007
- await plugin.check(ctx);
8008
- } catch (err) {
8009
- if (err instanceof DoctorConfigError) throw err;
8010
- raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
8011
- }
8012
- }
8294
+ const appChecks = [...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins];
8295
+ await runChecks(ctx, [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...appChecks]);
8013
8296
  if (options.build) {
8014
8297
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
8015
8298
  if (failure) raw.push(failure);
@@ -8019,30 +8302,57 @@ async function runDoctor(options = {}) {
8019
8302
  let changed = null;
8020
8303
  let skipped = false;
8021
8304
  const ratchetNeeded = newOnly.size > RATCHETED_BY_DEFAULT.length || raw.some((f) => RATCHETED_BY_DEFAULT.includes(f.rule));
8022
- if (options.base && (ratchetNeeded || config.ratchet)) {
8305
+ if (options.base && (ratchetNeeded || config.ratchet || config.extend?.length)) {
8023
8306
  changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
8024
8307
  skipped ||= !changed;
8025
8308
  }
8026
8309
  const configFile = "file" in loaded ? loaded.file : null;
8027
- const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
8310
+ const guarded = (config.allow?.length ?? 0) + (config.extend?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
8028
8311
  let configSkipped = false;
8312
+ let baseExtend = [];
8029
8313
  if (options.base && configFile) {
8030
8314
  const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
8315
+ if (before && before !== "absent") baseExtend = before.extend;
8316
+ if (before === "absent") raw.push(...extensionsAdded(config.extend ?? [], [], options.base));
8031
8317
  if (before && before !== "absent") {
8032
8318
  raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
8033
8319
  raw.push(...rulesWeakened(config, before, options.base));
8320
+ raw.push(...extensionsAdded(config.extend ?? [], before.extend, options.base));
8034
8321
  }
8035
8322
  configSkipped = !before && guarded;
8036
8323
  }
8037
8324
  if (skipped || configSkipped) {
8038
8325
  raw.push(
8039
- 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` }
8326
+ 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` }
8040
8327
  );
8041
8328
  }
8042
- let findings = applyConfig(raw, config, packageRuleIds(packages));
8329
+ const packageIds = packageRuleIds(packages);
8330
+ const extensionCtx = { config, files, packages, raw };
8331
+ const configured = applyConfig(raw, config, packageIds);
8332
+ let findings = applyExtensions(configured, extensionCtx);
8043
8333
  if (options.base && changed) {
8044
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path21.join(root, f)) });
8334
+ const isAppPath = (f) => existsSync(path21.join(root, f));
8335
+ const origins = options.changedFiles ? /* @__PURE__ */ new Map() : originsSince(root, options.base);
8336
+ const originOf = (f) => origins.get(f) ?? f;
8337
+ 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));
8338
+ 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))));
8339
+ for (const e of heldExtensions) dueRules.add(e.rule);
8340
+ const snapshot = dueRules.size ? snapshotAtBase(root, options.base, files, changed, originOf) : null;
8341
+ let baseCounts;
8342
+ if (snapshot) {
8343
+ const before = [];
8344
+ await runChecks({ ...ctx, files: snapshot.files, report: (f) => before.push(f) }, baseChecks(dueRules, packageIds, packagePlugins, () => [...builtinChecks(config, { contracts: false, figma: false }), ...appChecks]));
8345
+ baseCounts = countFindings(applyConfig(before, config, packageIds));
8346
+ if (heldExtensions.length) {
8347
+ const counts = baseCounts;
8348
+ const held = new Set(heldExtensions);
8349
+ findings = applyExtensions(configured, { ...extensionCtx, limit: (e) => held.has(e) ? counts.get(countKey(originOf(e.file), e.rule)) ?? 0 : void 0 });
8350
+ }
8351
+ }
8352
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath, originOf, ...snapshot && baseCounts ? { baseCounts, existedAtBase: snapshot.existed } : {} });
8045
8353
  }
8354
+ findings = dedupeFindings(findings);
8355
+ const extensionsNew = (config.extend ?? []).filter((e) => findings.some((f) => f.rule === "extension-added" && f.file === e.file && f.subject === e.rule));
8046
8356
  const errors = findings.filter((f) => f.level === "error").length;
8047
8357
  const warnings = findings.filter((f) => f.level === "warn").length;
8048
8358
  const infos = findings.length - errors - warnings;
@@ -8056,9 +8366,24 @@ async function runDoctor(options = {}) {
8056
8366
  primitives: primitivesSummary(packages),
8057
8367
  errors,
8058
8368
  warnings,
8059
- infos
8369
+ infos,
8370
+ ...extensionsNew.length ? { extensionsAdded: extensionsNew } : {}
8060
8371
  };
8061
8372
  }
8373
+ function baseChecks(rules, preferIds, packagePlugins, all) {
8374
+ if ([...rules].every((r) => preferIds.has(r))) return packagePlugins.filter((p) => p.name === "package-rules");
8375
+ return all();
8376
+ }
8377
+ async function runChecks(ctx, checks) {
8378
+ for (const plugin of checks) {
8379
+ try {
8380
+ await plugin.check(ctx);
8381
+ } catch (err) {
8382
+ if (err instanceof DoctorConfigError) throw err;
8383
+ ctx.report({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
8384
+ }
8385
+ }
8386
+ }
8062
8387
  function builtinChecks(config, options = {}) {
8063
8388
  const packs = {
8064
8389
  native: { name: "native", check: checkNativePack },
@@ -8152,10 +8477,14 @@ function formatReport(result, options = {}) {
8152
8477
  `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"}`
8153
8478
  ];
8154
8479
  for (const f of result.findings) {
8155
- lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
8480
+ lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${(f.rules ?? [f.rule]).join(", ")}] ${f.message}`);
8156
8481
  }
8157
8482
  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)`);
8158
8483
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
8484
+ if (result.extensionsAdded?.length) {
8485
+ lines.push(`Extensions added on this branch (${result.extensionsAdded.length}); the pull request's review accepts each:`);
8486
+ for (const e of result.extensionsAdded) lines.push(` ${e.file} [${e.rule}] builds on ${e.buildsOn}: ${e.reason}${e.upstream ? ` (upstream: ${e.upstream})` : ""}`);
8487
+ }
8159
8488
  const info = result.infos ? `, ${result.infos} info` : "";
8160
8489
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
8161
8490
  return lines.join("\n");