@marktiderman/genesis-cli 1.21.0 → 1.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -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)
@@ -366,14 +371,14 @@ function listApp(root, rel, options = {}) {
366
371
  const dir = path30.join(root, rel);
367
372
  if (!existsSync(dir)) return [];
368
373
  const out = [];
369
- const walk3 = (r) => {
374
+ const walk4 = (r) => {
370
375
  for (const entry of readdirSync(path30.join(root, r), { withFileTypes: true })) {
371
376
  const child = `${r}/${entry.name}`;
372
- if (entry.isDirectory()) walk3(child);
377
+ if (entry.isDirectory()) walk4(child);
373
378
  else if (entry.isFile() || options.symlinks && entry.isSymbolicLink()) out.push(child);
374
379
  }
375
380
  };
376
- walk3(rel);
381
+ walk4(rel);
377
382
  return out.sort();
378
383
  }
379
384
  var sha256;
@@ -1031,9 +1036,11 @@ __export(config_exports, {
1031
1036
  checkRegExp: () => checkRegExp,
1032
1037
  doctorBlock: () => doctorBlock,
1033
1038
  isPackageDeclaration: () => isPackageDeclaration,
1039
+ isPlainFolder: () => isPlainFolder,
1034
1040
  loadConfig: () => loadConfig,
1035
1041
  privacyDataType: () => privacyDataType,
1036
1042
  readGenesisConfig: () => readGenesisConfig,
1043
+ validateAppFolder: () => validateAppFolder,
1037
1044
  validateConfig: () => validateConfig,
1038
1045
  validateLinks: () => validateLinks,
1039
1046
  validatePrivacy: () => validatePrivacy,
@@ -1099,8 +1106,17 @@ function readGenesisConfig(root) {
1099
1106
  const supabase = validateSupabase(raw.supabase, file);
1100
1107
  if (supabase !== true) out.supabase = supabase;
1101
1108
  }
1109
+ if (raw.appFolder !== void 0) out.appFolder = validateAppFolder(raw.appFolder, file);
1102
1110
  return out;
1103
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
+ }
1104
1120
  function validateSupabase(raw, source = "config") {
1105
1121
  const fail = (msg) => {
1106
1122
  throw new GenesisConfigError(`${source}: ${msg}`);
@@ -1309,7 +1325,7 @@ function isObject2(v) {
1309
1325
  function isStringList(v) {
1310
1326
  return Array.isArray(v) && v.every((x) => typeof x === "string");
1311
1327
  }
1312
- 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;
1313
1329
  var init_config = __esm({
1314
1330
  "src/doctor/config.ts"() {
1315
1331
  GenesisConfigError = class extends Error {
@@ -1397,6 +1413,7 @@ var init_config = __esm({
1397
1413
  supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
1398
1414
  packages: { base: "string" }
1399
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}$/;
1400
1417
  PRIVACY_KEYS = /* @__PURE__ */ new Set(["blocks", "collects", "tracking"]);
1401
1418
  DATA_USE_KEYS = /* @__PURE__ */ new Set(["type", "purposes", "linked", "tracking"]);
1402
1419
  LINK_KEYS = /* @__PURE__ */ new Set(["hosts", "paths", "webcredentials"]);
@@ -1511,7 +1528,7 @@ function uiPackageFor(config) {
1511
1528
  function loadGenesis(root, config) {
1512
1529
  const uiPackage = uiPackageFor(config);
1513
1530
  const pkg = readPackageExports(root, uiPackage);
1514
- 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));
1515
1532
  const { dir: uiDir, exports: exportNames, values, components } = pkg;
1516
1533
  const tokens = /* @__PURE__ */ new Set();
1517
1534
  const themeFiles = resolveThemeFiles(root, config, uiDir);
@@ -1536,6 +1553,16 @@ function loadGenesis(root, config) {
1536
1553
  companions: loadCompanions(root, config, uiPackage)
1537
1554
  };
1538
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
+ }
1539
1566
  function loadCompanions(root, config, uiPackage) {
1540
1567
  const out = [];
1541
1568
  for (const name of config.componentPackages ?? DEFAULT_COMPONENT_PACKAGES) {
@@ -1762,6 +1789,7 @@ function loadPalette(root) {
1762
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;
1763
1790
  var init_genesis = __esm({
1764
1791
  "src/doctor/genesis.ts"() {
1792
+ init_pm();
1765
1793
  init_config();
1766
1794
  DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
1767
1795
  NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
@@ -1995,7 +2023,7 @@ function globToRegExp(glob) {
1995
2023
  }
1996
2024
  function globMatcher(globs) {
1997
2025
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1998
- return (path56) => res.some((re) => re.test(path56));
2026
+ return (path61) => res.some((re) => re.test(path61));
1999
2027
  }
2000
2028
  var init_glob = __esm({
2001
2029
  "src/doctor/glob.ts"() {
@@ -2016,10 +2044,10 @@ function scanFiles(root, config) {
2016
2044
  const text = readFileSync(abs, "utf8");
2017
2045
  files.push({ path: rel, absolutePath: abs, ext, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(ext)) });
2018
2046
  };
2019
- const walk3 = (dir) => {
2047
+ const walk4 = (dir) => {
2020
2048
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
2021
2049
  if (entry.isDirectory()) {
2022
- 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));
2023
2051
  } else if (entry.isFile()) {
2024
2052
  visit(path30.join(dir, entry.name));
2025
2053
  }
@@ -2028,7 +2056,7 @@ function scanFiles(root, config) {
2028
2056
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
2029
2057
  const abs = path30.resolve(root, src);
2030
2058
  if (!existsSync(abs)) continue;
2031
- if (statSync(abs).isDirectory()) walk3(abs);
2059
+ if (statSync(abs).isDirectory()) walk4(abs);
2032
2060
  else visit(abs);
2033
2061
  }
2034
2062
  let local = [];
@@ -2037,7 +2065,7 @@ function scanFiles(root, config) {
2037
2065
  } catch {
2038
2066
  local = [];
2039
2067
  }
2040
- for (const pkg of local) walk3(pkg.dir);
2068
+ for (const pkg of local) walk4(pkg.dir);
2041
2069
  return files;
2042
2070
  }
2043
2071
  function lineAt(text, index) {
@@ -4104,7 +4132,7 @@ function checkShadowedExports(ctx) {
4104
4132
  file.code.split("\n").forEach((text, i) => {
4105
4133
  for (const m of text.matchAll(re)) {
4106
4134
  if (!ctx.genesis.values.has(m[1])) continue;
4107
- 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)` });
4108
4136
  }
4109
4137
  });
4110
4138
  }
@@ -4132,6 +4160,8 @@ var init_rules = __esm({
4132
4160
  init_overlays();
4133
4161
  BUILTIN_RULES = [
4134
4162
  "local-primitives",
4163
+ // figma (figma/routes.ts; runs when genesis.config.json has a figma block)
4164
+ "figma-routes",
4135
4165
  "starter-leftover",
4136
4166
  "forbidden-import",
4137
4167
  "raw-tag",
@@ -5772,11 +5802,11 @@ function checkMigrations(ctx, pkg, json, locals) {
5772
5802
  }
5773
5803
  function checkExports(ctx, pkg, json) {
5774
5804
  const targets = [];
5775
- const walk3 = (v) => {
5805
+ const walk4 = (v) => {
5776
5806
  if (typeof v === "string") targets.push(v);
5777
- 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);
5778
5808
  };
5779
- walk3(json.exports);
5809
+ walk4(json.exports);
5780
5810
  for (const t of targets) {
5781
5811
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
5782
5812
  if (!existsSync(path30.join(pkg.dir, t))) {
@@ -6484,7 +6514,7 @@ function genesisInstalls(root) {
6484
6514
  via.get(real2).add(root2);
6485
6515
  if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
6486
6516
  };
6487
- const walk3 = (kind, roots) => {
6517
+ const walk4 = (kind, roots) => {
6488
6518
  const expanded = /* @__PURE__ */ new Set();
6489
6519
  const queue = [];
6490
6520
  const visit = (dir, by, range) => {
@@ -6535,9 +6565,9 @@ function genesisInstalls(root) {
6535
6565
  ...app?.dependencies
6536
6566
  };
6537
6567
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
6538
- walk3("runtime", rootsOf(runtimeDeps, "the app"));
6568
+ walk4("runtime", rootsOf(runtimeDeps, "the app"));
6539
6569
  const top = path30.join(root, "node_modules");
6540
- walk3(
6570
+ walk4(
6541
6571
  "hoisted",
6542
6572
  packagesIn(top).filter((dir) => {
6543
6573
  const name = path30.relative(top, dir).split(path30.sep).join("/");
@@ -6546,7 +6576,7 @@ function genesisInstalls(root) {
6546
6576
  );
6547
6577
  const devRoots = { ...devDeps };
6548
6578
  for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
6549
- walk3("dev", rootsOf(devRoots, "the app (dev)"));
6579
+ walk4("dev", rootsOf(devRoots, "the app (dev)"));
6550
6580
  for (const [key2, copy] of copies) {
6551
6581
  const kinds = via.get(key2);
6552
6582
  copy.runtime = kinds.has("runtime");
@@ -6810,6 +6840,29 @@ var init_dates = __esm({
6810
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;
6811
6841
  }
6812
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
+ });
6813
6866
 
6814
6867
  // src/upgrade/bump-core.mjs
6815
6868
  function compareVersions2(a, b) {
@@ -7043,6 +7096,113 @@ var init_bump_core = __esm({
7043
7096
  LEGACY_EXCLUDES = ["@marktiderman/genesis-*", UMBRELLA];
7044
7097
  }
7045
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
+ });
7046
7206
 
7047
7207
  // src/upgrade/scope-names.ts
7048
7208
  function maskComments(text) {
@@ -7375,25 +7535,71 @@ __export(codemods_exports, {
7375
7535
  CODEMODS: () => CODEMODS,
7376
7536
  appScripts: () => appScripts,
7377
7537
  codemodById: () => codemodById,
7538
+ codemodInstallNote: () => codemodInstallNote,
7378
7539
  codemodsFor: () => codemodsFor,
7540
+ composerBarHasContent: () => composerBarHasContent,
7379
7541
  genesisEslintConfig: () => genesisEslintConfig,
7542
+ rewriteComposerBarEmpty: () => rewriteComposerBarEmpty,
7380
7543
  scopeNeutralNames: () => scopeNeutralNames,
7381
7544
  uncoveredBreaks: () => uncoveredBreaks
7382
7545
  });
7383
- function appScripts(root) {
7384
- const out = [];
7385
- const walk3 = (dir) => {
7386
- for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
7387
- const abs = path30.join(dir, entry.name);
7388
- if (entry.isDirectory()) {
7389
- if (!SKIP_DIRS3.has(entry.name)) walk3(abs);
7390
- } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
7391
- 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
+ }
7392
7584
  }
7585
+ out += c;
7393
7586
  }
7394
- };
7395
- walk3(root);
7396
- 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).`;
7397
7603
  }
7398
7604
  function codemodById(id, registry = CODEMODS) {
7399
7605
  return registry.find((mod) => mod.id === id);
@@ -7408,17 +7614,19 @@ function uncoveredBreaks(changes, registry = CODEMODS) {
7408
7614
  const [a, b] = bare(v).split(".").map(Number);
7409
7615
  return a === 0 ? `0.${b}` : String(a);
7410
7616
  };
7411
- 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)));
7412
7620
  }
7413
- var SKIP_DIRS3, SCRIPT2, MAX_BYTES, scopeNeutralNames, genesisEslintConfig, CODEMODS, bare;
7621
+ var scopeNeutralNames, genesisEslintConfig, composerBarHasContent, CODEMODS, bare;
7414
7622
  var init_codemods = __esm({
7415
7623
  "src/upgrade/codemods.ts"() {
7624
+ init_pm();
7625
+ init_app_scripts();
7416
7626
  init_bump_core();
7627
+ init_doctor_rule_codemods();
7417
7628
  init_eslint_config();
7418
7629
  init_scope_names();
7419
- SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
7420
- SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
7421
- MAX_BYTES = 2 * 1024 * 1024;
7422
7630
  scopeNeutralNames = {
7423
7631
  id: "genesis-core-2-scope-names",
7424
7632
  package: "@marktiderman/genesis-core",
@@ -7483,12 +7691,31 @@ ${manualLines(result.kind, platform).map((l) => ` ${l}`).join("\n")}`);
7483
7691
  json.devDependencies = Object.fromEntries(sorted2 ? dev.sort(([a], [b]) => a.localeCompare(b)) : dev);
7484
7692
  changed.push("package.json");
7485
7693
  if (!dryRun) writeFileSync(pkgFile, `${JSON.stringify(json, null, indent)}${raw.endsWith("\n") ? "\n" : ""}`);
7486
- 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).`);
7487
7695
  }
7488
7696
  return changed;
7489
7697
  }
7490
7698
  };
7491
- CODEMODS = [scopeNeutralNames, genesisEslintConfig];
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);
7714
+ }
7715
+ return changed;
7716
+ }
7717
+ };
7718
+ CODEMODS = [scopeNeutralNames, genesisEslintConfig, overlaysFitThePhone, hapticsUseGenesis, composerBarHasContent];
7492
7719
  bare = (spec) => spec.replace(/^[\^~=]/, "");
7493
7720
  }
7494
7721
  });
@@ -8016,7 +8243,7 @@ var init_primitives = __esm({
8016
8243
  CORE = [
8017
8244
  {
8018
8245
  need: "anything, before building it",
8019
- 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`',
8020
8247
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
8021
8248
  from: "genesis-cli"
8022
8249
  },
@@ -8064,6 +8291,58 @@ var init_primitives = __esm({
8064
8291
  read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
8065
8292
  }
8066
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
+ });
8067
8346
  function copyOwned(root, lock, write, dryRun = false) {
8068
8347
  const existing = readApp(root, write.path);
8069
8348
  const record = () => {
@@ -8133,7 +8412,7 @@ function refreshOwned(root, lock, input, options = {}) {
8133
8412
  const theirsSha = sha256(input.theirs);
8134
8413
  if (theirsSha === entry.sha256) return { path: input.path, outcome: "unchanged" };
8135
8414
  const record = (sha) => {
8136
- const { pending: _settled, deleted: _back, ...rest } = entry;
8415
+ const { pending: _settled, pendingMine: _was, deleted: _back, ...rest } = entry;
8137
8416
  lock.files[input.path] = { ...rest, sha256: sha, ...input.version ? { version: input.version } : {} };
8138
8417
  };
8139
8418
  if (mine === null) {
@@ -8148,25 +8427,25 @@ function refreshOwned(root, lock, input, options = {}) {
8148
8427
  const next = `${input.path}.genesis-next`;
8149
8428
  const existingNext = readApp(root, next);
8150
8429
  if (entry.pending === theirsSha) {
8151
- if (existingNext === null) {
8152
- 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;
8153
8433
  lock.files[input.path] = { ...rest, sha256: theirsSha, ...input.version ? { version: input.version } : {} };
8154
- 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}` };
8155
8435
  }
8156
- return { path: input.path, outcome: "kept-mine", detail: `waiting for you: resolve ${next} into your file, then delete it` };
8157
8436
  }
8158
8437
  const writeNext = (text) => {
8159
8438
  if (existingNext !== null && existingNext !== text) return `${next} is already there with other text; resolve it (and delete it) first`;
8160
8439
  write(next, text);
8161
- lock.files[input.path] = { ...entry, pending: theirsSha };
8440
+ lock.files[input.path] = { ...entry, pending: theirsSha, pendingMine: mineSha };
8162
8441
  return null;
8163
8442
  };
8164
- if (!options.keepMine && input.base !== null && sha256(input.base) === entry.sha256) {
8443
+ if (!options.keepMine && input.base !== null) {
8165
8444
  const merged = mergeThreeWay(mine, input.base, input.theirs);
8166
8445
  if (merged?.clean) {
8167
8446
  write(input.path, merged.text);
8168
8447
  record(theirsSha);
8169
- 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" };
8170
8449
  }
8171
8450
  if (merged) {
8172
8451
  const blocked2 = writeNext(merged.text);
@@ -8437,6 +8716,11 @@ async function checkLockFiles(ctx) {
8437
8716
  home = databaseElsewhere(ctx.root);
8438
8717
  } catch {
8439
8718
  }
8719
+ let appFolder = null;
8720
+ try {
8721
+ appFolder = appFolderOf(ctx.root);
8722
+ } catch {
8723
+ }
8440
8724
  const elsewhere = home ? Object.keys(lock.files).filter(isSupabasePath) : [];
8441
8725
  if (home && elsewhere.length) {
8442
8726
  ctx.report({
@@ -8472,6 +8756,7 @@ async function checkLockFiles(ctx) {
8472
8756
  }
8473
8757
  if (text === null) {
8474
8758
  if (entry.deleted) continue;
8759
+ if (appFolder && isRepositoryWorkflow(rel)) continue;
8475
8760
  ctx.report({
8476
8761
  rule: "lock-files",
8477
8762
  level: "warn",
@@ -8496,6 +8781,7 @@ async function checkLockFiles(ctx) {
8496
8781
  }
8497
8782
  var init_lock_files = __esm({
8498
8783
  "src/doctor/lock-files.ts"() {
8784
+ init_app_folder();
8499
8785
  init_discover();
8500
8786
  init_files();
8501
8787
  init_lock();
@@ -8562,11 +8848,408 @@ function checkEslintConfig(ctx) {
8562
8848
  subject: TESTING_LIBRARY,
8563
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`
8564
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
+ });
8565
8859
  }
8566
8860
  }
8567
8861
  var init_eslint_config2 = __esm({
8568
8862
  "src/doctor/eslint-config.ts"() {
8863
+ init_pm();
8569
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 inProposal = (f) => /^Proposal\s*·/.test(f.section ?? "");
9108
+ const routeFrames = figma.frames.filter((f) => platformOf(f.page) && !inProposal(f));
9109
+ const framesFor = (r) => routeFrames.filter((f) => platformOf(f.page) === r.platform && (sameScreen(f.route, r.route) || r.route === "index" && f.route === "/"));
9110
+ const byId = new Map(figma.frames.map((f) => [f.id, f]));
9111
+ const framed = new Set(routes.flatMap((r) => framesFor(r).map((f) => f.id)));
9112
+ const covered = routes.filter((r) => framesFor(r).length > 0);
9113
+ const routesWithoutFrame = routes.filter((r) => framesFor(r).length === 0);
9114
+ const framesWithoutRoute = routeFrames.filter((f) => !framed.has(f.id));
9115
+ const proposals = {};
9116
+ for (const f of figma.frames.filter((x) => x.page === config.proposalsPage || platformOf(x.page) && inProposal(x))) (proposals[f.section ?? "(no section)"] ??= []).push(f);
9117
+ const missingHotspots = [];
9118
+ const seen = /* @__PURE__ */ new Set();
9119
+ for (const t of targets) {
9120
+ const source = routes.find((r) => r.file === t.file);
9121
+ if (!source) continue;
9122
+ const from = framesFor(source);
9123
+ if (!from.length) continue;
9124
+ const dest = routes.find((r) => r.platform === source.platform && routeMatches(r.route, t.target));
9125
+ if (!dest || dest === source) continue;
9126
+ const key2 = `${source.route}\u2192${dest.route}`;
9127
+ if (seen.has(key2)) continue;
9128
+ seen.add(key2);
9129
+ const to = new Set(framesFor(dest).map((f) => f.id));
9130
+ const linked = figma.hotspots.some((h) => from.some((f) => f.id === h.from) && to.has(h.to));
9131
+ if (!linked) missingHotspots.push({ ...t, from: source.route, to: dest.route, targetHasFrame: to.size > 0 });
9132
+ }
9133
+ const deadHotspots = [];
9134
+ for (const h of figma.hotspots) {
9135
+ const from = byId.get(h.from);
9136
+ const to = byId.get(h.to);
9137
+ if (from && to && platformOf(to.page) && !inProposal(to) && !framed.has(to.id)) deadHotspots.push({ from, to });
9138
+ }
9139
+ 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) }));
9140
+ const wantedPages = [...Object.values(config.pages), config.proposalsPage];
9141
+ const missingPages = wantedPages.filter((p) => p !== config.proposalsPage && !figma.pages.includes(p));
9142
+ const uncheckedNavigation = dynamicTargets.filter((t) => routes.some((r) => r.file === t.file));
9143
+ return {
9144
+ file: config.file,
9145
+ summary: {
9146
+ routes: routes.length,
9147
+ frames: routeFrames.length,
9148
+ covered: covered.length,
9149
+ coveredPercent: routes.length ? Math.round(covered.length / routes.length * 100) : 100,
9150
+ hotspots: figma.hotspots.length,
9151
+ missing: missingPages.length + routesWithoutFrame.length + missingHotspots.length + idMismatches.length
9152
+ },
9153
+ missingPages,
9154
+ routesWithoutFrame,
9155
+ framesWithoutRoute,
9156
+ proposals,
9157
+ missingHotspots,
9158
+ deadHotspots,
9159
+ idMismatches,
9160
+ uncheckedNavigation
9161
+ };
9162
+ }
9163
+ async function checkFigmaRoutes(options) {
9164
+ const config = options.config ?? readFigmaConfig(options.root);
9165
+ if (!config) throw new FigmaConfigError(`no "figma" block in ${path30.join(options.root, "genesis.config.json")}`);
9166
+ const token = options.token ?? process.env.FIGMA_ACCESS_TOKEN;
9167
+ if (!token) throw new FigmaConfigError("FIGMA_ACCESS_TOKEN isn't set");
9168
+ const figma = await readFigma(config, token, options.fetch);
9169
+ return compare(config, appRoutes(options.root), appNavTargets(options.root), figma, appDynamicNavTargets(options.root));
9170
+ }
9171
+ function formatCoverage(r) {
9172
+ const s = r.summary;
9173
+ 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`];
9174
+ const table = (title, head, rows) => {
9175
+ if (!rows.length) return;
9176
+ const widths = head.map((h, i) => Math.max(h.length, ...rows.map((row) => row[i].length)));
9177
+ const fmt = (row) => ` ${row.map((c, i) => c.padEnd(widths[i])).join(" ")}`.trimEnd();
9178
+ lines.push("", `${title} (${rows.length})`, fmt(head), fmt(widths.map((w) => "-".repeat(w))), ...rows.map(fmt));
9179
+ };
9180
+ if (r.missingPages.length) lines.push("", `Pages not in the file: ${r.missingPages.join(", ")}`);
9181
+ table("Routes with no frame", ["platform", "route", "file"], r.routesWithoutFrame.map((x) => [x.platform, x.route, x.file]));
9182
+ table("Frames with no route (put them in a Proposal section, or add the route)", ["page", "frame", "id"], r.framesWithoutRoute.map((f) => [f.page, f.name, f.id]));
9183
+ table("Navigation with no hotspot", ["from", "to", "at"], r.missingHotspots.map((m) => [m.from, `${m.to}${m.targetHasFrame ? "" : " (no frame)"}`, `${m.file}:${m.line}`]));
9184
+ table("Hotspots to a frame with no route", ["from", "to"], r.deadHotspots.map((d) => [d.from.name, d.to.name]));
9185
+ 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"]));
9186
+ table("Navigation not checked (not a string literal)", ["at", "target"], r.uncheckedNavigation.map((t) => [`${t.file}:${t.line}`, t.target]));
9187
+ table("Proposals", ["section", "frame", "id"], Object.entries(r.proposals).flatMap(([sec, fs2]) => fs2.map((f) => [sec, f.name, f.id])));
9188
+ return lines.join("\n");
9189
+ }
9190
+ function coverageFindings(r, strict) {
9191
+ const gap = strict ? "warn" : "info";
9192
+ return [
9193
+ ...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 })),
9194
+ ...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 })),
9195
+ ...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 })),
9196
+ ...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 })),
9197
+ ...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 })),
9198
+ ...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 })),
9199
+ ...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 }))
9200
+ ];
9201
+ }
9202
+ var FigmaConfigError, CODE, FIGMA_ID, STR, NAV_PATTERNS, DYNAMIC_PATTERNS, FIGMA_API, FIGMA_TIMEOUT_MS, SCREEN_TYPES;
9203
+ var init_routes2 = __esm({
9204
+ "src/figma/routes.ts"() {
9205
+ FigmaConfigError = class extends Error {
9206
+ };
9207
+ CODE = /\.(?:tsx|ts|jsx|js)$/;
9208
+ FIGMA_ID = /^\s*\/\/\s*figma:\s*(\d+[:-]\d+)\s*$/;
9209
+ STR = String.raw`(?:"([^"\n]*)"|'([^'\n]*)'|` + "`([^`$\\n]*)`)";
9210
+ NAV_PATTERNS = [
9211
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*` + STR, "g"),
9212
+ new RegExp(String.raw`<Link\b[^>]*?\b(?:href|to)=\{?\s*` + STR, "g"),
9213
+ new RegExp(String.raw`\bnavigate\(\s*\{[^}]*?\bto\s*:\s*` + STR, "g")
9214
+ ];
9215
+ DYNAMIC_PATTERNS = [
9216
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
9217
+ new RegExp(String.raw`<Link\b[^>]*?\b(?:href|to)=\{\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
9218
+ new RegExp(String.raw`\bnavigate\(\s*\{[^}]*?\bto\s*:\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
9219
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*(\{[^}\n]*?\bpathname\b[^}\n]*\}?)`, "g"),
9220
+ new RegExp(String.raw`<Link\b[^>]*?\bhref=\{(\{[^}\n]*?\bpathname\b[^}\n]*\}?)`, "g")
9221
+ ];
9222
+ FIGMA_API = "https://api.figma.com";
9223
+ FIGMA_TIMEOUT_MS = 3e4;
9224
+ SCREEN_TYPES = /* @__PURE__ */ new Set(["FRAME", "COMPONENT", "COMPONENT_SET", "INSTANCE"]);
9225
+ }
9226
+ });
9227
+
9228
+ // src/doctor/figma-routes.ts
9229
+ async function checkFigmaRoutesRule(ctx) {
9230
+ let config;
9231
+ try {
9232
+ config = readFigmaConfig(ctx.root);
9233
+ } catch (err) {
9234
+ if (!(err instanceof FigmaConfigError)) throw err;
9235
+ ctx.report({ rule: "figma-routes", level: "warn", file: "genesis.config.json", message: err.message });
9236
+ return;
9237
+ }
9238
+ if (!config) return;
9239
+ if (!process.env.FIGMA_ACCESS_TOKEN) {
9240
+ 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)" });
9241
+ return;
9242
+ }
9243
+ try {
9244
+ const report = await checkFigmaRoutes({ root: ctx.root, config });
9245
+ for (const f of coverageFindings(report, ctx.strict ?? false)) ctx.report({ rule: "figma-routes", ...f });
9246
+ } catch (err) {
9247
+ ctx.report({ rule: "figma-routes", level: "info", file: "genesis.config.json", message: `skipped: ${err.message}` });
9248
+ }
9249
+ }
9250
+ var init_figma_routes = __esm({
9251
+ "src/doctor/figma-routes.ts"() {
9252
+ init_routes2();
8570
9253
  }
8571
9254
  });
8572
9255
 
@@ -8634,7 +9317,7 @@ async function runDoctor(options = {}) {
8634
9317
  }
8635
9318
  const raw = [];
8636
9319
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
8637
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
9320
+ for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
8638
9321
  try {
8639
9322
  await plugin.check(ctx);
8640
9323
  } catch (err) {
@@ -8722,6 +9405,7 @@ function builtinChecks(config, options = {}) {
8722
9405
  { name: "database-elsewhere", check: checkDatabaseHome },
8723
9406
  { name: "eslint-config", check: checkEslintConfig },
8724
9407
  ...(config.packs ?? []).map((p) => packs[p]),
9408
+ ...options.figma !== false ? [{ name: "figma-routes", check: checkFigmaRoutesRule }] : [],
8725
9409
  ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
8726
9410
  ];
8727
9411
  }
@@ -8774,7 +9458,7 @@ function applyConfig(raw, config, packageIds) {
8774
9458
  }
8775
9459
  return out.sort((x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule));
8776
9460
  }
8777
- function formatReport(result) {
9461
+ function formatReport(result, options = {}) {
8778
9462
  const g = result.genesis;
8779
9463
  const lines = [
8780
9464
  `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"}`
@@ -8782,7 +9466,7 @@ function formatReport(result) {
8782
9466
  for (const f of result.findings) {
8783
9467
  lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
8784
9468
  }
8785
- lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
9469
+ 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)`);
8786
9470
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
8787
9471
  const info = result.infos ? `, ${result.infos} info` : "";
8788
9472
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
@@ -8838,6 +9522,7 @@ var init_doctor = __esm({
8838
9522
  init_lock_files();
8839
9523
  init_database2();
8840
9524
  init_eslint_config2();
9525
+ init_figma_routes();
8841
9526
  init_config();
8842
9527
  init_genesis();
8843
9528
  init_patterns();
@@ -9304,8 +9989,8 @@ function routeTags(source) {
9304
9989
  }
9305
9990
  function wireStudioRoute(source, route, pageImportPath) {
9306
9991
  const tags = routeTags(source);
9307
- const relative17 = route.replace(/^\//, "");
9308
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative17.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
9992
+ const relative18 = route.replace(/^\//, "");
9993
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative18.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
9309
9994
  if (existing) {
9310
9995
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
9311
9996
  }
@@ -9313,17 +9998,17 @@ function wireStudioRoute(source, route, pageImportPath) {
9313
9998
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
9314
9999
  if (roots.length !== 1) {
9315
10000
  return {
9316
- 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.`
10001
+ 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.`
9317
10002
  };
9318
10003
  }
9319
10004
  const layout = roots[0];
9320
10005
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
9321
- if (base && !relative17.startsWith(`${base}/`)) {
10006
+ if (base && !relative18.startsWith(`${base}/`)) {
9322
10007
  return {
9323
10008
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
9324
10009
  };
9325
10010
  }
9326
- const childPath = base ? relative17.slice(base.length + 1) : relative17;
10011
+ const childPath = base ? relative18.slice(base.length + 1) : relative18;
9327
10012
  const guard = GUARD.exec(source)?.[1];
9328
10013
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
9329
10014
  const before = source.slice(0, layout.close);
@@ -9833,7 +10518,7 @@ export default function Screen() {
9833
10518
  }
9834
10519
  `;
9835
10520
  }
9836
- var init_routes2 = __esm({
10521
+ var init_routes3 = __esm({
9837
10522
  "src/blocks/routes.ts"() {
9838
10523
  init_files();
9839
10524
  }
@@ -10155,7 +10840,7 @@ var init_add = __esm({
10155
10840
  init_owned();
10156
10841
  init_pm();
10157
10842
  init_registry_edit();
10158
- init_routes2();
10843
+ init_routes3();
10159
10844
  SILENT = { info() {
10160
10845
  }, warn() {
10161
10846
  } };
@@ -10351,11 +11036,120 @@ var init_migrate = __esm({
10351
11036
  init_notification_types();
10352
11037
  }
10353
11038
  });
10354
- function walk2(dir, rel = "", out = /* @__PURE__ */ new Map()) {
11039
+ async function fetchChangelog(directory) {
11040
+ try {
11041
+ const res = await fetch(`https://raw.githubusercontent.com/${REPOSITORY}/main/${directory}/CHANGELOG.md`, { signal: AbortSignal.timeout(5e3) });
11042
+ return res.ok ? await res.text() : null;
11043
+ } catch {
11044
+ return null;
11045
+ }
11046
+ }
11047
+ function breakingEntries(changelog, from, to) {
11048
+ const low = bare2(from);
11049
+ const high = bare2(to);
11050
+ const heading = low.startsWith("0.") ? /^### (?:Major|Minor) Changes\s*$/ : /^### Major Changes\s*$/;
11051
+ const parts = changelog.split(/^## (?=\d)/m).slice(1);
11052
+ let matched = false;
11053
+ const entries = [];
11054
+ for (const part of parts) {
11055
+ const version = part.split("\n", 1)[0].trim();
11056
+ if (compareVersions2(version, low) <= 0 || compareVersions2(version, high) > 0) continue;
11057
+ if (compareVersions2(version, high) === 0) matched = true;
11058
+ let inside3 = false;
11059
+ for (const line of part.split("\n")) {
11060
+ if (line.startsWith("### ")) inside3 = heading.test(line);
11061
+ else if (inside3 && line.startsWith("- ")) entries.push(firstLine(line));
11062
+ }
11063
+ }
11064
+ return matched ? entries : null;
11065
+ }
11066
+ function repositoryDirectory(root, name) {
11067
+ const dir = packageDir(root, name);
11068
+ if (!dir) return null;
11069
+ try {
11070
+ const { repository } = JSON.parse(readFileSync(path30.join(dir, "package.json"), "utf8"));
11071
+ return typeof repository?.directory === "string" ? repository.directory : null;
11072
+ } catch {
11073
+ return null;
11074
+ }
11075
+ }
11076
+ async function breakLines(root, breaks, reader) {
11077
+ const lowest = /* @__PURE__ */ new Map();
11078
+ for (const b of breaks) {
11079
+ const key2 = `${b.name}@${b.to}`;
11080
+ const held = lowest.get(key2);
11081
+ if (!held || compareVersions2(bare2(b.from), bare2(held.from)) < 0) lowest.set(key2, b);
11082
+ }
11083
+ const lines = [];
11084
+ for (const b of lowest.values()) {
11085
+ const directory = repositoryDirectory(root, b.name);
11086
+ 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}`;
11087
+ const head = `- \`${b.name}\` ${b.from} \u2192 ${b.to}`;
11088
+ const text = directory && reader.changelog ? await reader.changelog(directory) : null;
11089
+ const entries = text === null ? null : breakingEntries(text, b.from, b.to);
11090
+ if (entries === null) lines.push(`${head}: read [its changelog](${url})`);
11091
+ else if (!entries.length) lines.push(`${head}: no breaking changes of its own; moved with its dependencies, see [its changelog](${url})`);
11092
+ else lines.push(`${head}: [changelog](${url})`, ...entries.slice(0, 5).map((e) => ` - ${e}`), ...entries.length > 5 ? [` - and ${entries.length - 5} more`] : []);
11093
+ }
11094
+ return lines;
11095
+ }
11096
+ var REPOSITORY, bare2, firstLine;
11097
+ var init_changelog = __esm({
11098
+ "src/upgrade/changelog.ts"() {
11099
+ init_discover();
11100
+ init_bump_core();
11101
+ REPOSITORY = "marktiderman/genesis";
11102
+ bare2 = (spec) => spec.replace(/^[\^~=]/, "");
11103
+ firstLine = (entry) => {
11104
+ const line = entry.replace(/^-\s*(?:[0-9a-f]{7,}:\s*)?/, "").split("\n")[0].trim();
11105
+ return line.length > 160 ? `${line.slice(0, 157)}\u2026` : line;
11106
+ };
11107
+ }
11108
+ });
11109
+
11110
+ // src/upgrade/new-exports.ts
11111
+ function componentValues(root) {
11112
+ try {
11113
+ const { config } = loadConfig(root);
11114
+ return readPackageExports(root, uiPackageFor(config))?.values ?? null;
11115
+ } catch {
11116
+ return null;
11117
+ }
11118
+ }
11119
+ function handBuiltSwaps(root, before) {
11120
+ if (!before) return [];
11121
+ try {
11122
+ const { config } = loadConfig(root);
11123
+ if (config.rules?.["shadowed-export"] === "off") return [];
11124
+ const uiPackage = uiPackageFor(config);
11125
+ const after = readPackageExports(root, uiPackage)?.values;
11126
+ const gained = new Set([...after ?? []].filter((name) => !before.has(name)));
11127
+ if (!gained.size) return [];
11128
+ clearPackageRulesCache();
11129
+ const found = [];
11130
+ checkShadowedExports({ root, config, files: scanFiles(root, config), packages: discoverPackages(root), genesis: { uiPackage, values: gained }, report: (f) => found.push(f) });
11131
+ return found.map((f) => ({ name: f.subject, file: f.file, line: f.line ?? 0, package: uiPackage }));
11132
+ } catch {
11133
+ return [];
11134
+ }
11135
+ }
11136
+ function swapLines(swaps) {
11137
+ 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.`);
11138
+ }
11139
+ var init_new_exports = __esm({
11140
+ "src/upgrade/new-exports.ts"() {
11141
+ init_config();
11142
+ init_genesis();
11143
+ init_package_rules();
11144
+ init_rules();
11145
+ init_scan();
11146
+ }
11147
+ });
11148
+ function walk3(dir, rel = "", out = /* @__PURE__ */ new Map()) {
10355
11149
  for (const entry of readdirSync(path30.join(dir, rel), { withFileTypes: true })) {
10356
11150
  if (SKIP.has(entry.name)) continue;
10357
11151
  const child = rel ? `${rel}/${entry.name}` : entry.name;
10358
- if (entry.isDirectory()) walk2(dir, child, out);
11152
+ if (entry.isDirectory()) walk3(dir, child, out);
10359
11153
  else if (entry.isFile()) out.set(child, readFileSync(path30.join(dir, child)));
10360
11154
  }
10361
11155
  return out;
@@ -10532,7 +11326,7 @@ function planOverlays(root, wanted, upstream2, manifests = ["package.json"]) {
10532
11326
  }
10533
11327
  const base = baseRead.files;
10534
11328
  const next = nextRead.files;
10535
- const mine = walk2(pkg.dir);
11329
+ const mine = walk3(pkg.dir);
10536
11330
  const promoted = promotions(root, pkg.name);
10537
11331
  const verdict = (file) => {
10538
11332
  const appPath3 = `${pkg.rel}/${file}`;
@@ -10801,6 +11595,7 @@ var init_overlays2 = __esm({
10801
11595
  // src/upgrade/index.ts
10802
11596
  var upgrade_exports = {};
10803
11597
  __export(upgrade_exports, {
11598
+ checkSubstitutions: () => checkSubstitutions,
10804
11599
  npmLookup: () => npmLookup,
10805
11600
  pnpmWorkspaceFileFor: () => pnpmWorkspaceFileFor,
10806
11601
  releaseAgeError: () => releaseAgeError,
@@ -10852,9 +11647,25 @@ function npmLookup(cwd) {
10852
11647
  latest.set(name, typeof v === "string" ? v : null);
10853
11648
  }
10854
11649
  return latest.get(name);
10855
- }
11650
+ },
11651
+ changelog: fetchChangelog
10856
11652
  };
10857
11653
  }
11654
+ function checkInstalled(root, options) {
11655
+ const noInstall = options.install === false || options.dryRun;
11656
+ if (!Object.keys(readLock(root).files).length && !(noInstall && options.doctor !== false)) return;
11657
+ const text = readApp(root, "package.json");
11658
+ if (text === null) return;
11659
+ let pkg;
11660
+ try {
11661
+ pkg = JSON.parse(text);
11662
+ } catch {
11663
+ return;
11664
+ }
11665
+ const declared = ["dependencies", "devDependencies", "optionalDependencies"].some((s) => Object.keys(pkg[s] ?? {}).some((name) => name.startsWith("@marktiderman/genesis")));
11666
+ if (!declared || installedGenesis(root).size) return;
11667
+ 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.)`);
11668
+ }
10858
11669
  function readText2(file) {
10859
11670
  try {
10860
11671
  return readFileSync(file, "utf8");
@@ -10879,6 +11690,11 @@ function gitTopLevel(root) {
10879
11690
  return null;
10880
11691
  }
10881
11692
  }
11693
+ function folderBelowTopLevel(root) {
11694
+ const real2 = realpathSync(root);
11695
+ const top = gitTopLevel(real2);
11696
+ return top === null ? null : path30.relative(top, real2).split(path30.sep).join("/");
11697
+ }
10882
11698
  function pnpmWorkspaceFileFor(root) {
10883
11699
  const real2 = realpathSync(root);
10884
11700
  const top = gitTopLevel(real2);
@@ -10957,6 +11773,7 @@ async function runUpgrade(options) {
10957
11773
  const root = path30.resolve(options.root);
10958
11774
  const log = options.log ?? (() => {
10959
11775
  });
11776
+ checkInstalled(root, options);
10960
11777
  const lookup = options.lookup ?? npmLookup(root);
10961
11778
  const release = options.manifest ? JSON.parse(readFileSync(path30.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
10962
11779
  const pinned = { [UMBRELLA]: release.version, ...release.packages };
@@ -10997,12 +11814,29 @@ async function runUpgrade(options) {
10997
11814
  const lock = readLock(root);
10998
11815
  const home = databaseElsewhere(root);
10999
11816
  checkSubstitutions(lock.substitutions);
11817
+ const appFolder = appFolderOf(root);
11818
+ const written = folderSubstitutions(lock.substitutions, appFolder);
11819
+ const ownedText = (file, source) => {
11820
+ const text = sourceText(root, source, written);
11821
+ return text === null ? null : renderOwned(file, text, appFolder);
11822
+ };
11000
11823
  const bases = /* @__PURE__ */ new Map();
11824
+ const basesFromPending = /* @__PURE__ */ new Set();
11001
11825
  for (const [file, entry] of Object.entries(lock.files)) {
11002
11826
  if (ownedKeyProblem(file, entry.source, localPackageNames(root))) continue;
11003
- const text = sourceText(root, entry.source, lock.substitutions);
11004
- if (text !== null && sha256(text) === entry.sha256) bases.set(file, text);
11827
+ const text = ownedText(file, entry.source);
11828
+ if (text === null) continue;
11829
+ const was = sourceText(root, entry.source, lock.substitutions);
11830
+ const taken = [sha256(text), ...was === null ? [] : [sha256(was)]];
11831
+ const mine = entry.pending && entry.pendingMine && taken.includes(entry.pending) && readApp(root, `${file}.genesis-next`) === null ? readApp(root, file) : null;
11832
+ const resolved = mine !== null && sha256(mine) !== entry.pendingMine;
11833
+ if (taken.includes(entry.sha256)) bases.set(file, text);
11834
+ else if (resolved) {
11835
+ bases.set(file, text);
11836
+ basesFromPending.add(file);
11837
+ }
11005
11838
  }
11839
+ const valuesBefore = options.dryRun ? null : componentValues(root);
11006
11840
  const files = /* @__PURE__ */ new Set();
11007
11841
  const lockEdits = [];
11008
11842
  const codemodRuns = [];
@@ -11019,6 +11853,7 @@ async function runUpgrade(options) {
11019
11853
  codemodRuns.push({ id: mod.id, files: changed });
11020
11854
  for (const f of changed) files.add(f);
11021
11855
  }
11856
+ const codemodNeedsInstall = options.install === false ? codemodInstallNote(root, codemodRuns.flatMap((c) => c.files), Boolean(options.dryRun)) : null;
11022
11857
  let bunLock;
11023
11858
  const prune = (want) => {
11024
11859
  const result = pruneBunLock(root, want, Boolean(options.dryRun));
@@ -11085,7 +11920,7 @@ async function runUpgrade(options) {
11085
11920
  }
11086
11921
  const added = [];
11087
11922
  const newMigrations = [];
11088
- const warnings = [...excludeWarnings];
11923
+ const warnings = [...excludeWarnings, ...codemodNeedsInstall ? [codemodNeedsInstall] : []];
11089
11924
  const manifests = [];
11090
11925
  const catalog = catalogBlocks();
11091
11926
  const off = appBlocksSwitchedOff(root, catalog, Object.keys(lock.blocks));
@@ -11130,14 +11965,35 @@ async function runUpgrade(options) {
11130
11965
  continue;
11131
11966
  }
11132
11967
  const problem = ownedKeyProblem(file, entry.source, localPackageNames(root));
11133
- const theirs = problem ? null : sourceText(root, entry.source, lock.substitutions);
11968
+ const theirs = problem ? null : ownedText(file, entry.source);
11134
11969
  const dir = problem ? null : packageDir(root, parseSource(entry.source).package);
11135
11970
  const version = dir ? packageVersion(dir) : void 0;
11136
- const outcome = refreshOwned(root, lock, { path: file, theirs, base: bases.get(file) ?? null, ...version ? { version } : {} }, { ...options.dryRun ? { dryRun: true } : {}, ...options.keepMine ? { keepMine: true } : {} });
11971
+ if (appFolder && !problem && isRepositoryWorkflow(file)) {
11972
+ if (theirs !== null && sha256(theirs) !== entry.sha256) {
11973
+ lock.files[file] = { ...entry, sha256: sha256(theirs), ...version ? { version } : {} };
11974
+ 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}` });
11975
+ } else refreshed.push({ path: file, outcome: "unchanged" });
11976
+ continue;
11977
+ }
11978
+ 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 } : {} });
11137
11979
  refreshed.push(outcome);
11980
+ if (appFolder && outcome.outcome !== "updated" && !problem) {
11981
+ const template = sourceText(root, entry.source, written);
11982
+ const mine = template === null ? null : readApp(root, file);
11983
+ const stale = mine === null ? [] : unprefixedTemplatePaths(root, file, mine, template, appFolder);
11984
+ 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.`);
11985
+ }
11138
11986
  if (outcome.outcome === "updated" || outcome.outcome === "merged") files.add(file);
11139
11987
  if ((outcome.outcome === "conflict" || outcome.outcome === "kept-mine") && !outcome.detail?.includes("already there")) next.add(`${file}.genesis-next`);
11140
11988
  }
11989
+ const folderInRepo = appFolder ? null : folderBelowTopLevel(root);
11990
+ if (folderInRepo && refreshed.some((r) => (r.outcome === "conflict" || r.outcome === "kept-mine") && /^\.(?:eas|github)\/workflows\//.test(r.path))) {
11991
+ 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.`);
11992
+ }
11993
+ if (appFolder) {
11994
+ const actual = folderBelowTopLevel(root);
11995
+ if (actual !== null && actual !== appFolder) warnings.push(`genesis.config.json says "appFolder": "${appFolder}", but this app is at ${actual || "the repository's root"}.`);
11996
+ }
11141
11997
  const functionsLeft = [];
11142
11998
  for (const manifest of manifests) {
11143
11999
  for (const w of ownedWrites(root, manifest, warnings)) {
@@ -11168,21 +12024,56 @@ async function runUpgrade(options) {
11168
12024
  writeLock(root, lock);
11169
12025
  if (readApp(root, LOCK_FILE) !== before) files.add(LOCK_FILE);
11170
12026
  }
12027
+ const generated = /* @__PURE__ */ new Set();
12028
+ if (!options.dryRun) {
12029
+ clearPackageRulesCache();
12030
+ if (options.agents !== false) {
12031
+ try {
12032
+ const packages = discoverPackages(root);
12033
+ const state = agentGuideState(root, packages);
12034
+ if (state.skill !== "missing" || state.agents !== "missing") {
12035
+ const broken = packages.filter((p) => p.error);
12036
+ if (broken.length) warnings.push(`The agent guide wasn't regenerated: ${broken.map((p) => p.error).join("; ")}`);
12037
+ else for (const f of writeAgentGuide(root, packages)) generated.add(f);
12038
+ }
12039
+ } catch (err) {
12040
+ warnings.push(`genesis agents failed: ${err instanceof Error ? err.message : String(err)}`);
12041
+ }
12042
+ }
12043
+ if (options.featuresBuild !== false && registryFile(root)) {
12044
+ try {
12045
+ const { runFeaturesBuild: runFeaturesBuild2 } = await Promise.resolve().then(() => (init_features(), features_exports));
12046
+ for (const f of await runFeaturesBuild2({ dir: root })) generated.add(f);
12047
+ } catch (err) {
12048
+ warnings.push(`features build failed: ${err instanceof Error ? err.message : String(err)}`);
12049
+ }
12050
+ }
12051
+ }
12052
+ for (const f of generated) files.add(f);
12053
+ const swaps = handBuiltSwaps(root, valuesBefore);
12054
+ if (swaps.length) log(["", `This release adds exports the app builds by hand; genesis doctor's shadowed-export reports each:`, ...swapLines(swaps), ""].join("\n"));
11171
12055
  let doctor = "not run";
12056
+ let doctorProblem;
11172
12057
  if (options.doctor !== false) {
11173
12058
  try {
11174
12059
  const { runDoctor: runDoctor2, formatReport: formatReport2 } = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
11175
- const result = await runDoctor2({ root });
12060
+ const result = await runDoctor2({ root, figma: false });
11176
12061
  log(formatReport2(result));
11177
12062
  doctor = result.ok ? "passed" : "failed";
11178
12063
  } catch (err) {
11179
- log(`genesis doctor couldn't run: ${err instanceof Error ? err.message : String(err)}`);
12064
+ doctorProblem = err instanceof Error ? err.message : String(err);
12065
+ log(`genesis doctor couldn't run: ${doctorProblem}`);
11180
12066
  doctor = "failed";
11181
12067
  }
11182
12068
  }
12069
+ const ignored = options.pr && !options.dryRun ? gitIgnored(root, [...files, ...lockfilesFor(root)]) : [];
12070
+ for (const f of ignored) files.delete(f);
11183
12071
  const lines = [bumpSummary(release.version, changes, skipped)];
12072
+ if (ignored.length) lines.push("", `Changed but gitignored, so not in the pull request: ${ignored.join(", ")}.`);
11184
12073
  if (codemodRuns.length) lines.push("", "Codemods:", "", ...codemodRuns.map((c) => `- ${c.id}${c.files.length ? `: ${c.files.join(", ")}` : ""}`));
11185
- if (breaks.length) lines.push("", "Major moves with no codemod (read their changelogs):", "", ...breaks.map((b) => `- \`${b.name}\` ${b.from} \u2192 ${b.to}`));
12074
+ if (breaks.length) lines.push("", "Major moves with no codemod:", "", ...await breakLines(root, breaks, lookup));
12075
+ if (swaps.length) lines.push("", "New exports this app builds by hand (`shadowed-export` reports each until it's swapped or renamed):", "", ...swapLines(swaps));
12076
+ if (generated.size) lines.push("", `Regenerated from the installed packages: ${[...generated].join(", ")}.`);
11186
12077
  const touched2 = refreshed.filter((r) => r.outcome !== "unchanged");
11187
12078
  if (touched2.length || added.length) {
11188
12079
  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`));
@@ -11205,27 +12096,43 @@ async function runUpgrade(options) {
11205
12096
  }
11206
12097
  lines.push(...overlayChecklist(overlays));
11207
12098
  if (warnings.length) lines.push("", "Warnings:", "", ...warnings.map((w) => `- ${w}`));
11208
- lines.push("", `\`genesis doctor\` ${doctor === "not run" ? "was not run" : doctor} after the upgrade.`);
12099
+ lines.push("", doctorProblem ? `\`genesis doctor\` couldn't run after the upgrade: ${doctorProblem}` : `\`genesis doctor\` ${doctor === "not run" ? "was not run" : doctor} after the upgrade.`);
11209
12100
  const summary = lines.join("\n");
11210
- const report = { version: release.version, changes, skipped, codemods: codemodRuns, breaks, refreshed, added, switchedOff, newMigrations, doctor, files: [...files].sort(), summary, overlays, ...bunLock ? { bunLock } : {} };
12101
+ const report = { version: release.version, changes, skipped, codemods: codemodRuns, breaks, refreshed, added, switchedOff, newMigrations, swaps, doctor, files: [...files].sort(), summary, overlays, ...bunLock ? { bunLock } : {} };
11211
12102
  if (options.pr && !options.dryRun && files.size) report.pr = openPullRequest(root, release.version, report, prBase);
11212
12103
  return report;
11213
12104
  }
11214
12105
  function checkSubstitutions(substitutions) {
11215
12106
  if (!substitutions || !Object.keys(substitutions).length) return;
11216
- let allowed;
12107
+ let names;
11217
12108
  try {
11218
12109
  const was = starterIdentity(readFileSync(path30.join(starterDir(), "starter.config.ts"), "utf8"));
11219
- allowed = [was.name, was.slug, was.scheme, was.bundleId, APP_FOLDER_PLACEHOLDER];
12110
+ names = [was.name, was.slug, was.scheme, was.bundleId];
11220
12111
  } catch {
11221
- allowed = [];
12112
+ names = [];
11222
12113
  }
11223
12114
  for (const [from, to] of Object.entries(substitutions)) {
11224
- if (!allowed.includes(from) || !SUBSTITUTION_VALUE.test(to)) {
12115
+ if (from === APP_FOLDER_PLACEHOLDER) {
12116
+ 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.`);
12117
+ } else if (!names.includes(from) || !SUBSTITUTION_VALUE.test(to)) {
11225
12118
  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.`);
11226
12119
  }
11227
12120
  }
11228
12121
  }
12122
+ function lockfilesFor(root) {
12123
+ const top = gitTopLevel(root);
12124
+ const lockfiles = [];
12125
+ for (let dir = realpathSync(root); ; dir = path30.dirname(dir)) {
12126
+ 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)));
12127
+ if (lockfiles.length || dir === top || path30.dirname(dir) === dir) break;
12128
+ }
12129
+ return lockfiles;
12130
+ }
12131
+ function gitIgnored(root, files) {
12132
+ if (!files.length) return [];
12133
+ const result = spawnSync("git", ["check-ignore", "--stdin", "-z"], { cwd: root, input: files.join("\0"), encoding: "utf8" });
12134
+ return result.status === 0 ? result.stdout.split("\0").filter(Boolean) : [];
12135
+ }
11229
12136
  function checkPullRequest(root, version) {
11230
12137
  const git4 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
11231
12138
  if (git4("status", "--porcelain")) throw new Error("--pr needs a clean working tree (commit or stash your changes first).");
@@ -11246,13 +12153,9 @@ function openPullRequest(root, version, report, base) {
11246
12153
  const git4 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
11247
12154
  const branch = `genesis-upgrade/${version}`;
11248
12155
  git4("switch", "-c", branch);
11249
- const top = git4("rev-parse", "--show-toplevel");
11250
- const lockfiles = [];
11251
- for (let dir = path30.resolve(root); ; dir = path30.dirname(dir)) {
11252
- 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)));
11253
- if (lockfiles.length || dir === top || path30.dirname(dir) === dir) break;
11254
- }
11255
- const paths = [...report.files.filter((f) => existsSync(path30.join(root, f))), ...lockfiles];
12156
+ const lockfiles = lockfilesFor(root);
12157
+ const ignoredLocks = gitIgnored(root, lockfiles);
12158
+ const paths = [...report.files.filter((f) => existsSync(path30.join(root, f))), ...lockfiles.filter((f) => !ignoredLocks.includes(f))];
11256
12159
  git4("add", "--", ...paths);
11257
12160
  const overlayDirs = report.overlays.filter((o) => !o.skipped && !o.conflicts.length && (o.remove || [...o.writes.values()].includes(null))).map((o) => o.rel);
11258
12161
  if (overlayDirs.length) git4("add", "-A", "--", ...overlayDirs);
@@ -11270,7 +12173,11 @@ var init_upgrade = __esm({
11270
12173
  "src/upgrade/index.ts"() {
11271
12174
  init_add();
11272
12175
  init_agents();
12176
+ init_app_folder();
11273
12177
  init_discover();
12178
+ init_config();
12179
+ init_primitives();
12180
+ init_package_rules();
11274
12181
  init_starter_features();
11275
12182
  init_files();
11276
12183
  init_init_native();
@@ -11282,7 +12189,9 @@ var init_upgrade = __esm({
11282
12189
  init_pm();
11283
12190
  init_templates();
11284
12191
  init_bump_core();
12192
+ init_changelog();
11285
12193
  init_codemods();
12194
+ init_new_exports();
11286
12195
  init_overlays2();
11287
12196
  init_bun_lock();
11288
12197
  EXACT_OR_TAG = /^[0-9A-Za-z][0-9A-Za-z.+-]*$/;
@@ -11391,9 +12300,9 @@ async function runScaffold(opts, fs2) {
11391
12300
  function joinPath(...parts) {
11392
12301
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
11393
12302
  }
11394
- function dirname(path56) {
11395
- const idx = path56.lastIndexOf("/");
11396
- return idx === -1 ? "." : path56.slice(0, idx);
12303
+ function dirname(path61) {
12304
+ const idx = path61.lastIndexOf("/");
12305
+ return idx === -1 ? "." : path61.slice(0, idx);
11397
12306
  }
11398
12307
  function brandPackageJson(consumer, genesisVersion) {
11399
12308
  return JSON.stringify(
@@ -11729,7 +12638,7 @@ program.command("introspect").description("Write a checked-in contract (resource
11729
12638
  await fs.writeFile(target, content, "utf-8");
11730
12639
  console.log(`\u2714 Wrote ${label}: ${tables.length} tables.`);
11731
12640
  });
11732
- 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) => {
12641
+ 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) => {
11733
12642
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
11734
12643
  const root = path30.resolve(opts.dir);
11735
12644
  try {
@@ -11739,7 +12648,7 @@ program.command("doctor").description("Check this app against the installed Gene
11739
12648
  return;
11740
12649
  }
11741
12650
  const result = await doctor.runDoctor({ root, configPath: opts.config, strict: opts.strict, build: opts.build, quietBuild: opts.json, ...opts.base ? { base: opts.base } : {} });
11742
- console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result));
12651
+ console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result, { verbose: opts.verbose }));
11743
12652
  process.exitCode = result.ok ? 0 : 1;
11744
12653
  } catch (err) {
11745
12654
  if (!(err instanceof doctor.GenesisConfigError)) throw err;
@@ -11856,6 +12765,18 @@ featureOptions(
11856
12765
  const what = term ? `"${term}"` : "those filters";
11857
12766
  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).`);
11858
12767
  });
12768
+ 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) => {
12769
+ const figma = await Promise.resolve().then(() => (init_routes2(), routes_exports));
12770
+ try {
12771
+ const report = await figma.checkFigmaRoutes({ root: path30.resolve(opts.dir) });
12772
+ console.log(opts.json ? JSON.stringify(report, null, 2) : figma.formatCoverage(report));
12773
+ process.exitCode = opts.strict && report.summary.missing > 0 ? 1 : 0;
12774
+ } catch (err) {
12775
+ if (opts.json) console.log(JSON.stringify({ ok: false, error: err.message }, null, 2));
12776
+ else console.error(`\u2717 ${err.message}`);
12777
+ process.exitCode = 2;
12778
+ }
12779
+ });
11859
12780
  var upstream = program.command("upstream").description("The app's register of what it needed from Genesis (docs/genesis-upstream.md)");
11860
12781
  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) => {
11861
12782
  const { checkUpstream: checkUpstream2 } = await Promise.resolve().then(() => (init_upstream(), upstream_exports));
@@ -11882,36 +12803,36 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
11882
12803
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
11883
12804
  const root = path30.resolve(opts.dir);
11884
12805
  const packageJson = JSON.parse(await fs.readFile(path30.join(root, "package.json"), "utf-8").catch(() => "{}"));
11885
- const existsSync43 = (await import('fs')).existsSync;
12806
+ const existsSync45 = (await import('fs')).existsSync;
11886
12807
  const readSync = (await import('fs')).readFileSync;
11887
- const readdirSync19 = (await import('fs')).readdirSync;
12808
+ const readdirSync20 = (await import('fs')).readdirSync;
11888
12809
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
11889
12810
  throw new Error("--host must be next, tanstack-start or supabase-function.");
11890
12811
  }
11891
12812
  const plan = planStudioInit2(
11892
12813
  {
11893
12814
  packageJson,
11894
- exists: (p) => existsSync43(path30.join(root, p)),
11895
- read: (p) => existsSync43(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
12815
+ exists: (p) => existsSync45(path30.join(root, p)),
12816
+ read: (p) => existsSync45(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
11896
12817
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
11897
12818
  listDeep: (p) => {
11898
12819
  const out = [];
11899
- const walk3 = (rel) => {
11900
- for (const entry of readdirSync19(path30.join(root, rel), { withFileTypes: true })) {
12820
+ const walk4 = (rel) => {
12821
+ for (const entry of readdirSync20(path30.join(root, rel), { withFileTypes: true })) {
11901
12822
  const child = `${rel}/${entry.name}`;
11902
- if (entry.isDirectory()) walk3(child);
12823
+ if (entry.isDirectory()) walk4(child);
11903
12824
  else out.push(child);
11904
12825
  }
11905
12826
  };
11906
12827
  try {
11907
- walk3(p);
12828
+ walk4(p);
11908
12829
  } catch {
11909
12830
  }
11910
12831
  return out;
11911
12832
  },
11912
12833
  list: (p) => {
11913
12834
  try {
11914
- return readdirSync19(path30.join(root, p));
12835
+ return readdirSync20(path30.join(root, p));
11915
12836
  } catch {
11916
12837
  return [];
11917
12838
  }
@@ -11932,14 +12853,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
11932
12853
  console.log(`+ ${file.path} (appended)`);
11933
12854
  continue;
11934
12855
  }
11935
- if (existsSync43(target) && !opts.force) {
12856
+ if (existsSync45(target) && !opts.force) {
11936
12857
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
11937
12858
  continue;
11938
12859
  }
11939
12860
  await fs.writeFile(target, file.content, "utf-8");
11940
12861
  console.log(`+ ${file.path}`);
11941
12862
  }
11942
- 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";
12863
+ 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";
11943
12864
  console.log("");
11944
12865
  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:`);
11945
12866
  console.log(` 1. ${pm} ${plan.install.map((p) => /[\s<>|]/.test(p) ? `"${p}"` : p).join(" ")}`);
@@ -12010,7 +12931,7 @@ program.command("migrate").description("Copy new package migrations of the app's
12010
12931
  process.exitCode = 1;
12011
12932
  }
12012
12933
  });
12013
- 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) => {
12934
+ 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) => {
12014
12935
  const { runUpgrade: runUpgrade2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
12015
12936
  const report = await runUpgrade2({
12016
12937
  root: path30.resolve(opts.dir),
@@ -12019,6 +12940,8 @@ program.command("upgrade").description("Move every @marktiderman/genesis* depend
12019
12940
  dryRun: opts.dryRun,
12020
12941
  install: opts.install,
12021
12942
  doctor: opts.doctor,
12943
+ agents: opts.agents,
12944
+ featuresBuild: opts.featuresBuild,
12022
12945
  keepMine: opts.keepMine,
12023
12946
  pr: opts.pr,
12024
12947
  ...opts.genesisRepo ? { genesisRepo: opts.genesisRepo } : {},
@@ -12032,7 +12955,7 @@ program.command("upgrade").description("Move every @marktiderman/genesis* depend
12032
12955
  if (report.doctor === "failed") process.exitCode = 1;
12033
12956
  });
12034
12957
  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) => {
12035
- const { CODEMODS: CODEMODS2, codemodById: codemodById2 } = await Promise.resolve().then(() => (init_codemods(), codemods_exports));
12958
+ const { CODEMODS: CODEMODS2, codemodById: codemodById2, codemodInstallNote: codemodInstallNote2 } = await Promise.resolve().then(() => (init_codemods(), codemods_exports));
12036
12959
  if (!id) {
12037
12960
  for (const mod2 of CODEMODS2) console.log(`${mod2.id} (${mod2.package} ${mod2.version})
12038
12961
  ${mod2.description}`);
@@ -12043,6 +12966,8 @@ program.command("codemod [id]").description("Run one of Genesis's codemods by ha
12043
12966
  const changed = await mod.run({ root: path30.resolve(opts.dir), dryRun: opts.dryRun, log: (m) => console.log(m) });
12044
12967
  console.log(changed.length ? `${opts.dryRun ? "Would change" : "\u2714 Changed"} ${changed.length} file${changed.length === 1 ? "" : "s"}:
12045
12968
  ${changed.map((f) => ` ${f}`).join("\n")}` : "Nothing to change.");
12969
+ const note = codemodInstallNote2(path30.resolve(opts.dir), changed, opts.dryRun);
12970
+ if (note) console.log(`! ${note}`);
12046
12971
  });
12047
12972
  program.parseAsync(process.argv).catch((err) => {
12048
12973
  const message = err instanceof Error ? err.message : String(err);