@marktiderman/genesis-cli 1.19.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +98 -1
  2. package/dist/cli.js +682 -74
  3. package/dist/cli.js.map +1 -1
  4. package/dist/doctor.d.ts +1 -1
  5. package/dist/doctor.js +270 -8
  6. package/dist/doctor.js.map +1 -1
  7. package/dist/eslint.cjs +99 -0
  8. package/dist/eslint.cjs.map +1 -0
  9. package/dist/eslint.d.cts +68 -0
  10. package/dist/eslint.d.ts +68 -0
  11. package/dist/eslint.js +72 -0
  12. package/dist/eslint.js.map +1 -0
  13. package/dist/genesis-catalog.json +86 -14
  14. package/dist/index.js +278 -16
  15. package/dist/index.js.map +1 -1
  16. package/dist/starter/README.md +17 -5
  17. package/dist/starter/__tests__/components/setup.ts +11 -0
  18. package/dist/starter/__tests__/starter.test.ts +19 -0
  19. package/dist/starter/eslint.config.js +8 -1
  20. package/dist/starter/nativewind-env.d.ts +1 -0
  21. package/dist/starter/package.json +5 -3
  22. package/dist/starter/src/lib/app.ts +13 -5
  23. package/dist/starter/src/lib/define-starter.ts +1 -1
  24. package/dist/starter/src/lib/devtools-overlay.ts +3 -4
  25. package/dist/starter/src/lib/native-modules.ts +5 -1
  26. package/dist/starter/src/lib/offline.ts +14 -0
  27. package/dist/starter/supabase/migrations/20261024000750_support_default_tenant.sql +18 -0
  28. package/dist/starter/supabase/migrations/20261024000800_genesis_support_tickets.sql +800 -0
  29. package/dist/starter/supabase/migrations/20261025000070_starter_tenancy.sql +26 -0
  30. package/dist/starter/supabase/migrations/20261025000080_genesis_chat_tenants.sql +716 -0
  31. package/dist/starter/supabase/tests/database/chat_people.test.sql +1 -1
  32. package/dist/starter/supabase/tests/database/genesis_chat.test.sql +10 -2
  33. package/dist/starter/supabase/tests/database/genesis_chat_coaching.test.sql +8 -0
  34. package/dist/starter/supabase/tests/database/genesis_chat_search_threads.test.sql +8 -0
  35. package/dist/starter/supabase/tests/database/genesis_chat_tenants.test.sql +259 -0
  36. package/dist/starter/supabase/tests/database/genesis_support.test.sql +15 -3
  37. package/dist/starter/supabase/tests/database/genesis_support_findings.test.sql +10 -0
  38. package/dist/starter/supabase/tests/database/genesis_support_tickets.test.sql +327 -0
  39. package/dist/starter/supabase/tests/database/starter_tenancy.test.sql +19 -0
  40. package/dist/vite.js +270 -8
  41. package/dist/vite.js.map +1 -1
  42. package/package.json +18 -4
package/dist/cli.js CHANGED
@@ -121,6 +121,39 @@ function parseManifest(home, id, raw, version, options = {}) {
121
121
  });
122
122
  }
123
123
  }
124
+ if (m["needs"] !== void 0) {
125
+ if (!Array.isArray(m["needs"])) problems.push(`${where2}.needs: must be a list of { function, how }`);
126
+ else {
127
+ out.needs = m["needs"].flatMap((n, j) => {
128
+ const at2 = `${where2}.needs[${j}]`;
129
+ if (!isObject(n) || typeof n["function"] !== "string" || typeof n["how"] !== "string" || !n["how"].trim()) {
130
+ problems.push(`${at2}: must be { function: "schema.name", how: "what to add" }`);
131
+ return [];
132
+ }
133
+ if (!SQL_FUNCTION.test(n["function"])) {
134
+ problems.push(`${at2}.function: "${n["function"]}" must be a schema-qualified function name, like private.genesis_viewer_people`);
135
+ return [];
136
+ }
137
+ return [{ function: n["function"], how: n["how"].trim() }];
138
+ });
139
+ }
140
+ }
141
+ if (m["runsBefore"] !== void 0) {
142
+ if (!Array.isArray(m["runsBefore"])) problems.push(`${where2}.runsBefore: must be a list of { package, file }`);
143
+ else {
144
+ out.runsBefore = m["runsBefore"].map((r, j) => {
145
+ const at2 = `${where2}.runsBefore[${j}]`;
146
+ if (!isObject(r)) {
147
+ problems.push(`${at2}: must be an object`);
148
+ return { package: home, file: "" };
149
+ }
150
+ const before = { package: pkgOf(r["package"], at2), file: pathOf(r["file"], `${at2}.file`) };
151
+ if (before.file && !MIGRATION_FILE.test(before.file.split("/").pop())) problems.push(`${at2}.file: "${before.file}" must be named NNNN_name.sql`);
152
+ if (before.package === out.package && before.file === file) problems.push(`${at2}: a migration can't run before itself`);
153
+ return before;
154
+ });
155
+ }
156
+ }
124
157
  if (m["test"] !== void 0) {
125
158
  out.test = pathOf(m["test"], `${where2}.test`);
126
159
  if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where2}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
@@ -231,7 +264,7 @@ function declarationFields(block) {
231
264
  function isBlockDef(value) {
232
265
  return isObject(value) && typeof value["id"] === "string" && BLOCK_ID.test(value["id"]) && (value["contributes"] === void 0 || isObject(value["contributes"])) && (isObject(value["contributes"]) || Array.isArray(value["requires"]));
233
266
  }
234
- var GENESIS_PACKAGE, BLOCK_ID, MIGRATION_FILE, FUNCTION_NAME, ROUTE, INSTALL_SPEC, SECRET, ManifestError, isObject, strings;
267
+ var GENESIS_PACKAGE, BLOCK_ID, MIGRATION_FILE, FUNCTION_NAME, ROUTE, INSTALL_SPEC, SECRET, SQL_FUNCTION, ManifestError, isObject, strings;
235
268
  var init_manifest = __esm({
236
269
  "src/blocks/manifest.ts"() {
237
270
  GENESIS_PACKAGE = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
@@ -241,6 +274,7 @@ var init_manifest = __esm({
241
274
  ROUTE = /^\/(?:[A-Za-z0-9_\-[\]().]+\/?)*$/;
242
275
  INSTALL_SPEC = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9.^~<>=|* -]+)?$/;
243
276
  SECRET = /^[A-Z][A-Z0-9_]*$/;
277
+ SQL_FUNCTION = /^[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*$/;
244
278
  ManifestError = class extends Error {
245
279
  constructor(problems) {
246
280
  super(`Invalid block manifest:
@@ -689,20 +723,24 @@ __export(migrations_exports, {
689
723
  MIGRATIONS_DIR: () => MIGRATIONS_DIR,
690
724
  TESTS_DIR: () => TESTS_DIR,
691
725
  applyMigrationPlan: () => applyMigrationPlan,
726
+ definesFunction: () => definesFunction,
692
727
  formatMigrationRows: () => formatMigrationRows,
693
728
  migrationHeader: () => migrationHeader,
694
729
  needsAttention: () => needsAttention,
695
730
  nextStamp: () => nextStamp,
696
731
  nextTimestamps: () => nextTimestamps,
732
+ orderByRunsBefore: () => orderByRunsBefore,
697
733
  planMigrations: () => planMigrations,
698
734
  providingMigrations: () => providingMigrations,
699
735
  readAppMigrations: () => readAppMigrations,
700
736
  rememberMigrationCopies: () => rememberMigrationCopies,
701
737
  stemOf: () => stemOf,
702
738
  stemOrNull: () => stemOrNull,
739
+ stripSqlComments: () => stripSqlComments,
703
740
  supersededFunctions: () => supersededFunctions,
704
741
  textSha: () => textSha,
705
742
  timestampOf: () => timestampOf,
743
+ unmetNeeds: () => unmetNeeds,
706
744
  validHeaderFile: () => validHeaderFile
707
745
  });
708
746
  function migrationHeader(pkg, file, source) {
@@ -729,6 +767,46 @@ function readAppMigrations(root, dir = MIGRATIONS_DIR) {
729
767
  return { path: p, name, content };
730
768
  });
731
769
  }
770
+ function stripSqlComments(sql) {
771
+ return sql.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/--[^\n]*/g, " ");
772
+ }
773
+ function definesFunction(sql, fn) {
774
+ const [schema, name] = fn.split(".");
775
+ const quoted = (id) => `(?:${id}|"${id}")`;
776
+ sql = stripSqlComments(sql);
777
+ return new RegExp(`create\\s+(?:or\\s+replace\\s+)?function\\s+${quoted(schema)}\\s*\\.\\s*${quoted(name)}\\s*\\(`, "i").test(sql);
778
+ }
779
+ function orderByRunsBefore(sources) {
780
+ if (!sources.some((m) => m.runsBefore?.length)) return sources.slice();
781
+ const key2 = (m) => `${m.package} ${m.file}`;
782
+ const index = /* @__PURE__ */ new Map();
783
+ sources.forEach((m, i) => {
784
+ if (!index.has(key2(m))) index.set(key2(m), i);
785
+ });
786
+ const after = sources.map(() => /* @__PURE__ */ new Set());
787
+ const last = /* @__PURE__ */ new Map();
788
+ sources.forEach((m, i) => {
789
+ const prev = last.get(m.package);
790
+ if (prev !== void 0) after[i].add(prev);
791
+ last.set(m.package, i);
792
+ for (const target of m.runsBefore ?? []) {
793
+ const t = index.get(key2(target));
794
+ if (t !== void 0 && t !== i) after[t].add(i);
795
+ }
796
+ });
797
+ const out = [];
798
+ const done = /* @__PURE__ */ new Set();
799
+ while (out.length < sources.length) {
800
+ const next = sources.findIndex((_, i) => !done.has(i) && [...after[i]].every((d) => done.has(d)));
801
+ if (next === -1) return sources.slice();
802
+ done.add(next);
803
+ out.push(sources[next]);
804
+ }
805
+ return out;
806
+ }
807
+ function unmetNeeds(src, defined) {
808
+ return (src.needs ?? []).filter((n) => !defined(n.function)).map((n) => `needs ${n.function} first: ${n.how}`);
809
+ }
732
810
  function needsAttention(row) {
733
811
  return row.state !== "current" && row.state !== "new" && row.state !== "deleted" && row.state !== "provided" && !row.forward;
734
812
  }
@@ -784,6 +862,7 @@ function nextTimestamps(existing, now, count) {
784
862
  function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date() }) {
785
863
  const app = readAppMigrations(root);
786
864
  const rows = [];
865
+ sources = orderByRunsBefore(sources);
787
866
  const providers = providingMigrations([{ migrations: sources }]);
788
867
  for (const p of options.providers ?? []) if (!providers.some((o) => o.package === p.package && o.file === p.file)) providers.push(p);
789
868
  const providerAt = (p) => {
@@ -828,6 +907,12 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
828
907
  continue;
829
908
  }
830
909
  const row2 = { ...base, state: "new" };
910
+ const earlier = sources.slice(0, sources.indexOf(src)).filter((s) => s.source !== null);
911
+ const unmet = unmetNeeds(src, (fn) => app.some((m) => definesFunction(m.content, fn)) || earlier.some((s) => definesFunction(s.source, fn)));
912
+ if (unmet.length) {
913
+ row2.unmet = unmet;
914
+ row2.detail = unmet.join("; ");
915
+ }
831
916
  rows.push(row2);
832
917
  pending.push({ row: row2, src, kind: "migration" });
833
918
  continue;
@@ -1910,7 +1995,7 @@ function globToRegExp(glob) {
1910
1995
  }
1911
1996
  function globMatcher(globs) {
1912
1997
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1913
- return (path53) => res.some((re) => re.test(path53));
1998
+ return (path56) => res.some((re) => re.test(path56));
1914
1999
  }
1915
2000
  var init_glob = __esm({
1916
2001
  "src/doctor/glob.ts"() {
@@ -2158,8 +2243,8 @@ function pinnedVersion(root, name, manifests = ["package.json"]) {
2158
2243
  } catch {
2159
2244
  continue;
2160
2245
  }
2161
- for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
2162
- const spec = json[section]?.[name];
2246
+ for (const section2 of ["dependencies", "devDependencies", "optionalDependencies"]) {
2247
+ const spec = json[section2]?.[name];
2163
2248
  const v = typeof spec === "string" ? /^[\^~=]?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(spec)?.[1] : void 0;
2164
2249
  const parsed = v && parseVersion(v);
2165
2250
  if (parsed && (!best || compareVersions(parsed, parseVersion(best)) > 0)) best = v;
@@ -2678,8 +2763,8 @@ function initNative(options) {
2678
2763
  pkg.name = slug;
2679
2764
  const unpinned = [];
2680
2765
  const dependencies2 = {};
2681
- for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
2682
- const deps = pkg[section];
2766
+ for (const section2 of ["dependencies", "devDependencies", "optionalDependencies"]) {
2767
+ const deps = pkg[section2];
2683
2768
  for (const [name, spec] of Object.entries(deps ?? {})) {
2684
2769
  if (!spec.startsWith("workspace:")) continue;
2685
2770
  const version = versionFor(name);
@@ -4119,7 +4204,9 @@ var init_rules = __esm({
4119
4204
  // genesis.lock.json against the files (lock-files.ts)
4120
4205
  "lock-files",
4121
4206
  // an app whose database files live in another app (database.ts)
4122
- "database-elsewhere"
4207
+ "database-elsewhere",
4208
+ // the app's eslint config loads Genesis's lint rules (eslint-config.ts)
4209
+ "genesis-eslint-config"
4123
4210
  ];
4124
4211
  DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
4125
4212
  STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -6745,8 +6832,8 @@ function compareVersions2(a, b) {
6745
6832
  function bumpPackageJson(file, text, wanted) {
6746
6833
  const pkg = JSON.parse(text);
6747
6834
  const changes = [], skipped = [];
6748
- for (const section of SECTIONS) {
6749
- for (const [name, spec] of Object.entries(pkg[section] ?? {})) {
6835
+ for (const section2 of SECTIONS) {
6836
+ for (const [name, spec] of Object.entries(pkg[section2] ?? {})) {
6750
6837
  if (!GENESIS3.test(name)) continue;
6751
6838
  const m = EXACT.exec(spec);
6752
6839
  if (!m) {
@@ -6768,8 +6855,8 @@ function bumpPackageJson(file, text, wanted) {
6768
6855
  skipped.push({ file, name, spec, why: `newer than ${want}` });
6769
6856
  continue;
6770
6857
  }
6771
- pkg[section][name] = `${m[1] ?? ""}${want}`;
6772
- changes.push({ file, name, from: spec, to: pkg[section][name] });
6858
+ pkg[section2][name] = `${m[1] ?? ""}${want}`;
6859
+ changes.push({ file, name, from: spec, to: pkg[section2][name] });
6773
6860
  }
6774
6861
  }
6775
6862
  if (!changes.length) return { text: null, changes, skipped };
@@ -7156,6 +7243,131 @@ var init_scope_names = __esm({
7156
7243
  PRACTICE_ID_AUGMENTATION = 'declare module "@marktiderman/genesis-core" { interface ResourceScope { practiceId?: string } }';
7157
7244
  }
7158
7245
  });
7246
+ function findEslintConfig(root) {
7247
+ return FLAT_CONFIG_FILES.find((name) => existsSync(path30.join(root, name))) ?? null;
7248
+ }
7249
+ function readPackageJson(root) {
7250
+ try {
7251
+ return JSON.parse(readFileSync(path30.join(root, "package.json"), "utf8"));
7252
+ } catch {
7253
+ return null;
7254
+ }
7255
+ }
7256
+ function appPlatform(pkg) {
7257
+ return declares(pkg, "expo") || declares(pkg, "react-native") ? "native" : "web";
7258
+ }
7259
+ function hasTestingLibrary(pkg) {
7260
+ return declares(pkg, TESTING_LIBRARY);
7261
+ }
7262
+ function usesGenesisLint(text) {
7263
+ return text.includes(ESLINT_EXPORT);
7264
+ }
7265
+ function inlinesRntlRules(text) {
7266
+ return /testing-library\/await-async-events/.test(maskComments(text));
7267
+ }
7268
+ function maskCode(text) {
7269
+ const masked = maskComments(text).split("");
7270
+ let quote2 = null;
7271
+ for (let i = 0; i < masked.length; i++) {
7272
+ const ch = masked[i];
7273
+ if (quote2) {
7274
+ if (ch === "\\") {
7275
+ masked[i] = " ";
7276
+ if (i + 1 < masked.length && masked[i + 1] !== "\n") masked[i + 1] = " ";
7277
+ i++;
7278
+ } else if (ch === quote2) quote2 = null;
7279
+ else if (ch !== "\n") masked[i] = " ";
7280
+ continue;
7281
+ }
7282
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
7283
+ }
7284
+ return masked.join("");
7285
+ }
7286
+ function matching2(code, open) {
7287
+ const pairs = { "[": "]", "(": ")", "{": "}" };
7288
+ const stack = [];
7289
+ for (let i = open; i < code.length; i++) {
7290
+ const ch = code[i];
7291
+ if (ch in pairs) stack.push(pairs[ch]);
7292
+ else if (ch === "]" || ch === ")" || ch === "}") {
7293
+ if (stack.pop() !== ch) return -1;
7294
+ if (!stack.length) return i;
7295
+ }
7296
+ }
7297
+ return -1;
7298
+ }
7299
+ function importLine(kind, local = "genesis") {
7300
+ const binding = local === "genesis" ? "genesis" : `genesis: ${local}`;
7301
+ return kind === "cjs" ? `const { ${binding} } = require("${ESLINT_EXPORT}");` : `import { ${local === "genesis" ? "genesis" : `genesis as ${local}`} } from "${ESLINT_EXPORT}";`;
7302
+ }
7303
+ function spreadLine(platform, local = "genesis") {
7304
+ return `...${local}("${platform}")`;
7305
+ }
7306
+ function addGenesisLint(text, platform, file = "eslint.config.js") {
7307
+ const code = maskCode(text);
7308
+ const ext = path30.extname(file);
7309
+ const exportsCjs = [...code.matchAll(/(?:^|[\n;])\s*module\.exports\s*=\s*/g)];
7310
+ const exportsEsm = [...code.matchAll(/(?:^|[\n;])\s*export\s+default\s+/g)];
7311
+ const kind = ext === ".cjs" || ext === ".cts" ? "cjs" : ext === ".mjs" || ext === ".mts" ? "esm" : exportsCjs.length && !exportsEsm.length ? "cjs" : "esm";
7312
+ const found = [...exportsCjs, ...exportsEsm];
7313
+ if (found.length !== 1) return { ok: false, kind, reason: found.length ? "it exports its config more than once" : "it has no `module.exports =` or `export default`" };
7314
+ const local = /(?<![\w$])genesis(?![\w$])/.test(code) ? "genesisLint" : "genesis";
7315
+ if (local === "genesisLint" && /(?<![\w$])genesisLint(?![\w$])/.test(code)) return { ok: false, kind, reason: "it already declares `genesis` and `genesisLint`" };
7316
+ let at = found[0].index + found[0][0].length;
7317
+ let close;
7318
+ const call = /^(?!(?:async|function)\b)[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\s*\(\s*/.exec(code.slice(at));
7319
+ if (code[at] === "[") {
7320
+ close = matching2(code, at);
7321
+ } else if (call) {
7322
+ const paren = at + call[0].lastIndexOf("(");
7323
+ at += call[0].length;
7324
+ close = code[at] === "[" ? matching2(code, at) : matching2(code, paren);
7325
+ if (code[at] !== "[") at = paren;
7326
+ } else {
7327
+ return { ok: false, kind, reason: "it doesn't export an array or a `defineConfig(...)` call" };
7328
+ }
7329
+ if (close < 0) return { ok: false, kind, reason: "its exported array doesn't close where expected" };
7330
+ let last = close - 1;
7331
+ while (last > at && /\s/.test(code[last])) last--;
7332
+ const entry = spreadLine(platform, local);
7333
+ let next;
7334
+ if (last === at) {
7335
+ next = `${text.slice(0, at + 1)}${entry}${text.slice(close)}`;
7336
+ } else {
7337
+ const comma = code[last] === "," ? "" : ",";
7338
+ const multiline = code.slice(last, close).includes("\n");
7339
+ const lineStart = code.lastIndexOf("\n", last) + 1;
7340
+ const indent = /^[ \t]*/.exec(text.slice(lineStart))[0];
7341
+ next = multiline ? `${text.slice(0, last + 1)}${comma}
7342
+ ${indent}${entry},${text.slice(last + 1)}` : `${text.slice(0, last + 1)}${comma} ${entry}${text.slice(last + 1)}`;
7343
+ }
7344
+ const exportAt = found[0].index + found[0][0].search(/module|export/);
7345
+ const head = maskCode(next).slice(0, exportAt);
7346
+ const imports = [...head.matchAll(kind === "cjs" ? /^(?:const|let|var)\s[^\n]*\brequire\s*\([^\n]*$/gm : /^import\b[\s\S]*?(?:from\s*)?["'][^"'\n]*["'][^\n]*$/gm)];
7347
+ const line = importLine(kind, local);
7348
+ if (imports.length) {
7349
+ const end = imports.at(-1).index + imports.at(-1)[0].length;
7350
+ return { ok: true, text: `${next.slice(0, end)}
7351
+ ${line}${next.slice(end)}` };
7352
+ }
7353
+ const shebang = next.startsWith("#!") ? next.indexOf("\n") + 1 : 0;
7354
+ return { ok: true, text: `${next.slice(0, shebang)}${line}
7355
+ ${next.slice(shebang)}` };
7356
+ }
7357
+ function manualLines(kind, platform) {
7358
+ return [importLine(kind), `${spreadLine(platform)}, // last in the array the config exports`];
7359
+ }
7360
+ var ESLINT_EXPORT, TESTING_LIBRARY, TESTING_LIBRARY_RANGE, FLAT_CONFIG_FILES, declares;
7361
+ var init_eslint_config = __esm({
7362
+ "src/upgrade/eslint-config.ts"() {
7363
+ init_scope_names();
7364
+ ESLINT_EXPORT = "@marktiderman/genesis-cli/eslint";
7365
+ TESTING_LIBRARY = "eslint-plugin-testing-library";
7366
+ TESTING_LIBRARY_RANGE = "^7.16.2";
7367
+ FLAT_CONFIG_FILES = ["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs", "eslint.config.ts", "eslint.config.mts", "eslint.config.cts"];
7368
+ declares = (pkg, name) => Boolean(pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name] ?? pkg?.peerDependencies?.[name]);
7369
+ }
7370
+ });
7159
7371
 
7160
7372
  // src/upgrade/codemods.ts
7161
7373
  var codemods_exports = {};
@@ -7164,6 +7376,7 @@ __export(codemods_exports, {
7164
7376
  appScripts: () => appScripts,
7165
7377
  codemodById: () => codemodById,
7166
7378
  codemodsFor: () => codemodsFor,
7379
+ genesisEslintConfig: () => genesisEslintConfig,
7167
7380
  scopeNeutralNames: () => scopeNeutralNames,
7168
7381
  uncoveredBreaks: () => uncoveredBreaks
7169
7382
  });
@@ -7197,10 +7410,11 @@ function uncoveredBreaks(changes, registry = CODEMODS) {
7197
7410
  };
7198
7411
  return changes.filter((c) => major(c.from) !== major(c.to) && codemodsFor([c], registry).length === 0);
7199
7412
  }
7200
- var SKIP_DIRS3, SCRIPT2, MAX_BYTES, scopeNeutralNames, CODEMODS, bare;
7413
+ var SKIP_DIRS3, SCRIPT2, MAX_BYTES, scopeNeutralNames, genesisEslintConfig, CODEMODS, bare;
7201
7414
  var init_codemods = __esm({
7202
7415
  "src/upgrade/codemods.ts"() {
7203
7416
  init_bump_core();
7417
+ init_eslint_config();
7204
7418
  init_scope_names();
7205
7419
  SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
7206
7420
  SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
@@ -7232,7 +7446,49 @@ var init_codemods = __esm({
7232
7446
  return changed;
7233
7447
  }
7234
7448
  };
7235
- CODEMODS = [scopeNeutralNames];
7449
+ genesisEslintConfig = {
7450
+ id: "genesis-cli-eslint-config",
7451
+ package: "@marktiderman/genesis-cli",
7452
+ version: "1.20.0",
7453
+ description: "Loads Genesis's lint rules from @marktiderman/genesis-cli/eslint in the app's eslint.config, so genesis upgrade delivers new ones.",
7454
+ run({ root, dryRun, log }) {
7455
+ const file = findEslintConfig(root);
7456
+ if (!file) return [];
7457
+ const changed = [];
7458
+ const pkg = readPackageJson(root);
7459
+ const platform = appPlatform(pkg);
7460
+ const abs = path30.join(root, file);
7461
+ const text = readFileSync(abs, "utf8");
7462
+ if (!usesGenesisLint(text)) {
7463
+ const result = addGenesisLint(text, platform, file);
7464
+ if (result.ok) {
7465
+ changed.push(file);
7466
+ if (!dryRun) writeFileSync(abs, result.text);
7467
+ if (inlinesRntlRules(text)) {
7468
+ log(` ${file} still has its own React Native Testing Library await rules (testing-library/await-async-events and the no-restricted-syntax selectors); genesis("${platform}") now brings them, so delete that block.`);
7469
+ }
7470
+ } else {
7471
+ log(` ${file}: not edited, because ${result.reason}. Add Genesis's lint rules by hand:
7472
+ ${manualLines(result.kind, platform).map((l) => ` ${l}`).join("\n")}`);
7473
+ }
7474
+ }
7475
+ if (platform === "native" && pkg && !hasTestingLibrary(pkg)) {
7476
+ const pkgFile = path30.join(root, "package.json");
7477
+ const raw = readFileSync(pkgFile, "utf8");
7478
+ const indent = /^[ \t]+(?=")/m.exec(raw)?.[0] ?? " ";
7479
+ const json = JSON.parse(raw);
7480
+ const names = Object.keys(json.devDependencies ?? {});
7481
+ const sorted2 = names.every((name, i) => i === 0 || names[i - 1].localeCompare(name) <= 0);
7482
+ const dev = Object.entries({ ...json.devDependencies, [TESTING_LIBRARY]: TESTING_LIBRARY_RANGE });
7483
+ json.devDependencies = Object.fromEntries(sorted2 ? dev.sort(([a], [b]) => a.localeCompare(b)) : dev);
7484
+ changed.push("package.json");
7485
+ 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.`);
7487
+ }
7488
+ return changed;
7489
+ }
7490
+ };
7491
+ CODEMODS = [scopeNeutralNames, genesisEslintConfig];
7236
7492
  bare = (spec) => spec.replace(/^[\^~=]/, "");
7237
7493
  }
7238
7494
  });
@@ -7930,7 +8186,224 @@ var init_owned = __esm({
7930
8186
  CLI = "@marktiderman/genesis-cli";
7931
8187
  }
7932
8188
  });
8189
+ function skipSpace(text, i) {
8190
+ for (; ; ) {
8191
+ while (i < text.length && /\s/.test(text[i])) i++;
8192
+ if (text.startsWith("//", i)) {
8193
+ const nl = text.indexOf("\n", i);
8194
+ i = nl === -1 ? text.length : nl + 1;
8195
+ } else if (text.startsWith("/*", i)) {
8196
+ const close = text.indexOf("*/", i + 2);
8197
+ i = close === -1 ? text.length : close + 2;
8198
+ } else return i;
8199
+ }
8200
+ }
8201
+ function skipString(text, i) {
8202
+ for (let j = i + 1; j < text.length; j++) {
8203
+ if (text[j] === "\\") j++;
8204
+ else if (text[j] === '"') return j + 1;
8205
+ }
8206
+ throw new Error("an unterminated string");
8207
+ }
8208
+ function skipValue(text, i) {
8209
+ const c = text[i];
8210
+ if (c === '"') return skipString(text, i);
8211
+ if (c === "{" || c === "[") {
8212
+ let depth = 0;
8213
+ for (let j2 = i; j2 < text.length; ) {
8214
+ const d = text[j2];
8215
+ if (d === '"') {
8216
+ j2 = skipString(text, j2);
8217
+ continue;
8218
+ }
8219
+ if (text.startsWith("//", j2) || text.startsWith("/*", j2)) {
8220
+ j2 = skipSpace(text, j2);
8221
+ continue;
8222
+ }
8223
+ if (d === "{" || d === "[") depth++;
8224
+ else if (d === "}" || d === "]") {
8225
+ depth--;
8226
+ if (depth === 0) return j2 + 1;
8227
+ }
8228
+ j2++;
8229
+ }
8230
+ throw new Error("an unclosed object or array");
8231
+ }
8232
+ let j = i;
8233
+ while (j < text.length && !/[\s,}\]]/.test(text[j])) j++;
8234
+ if (j === i) throw new Error(`an unexpected ${JSON.stringify(c ?? "end")} at ${i}`);
8235
+ return j;
8236
+ }
8237
+ function members(text, open) {
8238
+ const out = [];
8239
+ let i = skipSpace(text, open + 1);
8240
+ while (text[i] !== "}") {
8241
+ if (text[i] !== '"') throw new Error(`a key expected at ${i}`);
8242
+ const keyEnd = skipString(text, i);
8243
+ const key2 = JSON.parse(text.slice(i, keyEnd));
8244
+ let j = skipSpace(text, keyEnd);
8245
+ if (text[j] !== ":") throw new Error(`":" expected at ${j}`);
8246
+ const value = skipSpace(text, j + 1);
8247
+ const end = skipValue(text, value);
8248
+ out.push({ key: key2, start: i, end, value });
8249
+ j = skipSpace(text, end);
8250
+ if (text[j] === ",") j = skipSpace(text, j + 1);
8251
+ i = j;
8252
+ if (i >= text.length) throw new Error("an unclosed object");
8253
+ }
8254
+ return out;
8255
+ }
8256
+ function section(text, name) {
8257
+ const open = skipSpace(text, 0);
8258
+ if (text[open] !== "{") throw new Error("not an object");
8259
+ const m = members(text, open).find((x) => x.key === name);
8260
+ return m && text[m.value] === "{" ? m : null;
8261
+ }
8262
+ function parseLoose(fragment) {
8263
+ let out = "";
8264
+ for (let i = 0; i < fragment.length; ) {
8265
+ const c = fragment[i];
8266
+ if (c === '"') {
8267
+ const end = skipString(fragment, i);
8268
+ out += fragment.slice(i, end);
8269
+ i = end;
8270
+ } else if (c === ",") {
8271
+ const next = skipSpace(fragment, i + 1);
8272
+ if (fragment[next] !== "}" && fragment[next] !== "]") out += c;
8273
+ i++;
8274
+ } else if (fragment.startsWith("//", i) || fragment.startsWith("/*", i)) {
8275
+ i = skipSpace(fragment, i);
8276
+ } else {
8277
+ out += c;
8278
+ i++;
8279
+ }
8280
+ }
8281
+ return JSON.parse(out);
8282
+ }
8283
+ function resolution(value) {
8284
+ const first = Array.isArray(value) ? value[0] : null;
8285
+ if (typeof first !== "string") return null;
8286
+ const at = first.lastIndexOf("@");
8287
+ if (at <= 0) return null;
8288
+ return { name: first.slice(0, at), spec: first.slice(at + 1) };
8289
+ }
8290
+ function staleNestedEntries(text, want = () => null) {
8291
+ const packages = section(text, "packages");
8292
+ if (!packages) return [];
8293
+ const list = members(text, packages.value);
8294
+ const value = (m) => parseLoose(text.slice(m.value, m.end));
8295
+ const byKey = new Map(list.map((m) => [m.key, m]));
8296
+ const out = [];
8297
+ for (const m of list) {
8298
+ const tail = GENESIS_TAIL.exec(m.key);
8299
+ if (!tail || tail[1] === m.key) continue;
8300
+ const name = tail[1];
8301
+ const nested = resolution(value(m));
8302
+ if (!nested || nested.name !== name || !PLAIN_VERSION.test(nested.spec)) continue;
8303
+ const rootEntry = byKey.get(name);
8304
+ const rootRes = rootEntry ? resolution(value(rootEntry)) : null;
8305
+ const target = want(name) ?? (rootRes && PLAIN_VERSION.test(rootRes.spec) ? rootRes.spec : null);
8306
+ if (!rootEntry || !target || target === nested.spec) continue;
8307
+ const parent = m.key.slice(0, m.key.length - name.length - 1);
8308
+ const parentEntry = byKey.get(parent);
8309
+ const meta = parentEntry ? value(parentEntry)[2] : void 0;
8310
+ const declared = meta && typeof meta === "object" ? meta : {};
8311
+ const range = ["dependencies", "peerDependencies", "optionalDependencies"].map((s) => declared[s]?.[name]).find((r) => typeof r === "string");
8312
+ if (!range || satisfies(target, range) !== true) continue;
8313
+ out.push({ key: m.key, name, parent, version: nested.spec, root: target, range });
8314
+ }
8315
+ return out;
8316
+ }
8317
+ function workspaceEntries(text, folder) {
8318
+ const rel = folder.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
8319
+ const ws = section(text, "workspaces");
8320
+ const workspaces = ws ? members(text, ws.value).filter((m) => m.key === rel).map((m) => m.key) : [];
8321
+ const pk = section(text, "packages");
8322
+ const packages = [];
8323
+ if (pk) {
8324
+ const list = members(text, pk.value);
8325
+ const names = list.filter((m) => resolution(parseLoose(text.slice(m.value, m.end)))?.spec === `workspace:${rel}`).map((m) => m.key);
8326
+ for (const m of list) if (names.some((n) => m.key === n || m.key.startsWith(`${n}/`))) packages.push(m.key);
8327
+ }
8328
+ return { workspaces, packages };
8329
+ }
8330
+ function removeBunLockEntries(text, remove) {
8331
+ const spans = [];
8332
+ const drop = (name, keys, nested) => {
8333
+ if (!keys?.length) return;
8334
+ const s = section(text, name);
8335
+ if (!s) return;
8336
+ const list = members(text, s.value);
8337
+ list.forEach((m, k) => {
8338
+ if (!keys.some((key2) => m.key === key2 || nested && m.key.startsWith(`${key2}/`))) return;
8339
+ let start = m.start;
8340
+ while (start > 0 && (text[start - 1] === " " || text[start - 1] === " ")) start--;
8341
+ let end = skipSpace(text, m.end);
8342
+ if (text[end] === ",") {
8343
+ end++;
8344
+ let eol = end;
8345
+ while (eol < text.length && (text[eol] === " " || text[eol] === " ")) eol++;
8346
+ if (text[eol] === "\n") end = eol + 1;
8347
+ else if (text.startsWith("\r\n", eol)) end = eol + 2;
8348
+ } else if (k > 0) {
8349
+ start = list[k - 1].end;
8350
+ end = m.end;
8351
+ } else {
8352
+ end = m.end;
8353
+ if (text[end] === "\n") end++;
8354
+ }
8355
+ spans.push([start, end]);
8356
+ });
8357
+ };
8358
+ drop("workspaces", remove.workspaces, false);
8359
+ drop("packages", remove.packages, true);
8360
+ if (!spans.length) return text;
8361
+ spans.sort((a, b) => a[0] - b[0]);
8362
+ let out = "";
8363
+ let at = 0;
8364
+ for (const [a, b] of spans) {
8365
+ if (a > at) out += text.slice(at, a);
8366
+ at = Math.max(at, b);
8367
+ }
8368
+ return out + text.slice(at);
8369
+ }
8370
+ function readBunLock(dir) {
8371
+ const file = path30.join(dir, BUN_LOCK);
8372
+ return existsSync(file) ? readFileSync(file, "utf8") : null;
8373
+ }
8374
+ var BUN_LOCK, GENESIS_TAIL, PLAIN_VERSION;
8375
+ var init_bun_lock = __esm({
8376
+ "src/blocks/bun-lock.ts"() {
8377
+ init_semver();
8378
+ BUN_LOCK = "bun.lock";
8379
+ GENESIS_TAIL = /(?:^|\/)(@marktiderman\/genesis(?:-[a-z0-9-]+)?)$/;
8380
+ PLAIN_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;
8381
+ }
8382
+ });
8383
+ function checkBunLock(ctx) {
8384
+ const found = findLockfile(ctx.root);
8385
+ if (found?.pm !== "bun") return;
8386
+ const text = readBunLock(found.dir);
8387
+ if (text === null) return;
8388
+ const file = path30.relative(ctx.root, path30.join(found.dir, BUN_LOCK)).split(path30.sep).join("/");
8389
+ let stale;
8390
+ try {
8391
+ stale = staleNestedEntries(text);
8392
+ } catch {
8393
+ return;
8394
+ }
8395
+ for (const s of stale) {
8396
+ ctx.report({
8397
+ rule: "lock-files",
8398
+ level: "warn",
8399
+ file,
8400
+ subject: s.key,
8401
+ message: `keeps a nested copy of ${s.name}@${s.version} under ${s.parent} beside the root's ${s.root}, which satisfies its ${s.range}: Bun keeps it across installs, so the app runs two copies (a provider from one is invisible to hooks from the other). Delete the "${s.key}" entry from ${file}'s packages, then reinstall (bun install); genesis upgrade does both`
8402
+ });
8403
+ }
8404
+ }
7933
8405
  async function checkLockFiles(ctx) {
8406
+ checkBunLock(ctx);
7934
8407
  if (!existsSync(path30.join(ctx.root, LOCK_FILE))) return;
7935
8408
  let lock;
7936
8409
  try {
@@ -8030,6 +8503,8 @@ var init_lock_files = __esm({
8030
8503
  init_owned();
8031
8504
  init_starter_features();
8032
8505
  init_database();
8506
+ init_bun_lock();
8507
+ init_pm();
8033
8508
  }
8034
8509
  });
8035
8510
  function checkDatabaseHome(ctx) {
@@ -8059,6 +8534,41 @@ var init_database2 = __esm({
8059
8534
  init_database();
8060
8535
  }
8061
8536
  });
8537
+ function checkEslintConfig(ctx) {
8538
+ const pkg = readPackageJson(ctx.root);
8539
+ const native = appPlatform(pkg) === "native" || (ctx.config.packs?.includes("native") ?? false);
8540
+ if (!native) return;
8541
+ const file = findEslintConfig(ctx.root);
8542
+ if (!file) return;
8543
+ let text;
8544
+ try {
8545
+ text = readFileSync(path30.join(ctx.root, file), "utf8");
8546
+ } catch {
8547
+ return;
8548
+ }
8549
+ if (!usesGenesisLint(text)) {
8550
+ ctx.report({
8551
+ rule: "genesis-eslint-config",
8552
+ level: "warn",
8553
+ file,
8554
+ subject: "@marktiderman/genesis-cli/eslint",
8555
+ message: `doesn't load Genesis's lint rules, so genesis upgrade can't bring new ones (React Native Testing Library 14's await rules today). Run genesis codemod genesis-cli-eslint-config, or add const { genesis } = require("@marktiderman/genesis-cli/eslint") (import { genesis } from \u2026 in an ES module) and ...genesis("native") last in the array the config exports, with ${TESTING_LIBRARY} in devDependencies`
8556
+ });
8557
+ } else if (!hasTestingLibrary(pkg)) {
8558
+ ctx.report({
8559
+ rule: "genesis-eslint-config",
8560
+ level: "warn",
8561
+ file: "package.json",
8562
+ subject: TESTING_LIBRARY,
8563
+ 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
+ });
8565
+ }
8566
+ }
8567
+ var init_eslint_config2 = __esm({
8568
+ "src/doctor/eslint-config.ts"() {
8569
+ init_eslint_config();
8570
+ }
8571
+ });
8062
8572
 
8063
8573
  // src/doctor/index.ts
8064
8574
  var doctor_exports = {};
@@ -8210,6 +8720,7 @@ function builtinChecks(config, options = {}) {
8210
8720
  { name: "overlays", check: (ctx) => checkOverlays(ctx) },
8211
8721
  { name: "lock-files", check: checkLockFiles },
8212
8722
  { name: "database-elsewhere", check: checkDatabaseHome },
8723
+ { name: "eslint-config", check: checkEslintConfig },
8213
8724
  ...(config.packs ?? []).map((p) => packs[p]),
8214
8725
  ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
8215
8726
  ];
@@ -8326,6 +8837,7 @@ var init_doctor = __esm({
8326
8837
  init_overlays();
8327
8838
  init_lock_files();
8328
8839
  init_database2();
8840
+ init_eslint_config2();
8329
8841
  init_config();
8330
8842
  init_genesis();
8331
8843
  init_patterns();
@@ -8342,7 +8854,7 @@ var init_doctor = __esm({
8342
8854
  init_primitives();
8343
8855
  init_ratchet();
8344
8856
  init_contracts();
8345
- RATCHETED_BY_DEFAULT = ["deprecated-import"];
8857
+ RATCHETED_BY_DEFAULT = ["deprecated-import", "genesis-eslint-config"];
8346
8858
  }
8347
8859
  });
8348
8860
 
@@ -8792,8 +9304,8 @@ function routeTags(source) {
8792
9304
  }
8793
9305
  function wireStudioRoute(source, route, pageImportPath) {
8794
9306
  const tags = routeTags(source);
8795
- const relative15 = route.replace(/^\//, "");
8796
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative15.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
9307
+ const relative17 = route.replace(/^\//, "");
9308
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative17.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
8797
9309
  if (existing) {
8798
9310
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
8799
9311
  }
@@ -8801,17 +9313,17 @@ function wireStudioRoute(source, route, pageImportPath) {
8801
9313
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
8802
9314
  if (roots.length !== 1) {
8803
9315
  return {
8804
- 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="${relative15}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
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.`
8805
9317
  };
8806
9318
  }
8807
9319
  const layout = roots[0];
8808
9320
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
8809
- if (base && !relative15.startsWith(`${base}/`)) {
9321
+ if (base && !relative17.startsWith(`${base}/`)) {
8810
9322
  return {
8811
9323
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
8812
9324
  };
8813
9325
  }
8814
- const childPath = base ? relative15.slice(base.length + 1) : relative15;
9326
+ const childPath = base ? relative17.slice(base.length + 1) : relative17;
8815
9327
  const guard = GUARD.exec(source)?.[1];
8816
9328
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
8817
9329
  const before = source.slice(0, layout.close);
@@ -9487,6 +9999,7 @@ async function runAdd(options) {
9487
9999
  const providers = providingMigrations([full, ...catalog]);
9488
10000
  const migrations2 = home ? { rows: [], creates: [] } : planMigrations(root, sourceMigrations(root, full), { now, ...lock.migrations ? { copied: lock.migrations } : {}, providers });
9489
10001
  const superseded = supersededFunctions(migrations2.rows, providers);
10002
+ for (const r of migrations2.rows) for (const u of r.unmet ?? []) planWarnings.push(`${r.package} ${r.file} ${u}`);
9490
10003
  const replaced2 = full.functions.filter((fn) => superseded.has(`${fn.package}:${fn.dir}`)).map((fn) => {
9491
10004
  const by = superseded.get(`${fn.package}:${fn.dir}`);
9492
10005
  const block = providers.find((p) => p.package === by.package && p.file === by.file)?.block;
@@ -9801,6 +10314,7 @@ async function runMigrate(options) {
9801
10314
  }
9802
10315
  if (!ids.length && !sources.length) warnings.push("No blocks in genesis.lock.json and no copied package migrations: nothing to compare. Add a block (genesis add <block>), or pass --block.");
9803
10316
  const plan = planMigrations(root, sources, { now: options.now ?? /* @__PURE__ */ new Date(), ...options.forward ? { forward: true } : {}, ...lock.migrations ? { copied: lock.migrations } : {}, providers: providingMigrations([...manifests, ...catalog]) });
10317
+ for (const r of plan.rows) for (const u of r.unmet ?? []) warnings.push(`${r.package} ${r.file} ${u}`);
9804
10318
  const attention = plan.rows.some(needsAttention);
9805
10319
  const notifies = ids.some((id) => (lock.blocks[id]?.package ?? (id === "notifications" ? NOTIFICATIONS_PACKAGE : "")) === NOTIFICATIONS_PACKAGE);
9806
10320
  const types = notifies ? await planNotificationTypes(root, {
@@ -9975,11 +10489,11 @@ function rebasedManifest(text, name, to, released, nextText) {
9975
10489
  const n = LOCAL_SUFFIX.exec(typeof json.version === "string" ? json.version : "")?.[1] ?? "1";
9976
10490
  json.version = `${to}+local.${n}`;
9977
10491
  if (json.genesis?.overlay) json.genesis.overlay.upstream = `${name}@${to}`;
9978
- for (const section of ["dependencies", "peerDependencies", "optionalDependencies"]) {
9979
- const deps = json[section];
10492
+ for (const section2 of ["dependencies", "peerDependencies", "optionalDependencies"]) {
10493
+ const deps = json[section2];
9980
10494
  if (!deps) continue;
9981
10495
  for (const [dep, spec] of Object.entries(deps)) {
9982
- if (!spec.startsWith("workspace:") && !next[section]?.[dep]?.startsWith("workspace:")) continue;
10496
+ if (!spec.startsWith("workspace:") && !next[section2]?.[dep]?.startsWith("workspace:")) continue;
9983
10497
  const v = released(dep);
9984
10498
  if (v && PLAIN.test(v)) deps[dep] = `^${v}`;
9985
10499
  }
@@ -10108,9 +10622,9 @@ function ownManifestFields(mergedText, upstreamText) {
10108
10622
  if (!Object.keys(genesis).length) delete json.genesis;
10109
10623
  }
10110
10624
  }
10111
- for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
10112
- const ours = mine[section];
10113
- const up = theirs[section];
10625
+ for (const section2 of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
10626
+ const ours = mine[section2];
10627
+ const up = theirs[section2];
10114
10628
  if (!ours || !up) continue;
10115
10629
  for (const [dep, spec] of Object.entries(up)) if (typeof spec === "string" && spec.startsWith("workspace:") && typeof ours[dep] === "string") ours[dep] = spec;
10116
10630
  }
@@ -10136,51 +10650,73 @@ function folderReferences(root, plan) {
10136
10650
  }
10137
10651
  function planPins(root, plan, manifests) {
10138
10652
  const pins = /* @__PURE__ */ new Map();
10139
- const overlay = path30.resolve(root, plan.rel);
10140
10653
  for (const file of manifests) {
10141
10654
  const abs = path30.join(root, file);
10142
10655
  if (!existsSync(abs)) continue;
10143
10656
  const text = readFileSync(abs, "utf8");
10144
- let json;
10145
- try {
10146
- json = JSON.parse(text);
10147
- } catch {
10657
+ const pinned = pinManifest(root, plan, file, text);
10658
+ if (pinned === void 0) {
10148
10659
  return `nothing of the app's own is left, but ${file} isn't valid JSON, so its dependency on ${plan.name} can't be pinned: fix it, then run genesis upgrade again`;
10149
10660
  }
10150
- const here = path30.dirname(abs);
10151
- const local = (spec) => typeof spec === "string" && (spec.startsWith("workspace:") || /^(file|link):/.test(spec) && path30.resolve(here, spec.slice(5)) === overlay);
10152
- let touched2 = false;
10153
- for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
10154
- const deps = json[section];
10155
- if (deps && local(deps[plan.name])) {
10156
- deps[plan.name] = plan.to;
10157
- touched2 = true;
10158
- }
10159
- }
10160
- for (const o of [json.overrides, json.resolutions, json.pnpm?.overrides]) {
10161
- if (isObject5(o) && local(o[plan.name])) {
10162
- delete o[plan.name];
10163
- touched2 = true;
10164
- }
10165
- }
10166
- if (!touched2) continue;
10167
- const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? " ";
10168
- pins.set(file, JSON.stringify(json, null, indent) + (text.endsWith("\n") ? "\n" : ""));
10661
+ if (pinned !== null) pins.set(file, pinned);
10169
10662
  }
10170
10663
  return pins;
10171
10664
  }
10172
- function applyOverlayPlans(root, plans) {
10665
+ function pinManifest(root, plan, file, text) {
10666
+ let json;
10667
+ try {
10668
+ json = JSON.parse(text);
10669
+ } catch {
10670
+ return void 0;
10671
+ }
10672
+ const overlay = path30.resolve(root, plan.rel);
10673
+ const here = path30.dirname(path30.join(root, file));
10674
+ const local = (spec) => typeof spec === "string" && (spec.startsWith("workspace:") || /^(file|link):/.test(spec) && path30.resolve(here, spec.slice(5)) === overlay);
10675
+ let touched2 = false;
10676
+ for (const section2 of ["dependencies", "devDependencies", "optionalDependencies"]) {
10677
+ const deps = json[section2];
10678
+ if (deps && local(deps[plan.name])) {
10679
+ deps[plan.name] = plan.to;
10680
+ touched2 = true;
10681
+ }
10682
+ }
10683
+ for (const o of [json.overrides, json.resolutions, json.pnpm?.overrides]) {
10684
+ if (isObject5(o) && local(o[plan.name])) {
10685
+ delete o[plan.name];
10686
+ touched2 = true;
10687
+ }
10688
+ }
10689
+ const names = (entry) => typeof entry === "string" && path30.resolve(here, entry) === overlay;
10690
+ const ws = json.workspaces;
10691
+ const list = Array.isArray(ws) ? ws : isObject5(ws) && Array.isArray(ws.packages) ? ws.packages : null;
10692
+ if (list?.some(names)) {
10693
+ const kept = list.filter((entry) => !names(entry));
10694
+ if (Array.isArray(ws)) json.workspaces = kept;
10695
+ else ws.packages = kept;
10696
+ touched2 = true;
10697
+ }
10698
+ if (!touched2) return null;
10699
+ const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? " ";
10700
+ return JSON.stringify(json, null, indent) + (text.endsWith("\n") ? "\n" : "");
10701
+ }
10702
+ function applyOverlayPlans(root, plans, lockEdits = []) {
10173
10703
  const changed = [];
10704
+ const removedFolders = [];
10174
10705
  for (const plan of plans) {
10175
10706
  if (plan.skipped || plan.conflicts.length) continue;
10176
10707
  const dir = path30.join(root, plan.rel);
10177
10708
  if (plan.remove) {
10178
- for (const [file, text] of plan.pins) {
10179
- writeFileSync(path30.join(root, file), text);
10709
+ for (const file of plan.pins.keys()) {
10710
+ const abs = path30.join(root, file);
10711
+ const now = existsSync(abs) ? readFileSync(abs, "utf8") : null;
10712
+ const text = now === null ? plan.pins.get(file) : pinManifest(root, plan, file, now);
10713
+ if (typeof text !== "string") continue;
10714
+ writeFileSync(abs, text);
10180
10715
  changed.push(file);
10181
10716
  }
10182
10717
  rmSync(dir, { recursive: true, force: true });
10183
10718
  changed.push(`${plan.rel}/package.json`);
10719
+ removedFolders.push(dir);
10184
10720
  continue;
10185
10721
  }
10186
10722
  for (const [file, bytes] of plan.writes) {
@@ -10193,7 +10729,32 @@ function applyOverlayPlans(root, plans) {
10193
10729
  changed.push(`${plan.rel}/${file}`);
10194
10730
  }
10195
10731
  }
10196
- return changed;
10732
+ const edit = removedFolders.length ? dropRemovedWorkspaces(root, removedFolders) : null;
10733
+ if (edit) {
10734
+ lockEdits.push(edit);
10735
+ if (!edit.file.startsWith("..")) changed.push(edit.file);
10736
+ }
10737
+ return [...new Set(changed)];
10738
+ }
10739
+ function dropRemovedWorkspaces(root, folders) {
10740
+ const found = findLockfile(root);
10741
+ if (found?.pm !== "bun") return null;
10742
+ const text = readBunLock(found.dir);
10743
+ if (text === null) return null;
10744
+ const workspaces = [];
10745
+ const packages = [];
10746
+ try {
10747
+ for (const folder of folders) {
10748
+ const entries = workspaceEntries(text, path30.relative(found.dir, folder).split(path30.sep).join("/"));
10749
+ workspaces.push(...entries.workspaces);
10750
+ packages.push(...entries.packages);
10751
+ }
10752
+ } catch {
10753
+ return null;
10754
+ }
10755
+ if (!workspaces.length && !packages.length) return null;
10756
+ writeFileSync(path30.join(found.dir, BUN_LOCK), removeBunLockEntries(text, { workspaces, packages }));
10757
+ return { file: path30.relative(root, path30.join(found.dir, BUN_LOCK)).split(path30.sep).join("/"), workspaces };
10197
10758
  }
10198
10759
  function overlayChecklist(plans) {
10199
10760
  if (!plans.length) return [];
@@ -10225,6 +10786,8 @@ var init_overlays2 = __esm({
10225
10786
  init_local();
10226
10787
  init_overlays();
10227
10788
  init_upstream();
10789
+ init_bun_lock();
10790
+ init_pm();
10228
10791
  init_bump_core();
10229
10792
  GENESIS_REPOSITORY = "https://github.com/marktiderman/genesis.git";
10230
10793
  SKIP = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo", ".git"]);
@@ -10243,6 +10806,21 @@ __export(upgrade_exports, {
10243
10806
  releaseAgeError: () => releaseAgeError,
10244
10807
  runUpgrade: () => runUpgrade
10245
10808
  });
10809
+ function pruneBunLock(root, want, dryRun) {
10810
+ const found = findLockfile(root);
10811
+ if (found?.pm !== "bun") return null;
10812
+ const text = readBunLock(found.dir);
10813
+ if (text === null) return null;
10814
+ let pruned;
10815
+ try {
10816
+ pruned = staleNestedEntries(text, want);
10817
+ } catch {
10818
+ return null;
10819
+ }
10820
+ if (!pruned.length) return null;
10821
+ if (!dryRun) writeFileSync(path30.join(found.dir, BUN_LOCK), removeBunLockEntries(text, { packages: pruned.map((p) => p.key) }));
10822
+ return { file: path30.relative(root, path30.join(found.dir, BUN_LOCK)).split(path30.sep).join("/"), pruned };
10823
+ }
10246
10824
  function npm(args, cwd) {
10247
10825
  return execFileSync("npm", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
10248
10826
  }
@@ -10426,13 +11004,14 @@ async function runUpgrade(options) {
10426
11004
  if (text !== null && sha256(text) === entry.sha256) bases.set(file, text);
10427
11005
  }
10428
11006
  const files = /* @__PURE__ */ new Set();
11007
+ const lockEdits = [];
10429
11008
  const codemodRuns = [];
10430
11009
  if (!options.dryRun) {
10431
11010
  for (const [file, text] of bumped) {
10432
11011
  replaceApp(root, file, text);
10433
11012
  files.add(file);
10434
11013
  }
10435
- for (const file of applyOverlayPlans(root, overlays)) files.add(file);
11014
+ for (const file of applyOverlayPlans(root, overlays, lockEdits)) files.add(file);
10436
11015
  }
10437
11016
  for (const mod of mods) {
10438
11017
  log(`codemod ${mod.id}: ${mod.description}`);
@@ -10440,10 +11019,24 @@ async function runUpgrade(options) {
10440
11019
  codemodRuns.push({ id: mod.id, files: changed });
10441
11020
  for (const f of changed) files.add(f);
10442
11021
  }
11022
+ let bunLock;
11023
+ const prune = (want) => {
11024
+ const result = pruneBunLock(root, want, Boolean(options.dryRun));
11025
+ if (!result) return 0;
11026
+ bunLock ??= { file: result.file, pruned: [], workspaces: [], reinstalled: false };
11027
+ for (const p of result.pruned) if (!bunLock.pruned.some((q) => q.key === p.key)) bunLock.pruned.push(p);
11028
+ if (!options.dryRun && !result.file.startsWith("..")) files.add(result.file);
11029
+ return result.pruned.length;
11030
+ };
11031
+ prune((name) => pinned[name] ?? null);
11032
+ for (const edit of lockEdits) {
11033
+ bunLock ??= { file: edit.file, pruned: [], workspaces: [], reinstalled: false };
11034
+ bunLock.workspaces.push(...edit.workspaces);
11035
+ }
10443
11036
  const pm = detectPackageManager(root);
10444
11037
  let tidiedExcludes = null;
10445
11038
  const excludeWarnings = [];
10446
- if (!options.dryRun && options.install !== false && bumped.size) {
11039
+ if (!options.dryRun && options.install !== false && (bumped.size || bunLock)) {
10447
11040
  const workspaceFile = pm === "pnpm" ? pnpmWorkspaceFileFor(root) : null;
10448
11041
  const relWorkspace = workspaceFile ? path30.relative(realpathSync(root), workspaceFile) : null;
10449
11042
  const workspaceBefore = workspaceFile ? readText2(workspaceFile) : null;
@@ -10452,17 +11045,25 @@ async function runUpgrade(options) {
10452
11045
  tidiedExcludes = relWorkspace;
10453
11046
  log(`${tidiedExcludes}: minimumReleaseAgeExclude lists each Genesis package's pinned versions in one entry, exact versions the lockfile holds`);
10454
11047
  };
10455
- if (typeof options.install === "function") {
10456
- try {
10457
- options.install(root);
10458
- } catch (err) {
10459
- const e = err;
10460
- throw releaseAgeError([e.message, e.stdout, e.stderr].map((x) => x == null ? "" : String(x)).join("\n")) ?? err;
11048
+ const install = async () => {
11049
+ if (typeof options.install === "function") {
11050
+ try {
11051
+ options.install(root);
11052
+ } catch (err) {
11053
+ const e = err;
11054
+ throw releaseAgeError([e.message, e.stdout, e.stderr].map((x) => x == null ? "" : String(x)).join("\n")) ?? err;
11055
+ }
11056
+ } else {
11057
+ log(`install: ${shellLine(installCommand(pm))}`);
11058
+ await runInstall(root, installCommand(pm));
10461
11059
  }
10462
- } else {
10463
- log(`install: ${shellLine(installCommand(pm))}`);
10464
- await runInstall(root, installCommand(pm));
11060
+ };
11061
+ await install();
11062
+ if (prune(() => null)) {
11063
+ log(`${bunLock.file}: dropped nested Genesis copies the root's version satisfies; installing again`);
11064
+ await install();
10465
11065
  }
11066
+ if (bunLock) bunLock.reinstalled = true;
10466
11067
  tidy();
10467
11068
  const dedupe = options.dedupe ?? (typeof options.install === "function" ? false : true);
10468
11069
  const dedupeArgv = dedupeCommand(pm);
@@ -10506,7 +11107,7 @@ async function runUpgrade(options) {
10506
11107
  manifests.push(manifest);
10507
11108
  if (!home) {
10508
11109
  for (const row of planMigrations(root, sourceMigrations(root, manifest), { now: /* @__PURE__ */ new Date(), tests: false, ...lock.migrations ? { copied: lock.migrations } : {}, providers: providingMigrations(catalog) }).rows) {
10509
- if (row.state === "new") newMigrations.push(`${row.package} ${row.file}`);
11110
+ if (row.state === "new") newMigrations.push(`${row.package} ${row.file}${row.unmet?.length ? ` (${row.unmet.join("; ")})` : ""}`);
10510
11111
  }
10511
11112
  }
10512
11113
  if (manifest.version && manifest.version !== entry.version) lock.blocks[id] = { ...entry, version: manifest.version };
@@ -10596,11 +11197,17 @@ async function runUpgrade(options) {
10596
11197
  if (elsewhereEntries.length) lines.push("", `genesis.lock.json still lists ${elsewhereEntries.length} file${elsewhereEntries.length === 1 ? "" : "s"} under supabase/; they're left alone and can be deleted from the lock (and the folder).`);
10597
11198
  }
10598
11199
  if (tidiedExcludes) lines.push("", `pnpm pinned the new Genesis versions in \`${tidiedExcludes}\`'s \`minimumReleaseAgeExclude\` (they are younger than \`minimumReleaseAge\`). Each Genesis package now has one entry listing its exact versions in the lockfile (\`'name@1.0.0 || 1.1.0'\`), which \`pnpm install --frozen-lockfile\` honours; versions the lockfile no longer holds were dropped. Never a pattern, so a future Genesis release still waits out \`minimumReleaseAge\`. Other entries are as they were.`);
11200
+ if (bunLock) {
11201
+ lines.push("", `${bunLock.file}:`, "");
11202
+ for (const p of bunLock.pruned) lines.push(`- ${options.dryRun ? "would drop" : "dropped"} the nested copy of ${p.name}@${p.version} under ${p.parent} (\`${p.key}\`): the root's ${p.root} satisfies its ${p.range}, and two copies are two module instances`);
11203
+ for (const w of bunLock.workspaces) lines.push(`- dropped the workspace ${w}: the overlay there was deleted, and \`bun install\` stops on a workspace that isn't there`);
11204
+ lines.push(bunLock.reinstalled ? "- reinstalled (`bun install`), so the lockfile and node_modules match" : "- reinstall now: `bun install` (then `genesis doctor`), so node_modules holds one copy of each");
11205
+ }
10599
11206
  lines.push(...overlayChecklist(overlays));
10600
11207
  if (warnings.length) lines.push("", "Warnings:", "", ...warnings.map((w) => `- ${w}`));
10601
11208
  lines.push("", `\`genesis doctor\` ${doctor === "not run" ? "was not run" : doctor} after the upgrade.`);
10602
11209
  const summary = lines.join("\n");
10603
- const report = { version: release.version, changes, skipped, codemods: codemodRuns, breaks, refreshed, added, switchedOff, newMigrations, doctor, files: [...files].sort(), summary, overlays };
11210
+ const report = { version: release.version, changes, skipped, codemods: codemodRuns, breaks, refreshed, added, switchedOff, newMigrations, doctor, files: [...files].sort(), summary, overlays, ...bunLock ? { bunLock } : {} };
10604
11211
  if (options.pr && !options.dryRun && files.size) report.pr = openPullRequest(root, release.version, report, prBase);
10605
11212
  return report;
10606
11213
  }
@@ -10677,6 +11284,7 @@ var init_upgrade = __esm({
10677
11284
  init_bump_core();
10678
11285
  init_codemods();
10679
11286
  init_overlays2();
11287
+ init_bun_lock();
10680
11288
  EXACT_OR_TAG = /^[0-9A-Za-z][0-9A-Za-z.+-]*$/;
10681
11289
  inside2 = (dir, file) => {
10682
11290
  const rel = path30.relative(dir, file);
@@ -10783,9 +11391,9 @@ async function runScaffold(opts, fs2) {
10783
11391
  function joinPath(...parts) {
10784
11392
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
10785
11393
  }
10786
- function dirname(path53) {
10787
- const idx = path53.lastIndexOf("/");
10788
- return idx === -1 ? "." : path53.slice(0, idx);
11394
+ function dirname(path56) {
11395
+ const idx = path56.lastIndexOf("/");
11396
+ return idx === -1 ? "." : path56.slice(0, idx);
10789
11397
  }
10790
11398
  function brandPackageJson(consumer, genesisVersion) {
10791
11399
  return JSON.stringify(
@@ -11274,7 +11882,7 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
11274
11882
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
11275
11883
  const root = path30.resolve(opts.dir);
11276
11884
  const packageJson = JSON.parse(await fs.readFile(path30.join(root, "package.json"), "utf-8").catch(() => "{}"));
11277
- const existsSync41 = (await import('fs')).existsSync;
11885
+ const existsSync43 = (await import('fs')).existsSync;
11278
11886
  const readSync = (await import('fs')).readFileSync;
11279
11887
  const readdirSync19 = (await import('fs')).readdirSync;
11280
11888
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
@@ -11283,8 +11891,8 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
11283
11891
  const plan = planStudioInit2(
11284
11892
  {
11285
11893
  packageJson,
11286
- exists: (p) => existsSync41(path30.join(root, p)),
11287
- read: (p) => existsSync41(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
11894
+ exists: (p) => existsSync43(path30.join(root, p)),
11895
+ read: (p) => existsSync43(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
11288
11896
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
11289
11897
  listDeep: (p) => {
11290
11898
  const out = [];
@@ -11324,14 +11932,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
11324
11932
  console.log(`+ ${file.path} (appended)`);
11325
11933
  continue;
11326
11934
  }
11327
- if (existsSync41(target) && !opts.force) {
11935
+ if (existsSync43(target) && !opts.force) {
11328
11936
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
11329
11937
  continue;
11330
11938
  }
11331
11939
  await fs.writeFile(target, file.content, "utf-8");
11332
11940
  console.log(`+ ${file.path}`);
11333
11941
  }
11334
- const pm = existsSync41(path30.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync41(path30.join(root, "yarn.lock")) ? "yarn add" : existsSync41(path30.join(root, "bun.lock")) || existsSync41(path30.join(root, "bun.lockb")) ? "bun add" : "npm install";
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";
11335
11943
  console.log("");
11336
11944
  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:`);
11337
11945
  console.log(` 1. ${pm} ${plan.install.map((p) => /[\s<>|]/.test(p) ? `"${p}"` : p).join(" ")}`);