@marktiderman/genesis-cli 1.20.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +168 -9
  2. package/dist/cli.js +1114 -103
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{config-Dj_f9T7J.d.ts → config-HOmiOLQc.d.ts} +2 -0
  5. package/dist/doctor.d.ts +10 -5
  6. package/dist/doctor.js +1515 -1095
  7. package/dist/doctor.js.map +1 -1
  8. package/dist/expo.d.ts +2 -2
  9. package/dist/expo.js +10 -0
  10. package/dist/expo.js.map +1 -1
  11. package/dist/genesis-catalog.json +140 -20
  12. package/dist/index.d.ts +114 -2
  13. package/dist/index.js +1538 -1099
  14. package/dist/index.js.map +1 -1
  15. package/dist/starter/README.md +8 -5
  16. package/dist/starter/__tests__/components/setup.ts +11 -0
  17. package/dist/starter/__tests__/starter.test.ts +28 -0
  18. package/dist/starter/package.json +4 -3
  19. package/dist/starter/pnpm-workspace.yaml +22 -0
  20. package/dist/starter/src/lib/app.ts +13 -5
  21. package/dist/starter/src/lib/check-in.ts +5 -3
  22. package/dist/starter/src/lib/define-starter.ts +1 -1
  23. package/dist/starter/src/lib/devtools-overlay.ts +3 -4
  24. package/dist/starter/src/lib/native-modules.ts +9 -2
  25. package/dist/starter/src/lib/offline.ts +14 -0
  26. package/dist/starter/supabase/migrations/20261024000750_support_default_tenant.sql +18 -0
  27. package/dist/starter/supabase/migrations/20261024000800_genesis_support_tickets.sql +800 -0
  28. package/dist/starter/supabase/migrations/20261025000070_starter_tenancy.sql +26 -0
  29. package/dist/starter/supabase/migrations/20261025000080_genesis_chat_tenants.sql +716 -0
  30. package/dist/starter/supabase/migrations/20261025000090_genesis_chat_attachment_paths.sql +80 -0
  31. package/dist/starter/supabase/tests/database/chat_people.test.sql +1 -1
  32. package/dist/starter/supabase/tests/database/genesis_chat.test.sql +10 -2
  33. package/dist/starter/supabase/tests/database/genesis_chat_attachment_paths.test.sql +111 -0
  34. package/dist/starter/supabase/tests/database/genesis_chat_coaching.test.sql +8 -0
  35. package/dist/starter/supabase/tests/database/genesis_chat_search_threads.test.sql +8 -0
  36. package/dist/starter/supabase/tests/database/genesis_chat_tenants.test.sql +259 -0
  37. package/dist/starter/supabase/tests/database/genesis_support.test.sql +15 -3
  38. package/dist/starter/supabase/tests/database/genesis_support_findings.test.sql +10 -0
  39. package/dist/starter/supabase/tests/database/genesis_support_tickets.test.sql +327 -0
  40. package/dist/starter/supabase/tests/database/starter_tenancy.test.sql +19 -0
  41. package/dist/vite.js +1514 -1094
  42. package/dist/vite.js.map +1 -1
  43. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -16,8 +16,13 @@ import * as fs from 'fs/promises';
16
16
 
17
17
  var __defProp = Object.defineProperty;
18
18
  var __getOwnPropNames = Object.getOwnPropertyNames;
19
- var __esm = (fn, res) => function __init() {
20
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
19
+ var __esm = (fn, res, err) => function __init() {
20
+ if (err) throw err[0];
21
+ try {
22
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
23
+ } catch (e) {
24
+ throw err = [e], e;
25
+ }
21
26
  };
22
27
  var __export = (target, all) => {
23
28
  for (var name in all)
@@ -121,6 +126,39 @@ function parseManifest(home, id, raw, version, options = {}) {
121
126
  });
122
127
  }
123
128
  }
129
+ if (m["needs"] !== void 0) {
130
+ if (!Array.isArray(m["needs"])) problems.push(`${where2}.needs: must be a list of { function, how }`);
131
+ else {
132
+ out.needs = m["needs"].flatMap((n, j) => {
133
+ const at2 = `${where2}.needs[${j}]`;
134
+ if (!isObject(n) || typeof n["function"] !== "string" || typeof n["how"] !== "string" || !n["how"].trim()) {
135
+ problems.push(`${at2}: must be { function: "schema.name", how: "what to add" }`);
136
+ return [];
137
+ }
138
+ if (!SQL_FUNCTION.test(n["function"])) {
139
+ problems.push(`${at2}.function: "${n["function"]}" must be a schema-qualified function name, like private.genesis_viewer_people`);
140
+ return [];
141
+ }
142
+ return [{ function: n["function"], how: n["how"].trim() }];
143
+ });
144
+ }
145
+ }
146
+ if (m["runsBefore"] !== void 0) {
147
+ if (!Array.isArray(m["runsBefore"])) problems.push(`${where2}.runsBefore: must be a list of { package, file }`);
148
+ else {
149
+ out.runsBefore = m["runsBefore"].map((r, j) => {
150
+ const at2 = `${where2}.runsBefore[${j}]`;
151
+ if (!isObject(r)) {
152
+ problems.push(`${at2}: must be an object`);
153
+ return { package: home, file: "" };
154
+ }
155
+ const before = { package: pkgOf(r["package"], at2), file: pathOf(r["file"], `${at2}.file`) };
156
+ if (before.file && !MIGRATION_FILE.test(before.file.split("/").pop())) problems.push(`${at2}.file: "${before.file}" must be named NNNN_name.sql`);
157
+ if (before.package === out.package && before.file === file) problems.push(`${at2}: a migration can't run before itself`);
158
+ return before;
159
+ });
160
+ }
161
+ }
124
162
  if (m["test"] !== void 0) {
125
163
  out.test = pathOf(m["test"], `${where2}.test`);
126
164
  if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where2}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
@@ -231,7 +269,7 @@ function declarationFields(block) {
231
269
  function isBlockDef(value) {
232
270
  return isObject(value) && typeof value["id"] === "string" && BLOCK_ID.test(value["id"]) && (value["contributes"] === void 0 || isObject(value["contributes"])) && (isObject(value["contributes"]) || Array.isArray(value["requires"]));
233
271
  }
234
- var GENESIS_PACKAGE, BLOCK_ID, MIGRATION_FILE, FUNCTION_NAME, ROUTE, INSTALL_SPEC, SECRET, ManifestError, isObject, strings;
272
+ var GENESIS_PACKAGE, BLOCK_ID, MIGRATION_FILE, FUNCTION_NAME, ROUTE, INSTALL_SPEC, SECRET, SQL_FUNCTION, ManifestError, isObject, strings;
235
273
  var init_manifest = __esm({
236
274
  "src/blocks/manifest.ts"() {
237
275
  GENESIS_PACKAGE = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
@@ -241,6 +279,7 @@ var init_manifest = __esm({
241
279
  ROUTE = /^\/(?:[A-Za-z0-9_\-[\]().]+\/?)*$/;
242
280
  INSTALL_SPEC = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9.^~<>=|* -]+)?$/;
243
281
  SECRET = /^[A-Z][A-Z0-9_]*$/;
282
+ SQL_FUNCTION = /^[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*$/;
244
283
  ManifestError = class extends Error {
245
284
  constructor(problems) {
246
285
  super(`Invalid block manifest:
@@ -332,14 +371,14 @@ function listApp(root, rel, options = {}) {
332
371
  const dir = path30.join(root, rel);
333
372
  if (!existsSync(dir)) return [];
334
373
  const out = [];
335
- const walk3 = (r) => {
374
+ const walk4 = (r) => {
336
375
  for (const entry of readdirSync(path30.join(root, r), { withFileTypes: true })) {
337
376
  const child = `${r}/${entry.name}`;
338
- if (entry.isDirectory()) walk3(child);
377
+ if (entry.isDirectory()) walk4(child);
339
378
  else if (entry.isFile() || options.symlinks && entry.isSymbolicLink()) out.push(child);
340
379
  }
341
380
  };
342
- walk3(rel);
381
+ walk4(rel);
343
382
  return out.sort();
344
383
  }
345
384
  var sha256;
@@ -689,20 +728,24 @@ __export(migrations_exports, {
689
728
  MIGRATIONS_DIR: () => MIGRATIONS_DIR,
690
729
  TESTS_DIR: () => TESTS_DIR,
691
730
  applyMigrationPlan: () => applyMigrationPlan,
731
+ definesFunction: () => definesFunction,
692
732
  formatMigrationRows: () => formatMigrationRows,
693
733
  migrationHeader: () => migrationHeader,
694
734
  needsAttention: () => needsAttention,
695
735
  nextStamp: () => nextStamp,
696
736
  nextTimestamps: () => nextTimestamps,
737
+ orderByRunsBefore: () => orderByRunsBefore,
697
738
  planMigrations: () => planMigrations,
698
739
  providingMigrations: () => providingMigrations,
699
740
  readAppMigrations: () => readAppMigrations,
700
741
  rememberMigrationCopies: () => rememberMigrationCopies,
701
742
  stemOf: () => stemOf,
702
743
  stemOrNull: () => stemOrNull,
744
+ stripSqlComments: () => stripSqlComments,
703
745
  supersededFunctions: () => supersededFunctions,
704
746
  textSha: () => textSha,
705
747
  timestampOf: () => timestampOf,
748
+ unmetNeeds: () => unmetNeeds,
706
749
  validHeaderFile: () => validHeaderFile
707
750
  });
708
751
  function migrationHeader(pkg, file, source) {
@@ -729,6 +772,46 @@ function readAppMigrations(root, dir = MIGRATIONS_DIR) {
729
772
  return { path: p, name, content };
730
773
  });
731
774
  }
775
+ function stripSqlComments(sql) {
776
+ return sql.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/--[^\n]*/g, " ");
777
+ }
778
+ function definesFunction(sql, fn) {
779
+ const [schema, name] = fn.split(".");
780
+ const quoted = (id) => `(?:${id}|"${id}")`;
781
+ sql = stripSqlComments(sql);
782
+ return new RegExp(`create\\s+(?:or\\s+replace\\s+)?function\\s+${quoted(schema)}\\s*\\.\\s*${quoted(name)}\\s*\\(`, "i").test(sql);
783
+ }
784
+ function orderByRunsBefore(sources) {
785
+ if (!sources.some((m) => m.runsBefore?.length)) return sources.slice();
786
+ const key2 = (m) => `${m.package} ${m.file}`;
787
+ const index = /* @__PURE__ */ new Map();
788
+ sources.forEach((m, i) => {
789
+ if (!index.has(key2(m))) index.set(key2(m), i);
790
+ });
791
+ const after = sources.map(() => /* @__PURE__ */ new Set());
792
+ const last = /* @__PURE__ */ new Map();
793
+ sources.forEach((m, i) => {
794
+ const prev = last.get(m.package);
795
+ if (prev !== void 0) after[i].add(prev);
796
+ last.set(m.package, i);
797
+ for (const target of m.runsBefore ?? []) {
798
+ const t = index.get(key2(target));
799
+ if (t !== void 0 && t !== i) after[t].add(i);
800
+ }
801
+ });
802
+ const out = [];
803
+ const done = /* @__PURE__ */ new Set();
804
+ while (out.length < sources.length) {
805
+ const next = sources.findIndex((_, i) => !done.has(i) && [...after[i]].every((d) => done.has(d)));
806
+ if (next === -1) return sources.slice();
807
+ done.add(next);
808
+ out.push(sources[next]);
809
+ }
810
+ return out;
811
+ }
812
+ function unmetNeeds(src, defined) {
813
+ return (src.needs ?? []).filter((n) => !defined(n.function)).map((n) => `needs ${n.function} first: ${n.how}`);
814
+ }
732
815
  function needsAttention(row) {
733
816
  return row.state !== "current" && row.state !== "new" && row.state !== "deleted" && row.state !== "provided" && !row.forward;
734
817
  }
@@ -784,6 +867,7 @@ function nextTimestamps(existing, now, count) {
784
867
  function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date() }) {
785
868
  const app = readAppMigrations(root);
786
869
  const rows = [];
870
+ sources = orderByRunsBefore(sources);
787
871
  const providers = providingMigrations([{ migrations: sources }]);
788
872
  for (const p of options.providers ?? []) if (!providers.some((o) => o.package === p.package && o.file === p.file)) providers.push(p);
789
873
  const providerAt = (p) => {
@@ -828,6 +912,12 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
828
912
  continue;
829
913
  }
830
914
  const row2 = { ...base, state: "new" };
915
+ const earlier = sources.slice(0, sources.indexOf(src)).filter((s) => s.source !== null);
916
+ const unmet = unmetNeeds(src, (fn) => app.some((m) => definesFunction(m.content, fn)) || earlier.some((s) => definesFunction(s.source, fn)));
917
+ if (unmet.length) {
918
+ row2.unmet = unmet;
919
+ row2.detail = unmet.join("; ");
920
+ }
831
921
  rows.push(row2);
832
922
  pending.push({ row: row2, src, kind: "migration" });
833
923
  continue;
@@ -946,9 +1036,11 @@ __export(config_exports, {
946
1036
  checkRegExp: () => checkRegExp,
947
1037
  doctorBlock: () => doctorBlock,
948
1038
  isPackageDeclaration: () => isPackageDeclaration,
1039
+ isPlainFolder: () => isPlainFolder,
949
1040
  loadConfig: () => loadConfig,
950
1041
  privacyDataType: () => privacyDataType,
951
1042
  readGenesisConfig: () => readGenesisConfig,
1043
+ validateAppFolder: () => validateAppFolder,
952
1044
  validateConfig: () => validateConfig,
953
1045
  validateLinks: () => validateLinks,
954
1046
  validatePrivacy: () => validatePrivacy,
@@ -1014,8 +1106,17 @@ function readGenesisConfig(root) {
1014
1106
  const supabase = validateSupabase(raw.supabase, file);
1015
1107
  if (supabase !== true) out.supabase = supabase;
1016
1108
  }
1109
+ if (raw.appFolder !== void 0) out.appFolder = validateAppFolder(raw.appFolder, file);
1017
1110
  return out;
1018
1111
  }
1112
+ function isPlainFolder(value) {
1113
+ return PLAIN_FOLDER.test(value) && !value.split("/").includes("..");
1114
+ }
1115
+ function validateAppFolder(raw, source = "config") {
1116
+ const norm = typeof raw === "string" ? raw.replace(/^\.\//, "").replace(/\/+$/, "") : "";
1117
+ if (!isPlainFolder(norm)) throw new GenesisConfigError(`${source}: "appFolder" must be the app's folder from the repository root, such as "mobile" or "apps/phone" (got ${JSON.stringify(raw)})`);
1118
+ return norm;
1119
+ }
1019
1120
  function validateSupabase(raw, source = "config") {
1020
1121
  const fail = (msg) => {
1021
1122
  throw new GenesisConfigError(`${source}: ${msg}`);
@@ -1224,7 +1325,7 @@ function isObject2(v) {
1224
1325
  function isStringList(v) {
1225
1326
  return Array.isArray(v) && v.every((x) => typeof x === "string");
1226
1327
  }
1227
- var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, STRING_LISTS, STRINGS, KNOWN, LEVELS, META_RULES, PATTERN_KEYS, PACKAGE_RULE_KEYS, CONTRACT_KEYS, PACKS, PACK_KEYS, PRIVACY_KEYS, DATA_USE_KEYS, LINK_KEYS, HOST;
1328
+ var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, 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;
1228
1329
  var init_config = __esm({
1229
1330
  "src/doctor/config.ts"() {
1230
1331
  GenesisConfigError = class extends Error {
@@ -1312,6 +1413,7 @@ var init_config = __esm({
1312
1413
  supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
1313
1414
  packages: { base: "string" }
1314
1415
  };
1416
+ PLAIN_FOLDER = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}){0,7}$/;
1315
1417
  PRIVACY_KEYS = /* @__PURE__ */ new Set(["blocks", "collects", "tracking"]);
1316
1418
  DATA_USE_KEYS = /* @__PURE__ */ new Set(["type", "purposes", "linked", "tracking"]);
1317
1419
  LINK_KEYS = /* @__PURE__ */ new Set(["hosts", "paths", "webcredentials"]);
@@ -1426,7 +1528,7 @@ function uiPackageFor(config) {
1426
1528
  function loadGenesis(root, config) {
1427
1529
  const uiPackage = uiPackageFor(config);
1428
1530
  const pkg = readPackageExports(root, uiPackage);
1429
- if (!pkg) throw new DoctorConfigError(`${uiPackage} is not installed here. Install it, or set doctor.uiPackage.`);
1531
+ if (!pkg) throw new DoctorConfigError(notInstalled(root, uiPackage));
1430
1532
  const { dir: uiDir, exports: exportNames, values, components } = pkg;
1431
1533
  const tokens = /* @__PURE__ */ new Set();
1432
1534
  const themeFiles = resolveThemeFiles(root, config, uiDir);
@@ -1451,6 +1553,16 @@ function loadGenesis(root, config) {
1451
1553
  companions: loadCompanions(root, config, uiPackage)
1452
1554
  };
1453
1555
  }
1556
+ function notInstalled(root, uiPackage) {
1557
+ let declared = false;
1558
+ try {
1559
+ const pkg = JSON.parse(readFileSync(path30.join(root, "package.json"), "utf8"));
1560
+ declared = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].some((s) => pkg[s]?.[uiPackage] !== void 0);
1561
+ } catch {
1562
+ }
1563
+ if (!declared) return `${uiPackage} is not installed here and isn't in this app's package.json. Add it, or set doctor.uiPackage.`;
1564
+ return `${uiPackage} is in package.json but not installed, so this app's dependencies aren't installed. Run \`${shellLine(installCommand(detectPackageManager(root)))}\`, then run this again.`;
1565
+ }
1454
1566
  function loadCompanions(root, config, uiPackage) {
1455
1567
  const out = [];
1456
1568
  for (const name of config.componentPackages ?? DEFAULT_COMPONENT_PACKAGES) {
@@ -1677,6 +1789,7 @@ function loadPalette(root) {
1677
1789
  var DEFAULT_UI_PACKAGE, NATIVE_UI_PACKAGE, DESIGN_SYSTEM_PACKAGE, DEFAULT_COMPONENT_PACKAGES, TAGS, TAG_ALIASES, NON_COMPONENT_SUFFIX, TAILWIND_PALETTE, TS_SOURCE, isTsSource;
1678
1790
  var init_genesis = __esm({
1679
1791
  "src/doctor/genesis.ts"() {
1792
+ init_pm();
1680
1793
  init_config();
1681
1794
  DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
1682
1795
  NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
@@ -1910,7 +2023,7 @@ function globToRegExp(glob) {
1910
2023
  }
1911
2024
  function globMatcher(globs) {
1912
2025
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1913
- return (path56) => res.some((re) => re.test(path56));
2026
+ return (path61) => res.some((re) => re.test(path61));
1914
2027
  }
1915
2028
  var init_glob = __esm({
1916
2029
  "src/doctor/glob.ts"() {
@@ -1931,10 +2044,10 @@ function scanFiles(root, config) {
1931
2044
  const text = readFileSync(abs, "utf8");
1932
2045
  files.push({ path: rel, absolutePath: abs, ext, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(ext)) });
1933
2046
  };
1934
- const walk3 = (dir) => {
2047
+ const walk4 = (dir) => {
1935
2048
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1936
2049
  if (entry.isDirectory()) {
1937
- if (!SKIP_DIRS.has(entry.name)) walk3(path30.join(dir, entry.name));
2050
+ if (!SKIP_DIRS.has(entry.name)) walk4(path30.join(dir, entry.name));
1938
2051
  } else if (entry.isFile()) {
1939
2052
  visit(path30.join(dir, entry.name));
1940
2053
  }
@@ -1943,7 +2056,7 @@ function scanFiles(root, config) {
1943
2056
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
1944
2057
  const abs = path30.resolve(root, src);
1945
2058
  if (!existsSync(abs)) continue;
1946
- if (statSync(abs).isDirectory()) walk3(abs);
2059
+ if (statSync(abs).isDirectory()) walk4(abs);
1947
2060
  else visit(abs);
1948
2061
  }
1949
2062
  let local = [];
@@ -1952,7 +2065,7 @@ function scanFiles(root, config) {
1952
2065
  } catch {
1953
2066
  local = [];
1954
2067
  }
1955
- for (const pkg of local) walk3(pkg.dir);
2068
+ for (const pkg of local) walk4(pkg.dir);
1956
2069
  return files;
1957
2070
  }
1958
2071
  function lineAt(text, index) {
@@ -4019,7 +4132,7 @@ function checkShadowedExports(ctx) {
4019
4132
  file.code.split("\n").forEach((text, i) => {
4020
4133
  for (const m of text.matchAll(re)) {
4021
4134
  if (!ctx.genesis.values.has(m[1])) continue;
4022
- ctx.report({ rule: "shadowed-export", file: file.path, line: i + 1, subject: m[1], message: `shadows the Genesis export '${m[1]}'; reuse or extend Genesis ${m[1]}` });
4135
+ ctx.report({ rule: "shadowed-export", file: file.path, line: i + 1, subject: m[1], message: `shadows the Genesis export '${m[1]}'; reuse or extend ${m[1]} from ${ctx.genesis.uiPackage} (or rename yours if it's a different thing)` });
4023
4136
  }
4024
4137
  });
4025
4138
  }
@@ -4047,6 +4160,8 @@ var init_rules = __esm({
4047
4160
  init_overlays();
4048
4161
  BUILTIN_RULES = [
4049
4162
  "local-primitives",
4163
+ // figma (figma/routes.ts; runs when genesis.config.json has a figma block)
4164
+ "figma-routes",
4050
4165
  "starter-leftover",
4051
4166
  "forbidden-import",
4052
4167
  "raw-tag",
@@ -5687,11 +5802,11 @@ function checkMigrations(ctx, pkg, json, locals) {
5687
5802
  }
5688
5803
  function checkExports(ctx, pkg, json) {
5689
5804
  const targets = [];
5690
- const walk3 = (v) => {
5805
+ const walk4 = (v) => {
5691
5806
  if (typeof v === "string") targets.push(v);
5692
- else if (v && typeof v === "object") for (const x of Object.values(v)) walk3(x);
5807
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk4(x);
5693
5808
  };
5694
- walk3(json.exports);
5809
+ walk4(json.exports);
5695
5810
  for (const t of targets) {
5696
5811
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
5697
5812
  if (!existsSync(path30.join(pkg.dir, t))) {
@@ -6399,7 +6514,7 @@ function genesisInstalls(root) {
6399
6514
  via.get(real2).add(root2);
6400
6515
  if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
6401
6516
  };
6402
- const walk3 = (kind, roots) => {
6517
+ const walk4 = (kind, roots) => {
6403
6518
  const expanded = /* @__PURE__ */ new Set();
6404
6519
  const queue = [];
6405
6520
  const visit = (dir, by, range) => {
@@ -6450,9 +6565,9 @@ function genesisInstalls(root) {
6450
6565
  ...app?.dependencies
6451
6566
  };
6452
6567
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
6453
- walk3("runtime", rootsOf(runtimeDeps, "the app"));
6568
+ walk4("runtime", rootsOf(runtimeDeps, "the app"));
6454
6569
  const top = path30.join(root, "node_modules");
6455
- walk3(
6570
+ walk4(
6456
6571
  "hoisted",
6457
6572
  packagesIn(top).filter((dir) => {
6458
6573
  const name = path30.relative(top, dir).split(path30.sep).join("/");
@@ -6461,7 +6576,7 @@ function genesisInstalls(root) {
6461
6576
  );
6462
6577
  const devRoots = { ...devDeps };
6463
6578
  for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
6464
- walk3("dev", rootsOf(devRoots, "the app (dev)"));
6579
+ walk4("dev", rootsOf(devRoots, "the app (dev)"));
6465
6580
  for (const [key2, copy] of copies) {
6466
6581
  const kinds = via.get(key2);
6467
6582
  copy.runtime = kinds.has("runtime");
@@ -6725,6 +6840,29 @@ var init_dates = __esm({
6725
6840
  ISO_DAY_CUT = /\.toISOString\(\)\s*\.\s*(?:slice\(\s*0\s*,\s*10\s*\)|substring\(\s*0\s*,\s*10\s*\)|substr\(\s*0\s*,\s*10\s*\)|split\(\s*(["'`])T\1\s*\)\s*\[\s*0\s*\]|split\(\s*(["'`])T\2\s*\)\s*\.\s*at\(\s*0\s*\))/g;
6726
6841
  }
6727
6842
  });
6843
+ function appScripts(root) {
6844
+ const out = [];
6845
+ const walk4 = (dir) => {
6846
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
6847
+ const abs = path30.join(dir, entry.name);
6848
+ if (entry.isDirectory()) {
6849
+ if (!SKIP_DIRS3.has(entry.name)) walk4(abs);
6850
+ } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
6851
+ out.push(path30.relative(root, abs).split(path30.sep).join("/"));
6852
+ }
6853
+ }
6854
+ };
6855
+ walk4(root);
6856
+ return out;
6857
+ }
6858
+ var SKIP_DIRS3, SCRIPT2, MAX_BYTES;
6859
+ var init_app_scripts = __esm({
6860
+ "src/upgrade/app-scripts.ts"() {
6861
+ SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
6862
+ SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
6863
+ MAX_BYTES = 2 * 1024 * 1024;
6864
+ }
6865
+ });
6728
6866
 
6729
6867
  // src/upgrade/bump-core.mjs
6730
6868
  function compareVersions2(a, b) {
@@ -6958,6 +7096,113 @@ var init_bump_core = __esm({
6958
7096
  LEGACY_EXCLUDES = ["@marktiderman/genesis-*", UMBRELLA];
6959
7097
  }
6960
7098
  });
7099
+ function capsOnlyFitTheScreen(tag) {
7100
+ if (OWN_HEIGHT.test(tag) || BOTTOM_SHEET.test(tag)) return false;
7101
+ return [...tag.matchAll(ANY_MAX_H)].every((m) => {
7102
+ const vh = /^\[(\d+(?:\.\d+)?)vh\]$/.exec(m[1]);
7103
+ return vh !== null && Number(vh[1]) >= CHOSEN_CAP_BELOW;
7104
+ });
7105
+ }
7106
+ function rewriteOverlayHeights(text) {
7107
+ return text.replace(OVERLAY_TAG, (tag) => {
7108
+ const drop = capsOnlyFitTheScreen(tag);
7109
+ const next = tag.replace(VH_CLASS, (_all, lead, variants, kind, size) => kind === "max-h" && drop ? lead : `${lead}${variants}${kind}-[${size}dvh]`);
7110
+ if (next === tag) return tag;
7111
+ return next.replace(/\bclassName=(["'])([^"']*)\1/, (_all, quote2, classes) => `className=${quote2}${classes.trim().replace(/\s+/g, " ")}${quote2}`).replace(/\s+className=(["'])\1/, "");
7112
+ });
7113
+ }
7114
+ function inComment(text, at) {
7115
+ const lineStart = text.lastIndexOf("\n", at - 1) + 1;
7116
+ if (/^\s*(?:\/\/|\*)/.test(text.slice(lineStart, at)) || /(?:^|[\s;{}()])\/\/[^"'`]*$/.test(text.slice(lineStart, at))) return true;
7117
+ return text.lastIndexOf("/*", at) > text.lastIndexOf("*/", at);
7118
+ }
7119
+ function rewriteHaptics(text) {
7120
+ const ns = NAMESPACE.exec(text)?.[1];
7121
+ if (!ns) return { text, left: /from\s*["']expo-haptics["']/.test(text) && ANY_CALL.test(text) };
7122
+ const call = (method, argument) => new RegExp(`(?:\\bawait\\s+)?\\b${ns}\\??\\.${method}\\(\\s*${argument}\\s*\\)(?!\\s*\\.(?:then|catch|finally)\\b)`, "g");
7123
+ let used = false;
7124
+ const rewrite = (source, method, argument, kindOf) => source.replace(call(method, argument), (all, ...rest) => {
7125
+ const captured = typeof rest[0] === "string" ? rest[0] : void 0;
7126
+ const offset = rest.find((r) => typeof r === "number");
7127
+ if (inComment(source, offset)) return all;
7128
+ used = true;
7129
+ return `playHaptic(${ns}, "${kindOf(captured)}")`;
7130
+ });
7131
+ let next = rewrite(text, "impactAsync", `(?:${ns}\\.ImpactFeedbackStyle\\.(Light|Medium|Heavy))?`, (style) => (style ?? "Medium").toLowerCase());
7132
+ next = rewrite(next, "selectionAsync", "", () => "select");
7133
+ next = rewrite(next, "notificationAsync", `(?:${ns}\\.NotificationFeedbackType\\.(Success|Warning|Error))?`, (type) => (type ?? "Success").toLowerCase());
7134
+ const left = new RegExp(`\\b${ns}\\??\\.(?:impactAsync|selectionAsync|notificationAsync)\\(`).test(stripComments(next));
7135
+ if (!used) return { text, left };
7136
+ if (!/\bimport\s*\{[^}]*\bplayHaptic\b[^}]*\}/.test(next)) {
7137
+ const existing = new RegExp(`\\bimport\\s*\\{([^}]*)\\}\\s*from\\s*(["'])${NATIVE_UI}\\2`).exec(next);
7138
+ if (existing) next = next.replace(existing[0], existing[0].replace(`{${existing[1]}}`, `{ ${existing[1].trim().replace(/,$/, "")}, playHaptic }`));
7139
+ else next = next.replace(NAMESPACE, (line) => `${line}
7140
+ import { playHaptic } from "${NATIVE_UI}";`);
7141
+ }
7142
+ return { text: next, left };
7143
+ }
7144
+ var IMPORTS_GENESIS_UI, OVERLAY_TAG, VH_CLASS, CHOSEN_CAP_BELOW, OWN_HEIGHT, BOTTOM_SHEET, ANY_MAX_H, overlaysFitThePhone, NATIVE_UI, NAMESPACE, ANY_CALL, hapticsUseGenesis;
7145
+ var init_doctor_rule_codemods = __esm({
7146
+ "src/upgrade/doctor-rule-codemods.ts"() {
7147
+ init_genesis();
7148
+ init_app_scripts();
7149
+ IMPORTS_GENESIS_UI = /from\s*["']@marktiderman\/genesis-ui(?:\/[^"']*)?["']/;
7150
+ OVERLAY_TAG = /<(?:Dialog|AlertDialog|Sheet)Content\b[^>]*>/g;
7151
+ VH_CLASS = /(^|[\s"'`{])((?:[\w-]+:)*)(max-h|min-h|h)-\[(\d+(?:\.\d+)?)vh\]/g;
7152
+ CHOSEN_CAP_BELOW = 80;
7153
+ OWN_HEIGHT = /(?:^|[\s"'`{:])h-[\w[]/;
7154
+ BOTTOM_SHEET = /\bside=(?:\{\s*)?["']bottom["']/;
7155
+ ANY_MAX_H = /(?:^|[\s"'`{:])max-h-([^\s"'`}]+)/g;
7156
+ overlaysFitThePhone = {
7157
+ id: "genesis-ui-overlays-fit-the-phone",
7158
+ package: "@marktiderman/genesis-ui",
7159
+ version: "2.31.0",
7160
+ description: "In Genesis's DialogContent, AlertDialogContent and SheetContent, drops a screen-sized max-h-[\u2026vh] of 80 or more (they cap themselves to the screen) and moves anything else in vh to dvh.",
7161
+ run({ root, dryRun, log }) {
7162
+ const changed = [];
7163
+ for (const rel of appScripts(root).filter((f) => /\.[jt]sx$/.test(f))) {
7164
+ const abs = path30.join(root, rel);
7165
+ const text = readFileSync(abs, "utf8");
7166
+ const next = rewriteOverlayHeights(text);
7167
+ if (next === text) continue;
7168
+ if (!IMPORTS_GENESIS_UI.test(text)) {
7169
+ log(` ${rel}: sizes an overlay in vh but doesn't import genesis-ui; left as it is`);
7170
+ continue;
7171
+ }
7172
+ changed.push(rel);
7173
+ if (!dryRun) writeFileSync(abs, next);
7174
+ }
7175
+ if (changed.length) log(' Remove any doctor.allow entry for ui/overlays-fit-the-phone these files had (stale-exception names it). A long form may want mobileLayout="fullscreen".');
7176
+ return changed;
7177
+ }
7178
+ };
7179
+ NATIVE_UI = "@marktiderman/genesis-ui-native";
7180
+ NAMESPACE = /\bimport\s*\*\s*as\s+(\w+)\s+from\s*(["'])expo-haptics\2;?/;
7181
+ ANY_CALL = /\b(?:impactAsync|selectionAsync|notificationAsync)\s*\(/;
7182
+ hapticsUseGenesis = {
7183
+ id: "genesis-ui-native-haptics",
7184
+ package: NATIVE_UI,
7185
+ version: "3.7.0",
7186
+ description: `Turns direct expo-haptics calls into playHaptic(Haptics, "light"), with Genesis's named kinds.`,
7187
+ run({ root, dryRun, log }) {
7188
+ const changed = [];
7189
+ for (const rel of appScripts(root)) {
7190
+ if (/(?:^|\/)__tests__\/|\.test\.[jt]sx?$/.test(rel)) continue;
7191
+ const abs = path30.join(root, rel);
7192
+ const text = readFileSync(abs, "utf8");
7193
+ if (!text.includes("expo-haptics")) continue;
7194
+ const result = rewriteHaptics(text);
7195
+ if (result.left) log(` ${rel}: has expo-haptics calls this can't rewrite (a Soft or Rigid style, a style in a variable, a chained call, named imports); use useHaptics() there`);
7196
+ if (result.text === text) continue;
7197
+ changed.push(rel);
7198
+ if (!dryRun) writeFileSync(abs, result.text);
7199
+ }
7200
+ if (changed.length) log(" Inside a component, useHaptics() (with expo-haptics passed once as GenesisModules.haptics) is the shorter form.");
7201
+ return changed;
7202
+ }
7203
+ };
7204
+ }
7205
+ });
6961
7206
 
6962
7207
  // src/upgrade/scope-names.ts
6963
7208
  function maskComments(text) {
@@ -7290,25 +7535,71 @@ __export(codemods_exports, {
7290
7535
  CODEMODS: () => CODEMODS,
7291
7536
  appScripts: () => appScripts,
7292
7537
  codemodById: () => codemodById,
7538
+ codemodInstallNote: () => codemodInstallNote,
7293
7539
  codemodsFor: () => codemodsFor,
7540
+ composerBarHasContent: () => composerBarHasContent,
7294
7541
  genesisEslintConfig: () => genesisEslintConfig,
7542
+ rewriteComposerBarEmpty: () => rewriteComposerBarEmpty,
7295
7543
  scopeNeutralNames: () => scopeNeutralNames,
7296
7544
  uncoveredBreaks: () => uncoveredBreaks
7297
7545
  });
7298
- function appScripts(root) {
7299
- const out = [];
7300
- const walk3 = (dir) => {
7301
- for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
7302
- const abs = path30.join(dir, entry.name);
7303
- if (entry.isDirectory()) {
7304
- if (!SKIP_DIRS3.has(entry.name)) walk3(abs);
7305
- } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
7306
- out.push(path30.relative(root, abs).split(path30.sep).join("/"));
7546
+ function rewriteComposerBarEmpty(text) {
7547
+ const open = /<NativeComposerBar\b/g;
7548
+ let out = "";
7549
+ let at = 0;
7550
+ for (let m = open.exec(text); m; m = open.exec(text)) {
7551
+ out += text.slice(at, m.index) + m[0];
7552
+ let i = m.index + m[0].length;
7553
+ let depth = 0;
7554
+ let quote2 = null;
7555
+ for (; i < text.length; i++) {
7556
+ const c = text[i];
7557
+ if (quote2) {
7558
+ if (c === quote2) quote2 = null;
7559
+ } else if (depth === 0 && (c === '"' || c === "'")) {
7560
+ quote2 = c;
7561
+ } else if (c === "{") {
7562
+ depth++;
7563
+ } else if (c === "}") {
7564
+ depth--;
7565
+ } else if (c === ">" && depth === 0) {
7566
+ break;
7567
+ } else if (depth === 0 && /\s/.test(c)) {
7568
+ const attr = /^empty(?![\w-])/.exec(text.slice(i + 1, i + 7));
7569
+ if (attr) {
7570
+ const after = i + 1 + "empty".length;
7571
+ const value = text.startsWith("={", after) ? closingBrace(text, after + 1) : -1;
7572
+ if (value >= 0) {
7573
+ const expr = text.slice(after + 2, value);
7574
+ out += `${c}${expr.trim() === "false" ? "hasContent" : expr.trim() === "true" ? "hasContent={false}" : `hasContent={!(${expr})}`}`;
7575
+ i = value;
7576
+ continue;
7577
+ }
7578
+ if (text[after] !== "=") {
7579
+ out += `${c}hasContent={false}`;
7580
+ i = after - 1;
7581
+ continue;
7582
+ }
7583
+ }
7307
7584
  }
7585
+ out += c;
7308
7586
  }
7309
- };
7310
- walk3(root);
7311
- return out;
7587
+ at = i;
7588
+ open.lastIndex = i;
7589
+ }
7590
+ return out + text.slice(at);
7591
+ }
7592
+ function closingBrace(text, start) {
7593
+ let depth = 0;
7594
+ for (let i = start; i < text.length; i++) {
7595
+ if (text[i] === "{") depth++;
7596
+ else if (text[i] === "}" && --depth === 0) return i;
7597
+ }
7598
+ return -1;
7599
+ }
7600
+ function codemodInstallNote(root, changed, dryRun) {
7601
+ if (dryRun || !changed.includes("package.json")) return null;
7602
+ return `Not installed yet: package.json changed and nothing was installed. Run \`${shellLine(installCommand(detectPackageManager(root)))}\`; until then, what it added isn't there (the lint can't load its config, say).`;
7312
7603
  }
7313
7604
  function codemodById(id, registry = CODEMODS) {
7314
7605
  return registry.find((mod) => mod.id === id);
@@ -7323,17 +7614,19 @@ function uncoveredBreaks(changes, registry = CODEMODS) {
7323
7614
  const [a, b] = bare(v).split(".").map(Number);
7324
7615
  return a === 0 ? `0.${b}` : String(a);
7325
7616
  };
7326
- return changes.filter((c) => major(c.from) !== major(c.to) && codemodsFor([c], registry).length === 0);
7617
+ const startsMajor = (v) => bare(v).split(".").map(Number)[0] === 0 ? bare(v).split(".")[2] === "0" : /^\d+\.0\.0$/.test(bare(v));
7618
+ const covers = (mod, c) => startsMajor(mod.version) && major(mod.version) === major(c.to);
7619
+ return changes.filter((c) => major(c.from) !== major(c.to) && !codemodsFor([c], registry).some((mod) => covers(mod, c)));
7327
7620
  }
7328
- var SKIP_DIRS3, SCRIPT2, MAX_BYTES, scopeNeutralNames, genesisEslintConfig, CODEMODS, bare;
7621
+ var scopeNeutralNames, genesisEslintConfig, composerBarHasContent, CODEMODS, bare;
7329
7622
  var init_codemods = __esm({
7330
7623
  "src/upgrade/codemods.ts"() {
7624
+ init_pm();
7625
+ init_app_scripts();
7331
7626
  init_bump_core();
7627
+ init_doctor_rule_codemods();
7332
7628
  init_eslint_config();
7333
7629
  init_scope_names();
7334
- SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
7335
- SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
7336
- MAX_BYTES = 2 * 1024 * 1024;
7337
7630
  scopeNeutralNames = {
7338
7631
  id: "genesis-core-2-scope-names",
7339
7632
  package: "@marktiderman/genesis-core",
@@ -7398,12 +7691,31 @@ ${manualLines(result.kind, platform).map((l) => ` ${l}`).join("\n")}`);
7398
7691
  json.devDependencies = Object.fromEntries(sorted2 ? dev.sort(([a], [b]) => a.localeCompare(b)) : dev);
7399
7692
  changed.push("package.json");
7400
7693
  if (!dryRun) writeFileSync(pkgFile, `${JSON.stringify(json, null, indent)}${raw.endsWith("\n") ? "\n" : ""}`);
7401
- log(` package.json: added ${TESTING_LIBRARY}@${TESTING_LIBRARY_RANGE} to devDependencies (Genesis's native lint rules use it); install to fetch it.`);
7694
+ log(` package.json: added ${TESTING_LIBRARY}@${TESTING_LIBRARY_RANGE} to devDependencies (Genesis's native lint rules use it).`);
7695
+ }
7696
+ return changed;
7697
+ }
7698
+ };
7699
+ composerBarHasContent = {
7700
+ id: "genesis-ui-native-3-8-composer-has-content",
7701
+ package: "@marktiderman/genesis-ui-native",
7702
+ version: "3.8.0",
7703
+ description: "NativeComposerBar's empty is now hasContent, with the opposite sense: empty={false} \u2192 hasContent.",
7704
+ run({ root, dryRun }) {
7705
+ const changed = [];
7706
+ for (const rel of appScripts(root)) {
7707
+ const abs = path30.join(root, rel);
7708
+ const text = readFileSync(abs, "utf8");
7709
+ if (!text.includes("NativeComposerBar")) continue;
7710
+ const next = rewriteComposerBarEmpty(text);
7711
+ if (next === text) continue;
7712
+ changed.push(rel);
7713
+ if (!dryRun) writeFileSync(abs, next);
7402
7714
  }
7403
7715
  return changed;
7404
7716
  }
7405
7717
  };
7406
- CODEMODS = [scopeNeutralNames, genesisEslintConfig];
7718
+ CODEMODS = [scopeNeutralNames, genesisEslintConfig, overlaysFitThePhone, hapticsUseGenesis, composerBarHasContent];
7407
7719
  bare = (spec) => spec.replace(/^[\^~=]/, "");
7408
7720
  }
7409
7721
  });
@@ -7931,7 +8243,7 @@ var init_primitives = __esm({
7931
8243
  CORE = [
7932
8244
  {
7933
8245
  need: "anything, before building it",
7934
- use: 'search what exists: `genesis features find <term>`, this catalog, and the doctor\'s "Available but unused" list',
8246
+ use: 'search what exists: `genesis features find <term>`, this catalog, and the "Available but unused" list in `genesis doctor --verbose`',
7935
8247
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
7936
8248
  from: "genesis-cli"
7937
8249
  },
@@ -7979,6 +8291,58 @@ var init_primitives = __esm({
7979
8291
  read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
7980
8292
  }
7981
8293
  });
8294
+ function appFolderOf(root) {
8295
+ return readGenesisConfig(root)?.appFolder ?? null;
8296
+ }
8297
+ function folderSubstitutions(substitutions, folder) {
8298
+ if (!folder || substitutions?.[APP_FOLDER_PLACEHOLDER]) return substitutions;
8299
+ return { [APP_FOLDER_PLACEHOLDER]: "src", ...substitutions };
8300
+ }
8301
+ function fromRepositoryRoot(entry, folder) {
8302
+ const negated = entry.startsWith("!");
8303
+ const body = negated ? entry.slice(1) : entry;
8304
+ return `${negated ? "!" : ""}${body === folder || body.startsWith(`${folder}/`) ? body : `${folder}/${body}`}`;
8305
+ }
8306
+ function unprefixedTemplatePaths(root, rel, mine, template, folder) {
8307
+ const rendered = renderOwned(rel, template, folder).split("\n");
8308
+ const lines = new Set(mine.split("\n"));
8309
+ const lockfileElsewhere = (line) => {
8310
+ const name = PATH_ITEM.exec(line)?.[3];
8311
+ return name !== void 0 && LOCKFILES2.has(name) && !existsSync(path30.join(root, name));
8312
+ };
8313
+ return template.split("\n").filter((line, i) => line !== rendered[i] && !/^\s*#/.test(line) && lines.has(line) && !lockfileElsewhere(line)).map((line) => line.trim());
8314
+ }
8315
+ function renderOwned(rel, text, folder) {
8316
+ if (!folder || !EAS_WORKFLOW.test(rel)) return text;
8317
+ let inList = false;
8318
+ return text.split("\n").map((line) => {
8319
+ const inline = INLINE_PATHS.exec(line);
8320
+ if (inline) return `${inline[1]}${inline[2].replace(/(["'])([^"']+)\1/g, (_all, quote2, entry) => `${quote2}${fromRepositoryRoot(entry, folder)}${quote2}`)}${inline[3]}`;
8321
+ if (/^\s*paths:\s*$/.test(line)) {
8322
+ inList = true;
8323
+ return line;
8324
+ }
8325
+ if (!inList || /^\s*#/.test(line)) return line;
8326
+ const item = PATH_ITEM.exec(line);
8327
+ if (!item) {
8328
+ inList = false;
8329
+ return line;
8330
+ }
8331
+ return `${item[1]}${item[2]}${fromRepositoryRoot(item[3], folder)}${item[2]}${item[4]}`;
8332
+ }).join("\n");
8333
+ }
8334
+ var LOCKFILES2, EAS_WORKFLOW, PATH_ITEM, INLINE_PATHS, isRepositoryWorkflow;
8335
+ var init_app_folder = __esm({
8336
+ "src/blocks/app-folder.ts"() {
8337
+ init_config();
8338
+ init_init_native();
8339
+ LOCKFILES2 = /* @__PURE__ */ new Set(["pnpm-lock.yaml", "yarn.lock", "package-lock.json", "bun.lock", "bun.lockb"]);
8340
+ EAS_WORKFLOW = /^\.eas\/workflows\/[^/]+\.ya?ml$/;
8341
+ PATH_ITEM = /^(\s*-\s*)(["']?)([^"'#\s]+)\2(\s*(?:#.*)?)$/;
8342
+ INLINE_PATHS = /^(\s*(?:#\s*)?paths:\s*\[)(.*)(\]\s*)$/;
8343
+ isRepositoryWorkflow = (rel) => rel.startsWith(".github/workflows/");
8344
+ }
8345
+ });
7982
8346
  function copyOwned(root, lock, write, dryRun = false) {
7983
8347
  const existing = readApp(root, write.path);
7984
8348
  const record = () => {
@@ -8048,7 +8412,7 @@ function refreshOwned(root, lock, input, options = {}) {
8048
8412
  const theirsSha = sha256(input.theirs);
8049
8413
  if (theirsSha === entry.sha256) return { path: input.path, outcome: "unchanged" };
8050
8414
  const record = (sha) => {
8051
- const { pending: _settled, deleted: _back, ...rest } = entry;
8415
+ const { pending: _settled, pendingMine: _was, deleted: _back, ...rest } = entry;
8052
8416
  lock.files[input.path] = { ...rest, sha256: sha, ...input.version ? { version: input.version } : {} };
8053
8417
  };
8054
8418
  if (mine === null) {
@@ -8063,25 +8427,25 @@ function refreshOwned(root, lock, input, options = {}) {
8063
8427
  const next = `${input.path}.genesis-next`;
8064
8428
  const existingNext = readApp(root, next);
8065
8429
  if (entry.pending === theirsSha) {
8066
- if (existingNext === null) {
8067
- const { pending: _done, ...rest } = entry;
8430
+ if (existingNext !== null) return { path: input.path, outcome: "kept-mine", detail: `waiting for you: resolve ${next} into your file, then delete it` };
8431
+ if (mineSha !== entry.pendingMine) {
8432
+ const { pending: _done, pendingMine: _was, ...rest } = entry;
8068
8433
  lock.files[input.path] = { ...rest, sha256: theirsSha, ...input.version ? { version: input.version } : {} };
8069
- return { path: input.path, outcome: "resolved", detail: "your file is kept as the resolution of the last upgrade" };
8434
+ return { path: input.path, outcome: "resolved", detail: `your file is kept as the resolution of the last upgrade because it changed since; if that was unrelated, compare with ${entry.source}` };
8070
8435
  }
8071
- return { path: input.path, outcome: "kept-mine", detail: `waiting for you: resolve ${next} into your file, then delete it` };
8072
8436
  }
8073
8437
  const writeNext = (text) => {
8074
8438
  if (existingNext !== null && existingNext !== text) return `${next} is already there with other text; resolve it (and delete it) first`;
8075
8439
  write(next, text);
8076
- lock.files[input.path] = { ...entry, pending: theirsSha };
8440
+ lock.files[input.path] = { ...entry, pending: theirsSha, pendingMine: mineSha };
8077
8441
  return null;
8078
8442
  };
8079
- if (!options.keepMine && input.base !== null && sha256(input.base) === entry.sha256) {
8443
+ if (!options.keepMine && input.base !== null) {
8080
8444
  const merged = mergeThreeWay(mine, input.base, input.theirs);
8081
8445
  if (merged?.clean) {
8082
8446
  write(input.path, merged.text);
8083
8447
  record(theirsSha);
8084
- return { path: input.path, outcome: "merged", detail: "your edits kept on top of the new version" };
8448
+ return { path: input.path, outcome: "merged", detail: input.baseIsPending ? `merged on the version the last .genesis-next held, because this file changed since; if that was unrelated, compare with ${entry.source}` : "your edits kept on top of the new version" };
8085
8449
  }
8086
8450
  if (merged) {
8087
8451
  const blocked2 = writeNext(merged.text);
@@ -8352,6 +8716,11 @@ async function checkLockFiles(ctx) {
8352
8716
  home = databaseElsewhere(ctx.root);
8353
8717
  } catch {
8354
8718
  }
8719
+ let appFolder = null;
8720
+ try {
8721
+ appFolder = appFolderOf(ctx.root);
8722
+ } catch {
8723
+ }
8355
8724
  const elsewhere = home ? Object.keys(lock.files).filter(isSupabasePath) : [];
8356
8725
  if (home && elsewhere.length) {
8357
8726
  ctx.report({
@@ -8387,6 +8756,7 @@ async function checkLockFiles(ctx) {
8387
8756
  }
8388
8757
  if (text === null) {
8389
8758
  if (entry.deleted) continue;
8759
+ if (appFolder && isRepositoryWorkflow(rel)) continue;
8390
8760
  ctx.report({
8391
8761
  rule: "lock-files",
8392
8762
  level: "warn",
@@ -8411,6 +8781,7 @@ async function checkLockFiles(ctx) {
8411
8781
  }
8412
8782
  var init_lock_files = __esm({
8413
8783
  "src/doctor/lock-files.ts"() {
8784
+ init_app_folder();
8414
8785
  init_discover();
8415
8786
  init_files();
8416
8787
  init_lock();
@@ -8477,11 +8848,407 @@ function checkEslintConfig(ctx) {
8477
8848
  subject: TESTING_LIBRARY,
8478
8849
  message: `${file} loads Genesis's native lint rules, which need ${TESTING_LIBRARY}: add it to devDependencies (pnpm add -D ${TESTING_LIBRARY}), or the lint can't load its config`
8479
8850
  });
8851
+ } else if (!findPackageDir(ctx.root, TESTING_LIBRARY)) {
8852
+ ctx.report({
8853
+ rule: "genesis-eslint-config",
8854
+ level: "warn",
8855
+ file: "package.json",
8856
+ subject: TESTING_LIBRARY,
8857
+ message: `lists ${TESTING_LIBRARY}, which ${file} needs, but it isn't installed, so the lint can't load its config: run ${shellLine(installCommand(detectPackageManager(ctx.root)))}`
8858
+ });
8480
8859
  }
8481
8860
  }
8482
8861
  var init_eslint_config2 = __esm({
8483
8862
  "src/doctor/eslint-config.ts"() {
8863
+ init_pm();
8484
8864
  init_eslint_config();
8865
+ init_genesis();
8866
+ }
8867
+ });
8868
+
8869
+ // src/figma/routes.ts
8870
+ var routes_exports = {};
8871
+ __export(routes_exports, {
8872
+ FIGMA_API: () => FIGMA_API,
8873
+ FIGMA_TIMEOUT_MS: () => FIGMA_TIMEOUT_MS,
8874
+ FigmaConfigError: () => FigmaConfigError,
8875
+ appDynamicNavTargets: () => appDynamicNavTargets,
8876
+ appNavTargets: () => appNavTargets,
8877
+ appRoutes: () => appRoutes,
8878
+ checkFigmaRoutes: () => checkFigmaRoutes,
8879
+ compare: () => compare,
8880
+ coverageFindings: () => coverageFindings,
8881
+ destinations: () => destinations,
8882
+ dynamicNavTargets: () => dynamicNavTargets,
8883
+ expoRoot: () => expoRoot,
8884
+ figmaIdOf: () => figmaIdOf,
8885
+ formatCoverage: () => formatCoverage,
8886
+ navTargets: () => navTargets,
8887
+ readFigma: () => readFigma,
8888
+ readFigmaConfig: () => readFigmaConfig,
8889
+ routeMatches: () => routeMatches,
8890
+ validateFigmaConfig: () => validateFigmaConfig
8891
+ });
8892
+ function validateFigmaConfig(raw, source = "genesis.config.json") {
8893
+ const obj = raw;
8894
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new FigmaConfigError(`${source}: figma must be an object`);
8895
+ if (typeof obj.file !== "string" || !/^[A-Za-z0-9]+$/.test(obj.file)) throw new FigmaConfigError(`${source}: figma.file must be the file key (letters and digits, from the file's URL)`);
8896
+ const pages = obj.pages;
8897
+ if (!pages || typeof pages !== "object" || Array.isArray(pages)) throw new FigmaConfigError(`${source}: figma.pages must be { "web"?: "<page>", "native"?: "<page>" }`);
8898
+ const out = {};
8899
+ for (const [k, v] of Object.entries(pages)) {
8900
+ if (k !== "web" && k !== "native") throw new FigmaConfigError(`${source}: figma.pages.${k}: only "web" and "native"`);
8901
+ if (typeof v !== "string" || !v) throw new FigmaConfigError(`${source}: figma.pages.${k} must be a page name`);
8902
+ out[k] = v;
8903
+ }
8904
+ if (!out.web && !out.native) throw new FigmaConfigError(`${source}: figma.pages needs "web" or "native"`);
8905
+ if (obj.proposalsPage !== void 0 && (typeof obj.proposalsPage !== "string" || !obj.proposalsPage)) throw new FigmaConfigError(`${source}: figma.proposalsPage must be a page name`);
8906
+ return { file: obj.file, pages: out, proposalsPage: obj.proposalsPage ?? "Proposals" };
8907
+ }
8908
+ function readFigmaConfig(root) {
8909
+ const file = path30.join(root, "genesis.config.json");
8910
+ if (!existsSync(file)) return null;
8911
+ let raw;
8912
+ try {
8913
+ raw = JSON.parse(readFileSync(file, "utf8"));
8914
+ } catch (err) {
8915
+ throw new FigmaConfigError(`${file} isn't valid JSON: ${err.message}`);
8916
+ }
8917
+ return raw?.figma === void 0 ? null : validateFigmaConfig(raw.figma, file);
8918
+ }
8919
+ function walk2(dir, out = []) {
8920
+ if (!existsSync(dir)) return out;
8921
+ for (const name of readdirSync(dir).sort()) {
8922
+ if (name === "node_modules" || name.startsWith(".")) continue;
8923
+ const full = path30.join(dir, name);
8924
+ if (statSync(full).isDirectory()) walk2(full, out);
8925
+ else if (CODE.test(name) && !/\.(?:test|spec|d)\.[jt]sx?$/.test(name)) out.push(full);
8926
+ }
8927
+ return out;
8928
+ }
8929
+ function figmaIdOf(code) {
8930
+ for (const line of code.split("\n").slice(0, 5)) {
8931
+ const m = FIGMA_ID.exec(line);
8932
+ if (m) return m[1].replace("-", ":");
8933
+ }
8934
+ return void 0;
8935
+ }
8936
+ function tanstackSegments(stem) {
8937
+ const out = [];
8938
+ let cur = "";
8939
+ let depth = 0;
8940
+ for (const ch of stem) {
8941
+ if (ch === "{") depth++;
8942
+ if (ch === "}") depth--;
8943
+ if (ch === "." && depth === 0) {
8944
+ out.push(cur);
8945
+ cur = "";
8946
+ } else cur += ch;
8947
+ }
8948
+ out.push(cur);
8949
+ return out;
8950
+ }
8951
+ function expoRoot(root) {
8952
+ for (const dir of ["src/app", "app"]) if (existsSync(path30.join(root, dir))) return dir;
8953
+ return null;
8954
+ }
8955
+ function appRoutes(root) {
8956
+ const out = [];
8957
+ const rel = (f) => path30.relative(root, f).split(path30.sep).join("/");
8958
+ const expo = expoRoot(root);
8959
+ if (expo) {
8960
+ for (const f of walk2(path30.join(root, expo))) {
8961
+ const parts = path30.relative(path30.join(root, expo), f).split(path30.sep);
8962
+ const stem = parts.pop().replace(CODE, "");
8963
+ if (stem === "_layout" || stem.startsWith("+")) continue;
8964
+ if (stem !== "index") parts.push(stem);
8965
+ out.push(withId({ route: parts.join("/") || "index", platform: "native", file: rel(f) }, f));
8966
+ }
8967
+ }
8968
+ const tanstack = path30.join(root, "src/routes");
8969
+ if (existsSync(tanstack)) {
8970
+ const seen = /* @__PURE__ */ new Set();
8971
+ for (const f of walk2(tanstack)) {
8972
+ const parts = path30.relative(tanstack, f).split(path30.sep);
8973
+ const stem = parts.pop().replace(CODE, "").replace(/\.lazy$/, "");
8974
+ if (stem === "__root" || stem === "route" || stem.startsWith("-") || parts.some((p) => p.startsWith("-"))) continue;
8975
+ const segs = [...parts.flatMap(tanstackSegments), ...tanstackSegments(stem)];
8976
+ if (segs.at(-1) === "index") segs.pop();
8977
+ const route = segs.join("/") || "index";
8978
+ if (seen.has(route)) continue;
8979
+ seen.add(route);
8980
+ out.push(withId({ route, platform: "web", file: rel(f) }, f));
8981
+ }
8982
+ }
8983
+ return out;
8984
+ }
8985
+ function withId(r, file) {
8986
+ const id = figmaIdOf(readFileSync(file, "utf8"));
8987
+ return id ? { ...r, figmaId: id } : r;
8988
+ }
8989
+ function urlSegments(route) {
8990
+ return route.replace(/^\/+/, "").split("/").filter((s) => s && s !== "index" && !/^\(.*\)$/.test(s) && !/^_/.test(s)).map((s) => s.replace(/_$/, "")).map((s) => /^\{-\$.*\}$/.test(s) ? "?" : /^\[\.\.\..+\]$/.test(s) ? "**" : /^\$|^\[.*\]$/.test(s) ? "*" : s);
8991
+ }
8992
+ function routeMatches(route, target) {
8993
+ const pattern = urlSegments(route);
8994
+ const url = target.split(/[?#]/)[0].split("/").filter(Boolean);
8995
+ if (/(?:^|\/)\$$/.test(route)) {
8996
+ const head = pattern.slice(0, -1);
8997
+ return url.length >= head.length && head.every((p, i) => p === "*" || p === url[i]);
8998
+ }
8999
+ const go = (i, j) => {
9000
+ if (i === pattern.length) return j === url.length;
9001
+ const p = pattern[i];
9002
+ if (p === "?") return go(i + 1, j) || j < url.length && go(i + 1, j + 1);
9003
+ if (j === url.length) return false;
9004
+ if (p === "**") {
9005
+ for (let k = j + 1; k <= url.length; k++) if (go(i + 1, k)) return true;
9006
+ return false;
9007
+ }
9008
+ return (p === "*" || p === url[j]) && go(i + 1, j + 1);
9009
+ };
9010
+ return go(0, 0);
9011
+ }
9012
+ function sameScreen(a, b) {
9013
+ return a.replace(/^\/+/, "") === b.replace(/^\/+/, "") || urlSegments(a).join("/") === urlSegments(b).join("/");
9014
+ }
9015
+ function dynamicNavTargets(code, file) {
9016
+ const out = [];
9017
+ for (const re of DYNAMIC_PATTERNS) {
9018
+ for (const m of code.matchAll(re)) {
9019
+ const raw = m[1].trim();
9020
+ out.push({ file, line: code.slice(0, m.index).split("\n").length, target: raw.length > 60 ? `${raw.slice(0, 57)}...` : raw });
9021
+ }
9022
+ }
9023
+ return out.sort((a, b) => a.line - b.line);
9024
+ }
9025
+ function navTargets(code, file) {
9026
+ const out = [];
9027
+ for (const re of NAV_PATTERNS) {
9028
+ for (const m of code.matchAll(re)) {
9029
+ const target = m[1] ?? m[2] ?? m[3];
9030
+ if (target === void 0 || /^[a-z]+:/i.test(target) || target.startsWith("#") || target.startsWith(".")) continue;
9031
+ out.push({ file, line: code.slice(0, m.index).split("\n").length, target });
9032
+ }
9033
+ }
9034
+ return out.sort((a, b) => a.line - b.line);
9035
+ }
9036
+ function appNavTargets(root) {
9037
+ const files = [.../* @__PURE__ */ new Set([...walk2(path30.join(root, "src")), ...walk2(path30.join(root, "app"))])];
9038
+ return files.flatMap((f) => navTargets(readFileSync(f, "utf8"), path30.relative(root, f).split(path30.sep).join("/")));
9039
+ }
9040
+ function appDynamicNavTargets(root) {
9041
+ const files = [.../* @__PURE__ */ new Set([...walk2(path30.join(root, "src")), ...walk2(path30.join(root, "app"))])];
9042
+ return files.flatMap((f) => dynamicNavTargets(readFileSync(f, "utf8"), path30.relative(root, f).split(path30.sep).join("/")));
9043
+ }
9044
+ function splitName(name) {
9045
+ const i = name.indexOf(" \xB7 ");
9046
+ return i < 0 ? { route: name.trim() } : { route: name.slice(0, i).trim(), state: name.slice(i + 3).trim() };
9047
+ }
9048
+ function destinations(node, out = /* @__PURE__ */ new Set()) {
9049
+ if (node.transitionNodeID) out.add(node.transitionNodeID);
9050
+ for (const i of node.interactions ?? []) {
9051
+ for (const a of i.actions ?? []) if (a?.type === "NODE" && a.destinationId && a.navigation !== "CHANGE_TO") out.add(a.destinationId);
9052
+ }
9053
+ for (const c of node.children ?? []) destinations(c, out);
9054
+ return out;
9055
+ }
9056
+ async function readFigma(config, token, fetchImpl = fetch, timeoutMs = FIGMA_TIMEOUT_MS) {
9057
+ const get2 = async (p) => {
9058
+ const where2 = p.split("?")[0];
9059
+ try {
9060
+ const res = await fetchImpl(`${FIGMA_API}${p}`, { headers: { "X-Figma-Token": token }, signal: AbortSignal.timeout(timeoutMs) });
9061
+ if (!res.ok) throw new Error(`Figma API ${where2} answered ${res.status}${res.status === 403 ? " (check FIGMA_ACCESS_TOKEN and its access to the file)" : ""}`);
9062
+ return await res.json();
9063
+ } catch (err) {
9064
+ const name = err?.name;
9065
+ if (name === "TimeoutError" || name === "AbortError") throw new Error(`Figma API ${where2} didn't answer within ${Math.round(timeoutMs / 1e3)}s`);
9066
+ throw err;
9067
+ }
9068
+ };
9069
+ const nodes = async (ids, depth) => {
9070
+ const out = [];
9071
+ for (let i = 0; i < ids.length; i += 50) {
9072
+ const chunk = ids.slice(i, i + 50);
9073
+ const body = await get2(`/v1/files/${config.file}/nodes?ids=${encodeURIComponent(chunk.join(","))}${depth ? `&depth=${depth}` : ""}`);
9074
+ for (const id of chunk) {
9075
+ const doc = body.nodes[id]?.document;
9076
+ if (doc) out.push(doc);
9077
+ }
9078
+ }
9079
+ return out;
9080
+ };
9081
+ const file = await get2(`/v1/files/${config.file}?depth=2`);
9082
+ const canvases = file.document.children ?? [];
9083
+ const wanted = /* @__PURE__ */ new Set([...Object.values(config.pages), config.proposalsPage]);
9084
+ const frames = [];
9085
+ const sections = [];
9086
+ for (const page of canvases) {
9087
+ if (!wanted.has(page.name)) continue;
9088
+ for (const child of page.children ?? []) {
9089
+ if (child.type === "SECTION") sections.push({ id: child.id, name: child.name, page: page.name });
9090
+ else if (SCREEN_TYPES.has(child.type)) frames.push({ id: child.id, name: child.name, page: page.name, ...splitName(child.name) });
9091
+ }
9092
+ }
9093
+ for (const s of await nodes(sections.map((x) => x.id), 1)) {
9094
+ const section2 = sections.find((x) => x.id === s.id);
9095
+ for (const child of s.children ?? []) {
9096
+ if (SCREEN_TYPES.has(child.type)) frames.push({ id: child.id, name: child.name, page: section2.page, section: section2.name, ...splitName(child.name) });
9097
+ }
9098
+ }
9099
+ const hotspots = [];
9100
+ for (const tree of await nodes(frames.filter((f) => f.page !== config.proposalsPage).map((f) => f.id))) {
9101
+ for (const to of destinations(tree)) if (to !== tree.id) hotspots.push({ from: tree.id, to });
9102
+ }
9103
+ return { pages: canvases.map((p) => p.name), frames, hotspots };
9104
+ }
9105
+ function compare(config, routes, targets, figma, dynamicTargets = []) {
9106
+ const platformOf = (page) => config.pages.web === page ? "web" : config.pages.native === page ? "native" : void 0;
9107
+ const routeFrames = figma.frames.filter((f) => platformOf(f.page));
9108
+ const framesFor = (r) => routeFrames.filter((f) => platformOf(f.page) === r.platform && (sameScreen(f.route, r.route) || r.route === "index" && f.route === "/"));
9109
+ const byId = new Map(figma.frames.map((f) => [f.id, f]));
9110
+ const framed = new Set(routes.flatMap((r) => framesFor(r).map((f) => f.id)));
9111
+ const covered = routes.filter((r) => framesFor(r).length > 0);
9112
+ const routesWithoutFrame = routes.filter((r) => framesFor(r).length === 0);
9113
+ const framesWithoutRoute = routeFrames.filter((f) => !framed.has(f.id));
9114
+ const proposals = {};
9115
+ for (const f of figma.frames.filter((x) => x.page === config.proposalsPage)) (proposals[f.section ?? "(no section)"] ??= []).push(f);
9116
+ const missingHotspots = [];
9117
+ const seen = /* @__PURE__ */ new Set();
9118
+ for (const t of targets) {
9119
+ const source = routes.find((r) => r.file === t.file);
9120
+ if (!source) continue;
9121
+ const from = framesFor(source);
9122
+ if (!from.length) continue;
9123
+ const dest = routes.find((r) => r.platform === source.platform && routeMatches(r.route, t.target));
9124
+ if (!dest || dest === source) continue;
9125
+ const key2 = `${source.route}\u2192${dest.route}`;
9126
+ if (seen.has(key2)) continue;
9127
+ seen.add(key2);
9128
+ const to = new Set(framesFor(dest).map((f) => f.id));
9129
+ const linked = figma.hotspots.some((h) => from.some((f) => f.id === h.from) && to.has(h.to));
9130
+ if (!linked) missingHotspots.push({ ...t, from: source.route, to: dest.route, targetHasFrame: to.size > 0 });
9131
+ }
9132
+ const deadHotspots = [];
9133
+ for (const h of figma.hotspots) {
9134
+ const from = byId.get(h.from);
9135
+ const to = byId.get(h.to);
9136
+ if (from && to && platformOf(to.page) && !framed.has(to.id)) deadHotspots.push({ from, to });
9137
+ }
9138
+ const idMismatches = routes.filter((r) => r.figmaId && !framesFor(r).some((f) => f.id === r.figmaId)).map((r) => ({ ...r, frames: framesFor(r).map((f) => f.id) }));
9139
+ const wantedPages = [...Object.values(config.pages), config.proposalsPage];
9140
+ const missingPages = wantedPages.filter((p) => !figma.pages.includes(p));
9141
+ const uncheckedNavigation = dynamicTargets.filter((t) => routes.some((r) => r.file === t.file));
9142
+ return {
9143
+ file: config.file,
9144
+ summary: {
9145
+ routes: routes.length,
9146
+ frames: routeFrames.length,
9147
+ covered: covered.length,
9148
+ coveredPercent: routes.length ? Math.round(covered.length / routes.length * 100) : 100,
9149
+ hotspots: figma.hotspots.length,
9150
+ missing: missingPages.length + routesWithoutFrame.length + missingHotspots.length + idMismatches.length
9151
+ },
9152
+ missingPages,
9153
+ routesWithoutFrame,
9154
+ framesWithoutRoute,
9155
+ proposals,
9156
+ missingHotspots,
9157
+ deadHotspots,
9158
+ idMismatches,
9159
+ uncheckedNavigation
9160
+ };
9161
+ }
9162
+ async function checkFigmaRoutes(options) {
9163
+ const config = options.config ?? readFigmaConfig(options.root);
9164
+ if (!config) throw new FigmaConfigError(`no "figma" block in ${path30.join(options.root, "genesis.config.json")}`);
9165
+ const token = options.token ?? process.env.FIGMA_ACCESS_TOKEN;
9166
+ if (!token) throw new FigmaConfigError("FIGMA_ACCESS_TOKEN isn't set");
9167
+ const figma = await readFigma(config, token, options.fetch);
9168
+ return compare(config, appRoutes(options.root), appNavTargets(options.root), figma, appDynamicNavTargets(options.root));
9169
+ }
9170
+ function formatCoverage(r) {
9171
+ const s = r.summary;
9172
+ const lines = [`Figma route coverage (file ${r.file}): ${s.routes} routes, ${s.frames} frames, ${s.covered} covered (${s.coveredPercent}%), ${s.hotspots} hotspots, ${s.missing} missing`];
9173
+ const table = (title, head, rows) => {
9174
+ if (!rows.length) return;
9175
+ const widths = head.map((h, i) => Math.max(h.length, ...rows.map((row) => row[i].length)));
9176
+ const fmt = (row) => ` ${row.map((c, i) => c.padEnd(widths[i])).join(" ")}`.trimEnd();
9177
+ lines.push("", `${title} (${rows.length})`, fmt(head), fmt(widths.map((w) => "-".repeat(w))), ...rows.map(fmt));
9178
+ };
9179
+ if (r.missingPages.length) lines.push("", `Pages not in the file: ${r.missingPages.join(", ")}`);
9180
+ table("Routes with no frame", ["platform", "route", "file"], r.routesWithoutFrame.map((x) => [x.platform, x.route, x.file]));
9181
+ table("Frames with no route (move to Proposals, or add the route)", ["page", "frame", "id"], r.framesWithoutRoute.map((f) => [f.page, f.name, f.id]));
9182
+ table("Navigation with no hotspot", ["from", "to", "at"], r.missingHotspots.map((m) => [m.from, `${m.to}${m.targetHasFrame ? "" : " (no frame)"}`, `${m.file}:${m.line}`]));
9183
+ table("Hotspots to a frame with no route", ["from", "to"], r.deadHotspots.map((d) => [d.from.name, d.to.name]));
9184
+ table("figma: ids that don't match the route's frame", ["route", "comment", "frames"], r.idMismatches.map((m) => [m.route, m.figmaId, m.frames.join(", ") || "none"]));
9185
+ table("Navigation not checked (not a string literal)", ["at", "target"], r.uncheckedNavigation.map((t) => [`${t.file}:${t.line}`, t.target]));
9186
+ table("Proposals", ["section", "frame", "id"], Object.entries(r.proposals).flatMap(([sec, fs2]) => fs2.map((f) => [sec, f.name, f.id])));
9187
+ return lines.join("\n");
9188
+ }
9189
+ function coverageFindings(r, strict) {
9190
+ const gap = strict ? "warn" : "info";
9191
+ return [
9192
+ ...r.missingPages.map((p) => ({ level: gap, file: `figma:${p}`, message: `the Figma file has no page "${p}" (named in genesis.config.json figma)`, subject: p })),
9193
+ ...r.routesWithoutFrame.map((x) => ({ level: gap, file: x.file, message: `route ${x.route} has no ${x.platform} frame in the Figma file`, subject: x.route })),
9194
+ ...r.missingHotspots.map((m) => ({ level: gap, file: m.file, line: m.line, message: `navigates to ${m.to}, but the ${m.from} frame has no hotspot to it${m.targetHasFrame ? "" : " (and it has no frame)"}`, subject: m.to })),
9195
+ ...r.idMismatches.map((m) => ({ level: gap, file: m.file, line: 1, message: `// figma: ${m.figmaId} isn't the frame named ${m.route} (${m.frames.join(", ") || "none"})`, subject: m.route })),
9196
+ ...r.framesWithoutRoute.map((f) => ({ level: "info", file: `figma:${f.page}`, message: `frame "${f.name}" (${f.id}) has no route: move it to Proposals, or add the route`, subject: f.route })),
9197
+ ...r.deadHotspots.map((d) => ({ level: "info", file: `figma:${d.from.page}`, message: `"${d.from.name}" links to "${d.to.name}", which has no route`, subject: d.to.route })),
9198
+ ...r.uncheckedNavigation.map((t) => ({ level: "info", file: t.file, line: t.line, message: `navigation to ${t.target} isn't a string literal, so it isn't checked against the Figma file`, subject: t.target }))
9199
+ ];
9200
+ }
9201
+ var FigmaConfigError, CODE, FIGMA_ID, STR, NAV_PATTERNS, DYNAMIC_PATTERNS, FIGMA_API, FIGMA_TIMEOUT_MS, SCREEN_TYPES;
9202
+ var init_routes2 = __esm({
9203
+ "src/figma/routes.ts"() {
9204
+ FigmaConfigError = class extends Error {
9205
+ };
9206
+ CODE = /\.(?:tsx|ts|jsx|js)$/;
9207
+ FIGMA_ID = /^\s*\/\/\s*figma:\s*(\d+[:-]\d+)\s*$/;
9208
+ STR = String.raw`(?:"([^"\n]*)"|'([^'\n]*)'|` + "`([^`$\\n]*)`)";
9209
+ NAV_PATTERNS = [
9210
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*` + STR, "g"),
9211
+ new RegExp(String.raw`<Link\b[^>]*?\b(?:href|to)=\{?\s*` + STR, "g"),
9212
+ new RegExp(String.raw`\bnavigate\(\s*\{[^}]*?\bto\s*:\s*` + STR, "g")
9213
+ ];
9214
+ DYNAMIC_PATTERNS = [
9215
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
9216
+ new RegExp(String.raw`<Link\b[^>]*?\b(?:href|to)=\{\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
9217
+ new RegExp(String.raw`\bnavigate\(\s*\{[^}]*?\bto\s*:\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
9218
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*(\{[^}\n]*?\bpathname\b[^}\n]*\}?)`, "g"),
9219
+ new RegExp(String.raw`<Link\b[^>]*?\bhref=\{(\{[^}\n]*?\bpathname\b[^}\n]*\}?)`, "g")
9220
+ ];
9221
+ FIGMA_API = "https://api.figma.com";
9222
+ FIGMA_TIMEOUT_MS = 3e4;
9223
+ SCREEN_TYPES = /* @__PURE__ */ new Set(["FRAME", "COMPONENT", "COMPONENT_SET", "INSTANCE"]);
9224
+ }
9225
+ });
9226
+
9227
+ // src/doctor/figma-routes.ts
9228
+ async function checkFigmaRoutesRule(ctx) {
9229
+ let config;
9230
+ try {
9231
+ config = readFigmaConfig(ctx.root);
9232
+ } catch (err) {
9233
+ if (!(err instanceof FigmaConfigError)) throw err;
9234
+ ctx.report({ rule: "figma-routes", level: "warn", file: "genesis.config.json", message: err.message });
9235
+ return;
9236
+ }
9237
+ if (!config) return;
9238
+ if (!process.env.FIGMA_ACCESS_TOKEN) {
9239
+ ctx.report({ rule: "figma-routes", level: "info", file: "genesis.config.json", message: "skipped: FIGMA_ACCESS_TOKEN isn't set (CI sets it from a secret)" });
9240
+ return;
9241
+ }
9242
+ try {
9243
+ const report = await checkFigmaRoutes({ root: ctx.root, config });
9244
+ for (const f of coverageFindings(report, ctx.strict ?? false)) ctx.report({ rule: "figma-routes", ...f });
9245
+ } catch (err) {
9246
+ ctx.report({ rule: "figma-routes", level: "info", file: "genesis.config.json", message: `skipped: ${err.message}` });
9247
+ }
9248
+ }
9249
+ var init_figma_routes = __esm({
9250
+ "src/doctor/figma-routes.ts"() {
9251
+ init_routes2();
8485
9252
  }
8486
9253
  });
8487
9254
 
@@ -8549,7 +9316,7 @@ async function runDoctor(options = {}) {
8549
9316
  }
8550
9317
  const raw = [];
8551
9318
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
8552
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
9319
+ for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
8553
9320
  try {
8554
9321
  await plugin.check(ctx);
8555
9322
  } catch (err) {
@@ -8637,6 +9404,7 @@ function builtinChecks(config, options = {}) {
8637
9404
  { name: "database-elsewhere", check: checkDatabaseHome },
8638
9405
  { name: "eslint-config", check: checkEslintConfig },
8639
9406
  ...(config.packs ?? []).map((p) => packs[p]),
9407
+ ...options.figma !== false ? [{ name: "figma-routes", check: checkFigmaRoutesRule }] : [],
8640
9408
  ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
8641
9409
  ];
8642
9410
  }
@@ -8689,7 +9457,7 @@ function applyConfig(raw, config, packageIds) {
8689
9457
  }
8690
9458
  return out.sort((x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule));
8691
9459
  }
8692
- function formatReport(result) {
9460
+ function formatReport(result, options = {}) {
8693
9461
  const g = result.genesis;
8694
9462
  const lines = [
8695
9463
  `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"}`
@@ -8697,7 +9465,7 @@ function formatReport(result) {
8697
9465
  for (const f of result.findings) {
8698
9466
  lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
8699
9467
  }
8700
- lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
9468
+ 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)`);
8701
9469
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
8702
9470
  const info = result.infos ? `, ${result.infos} info` : "";
8703
9471
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
@@ -8753,6 +9521,7 @@ var init_doctor = __esm({
8753
9521
  init_lock_files();
8754
9522
  init_database2();
8755
9523
  init_eslint_config2();
9524
+ init_figma_routes();
8756
9525
  init_config();
8757
9526
  init_genesis();
8758
9527
  init_patterns();
@@ -9219,8 +9988,8 @@ function routeTags(source) {
9219
9988
  }
9220
9989
  function wireStudioRoute(source, route, pageImportPath) {
9221
9990
  const tags = routeTags(source);
9222
- const relative17 = route.replace(/^\//, "");
9223
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative17.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
9991
+ const relative18 = route.replace(/^\//, "");
9992
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative18.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
9224
9993
  if (existing) {
9225
9994
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
9226
9995
  }
@@ -9228,17 +9997,17 @@ function wireStudioRoute(source, route, pageImportPath) {
9228
9997
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
9229
9998
  if (roots.length !== 1) {
9230
9999
  return {
9231
- skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative17}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
10000
+ skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative18}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
9232
10001
  };
9233
10002
  }
9234
10003
  const layout = roots[0];
9235
10004
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
9236
- if (base && !relative17.startsWith(`${base}/`)) {
10005
+ if (base && !relative18.startsWith(`${base}/`)) {
9237
10006
  return {
9238
10007
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
9239
10008
  };
9240
10009
  }
9241
- const childPath = base ? relative17.slice(base.length + 1) : relative17;
10010
+ const childPath = base ? relative18.slice(base.length + 1) : relative18;
9242
10011
  const guard = GUARD.exec(source)?.[1];
9243
10012
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
9244
10013
  const before = source.slice(0, layout.close);
@@ -9748,7 +10517,7 @@ export default function Screen() {
9748
10517
  }
9749
10518
  `;
9750
10519
  }
9751
- var init_routes2 = __esm({
10520
+ var init_routes3 = __esm({
9752
10521
  "src/blocks/routes.ts"() {
9753
10522
  init_files();
9754
10523
  }
@@ -9914,6 +10683,7 @@ async function runAdd(options) {
9914
10683
  const providers = providingMigrations([full, ...catalog]);
9915
10684
  const migrations2 = home ? { rows: [], creates: [] } : planMigrations(root, sourceMigrations(root, full), { now, ...lock.migrations ? { copied: lock.migrations } : {}, providers });
9916
10685
  const superseded = supersededFunctions(migrations2.rows, providers);
10686
+ for (const r of migrations2.rows) for (const u of r.unmet ?? []) planWarnings.push(`${r.package} ${r.file} ${u}`);
9917
10687
  const replaced2 = full.functions.filter((fn) => superseded.has(`${fn.package}:${fn.dir}`)).map((fn) => {
9918
10688
  const by = superseded.get(`${fn.package}:${fn.dir}`);
9919
10689
  const block = providers.find((p) => p.package === by.package && p.file === by.file)?.block;
@@ -10069,7 +10839,7 @@ var init_add = __esm({
10069
10839
  init_owned();
10070
10840
  init_pm();
10071
10841
  init_registry_edit();
10072
- init_routes2();
10842
+ init_routes3();
10073
10843
  SILENT = { info() {
10074
10844
  }, warn() {
10075
10845
  } };
@@ -10228,6 +10998,7 @@ async function runMigrate(options) {
10228
10998
  }
10229
10999
  if (!ids.length && !sources.length) warnings.push("No blocks in genesis.lock.json and no copied package migrations: nothing to compare. Add a block (genesis add <block>), or pass --block.");
10230
11000
  const plan = planMigrations(root, sources, { now: options.now ?? /* @__PURE__ */ new Date(), ...options.forward ? { forward: true } : {}, ...lock.migrations ? { copied: lock.migrations } : {}, providers: providingMigrations([...manifests, ...catalog]) });
11001
+ for (const r of plan.rows) for (const u of r.unmet ?? []) warnings.push(`${r.package} ${r.file} ${u}`);
10231
11002
  const attention = plan.rows.some(needsAttention);
10232
11003
  const notifies = ids.some((id) => (lock.blocks[id]?.package ?? (id === "notifications" ? NOTIFICATIONS_PACKAGE : "")) === NOTIFICATIONS_PACKAGE);
10233
11004
  const types = notifies ? await planNotificationTypes(root, {
@@ -10264,11 +11035,120 @@ var init_migrate = __esm({
10264
11035
  init_notification_types();
10265
11036
  }
10266
11037
  });
10267
- function walk2(dir, rel = "", out = /* @__PURE__ */ new Map()) {
11038
+ async function fetchChangelog(directory) {
11039
+ try {
11040
+ const res = await fetch(`https://raw.githubusercontent.com/${REPOSITORY}/main/${directory}/CHANGELOG.md`, { signal: AbortSignal.timeout(5e3) });
11041
+ return res.ok ? await res.text() : null;
11042
+ } catch {
11043
+ return null;
11044
+ }
11045
+ }
11046
+ function breakingEntries(changelog, from, to) {
11047
+ const low = bare2(from);
11048
+ const high = bare2(to);
11049
+ const heading = low.startsWith("0.") ? /^### (?:Major|Minor) Changes\s*$/ : /^### Major Changes\s*$/;
11050
+ const parts = changelog.split(/^## (?=\d)/m).slice(1);
11051
+ let matched = false;
11052
+ const entries = [];
11053
+ for (const part of parts) {
11054
+ const version = part.split("\n", 1)[0].trim();
11055
+ if (compareVersions2(version, low) <= 0 || compareVersions2(version, high) > 0) continue;
11056
+ if (compareVersions2(version, high) === 0) matched = true;
11057
+ let inside3 = false;
11058
+ for (const line of part.split("\n")) {
11059
+ if (line.startsWith("### ")) inside3 = heading.test(line);
11060
+ else if (inside3 && line.startsWith("- ")) entries.push(firstLine(line));
11061
+ }
11062
+ }
11063
+ return matched ? entries : null;
11064
+ }
11065
+ function repositoryDirectory(root, name) {
11066
+ const dir = packageDir(root, name);
11067
+ if (!dir) return null;
11068
+ try {
11069
+ const { repository } = JSON.parse(readFileSync(path30.join(dir, "package.json"), "utf8"));
11070
+ return typeof repository?.directory === "string" ? repository.directory : null;
11071
+ } catch {
11072
+ return null;
11073
+ }
11074
+ }
11075
+ async function breakLines(root, breaks, reader) {
11076
+ const lowest = /* @__PURE__ */ new Map();
11077
+ for (const b of breaks) {
11078
+ const key2 = `${b.name}@${b.to}`;
11079
+ const held = lowest.get(key2);
11080
+ if (!held || compareVersions2(bare2(b.from), bare2(held.from)) < 0) lowest.set(key2, b);
11081
+ }
11082
+ const lines = [];
11083
+ for (const b of lowest.values()) {
11084
+ const directory = repositoryDirectory(root, b.name);
11085
+ const url = directory ? `https://github.com/${REPOSITORY}/blob/main/${directory}/CHANGELOG.md#${bare2(b.to).replace(/\D/g, "")}` : `https://www.npmjs.com/package/${b.name}`;
11086
+ const head = `- \`${b.name}\` ${b.from} \u2192 ${b.to}`;
11087
+ const text = directory && reader.changelog ? await reader.changelog(directory) : null;
11088
+ const entries = text === null ? null : breakingEntries(text, b.from, b.to);
11089
+ if (entries === null) lines.push(`${head}: read [its changelog](${url})`);
11090
+ else if (!entries.length) lines.push(`${head}: no breaking changes of its own; moved with its dependencies, see [its changelog](${url})`);
11091
+ else lines.push(`${head}: [changelog](${url})`, ...entries.slice(0, 5).map((e) => ` - ${e}`), ...entries.length > 5 ? [` - and ${entries.length - 5} more`] : []);
11092
+ }
11093
+ return lines;
11094
+ }
11095
+ var REPOSITORY, bare2, firstLine;
11096
+ var init_changelog = __esm({
11097
+ "src/upgrade/changelog.ts"() {
11098
+ init_discover();
11099
+ init_bump_core();
11100
+ REPOSITORY = "marktiderman/genesis";
11101
+ bare2 = (spec) => spec.replace(/^[\^~=]/, "");
11102
+ firstLine = (entry) => {
11103
+ const line = entry.replace(/^-\s*(?:[0-9a-f]{7,}:\s*)?/, "").split("\n")[0].trim();
11104
+ return line.length > 160 ? `${line.slice(0, 157)}\u2026` : line;
11105
+ };
11106
+ }
11107
+ });
11108
+
11109
+ // src/upgrade/new-exports.ts
11110
+ function componentValues(root) {
11111
+ try {
11112
+ const { config } = loadConfig(root);
11113
+ return readPackageExports(root, uiPackageFor(config))?.values ?? null;
11114
+ } catch {
11115
+ return null;
11116
+ }
11117
+ }
11118
+ function handBuiltSwaps(root, before) {
11119
+ if (!before) return [];
11120
+ try {
11121
+ const { config } = loadConfig(root);
11122
+ if (config.rules?.["shadowed-export"] === "off") return [];
11123
+ const uiPackage = uiPackageFor(config);
11124
+ const after = readPackageExports(root, uiPackage)?.values;
11125
+ const gained = new Set([...after ?? []].filter((name) => !before.has(name)));
11126
+ if (!gained.size) return [];
11127
+ clearPackageRulesCache();
11128
+ const found = [];
11129
+ checkShadowedExports({ root, config, files: scanFiles(root, config), packages: discoverPackages(root), genesis: { uiPackage, values: gained }, report: (f) => found.push(f) });
11130
+ return found.map((f) => ({ name: f.subject, file: f.file, line: f.line ?? 0, package: uiPackage }));
11131
+ } catch {
11132
+ return [];
11133
+ }
11134
+ }
11135
+ function swapLines(swaps) {
11136
+ return swaps.map((s) => `- \`${s.name}\` in ${s.file}${s.line ? `:${s.line}` : ""}: ${s.package} now exports it. Compare the two and swap to \`import { ${s.name} } from "${s.package}"\`, or rename yours if it's a different thing.`);
11137
+ }
11138
+ var init_new_exports = __esm({
11139
+ "src/upgrade/new-exports.ts"() {
11140
+ init_config();
11141
+ init_genesis();
11142
+ init_package_rules();
11143
+ init_rules();
11144
+ init_scan();
11145
+ }
11146
+ });
11147
+ function walk3(dir, rel = "", out = /* @__PURE__ */ new Map()) {
10268
11148
  for (const entry of readdirSync(path30.join(dir, rel), { withFileTypes: true })) {
10269
11149
  if (SKIP.has(entry.name)) continue;
10270
11150
  const child = rel ? `${rel}/${entry.name}` : entry.name;
10271
- if (entry.isDirectory()) walk2(dir, child, out);
11151
+ if (entry.isDirectory()) walk3(dir, child, out);
10272
11152
  else if (entry.isFile()) out.set(child, readFileSync(path30.join(dir, child)));
10273
11153
  }
10274
11154
  return out;
@@ -10445,7 +11325,7 @@ function planOverlays(root, wanted, upstream2, manifests = ["package.json"]) {
10445
11325
  }
10446
11326
  const base = baseRead.files;
10447
11327
  const next = nextRead.files;
10448
- const mine = walk2(pkg.dir);
11328
+ const mine = walk3(pkg.dir);
10449
11329
  const promoted = promotions(root, pkg.name);
10450
11330
  const verdict = (file) => {
10451
11331
  const appPath3 = `${pkg.rel}/${file}`;
@@ -10714,6 +11594,7 @@ var init_overlays2 = __esm({
10714
11594
  // src/upgrade/index.ts
10715
11595
  var upgrade_exports = {};
10716
11596
  __export(upgrade_exports, {
11597
+ checkSubstitutions: () => checkSubstitutions,
10717
11598
  npmLookup: () => npmLookup,
10718
11599
  pnpmWorkspaceFileFor: () => pnpmWorkspaceFileFor,
10719
11600
  releaseAgeError: () => releaseAgeError,
@@ -10765,9 +11646,25 @@ function npmLookup(cwd) {
10765
11646
  latest.set(name, typeof v === "string" ? v : null);
10766
11647
  }
10767
11648
  return latest.get(name);
10768
- }
11649
+ },
11650
+ changelog: fetchChangelog
10769
11651
  };
10770
11652
  }
11653
+ function checkInstalled(root, options) {
11654
+ const noInstall = options.install === false || options.dryRun;
11655
+ if (!Object.keys(readLock(root).files).length && !(noInstall && options.doctor !== false)) return;
11656
+ const text = readApp(root, "package.json");
11657
+ if (text === null) return;
11658
+ let pkg;
11659
+ try {
11660
+ pkg = JSON.parse(text);
11661
+ } catch {
11662
+ return;
11663
+ }
11664
+ const declared = ["dependencies", "devDependencies", "optionalDependencies"].some((s) => Object.keys(pkg[s] ?? {}).some((name) => name.startsWith("@marktiderman/genesis")));
11665
+ if (!declared || installedGenesis(root).size) return;
11666
+ throw new Error(`This app's dependencies aren't installed: package.json lists Genesis packages, but none is in node_modules. Run \`${shellLine(installCommand(detectPackageManager(root)))}\`, then genesis upgrade again. Nothing was changed. (The upgrade merges your edits to owned files against the installed versions, and the doctor reads them.)`);
11667
+ }
10771
11668
  function readText2(file) {
10772
11669
  try {
10773
11670
  return readFileSync(file, "utf8");
@@ -10792,6 +11689,11 @@ function gitTopLevel(root) {
10792
11689
  return null;
10793
11690
  }
10794
11691
  }
11692
+ function folderBelowTopLevel(root) {
11693
+ const real2 = realpathSync(root);
11694
+ const top = gitTopLevel(real2);
11695
+ return top === null ? null : path30.relative(top, real2).split(path30.sep).join("/");
11696
+ }
10795
11697
  function pnpmWorkspaceFileFor(root) {
10796
11698
  const real2 = realpathSync(root);
10797
11699
  const top = gitTopLevel(real2);
@@ -10870,6 +11772,7 @@ async function runUpgrade(options) {
10870
11772
  const root = path30.resolve(options.root);
10871
11773
  const log = options.log ?? (() => {
10872
11774
  });
11775
+ checkInstalled(root, options);
10873
11776
  const lookup = options.lookup ?? npmLookup(root);
10874
11777
  const release = options.manifest ? JSON.parse(readFileSync(path30.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
10875
11778
  const pinned = { [UMBRELLA]: release.version, ...release.packages };
@@ -10910,12 +11813,29 @@ async function runUpgrade(options) {
10910
11813
  const lock = readLock(root);
10911
11814
  const home = databaseElsewhere(root);
10912
11815
  checkSubstitutions(lock.substitutions);
11816
+ const appFolder = appFolderOf(root);
11817
+ const written = folderSubstitutions(lock.substitutions, appFolder);
11818
+ const ownedText = (file, source) => {
11819
+ const text = sourceText(root, source, written);
11820
+ return text === null ? null : renderOwned(file, text, appFolder);
11821
+ };
10913
11822
  const bases = /* @__PURE__ */ new Map();
11823
+ const basesFromPending = /* @__PURE__ */ new Set();
10914
11824
  for (const [file, entry] of Object.entries(lock.files)) {
10915
11825
  if (ownedKeyProblem(file, entry.source, localPackageNames(root))) continue;
10916
- const text = sourceText(root, entry.source, lock.substitutions);
10917
- if (text !== null && sha256(text) === entry.sha256) bases.set(file, text);
11826
+ const text = ownedText(file, entry.source);
11827
+ if (text === null) continue;
11828
+ const was = sourceText(root, entry.source, lock.substitutions);
11829
+ const taken = [sha256(text), ...was === null ? [] : [sha256(was)]];
11830
+ const mine = entry.pending && entry.pendingMine && taken.includes(entry.pending) && readApp(root, `${file}.genesis-next`) === null ? readApp(root, file) : null;
11831
+ const resolved = mine !== null && sha256(mine) !== entry.pendingMine;
11832
+ if (taken.includes(entry.sha256)) bases.set(file, text);
11833
+ else if (resolved) {
11834
+ bases.set(file, text);
11835
+ basesFromPending.add(file);
11836
+ }
10918
11837
  }
11838
+ const valuesBefore = options.dryRun ? null : componentValues(root);
10919
11839
  const files = /* @__PURE__ */ new Set();
10920
11840
  const lockEdits = [];
10921
11841
  const codemodRuns = [];
@@ -10932,6 +11852,7 @@ async function runUpgrade(options) {
10932
11852
  codemodRuns.push({ id: mod.id, files: changed });
10933
11853
  for (const f of changed) files.add(f);
10934
11854
  }
11855
+ const codemodNeedsInstall = options.install === false ? codemodInstallNote(root, codemodRuns.flatMap((c) => c.files), Boolean(options.dryRun)) : null;
10935
11856
  let bunLock;
10936
11857
  const prune = (want) => {
10937
11858
  const result = pruneBunLock(root, want, Boolean(options.dryRun));
@@ -10998,7 +11919,7 @@ async function runUpgrade(options) {
10998
11919
  }
10999
11920
  const added = [];
11000
11921
  const newMigrations = [];
11001
- const warnings = [...excludeWarnings];
11922
+ const warnings = [...excludeWarnings, ...codemodNeedsInstall ? [codemodNeedsInstall] : []];
11002
11923
  const manifests = [];
11003
11924
  const catalog = catalogBlocks();
11004
11925
  const off = appBlocksSwitchedOff(root, catalog, Object.keys(lock.blocks));
@@ -11020,7 +11941,7 @@ async function runUpgrade(options) {
11020
11941
  manifests.push(manifest);
11021
11942
  if (!home) {
11022
11943
  for (const row of planMigrations(root, sourceMigrations(root, manifest), { now: /* @__PURE__ */ new Date(), tests: false, ...lock.migrations ? { copied: lock.migrations } : {}, providers: providingMigrations(catalog) }).rows) {
11023
- if (row.state === "new") newMigrations.push(`${row.package} ${row.file}`);
11944
+ if (row.state === "new") newMigrations.push(`${row.package} ${row.file}${row.unmet?.length ? ` (${row.unmet.join("; ")})` : ""}`);
11024
11945
  }
11025
11946
  }
11026
11947
  if (manifest.version && manifest.version !== entry.version) lock.blocks[id] = { ...entry, version: manifest.version };
@@ -11043,14 +11964,35 @@ async function runUpgrade(options) {
11043
11964
  continue;
11044
11965
  }
11045
11966
  const problem = ownedKeyProblem(file, entry.source, localPackageNames(root));
11046
- const theirs = problem ? null : sourceText(root, entry.source, lock.substitutions);
11967
+ const theirs = problem ? null : ownedText(file, entry.source);
11047
11968
  const dir = problem ? null : packageDir(root, parseSource(entry.source).package);
11048
11969
  const version = dir ? packageVersion(dir) : void 0;
11049
- const outcome = refreshOwned(root, lock, { path: file, theirs, base: bases.get(file) ?? null, ...version ? { version } : {} }, { ...options.dryRun ? { dryRun: true } : {}, ...options.keepMine ? { keepMine: true } : {} });
11970
+ if (appFolder && !problem && isRepositoryWorkflow(file)) {
11971
+ if (theirs !== null && sha256(theirs) !== entry.sha256) {
11972
+ lock.files[file] = { ...entry, sha256: sha256(theirs), ...version ? { version } : {} };
11973
+ refreshed.push({ path: file, outcome: "repository", detail: `the template changed; your copy is in the repository's own .github/workflows (with working-directory: ${appFolder}), so compare it with ${entry.source}` });
11974
+ } else refreshed.push({ path: file, outcome: "unchanged" });
11975
+ continue;
11976
+ }
11977
+ const outcome = refreshOwned(root, lock, { path: file, theirs, base: bases.get(file) ?? null, ...basesFromPending.has(file) ? { baseIsPending: true } : {}, ...version ? { version } : {} }, { ...options.dryRun ? { dryRun: true } : {}, ...options.keepMine ? { keepMine: true } : {} });
11050
11978
  refreshed.push(outcome);
11979
+ if (appFolder && outcome.outcome !== "updated" && !problem) {
11980
+ const template = sourceText(root, entry.source, written);
11981
+ const mine = template === null ? null : readApp(root, file);
11982
+ const stale = mine === null ? [] : unprefixedTemplatePaths(root, file, mine, template, appFolder);
11983
+ if (stale.length) warnings.push(`${file} keeps your edits, so these paths are still from the app's folder and never match: ${stale.join(", ")}. Start them with ${appFolder}/ by hand.`);
11984
+ }
11051
11985
  if (outcome.outcome === "updated" || outcome.outcome === "merged") files.add(file);
11052
11986
  if ((outcome.outcome === "conflict" || outcome.outcome === "kept-mine") && !outcome.detail?.includes("already there")) next.add(`${file}.genesis-next`);
11053
11987
  }
11988
+ const folderInRepo = appFolder ? null : folderBelowTopLevel(root);
11989
+ if (folderInRepo && refreshed.some((r) => (r.outcome === "conflict" || r.outcome === "kept-mine") && /^\.(?:eas|github)\/workflows\//.test(r.path))) {
11990
+ warnings.push(`This app sits in ${folderInRepo}/ in its repository. Set "appFolder": "${folderInRepo}" in genesis.config.json, and the next upgrade writes the EAS workflows' paths from the repository root, so they stop conflicting.`);
11991
+ }
11992
+ if (appFolder) {
11993
+ const actual = folderBelowTopLevel(root);
11994
+ if (actual !== null && actual !== appFolder) warnings.push(`genesis.config.json says "appFolder": "${appFolder}", but this app is at ${actual || "the repository's root"}.`);
11995
+ }
11054
11996
  const functionsLeft = [];
11055
11997
  for (const manifest of manifests) {
11056
11998
  for (const w of ownedWrites(root, manifest, warnings)) {
@@ -11081,21 +12023,56 @@ async function runUpgrade(options) {
11081
12023
  writeLock(root, lock);
11082
12024
  if (readApp(root, LOCK_FILE) !== before) files.add(LOCK_FILE);
11083
12025
  }
12026
+ const generated = /* @__PURE__ */ new Set();
12027
+ if (!options.dryRun) {
12028
+ clearPackageRulesCache();
12029
+ if (options.agents !== false) {
12030
+ try {
12031
+ const packages = discoverPackages(root);
12032
+ const state = agentGuideState(root, packages);
12033
+ if (state.skill !== "missing" || state.agents !== "missing") {
12034
+ const broken = packages.filter((p) => p.error);
12035
+ if (broken.length) warnings.push(`The agent guide wasn't regenerated: ${broken.map((p) => p.error).join("; ")}`);
12036
+ else for (const f of writeAgentGuide(root, packages)) generated.add(f);
12037
+ }
12038
+ } catch (err) {
12039
+ warnings.push(`genesis agents failed: ${err instanceof Error ? err.message : String(err)}`);
12040
+ }
12041
+ }
12042
+ if (options.featuresBuild !== false && registryFile(root)) {
12043
+ try {
12044
+ const { runFeaturesBuild: runFeaturesBuild2 } = await Promise.resolve().then(() => (init_features(), features_exports));
12045
+ for (const f of await runFeaturesBuild2({ dir: root })) generated.add(f);
12046
+ } catch (err) {
12047
+ warnings.push(`features build failed: ${err instanceof Error ? err.message : String(err)}`);
12048
+ }
12049
+ }
12050
+ }
12051
+ for (const f of generated) files.add(f);
12052
+ const swaps = handBuiltSwaps(root, valuesBefore);
12053
+ if (swaps.length) log(["", `This release adds exports the app builds by hand; genesis doctor's shadowed-export reports each:`, ...swapLines(swaps), ""].join("\n"));
11084
12054
  let doctor = "not run";
12055
+ let doctorProblem;
11085
12056
  if (options.doctor !== false) {
11086
12057
  try {
11087
12058
  const { runDoctor: runDoctor2, formatReport: formatReport2 } = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
11088
- const result = await runDoctor2({ root });
12059
+ const result = await runDoctor2({ root, figma: false });
11089
12060
  log(formatReport2(result));
11090
12061
  doctor = result.ok ? "passed" : "failed";
11091
12062
  } catch (err) {
11092
- log(`genesis doctor couldn't run: ${err instanceof Error ? err.message : String(err)}`);
12063
+ doctorProblem = err instanceof Error ? err.message : String(err);
12064
+ log(`genesis doctor couldn't run: ${doctorProblem}`);
11093
12065
  doctor = "failed";
11094
12066
  }
11095
12067
  }
12068
+ const ignored = options.pr && !options.dryRun ? gitIgnored(root, [...files, ...lockfilesFor(root)]) : [];
12069
+ for (const f of ignored) files.delete(f);
11096
12070
  const lines = [bumpSummary(release.version, changes, skipped)];
12071
+ if (ignored.length) lines.push("", `Changed but gitignored, so not in the pull request: ${ignored.join(", ")}.`);
11097
12072
  if (codemodRuns.length) lines.push("", "Codemods:", "", ...codemodRuns.map((c) => `- ${c.id}${c.files.length ? `: ${c.files.join(", ")}` : ""}`));
11098
- if (breaks.length) lines.push("", "Major moves with no codemod (read their changelogs):", "", ...breaks.map((b) => `- \`${b.name}\` ${b.from} \u2192 ${b.to}`));
12073
+ if (breaks.length) lines.push("", "Major moves with no codemod:", "", ...await breakLines(root, breaks, lookup));
12074
+ if (swaps.length) lines.push("", "New exports this app builds by hand (`shadowed-export` reports each until it's swapped or renamed):", "", ...swapLines(swaps));
12075
+ if (generated.size) lines.push("", `Regenerated from the installed packages: ${[...generated].join(", ")}.`);
11099
12076
  const touched2 = refreshed.filter((r) => r.outcome !== "unchanged");
11100
12077
  if (touched2.length || added.length) {
11101
12078
  lines.push("", options.dryRun ? "Files Genesis owns (against the packages installed now; a real run compares with the new versions after the install):" : "Files Genesis owns:", "", ...touched2.map((r) => `- ${r.path}: ${r.outcome}${r.detail ? ` (${r.detail})` : ""}`), ...added.map((a) => `- ${a}: added`));
@@ -11118,27 +12095,43 @@ async function runUpgrade(options) {
11118
12095
  }
11119
12096
  lines.push(...overlayChecklist(overlays));
11120
12097
  if (warnings.length) lines.push("", "Warnings:", "", ...warnings.map((w) => `- ${w}`));
11121
- lines.push("", `\`genesis doctor\` ${doctor === "not run" ? "was not run" : doctor} after the upgrade.`);
12098
+ lines.push("", doctorProblem ? `\`genesis doctor\` couldn't run after the upgrade: ${doctorProblem}` : `\`genesis doctor\` ${doctor === "not run" ? "was not run" : doctor} after the upgrade.`);
11122
12099
  const summary = lines.join("\n");
11123
- const report = { version: release.version, changes, skipped, codemods: codemodRuns, breaks, refreshed, added, switchedOff, newMigrations, doctor, files: [...files].sort(), summary, overlays, ...bunLock ? { bunLock } : {} };
12100
+ const report = { version: release.version, changes, skipped, codemods: codemodRuns, breaks, refreshed, added, switchedOff, newMigrations, swaps, doctor, files: [...files].sort(), summary, overlays, ...bunLock ? { bunLock } : {} };
11124
12101
  if (options.pr && !options.dryRun && files.size) report.pr = openPullRequest(root, release.version, report, prBase);
11125
12102
  return report;
11126
12103
  }
11127
12104
  function checkSubstitutions(substitutions) {
11128
12105
  if (!substitutions || !Object.keys(substitutions).length) return;
11129
- let allowed;
12106
+ let names;
11130
12107
  try {
11131
12108
  const was = starterIdentity(readFileSync(path30.join(starterDir(), "starter.config.ts"), "utf8"));
11132
- allowed = [was.name, was.slug, was.scheme, was.bundleId, APP_FOLDER_PLACEHOLDER];
12109
+ names = [was.name, was.slug, was.scheme, was.bundleId];
11133
12110
  } catch {
11134
- allowed = [];
12111
+ names = [];
11135
12112
  }
11136
12113
  for (const [from, to] of Object.entries(substitutions)) {
11137
- if (!allowed.includes(from) || !SUBSTITUTION_VALUE.test(to)) {
12114
+ if (from === APP_FOLDER_PLACEHOLDER) {
12115
+ if (!isPlainFolder(to)) throw new Error(`genesis.lock.json: the substitution ${from} \u2192 ${JSON.stringify(to)} isn't a plain folder inside the repository (src, or apps/web); fix the lock by hand.`);
12116
+ } else if (!names.includes(from) || !SUBSTITUTION_VALUE.test(to)) {
11138
12117
  throw new Error(`genesis.lock.json: the substitution ${JSON.stringify(from)} \u2192 ${JSON.stringify(to)} isn't one of the starter's names with a plain value; fix the lock by hand.`);
11139
12118
  }
11140
12119
  }
11141
12120
  }
12121
+ function lockfilesFor(root) {
12122
+ const top = gitTopLevel(root);
12123
+ const lockfiles = [];
12124
+ for (let dir = realpathSync(root); ; dir = path30.dirname(dir)) {
12125
+ for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path30.join(dir, f))) lockfiles.push(path30.relative(realpathSync(root), path30.join(dir, f)));
12126
+ if (lockfiles.length || dir === top || path30.dirname(dir) === dir) break;
12127
+ }
12128
+ return lockfiles;
12129
+ }
12130
+ function gitIgnored(root, files) {
12131
+ if (!files.length) return [];
12132
+ const result = spawnSync("git", ["check-ignore", "--stdin", "-z"], { cwd: root, input: files.join("\0"), encoding: "utf8" });
12133
+ return result.status === 0 ? result.stdout.split("\0").filter(Boolean) : [];
12134
+ }
11142
12135
  function checkPullRequest(root, version) {
11143
12136
  const git4 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
11144
12137
  if (git4("status", "--porcelain")) throw new Error("--pr needs a clean working tree (commit or stash your changes first).");
@@ -11159,13 +12152,9 @@ function openPullRequest(root, version, report, base) {
11159
12152
  const git4 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
11160
12153
  const branch = `genesis-upgrade/${version}`;
11161
12154
  git4("switch", "-c", branch);
11162
- const top = git4("rev-parse", "--show-toplevel");
11163
- const lockfiles = [];
11164
- for (let dir = path30.resolve(root); ; dir = path30.dirname(dir)) {
11165
- for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path30.join(dir, f))) lockfiles.push(path30.relative(root, path30.join(dir, f)));
11166
- if (lockfiles.length || dir === top || path30.dirname(dir) === dir) break;
11167
- }
11168
- const paths = [...report.files.filter((f) => existsSync(path30.join(root, f))), ...lockfiles];
12155
+ const lockfiles = lockfilesFor(root);
12156
+ const ignoredLocks = gitIgnored(root, lockfiles);
12157
+ const paths = [...report.files.filter((f) => existsSync(path30.join(root, f))), ...lockfiles.filter((f) => !ignoredLocks.includes(f))];
11169
12158
  git4("add", "--", ...paths);
11170
12159
  const overlayDirs = report.overlays.filter((o) => !o.skipped && !o.conflicts.length && (o.remove || [...o.writes.values()].includes(null))).map((o) => o.rel);
11171
12160
  if (overlayDirs.length) git4("add", "-A", "--", ...overlayDirs);
@@ -11183,7 +12172,11 @@ var init_upgrade = __esm({
11183
12172
  "src/upgrade/index.ts"() {
11184
12173
  init_add();
11185
12174
  init_agents();
12175
+ init_app_folder();
11186
12176
  init_discover();
12177
+ init_config();
12178
+ init_primitives();
12179
+ init_package_rules();
11187
12180
  init_starter_features();
11188
12181
  init_files();
11189
12182
  init_init_native();
@@ -11195,7 +12188,9 @@ var init_upgrade = __esm({
11195
12188
  init_pm();
11196
12189
  init_templates();
11197
12190
  init_bump_core();
12191
+ init_changelog();
11198
12192
  init_codemods();
12193
+ init_new_exports();
11199
12194
  init_overlays2();
11200
12195
  init_bun_lock();
11201
12196
  EXACT_OR_TAG = /^[0-9A-Za-z][0-9A-Za-z.+-]*$/;
@@ -11304,9 +12299,9 @@ async function runScaffold(opts, fs2) {
11304
12299
  function joinPath(...parts) {
11305
12300
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
11306
12301
  }
11307
- function dirname(path56) {
11308
- const idx = path56.lastIndexOf("/");
11309
- return idx === -1 ? "." : path56.slice(0, idx);
12302
+ function dirname(path61) {
12303
+ const idx = path61.lastIndexOf("/");
12304
+ return idx === -1 ? "." : path61.slice(0, idx);
11310
12305
  }
11311
12306
  function brandPackageJson(consumer, genesisVersion) {
11312
12307
  return JSON.stringify(
@@ -11642,7 +12637,7 @@ program.command("introspect").description("Write a checked-in contract (resource
11642
12637
  await fs.writeFile(target, content, "utf-8");
11643
12638
  console.log(`\u2714 Wrote ${label}: ${tables.length} tables.`);
11644
12639
  });
11645
- program.command("doctor").description("Check this app against the installed Genesis: components, tokens, imports, colors, plus the app's own rules").option("--strict", "Fail on warnings too", false).option("--json", "Print the report as JSON", false).option("--build", "Also run the app's typecheck and build (doctor.build, or its typecheck/build scripts)", false).option("-c, --config <path>", 'Config file (default: genesis.config.json, then package.json "genesis")').option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--print-genesis", "Print the components, tokens and raw tags read from Genesis, and exit", false).option("--base <ref>", "The git ref change checks compare against (the packages pack's change gate, and the ratchet: newOnly rules report unchanged files as info), e.g. origin/main").action(async (opts) => {
12640
+ program.command("doctor").description("Check this app against the installed Genesis: components, tokens, imports, colors, plus the app's own rules").option("--strict", "Fail on warnings too", false).option("--json", "Print the report as JSON", false).option("--verbose", "List the Genesis components no file imports (otherwise only their count)", false).option("--build", "Also run the app's typecheck and build (doctor.build, or its typecheck/build scripts)", false).option("-c, --config <path>", 'Config file (default: genesis.config.json, then package.json "genesis")').option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--print-genesis", "Print the components, tokens and raw tags read from Genesis, and exit", false).option("--base <ref>", "The git ref change checks compare against (the packages pack's change gate, and the ratchet: newOnly rules report unchanged files as info), e.g. origin/main").action(async (opts) => {
11646
12641
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
11647
12642
  const root = path30.resolve(opts.dir);
11648
12643
  try {
@@ -11652,7 +12647,7 @@ program.command("doctor").description("Check this app against the installed Gene
11652
12647
  return;
11653
12648
  }
11654
12649
  const result = await doctor.runDoctor({ root, configPath: opts.config, strict: opts.strict, build: opts.build, quietBuild: opts.json, ...opts.base ? { base: opts.base } : {} });
11655
- console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result));
12650
+ console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result, { verbose: opts.verbose }));
11656
12651
  process.exitCode = result.ok ? 0 : 1;
11657
12652
  } catch (err) {
11658
12653
  if (!(err instanceof doctor.GenesisConfigError)) throw err;
@@ -11769,6 +12764,18 @@ featureOptions(
11769
12764
  const what = term ? `"${term}"` : "those filters";
11770
12765
  console.log(hits.length ? hits.map(formatFeature2).join("\n\n") : `No feature matches ${what}. If this is new work, add it to the registry first (an idea is enough).`);
11771
12766
  });
12767
+ program.command("figma:routes").description("Report drift between this app's routes and its Figma app file (read-only; genesis.config.json figma block, FIGMA_ACCESS_TOKEN)").option("--json", "Print the report as JSON", false).option("--strict", "Exit 1 when a route, hotspot or figma: id is missing", false).option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
12768
+ const figma = await Promise.resolve().then(() => (init_routes2(), routes_exports));
12769
+ try {
12770
+ const report = await figma.checkFigmaRoutes({ root: path30.resolve(opts.dir) });
12771
+ console.log(opts.json ? JSON.stringify(report, null, 2) : figma.formatCoverage(report));
12772
+ process.exitCode = opts.strict && report.summary.missing > 0 ? 1 : 0;
12773
+ } catch (err) {
12774
+ if (opts.json) console.log(JSON.stringify({ ok: false, error: err.message }, null, 2));
12775
+ else console.error(`\u2717 ${err.message}`);
12776
+ process.exitCode = 2;
12777
+ }
12778
+ });
11772
12779
  var upstream = program.command("upstream").description("The app's register of what it needed from Genesis (docs/genesis-upstream.md)");
11773
12780
  upstream.command("check").description("Check docs/genesis-upstream.md: kinds, statuses, local paths, and promoted entries whose local copy is still there").option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
11774
12781
  const { checkUpstream: checkUpstream2 } = await Promise.resolve().then(() => (init_upstream(), upstream_exports));
@@ -11795,36 +12802,36 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
11795
12802
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
11796
12803
  const root = path30.resolve(opts.dir);
11797
12804
  const packageJson = JSON.parse(await fs.readFile(path30.join(root, "package.json"), "utf-8").catch(() => "{}"));
11798
- const existsSync43 = (await import('fs')).existsSync;
12805
+ const existsSync45 = (await import('fs')).existsSync;
11799
12806
  const readSync = (await import('fs')).readFileSync;
11800
- const readdirSync19 = (await import('fs')).readdirSync;
12807
+ const readdirSync20 = (await import('fs')).readdirSync;
11801
12808
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
11802
12809
  throw new Error("--host must be next, tanstack-start or supabase-function.");
11803
12810
  }
11804
12811
  const plan = planStudioInit2(
11805
12812
  {
11806
12813
  packageJson,
11807
- exists: (p) => existsSync43(path30.join(root, p)),
11808
- read: (p) => existsSync43(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
12814
+ exists: (p) => existsSync45(path30.join(root, p)),
12815
+ read: (p) => existsSync45(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
11809
12816
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
11810
12817
  listDeep: (p) => {
11811
12818
  const out = [];
11812
- const walk3 = (rel) => {
11813
- for (const entry of readdirSync19(path30.join(root, rel), { withFileTypes: true })) {
12819
+ const walk4 = (rel) => {
12820
+ for (const entry of readdirSync20(path30.join(root, rel), { withFileTypes: true })) {
11814
12821
  const child = `${rel}/${entry.name}`;
11815
- if (entry.isDirectory()) walk3(child);
12822
+ if (entry.isDirectory()) walk4(child);
11816
12823
  else out.push(child);
11817
12824
  }
11818
12825
  };
11819
12826
  try {
11820
- walk3(p);
12827
+ walk4(p);
11821
12828
  } catch {
11822
12829
  }
11823
12830
  return out;
11824
12831
  },
11825
12832
  list: (p) => {
11826
12833
  try {
11827
- return readdirSync19(path30.join(root, p));
12834
+ return readdirSync20(path30.join(root, p));
11828
12835
  } catch {
11829
12836
  return [];
11830
12837
  }
@@ -11845,14 +12852,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
11845
12852
  console.log(`+ ${file.path} (appended)`);
11846
12853
  continue;
11847
12854
  }
11848
- if (existsSync43(target) && !opts.force) {
12855
+ if (existsSync45(target) && !opts.force) {
11849
12856
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
11850
12857
  continue;
11851
12858
  }
11852
12859
  await fs.writeFile(target, file.content, "utf-8");
11853
12860
  console.log(`+ ${file.path}`);
11854
12861
  }
11855
- const pm = existsSync43(path30.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync43(path30.join(root, "yarn.lock")) ? "yarn add" : existsSync43(path30.join(root, "bun.lock")) || existsSync43(path30.join(root, "bun.lockb")) ? "bun add" : "npm install";
12862
+ const pm = existsSync45(path30.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync45(path30.join(root, "yarn.lock")) ? "yarn add" : existsSync45(path30.join(root, "bun.lock")) || existsSync45(path30.join(root, "bun.lockb")) ? "bun add" : "npm install";
11856
12863
  console.log("");
11857
12864
  console.log(`\u2714 The Data Studio is set up for ${{ next: "Next.js", "tanstack-start": "TanStack Start", "supabase-function": "a Supabase Edge Function" }[plan.host]}. To finish:`);
11858
12865
  console.log(` 1. ${pm} ${plan.install.map((p) => /[\s<>|]/.test(p) ? `"${p}"` : p).join(" ")}`);
@@ -11923,7 +12930,7 @@ program.command("migrate").description("Copy new package migrations of the app's
11923
12930
  process.exitCode = 1;
11924
12931
  }
11925
12932
  });
11926
- program.command("upgrade").description("Move every @marktiderman/genesis* dependency to one Genesis release, refresh the files Genesis owns, run codemods and the doctor").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--version <v>", "The @marktiderman/genesis release: an exact version or a dist-tag", "latest").option("--manifest <file>", "Read the release from this versions.json instead of npm").option("--dry-run", "Report the bump, and owned files compared with the packages installed now; change nothing", false).option("--no-install", "Don't reinstall after the bump").option("--no-doctor", "Don't run genesis doctor after").option("--keep-mine", "Never merge an owned file you changed; write the new text to .genesis-next", false).option("--pr", "Commit to a genesis-upgrade/<version> branch, push it and open a pull request", false).option("--genesis-repo <url>", "The Genesis git repository whose <package>@<version> tags overlays are rebased from (default: the public one)").action(async (opts) => {
12933
+ program.command("upgrade").description("Move every @marktiderman/genesis* dependency to one Genesis release, refresh the files Genesis owns and what's generated, run codemods and the doctor").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--version <v>", "The @marktiderman/genesis release: an exact version or a dist-tag", "latest").option("--manifest <file>", "Read the release from this versions.json instead of npm").option("--dry-run", "Report the bump, and owned files compared with the packages installed now; change nothing", false).option("--no-install", "Don't reinstall after the bump").option("--no-doctor", "Don't run genesis doctor after").option("--no-agents", "Don't regenerate the agent guide (genesis agents) after").option("--no-features-build", "Don't run features build after").option("--keep-mine", "Never merge an owned file you changed; write the new text to .genesis-next", false).option("--pr", "Commit to a genesis-upgrade/<version> branch, push it and open a pull request", false).option("--genesis-repo <url>", "The Genesis git repository whose <package>@<version> tags overlays are rebased from (default: the public one)").action(async (opts) => {
11927
12934
  const { runUpgrade: runUpgrade2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
11928
12935
  const report = await runUpgrade2({
11929
12936
  root: path30.resolve(opts.dir),
@@ -11932,6 +12939,8 @@ program.command("upgrade").description("Move every @marktiderman/genesis* depend
11932
12939
  dryRun: opts.dryRun,
11933
12940
  install: opts.install,
11934
12941
  doctor: opts.doctor,
12942
+ agents: opts.agents,
12943
+ featuresBuild: opts.featuresBuild,
11935
12944
  keepMine: opts.keepMine,
11936
12945
  pr: opts.pr,
11937
12946
  ...opts.genesisRepo ? { genesisRepo: opts.genesisRepo } : {},
@@ -11945,7 +12954,7 @@ program.command("upgrade").description("Move every @marktiderman/genesis* depend
11945
12954
  if (report.doctor === "failed") process.exitCode = 1;
11946
12955
  });
11947
12956
  program.command("codemod [id]").description("Run one of Genesis's codemods by hand (genesis upgrade runs them for you); without an id, list them").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--dry-run", "List the files it would change; change nothing", false).action(async (id, opts) => {
11948
- const { CODEMODS: CODEMODS2, codemodById: codemodById2 } = await Promise.resolve().then(() => (init_codemods(), codemods_exports));
12957
+ const { CODEMODS: CODEMODS2, codemodById: codemodById2, codemodInstallNote: codemodInstallNote2 } = await Promise.resolve().then(() => (init_codemods(), codemods_exports));
11949
12958
  if (!id) {
11950
12959
  for (const mod2 of CODEMODS2) console.log(`${mod2.id} (${mod2.package} ${mod2.version})
11951
12960
  ${mod2.description}`);
@@ -11956,6 +12965,8 @@ program.command("codemod [id]").description("Run one of Genesis's codemods by ha
11956
12965
  const changed = await mod.run({ root: path30.resolve(opts.dir), dryRun: opts.dryRun, log: (m) => console.log(m) });
11957
12966
  console.log(changed.length ? `${opts.dryRun ? "Would change" : "\u2714 Changed"} ${changed.length} file${changed.length === 1 ? "" : "s"}:
11958
12967
  ${changed.map((f) => ` ${f}`).join("\n")}` : "Nothing to change.");
12968
+ const note = codemodInstallNote2(path30.resolve(opts.dir), changed, opts.dryRun);
12969
+ if (note) console.log(`! ${note}`);
11959
12970
  });
11960
12971
  program.parseAsync(process.argv).catch((err) => {
11961
12972
  const message = err instanceof Error ? err.message : String(err);