@marktiderman/genesis-cli 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, readFileSync, readdirSync, mkdirSync, writeFileSync, mkdtempSync, rmSync, realpathSync, statSync, lstatSync } from 'fs';
3
- import * as path29 from 'path';
3
+ import * as path30 from 'path';
4
4
  import { FEATURE_PLATFORMS, defineBlock, BlockError } from '@marktiderman/genesis-features/blocks';
5
5
  import { createHash } from 'crypto';
6
6
  import { fileURLToPath, pathToFileURL } from 'url';
@@ -26,7 +26,7 @@ var __export = (target, all) => {
26
26
  function buildCatalog(packagesDir) {
27
27
  const packages = {};
28
28
  for (const dir of readdirSync(packagesDir).sort()) {
29
- const file = path29.join(packagesDir, dir, "package.json");
29
+ const file = path30.join(packagesDir, dir, "package.json");
30
30
  if (!existsSync(file)) continue;
31
31
  const pkg = JSON.parse(readFileSync(file, "utf8"));
32
32
  if (!pkg.name || !pkg.version || pkg.private || !pkg.name.startsWith("@marktiderman/genesis")) continue;
@@ -101,6 +101,26 @@ function parseManifest(home, id, raw, version, options = {}) {
101
101
  const file = pathOf(m["file"], `${where2}.file`);
102
102
  if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where2}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
103
103
  const out = { package: pkgOf(m["package"], where2), file };
104
+ if (m["provides"] !== void 0) {
105
+ if (!Array.isArray(m["provides"])) problems.push(`${where2}.provides: must be a list of { package, file }`);
106
+ else {
107
+ out.provides = m["provides"].map((p, j) => {
108
+ const at2 = `${where2}.provides[${j}]`;
109
+ if (!isObject(p)) {
110
+ problems.push(`${at2}: must be an object`);
111
+ return { package: home, file: "" };
112
+ }
113
+ const provided = { package: pkgOf(p["package"], at2), file: pathOf(p["file"], `${at2}.file`) };
114
+ if (p["functions"] !== void 0) {
115
+ if (!Array.isArray(p["functions"])) problems.push(`${at2}.functions: must be a list of function folders`);
116
+ else provided.functions = p["functions"].map((f, k) => pathOf(f, `${at2}.functions[${k}]`));
117
+ }
118
+ if (provided.file && !MIGRATION_FILE.test(provided.file.split("/").pop())) problems.push(`${at2}.file: "${provided.file}" must be named NNNN_name.sql`);
119
+ if (provided.package === out.package && provided.file === file) problems.push(`${at2}: a migration can't provide itself`);
120
+ return provided;
121
+ });
122
+ }
123
+ }
104
124
  if (m["test"] !== void 0) {
105
125
  out.test = pathOf(m["test"], `${where2}.test`);
106
126
  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`);
@@ -235,14 +255,14 @@ ${problems.map((p) => ` - ${p}`).join("\n")}`);
235
255
  }
236
256
  });
237
257
  function inside(parent, child) {
238
- const rel = path29.relative(parent, child);
239
- return rel === "" || !rel.startsWith("..") && !path29.isAbsolute(rel);
258
+ const rel = path30.relative(parent, child);
259
+ return rel === "" || !rel.startsWith("..") && !path30.isAbsolute(rel);
240
260
  }
241
261
  function readPackageFile(packageDir2, rel) {
242
262
  const safe = safeRelative(rel);
243
263
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the package`);
244
264
  const root = realpathSync(packageDir2);
245
- const file = path29.join(root, ...safe.split("/"));
265
+ const file = path30.join(root, ...safe.split("/"));
246
266
  if (!existsSync(file)) return null;
247
267
  const real2 = realpathSync(file);
248
268
  if (!inside(root, real2)) throw new Error(`${rel} in ${packageDir2} points outside the package`);
@@ -253,7 +273,7 @@ function readPackageDir(packageDir2, rel, skipped = []) {
253
273
  const safe = safeRelative(rel);
254
274
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the package`);
255
275
  const root = realpathSync(packageDir2);
256
- const dir = path29.join(root, ...safe.split("/"));
276
+ const dir = path30.join(root, ...safe.split("/"));
257
277
  if (!existsSync(dir)) return null;
258
278
  const real2 = realpathSync(dir);
259
279
  if (!inside(root, real2) || !statSync(real2).isDirectory()) throw new Error(`${rel} in ${packageDir2} is not a folder inside the package`);
@@ -273,7 +293,7 @@ function appPath(root, rel) {
273
293
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the app`);
274
294
  if (safe.split("/").some((s) => s.toLowerCase() === ".git")) throw new Error(`"${rel}" is inside .git; refused`);
275
295
  const realRoot = realpathSync(root);
276
- const target = path29.join(realRoot, ...safe.split("/"));
296
+ const target = path30.join(realRoot, ...safe.split("/"));
277
297
  const there = (p) => {
278
298
  try {
279
299
  lstatSync(p);
@@ -282,13 +302,13 @@ function appPath(root, rel) {
282
302
  return false;
283
303
  }
284
304
  };
285
- let probe = path29.dirname(target);
286
- while (!there(probe)) probe = path29.dirname(probe);
305
+ let probe = path30.dirname(target);
306
+ while (!there(probe)) probe = path30.dirname(probe);
287
307
  let real2;
288
308
  try {
289
309
  real2 = realpathSync(probe);
290
310
  } catch {
291
- throw new Error(`${rel} goes through a broken symlink (${path29.relative(realRoot, probe)}); refused`);
311
+ throw new Error(`${rel} goes through a broken symlink (${path30.relative(realRoot, probe)}); refused`);
292
312
  }
293
313
  if (!inside(realRoot, real2)) throw new Error(`${rel} is outside the app (a symlinked folder?)`);
294
314
  if (there(target) && lstatSync(target).isSymbolicLink()) throw new Error(`${rel} is a symlink; left alone`);
@@ -300,20 +320,20 @@ function readApp(root, rel) {
300
320
  }
301
321
  function createApp(root, rel, content) {
302
322
  const file = appPath(root, rel);
303
- mkdirSync(path29.dirname(file), { recursive: true });
323
+ mkdirSync(path30.dirname(file), { recursive: true });
304
324
  writeFileSync(file, content, { encoding: "utf8", flag: "wx" });
305
325
  }
306
326
  function replaceApp(root, rel, content) {
307
327
  const file = appPath(root, rel);
308
- mkdirSync(path29.dirname(file), { recursive: true });
328
+ mkdirSync(path30.dirname(file), { recursive: true });
309
329
  writeFileSync(file, content, "utf8");
310
330
  }
311
331
  function listApp(root, rel, options = {}) {
312
- const dir = path29.join(root, rel);
332
+ const dir = path30.join(root, rel);
313
333
  if (!existsSync(dir)) return [];
314
334
  const out = [];
315
335
  const walk3 = (r) => {
316
- for (const entry of readdirSync(path29.join(root, r), { withFileTypes: true })) {
336
+ for (const entry of readdirSync(path30.join(root, r), { withFileTypes: true })) {
317
337
  const child = `${r}/${entry.name}`;
318
338
  if (entry.isDirectory()) walk3(child);
319
339
  else if (entry.isFile() || options.symlinks && entry.isSymbolicLink()) out.push(child);
@@ -334,8 +354,8 @@ function validateLocalPackages(raw, source = "genesis.config.json") {
334
354
  return raw.map((entry, i) => {
335
355
  const where2 = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
336
356
  if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where2} must be a non-empty folder`);
337
- if (path29.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where2} must be relative to the app ("${entry}")`);
338
- const norm = path29.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
357
+ if (path30.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where2} must be relative to the app ("${entry}")`);
358
+ const norm = path30.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
339
359
  if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where2} must name a package folder, not the app or a parent of it ("${entry}")`);
340
360
  const parts = norm.split("/");
341
361
  if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
@@ -346,7 +366,7 @@ function validateLocalPackages(raw, source = "genesis.config.json") {
346
366
  });
347
367
  }
348
368
  function localPackageGlobs(root) {
349
- const file = path29.join(root, "genesis.config.json");
369
+ const file = path30.join(root, "genesis.config.json");
350
370
  if (!existsSync(file)) return [];
351
371
  let raw;
352
372
  try {
@@ -359,14 +379,14 @@ function localPackageGlobs(root) {
359
379
  }
360
380
  function repositoryRoot(appRoot) {
361
381
  for (let dir = appRoot; ; ) {
362
- if (existsSync(path29.join(dir, ".git"))) return dir;
363
- const parent = path29.dirname(dir);
382
+ if (existsSync(path30.join(dir, ".git"))) return dir;
383
+ const parent = path30.dirname(dir);
364
384
  if (parent === dir) return appRoot;
365
385
  dir = parent;
366
386
  }
367
387
  }
368
388
  function localPackages(root) {
369
- const appRoot = path29.resolve(root);
389
+ const appRoot = path30.resolve(root);
370
390
  const globs = localPackageGlobs(appRoot);
371
391
  const key2 = `${appRoot}
372
392
  ${globs.join("\n")}`;
@@ -375,24 +395,24 @@ ${globs.join("\n")}`;
375
395
  const dirs = /* @__PURE__ */ new Set();
376
396
  for (const glob of globs) {
377
397
  if (glob.endsWith("/*") || glob === "*") {
378
- const parent = path29.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
398
+ const parent = path30.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
379
399
  if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
380
400
  for (const entry of readdirSync(parent).sort()) {
381
401
  if (entry.startsWith(".") || entry === "node_modules") continue;
382
- dirs.add(path29.join(parent, entry));
402
+ dirs.add(path30.join(parent, entry));
383
403
  }
384
404
  } else {
385
- dirs.add(path29.join(appRoot, glob));
405
+ dirs.add(path30.join(appRoot, glob));
386
406
  }
387
407
  }
388
408
  const real2 = realpathSync(repositoryRoot(appRoot));
389
409
  const out = [];
390
410
  const byName = /* @__PURE__ */ new Map();
391
411
  for (const dir of [...dirs].sort()) {
392
- const manifest = path29.join(dir, "package.json");
412
+ const manifest = path30.join(dir, "package.json");
393
413
  if (!existsSync(manifest)) continue;
394
414
  if (!inside(real2, realpathSync(dir))) {
395
- throw new LocalPackagesError(`${path29.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
415
+ throw new LocalPackagesError(`${path30.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
396
416
  }
397
417
  let pkg;
398
418
  try {
@@ -401,7 +421,7 @@ ${globs.join("\n")}`;
401
421
  continue;
402
422
  }
403
423
  if (typeof pkg.name !== "string" || !pkg.name) continue;
404
- const rel = path29.relative(appRoot, dir).split(path29.sep).join("/");
424
+ const rel = path30.relative(appRoot, dir).split(path30.sep).join("/");
405
425
  const other = byName.get(pkg.name);
406
426
  if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
407
427
  byName.set(pkg.name, rel);
@@ -444,41 +464,41 @@ __export(discover_exports, {
444
464
  workspacePackagesDir: () => workspacePackagesDir
445
465
  });
446
466
  function cliPackageDir() {
447
- let dir = path29.dirname(fileURLToPath(import.meta.url));
467
+ let dir = path30.dirname(fileURLToPath(import.meta.url));
448
468
  for (; ; ) {
449
- const file = path29.join(dir, "package.json");
469
+ const file = path30.join(dir, "package.json");
450
470
  if (existsSync(file) && JSON.parse(readFileSync(file, "utf8")).name === CLI_PACKAGE) return dir;
451
- const parent = path29.dirname(dir);
471
+ const parent = path30.dirname(dir);
452
472
  if (parent === dir) throw new Error("Can't find the genesis-cli package folder.");
453
473
  dir = parent;
454
474
  }
455
475
  }
456
476
  function workspacePackagesDir() {
457
- const dir = path29.resolve(cliPackageDir(), "..");
458
- return existsSync(path29.join(dir, "features", "package.json")) && existsSync(path29.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
477
+ const dir = path30.resolve(cliPackageDir(), "..");
478
+ return existsSync(path30.join(dir, "features", "package.json")) && existsSync(path30.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
459
479
  }
460
480
  function readCatalog() {
461
481
  if (catalogCache) return catalogCache;
462
482
  const workspace = workspacePackagesDir();
463
483
  if (workspace) return catalogCache = buildCatalog(workspace);
464
- const file = path29.join(cliPackageDir(), "dist", "genesis-catalog.json");
484
+ const file = path30.join(cliPackageDir(), "dist", "genesis-catalog.json");
465
485
  catalogCache = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : { packages: {} };
466
486
  return catalogCache;
467
487
  }
468
488
  function installedGenesis(root) {
469
489
  const found = /* @__PURE__ */ new Map();
470
- let dir = path29.resolve(root);
490
+ let dir = path30.resolve(root);
471
491
  for (; ; ) {
472
- const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path29.join(dir, m)));
473
- const scope = path29.join(dir, "node_modules", "@marktiderman");
492
+ const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path30.join(dir, m)));
493
+ const scope = path30.join(dir, "node_modules", "@marktiderman");
474
494
  if (existsSync(scope)) {
475
495
  for (const entry of readdirSync(scope)) {
476
496
  const name = `@marktiderman/${entry}`;
477
497
  if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
478
- if (existsSync(path29.join(scope, entry, "package.json"))) found.set(name, path29.join(scope, entry));
498
+ if (existsSync(path30.join(scope, entry, "package.json"))) found.set(name, path30.join(scope, entry));
479
499
  }
480
500
  }
481
- const parent = path29.dirname(dir);
501
+ const parent = path30.dirname(dir);
482
502
  if (atInstallRoot || parent === dir) return found;
483
503
  dir = parent;
484
504
  }
@@ -492,10 +512,10 @@ function packageDir(root, name) {
492
512
  return null;
493
513
  }
494
514
  function packageVersion(dir) {
495
- return JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8")).version;
515
+ return JSON.parse(readFileSync(path30.join(dir, "package.json"), "utf8")).version;
496
516
  }
497
517
  function declarationsOf(dir, warnings) {
498
- const pkg = JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8"));
518
+ const pkg = JSON.parse(readFileSync(path30.join(dir, "package.json"), "utf8"));
499
519
  const key2 = `${realpathSync(dir)}@${pkg.version ?? ""}`;
500
520
  let cached = declarationCache.get(key2);
501
521
  if (!cached) {
@@ -505,15 +525,15 @@ function declarationsOf(dir, warnings) {
505
525
  return cached;
506
526
  }
507
527
  async function loadDeclarations(dir, warnings) {
508
- const pkg = JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8"));
528
+ const pkg = JSON.parse(readFileSync(path30.join(dir, "package.json"), "utf8"));
509
529
  const entry = pkg.exports?.["./blocks"];
510
530
  const target = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry["import"] ?? entry["default"] : void 0;
511
531
  if (typeof target !== "string") return {};
512
532
  const rel = safeRelative(target.replace(/^\.\//, ""));
513
- const file = rel && path29.join(dir, ...rel.split("/"));
533
+ const file = rel && path30.join(dir, ...rel.split("/"));
514
534
  if (!file || !inside(dir, file) || !existsSync(file)) return {};
515
535
  try {
516
- const jiti = createJiti(path29.join(dir, "package.json"), { moduleCache: false });
536
+ const jiti = createJiti(path30.join(dir, "package.json"), { moduleCache: false });
517
537
  const mod = await jiti.import(file);
518
538
  const out = {};
519
539
  for (const value of Object.values(mod)) if (isBlockDef(value)) out[value.id] = declarationFields(value);
@@ -524,18 +544,28 @@ async function loadDeclarations(dir, warnings) {
524
544
  }
525
545
  }
526
546
  async function blocksOfInstalled(dir, warnings = [], options = {}) {
527
- const pkg = JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8"));
547
+ const pkg = JSON.parse(readFileSync(path30.join(dir, "package.json"), "utf8"));
528
548
  const raw = rawBlocksOf(pkg);
529
549
  const declared = await declarationsOf(dir, warnings);
530
550
  const ids = /* @__PURE__ */ new Set([...Object.keys(raw), ...Object.keys(declared)]);
531
551
  const out = [];
532
552
  for (const id of [...ids].sort()) {
533
553
  const fromJson = raw[id] ?? {};
534
- const manifest = tryParse(() => parseManifest(pkg.name, id, { ...fromJson, ...declared[id] }, pkg.version, options), warnings);
554
+ const merged = { ...fromJson, ...declared[id] };
555
+ if (declared[id]?.["migrations"] && Array.isArray(fromJson["migrations"])) merged["migrations"] = withProvides(declared[id]["migrations"], fromJson["migrations"]);
556
+ const manifest = tryParse(() => parseManifest(pkg.name, id, merged, pkg.version, options), warnings);
535
557
  if (manifest) out.push(manifest);
536
558
  }
537
559
  return out;
538
560
  }
561
+ function withProvides(declared, json) {
562
+ if (!Array.isArray(declared)) return declared;
563
+ const fileOf = (m) => m && typeof m === "object" ? m["file"] : void 0;
564
+ return declared.map((m) => {
565
+ const same2 = json.find((j) => fileOf(j) === fileOf(m));
566
+ return same2?.["provides"] !== void 0 && m && typeof m === "object" && !("provides" in m) ? { ...m, provides: same2["provides"] } : m;
567
+ });
568
+ }
539
569
  async function allBlocks(root, warnings = []) {
540
570
  const out = [];
541
571
  for (const local of localPackages(root)) {
@@ -608,7 +638,7 @@ function emptyLock() {
608
638
  return { version: 1, blocks: {}, files: {} };
609
639
  }
610
640
  function readLock(root) {
611
- const file = path29.join(root, LOCK_FILE);
641
+ const file = path30.join(root, LOCK_FILE);
612
642
  if (!existsSync(file)) return emptyLock();
613
643
  const raw = JSON.parse(readFileSync(file, "utf8"));
614
644
  if (raw.version !== 1) throw new Error(`${LOCK_FILE} has version ${String(raw.version)}; this CLI reads version 1.`);
@@ -665,10 +695,12 @@ __export(migrations_exports, {
665
695
  nextStamp: () => nextStamp,
666
696
  nextTimestamps: () => nextTimestamps,
667
697
  planMigrations: () => planMigrations,
698
+ providingMigrations: () => providingMigrations,
668
699
  readAppMigrations: () => readAppMigrations,
669
700
  rememberMigrationCopies: () => rememberMigrationCopies,
670
701
  stemOf: () => stemOf,
671
702
  stemOrNull: () => stemOrNull,
703
+ supersededFunctions: () => supersededFunctions,
672
704
  textSha: () => textSha,
673
705
  timestampOf: () => timestampOf,
674
706
  validHeaderFile: () => validHeaderFile
@@ -679,7 +711,7 @@ function migrationHeader(pkg, file, source) {
679
711
  `;
680
712
  }
681
713
  function stemOrNull(file) {
682
- return MIGRATION_FILE.exec(path29.posix.basename(file))?.[2] ?? null;
714
+ return MIGRATION_FILE.exec(path30.posix.basename(file))?.[2] ?? null;
683
715
  }
684
716
  function stemOf(file) {
685
717
  const stem = stemOrNull(file);
@@ -689,7 +721,7 @@ function stemOf(file) {
689
721
  function readAppMigrations(root, dir = MIGRATIONS_DIR) {
690
722
  return listApp(root, dir, { symlinks: true }).filter((p) => p.endsWith(".sql")).map((p) => {
691
723
  const content = readApp(root, p) ?? "";
692
- const name = path29.posix.basename(p);
724
+ const name = path30.posix.basename(p);
693
725
  const m = HEADER.exec(content);
694
726
  if (m) return { path: p, name, content, tracked: { package: m[1], file: m[2], sha256: m[3], body: content.slice(m[0].length) } };
695
727
  const f = FORWARD.exec(content);
@@ -698,7 +730,28 @@ function readAppMigrations(root, dir = MIGRATIONS_DIR) {
698
730
  });
699
731
  }
700
732
  function needsAttention(row) {
701
- return row.state !== "current" && row.state !== "new" && row.state !== "deleted" && !row.forward;
733
+ return row.state !== "current" && row.state !== "new" && row.state !== "deleted" && row.state !== "provided" && !row.forward;
734
+ }
735
+ function supersededFunctions(rows, providers) {
736
+ const out = /* @__PURE__ */ new Map();
737
+ for (const row of rows) {
738
+ if (row.state !== "provided" || !row.providedBy) continue;
739
+ const by = providers.find((p) => p.package === row.providedBy.package && p.file === row.providedBy.file);
740
+ const entry = by?.provides.find((x) => x.package === row.package && x.file === row.file);
741
+ for (const dir of entry?.functions ?? []) out.set(`${row.package}:${dir}`, row.providedBy);
742
+ }
743
+ return out;
744
+ }
745
+ function providingMigrations(manifests) {
746
+ const out = [];
747
+ for (const m of manifests) {
748
+ for (const mig of m.migrations) {
749
+ if (!mig.provides?.length || out.some((o) => o.package === mig.package && o.file === mig.file)) continue;
750
+ const block = m.id ?? mig.block;
751
+ out.push({ ...block ? { block } : {}, package: mig.package, file: mig.file, provides: mig.provides });
752
+ }
753
+ }
754
+ return out;
702
755
  }
703
756
  function timestampOf(date) {
704
757
  return date.toISOString().replace(/\D/g, "").slice(0, 14);
@@ -731,6 +784,16 @@ function nextTimestamps(existing, now, count) {
731
784
  function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date() }) {
732
785
  const app = readAppMigrations(root);
733
786
  const rows = [];
787
+ const providers = providingMigrations([{ migrations: sources }]);
788
+ for (const p of options.providers ?? []) if (!providers.some((o) => o.package === p.package && o.file === p.file)) providers.push(p);
789
+ const providerAt = (p) => {
790
+ const stem = stemOrNull(p.file);
791
+ const copy = app.find((m) => !m.forward && (m.tracked ? m.tracked.package === p.package && m.tracked.file === p.file : stem !== null && m.name.replace(/^\d+_/, "") === `${stem}.sql`));
792
+ if (copy) return copy.path;
793
+ const copied = options.copied?.[migrationKey(p.package, p.file)];
794
+ if (copied) return app.some((m) => m.path === copied) ? copied : null;
795
+ return sources.some((s) => s.package === p.package && s.file === p.file && s.source !== null) ? "this run" : null;
796
+ };
734
797
  const pending = [];
735
798
  const seen = /* @__PURE__ */ new Set();
736
799
  for (const src of sources) {
@@ -758,6 +821,12 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
758
821
  continue;
759
822
  }
760
823
  if (!copy) {
824
+ const by = providers.find((p) => p.provides.some((x) => x.package === src.package && x.file === src.file) && providerAt(p) !== null);
825
+ if (by) {
826
+ const at = providerAt(by);
827
+ rows.push({ ...base, state: "provided", providedBy: { package: by.package, file: by.file }, detail: `${by.package} ${by.file} provides its objects (${at === "this run" ? "copied in this run" : at}); not copied` });
828
+ continue;
829
+ }
761
830
  const row2 = { ...base, state: "new" };
762
831
  rows.push(row2);
763
832
  pending.push({ row: row2, src, kind: "migration" });
@@ -776,7 +845,7 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
776
845
  detail = copy.tracked ? renamed.trim() : "copied before headers; matches the package";
777
846
  } else if (copy.tracked) {
778
847
  state = "changed-upstream";
779
- detail = `${src.package} now ships a different ${path29.posix.basename(src.file)}; the applied copy is never rewritten`;
848
+ detail = `${src.package} now ships a different ${path30.posix.basename(src.file)}; the applied copy is never rewritten`;
780
849
  } else {
781
850
  state = "differs";
782
851
  detail = "has the package migration's name but other text and no header; treated as the app's own";
@@ -798,7 +867,7 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
798
867
  row.target = target2;
799
868
  creates.push({ path: target2, content: migrationHeader(src.package, src.file, src.source) + src.source, kind, source: { package: src.package, file: src.file } });
800
869
  if (options.tests !== false && src.test && src.testSource != null) {
801
- const test2 = `${TESTS_DIR}/${path29.posix.basename(src.test).replace(/^\d{4}_/, "")}`;
870
+ const test2 = `${TESTS_DIR}/${path30.posix.basename(src.test).replace(/^\d{4}_/, "")}`;
802
871
  if (readApp(root, test2) === null && !creates.some((c) => c.path === test2)) creates.push({ path: test2, content: src.testSource, kind: "test", source: { package: src.package, file: src.test } });
803
872
  }
804
873
  return;
@@ -844,7 +913,7 @@ function validHeaderFile(file) {
844
913
  }
845
914
  function formatMigrationRows(rows) {
846
915
  if (!rows.length) return "No package migrations to compare.";
847
- const mark = { current: "=", new: "+", edited: "!", "changed-upstream": "!", differs: "!", deleted: "!", unavailable: "?" };
916
+ const mark = { current: "=", new: "+", edited: "!", "changed-upstream": "!", differs: "!", deleted: "!", provided: "=", unavailable: "?" };
848
917
  return rows.map((r) => {
849
918
  const where2 = r.target ? ` \u2192 ${r.target}` : r.copy ? ` (${r.copy})` : "";
850
919
  const fwd = r.forward && !r.target ? `; carried by ${r.forward}` : "";
@@ -882,32 +951,33 @@ __export(config_exports, {
882
951
  readGenesisConfig: () => readGenesisConfig,
883
952
  validateConfig: () => validateConfig,
884
953
  validateLinks: () => validateLinks,
885
- validatePrivacy: () => validatePrivacy
954
+ validatePrivacy: () => validatePrivacy,
955
+ validateSupabase: () => validateSupabase
886
956
  });
887
957
  function privacyDataType(type) {
888
958
  return PRIVACY_DATA_TYPES[type.toLowerCase()];
889
959
  }
890
960
  function appPath2(v, where2, fail) {
891
961
  if (typeof v !== "string" || !v.trim()) return fail(`${where2} must be a non-empty path`);
892
- if (path29.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
893
- const norm = path29.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
962
+ if (path30.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
963
+ const norm = path30.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
894
964
  if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where2} must be a folder inside the app ("${v}")`);
895
965
  return norm;
896
966
  }
897
967
  function loadConfig(root, configPath) {
898
968
  if (configPath) {
899
- const file = path29.resolve(root, configPath);
969
+ const file = path30.resolve(root, configPath);
900
970
  if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
901
971
  const json = readJson(file);
902
- const block = path29.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
903
- return { config: validateConfig(block ?? {}, file), file, dir: path29.dirname(file) };
972
+ const block = path30.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
973
+ return { config: validateConfig(block ?? {}, file), file, dir: path30.dirname(file) };
904
974
  }
905
- const own = path29.join(root, "genesis.config.json");
975
+ const own = path30.join(root, "genesis.config.json");
906
976
  if (existsSync(own)) {
907
977
  const block = readGenesisConfig(root)?.raw.doctor;
908
978
  return { config: validateConfig(block ?? {}, own), file: own, dir: root };
909
979
  }
910
- const pkg = path29.join(root, "package.json");
980
+ const pkg = path30.join(root, "package.json");
911
981
  if (existsSync(pkg)) {
912
982
  const block = readJson(pkg)?.genesis?.doctor;
913
983
  if (block !== void 0 && !isPackageDeclaration(block)) return { config: validateConfig(block, pkg), file: pkg, dir: root };
@@ -916,7 +986,7 @@ function loadConfig(root, configPath) {
916
986
  }
917
987
  function doctorBlock(json, file, explicit) {
918
988
  const j = json;
919
- if (path29.basename(file) === "package.json") return j?.genesis?.doctor;
989
+ if (path30.basename(file) === "package.json") return j?.genesis?.doctor;
920
990
  return explicit ? j?.doctor ?? j : j?.doctor;
921
991
  }
922
992
  function isPackageDeclaration(block) {
@@ -933,15 +1003,33 @@ function readJson(file) {
933
1003
  }
934
1004
  }
935
1005
  function readGenesisConfig(root) {
936
- const file = path29.join(root, "genesis.config.json");
1006
+ const file = path30.join(root, "genesis.config.json");
937
1007
  if (!existsSync(file)) return null;
938
1008
  const raw = readJson(file);
939
1009
  if (!isObject2(raw)) throw new GenesisConfigError(`${file}: the config must be a JSON object`);
940
1010
  const out = { raw };
941
1011
  if (raw.links !== void 0) out.links = validateLinks(raw.links, file);
942
1012
  if (raw.privacy !== void 0) out.privacy = validatePrivacy(raw.privacy, file);
1013
+ if (raw.supabase !== void 0) {
1014
+ const supabase = validateSupabase(raw.supabase, file);
1015
+ if (supabase !== true) out.supabase = supabase;
1016
+ }
943
1017
  return out;
944
1018
  }
1019
+ function validateSupabase(raw, source = "config") {
1020
+ const fail = (msg) => {
1021
+ throw new GenesisConfigError(`${source}: ${msg}`);
1022
+ };
1023
+ if (typeof raw === "boolean") return raw ? true : false;
1024
+ if (!isObject2(raw)) return fail(`"supabase" must be false or { "app": "<the folder of the app that holds supabase/>" }`);
1025
+ for (const key2 of Object.keys(raw)) if (key2 !== "app" && key2 !== "$comment") fail(`supabase: unknown setting "${key2}" (known: app)`);
1026
+ const app = raw.app;
1027
+ if (typeof app !== "string" || !app.trim()) return fail(`supabase.app must be the folder of the app that holds supabase/, relative to this one (e.g. "../app")`);
1028
+ if (path30.isAbsolute(app) || /^[A-Za-z]:[\\/]/.test(app) || app.includes("\\")) fail(`supabase.app must be relative to this app, with forward slashes ("${app}")`);
1029
+ const norm = path30.posix.normalize(app).replace(/\/+$/, "");
1030
+ if (norm === "." || norm === "") fail(`supabase.app names this app itself; leave "supabase" out instead`);
1031
+ return { app: norm };
1032
+ }
945
1033
  function validatePrivacy(raw, source = "config") {
946
1034
  const fail = (msg) => {
947
1035
  throw new GenesisConfigError(`${source}: ${msg}`);
@@ -1094,7 +1182,7 @@ function validateConfig(raw, source = "config") {
1094
1182
  if (!(c.packs ?? []).includes("supabase")) fail(`"contracts" is set but the supabase pack is not in "packs"`);
1095
1183
  if (contracts.out !== void 0) {
1096
1184
  if (typeof contracts.out !== "string" || !contracts.out.trim()) fail(`contracts.out must be a file path`);
1097
- if (path29.isAbsolute(contracts.out) || contracts.out.replace(/\\/g, "/").split("/").includes("..")) fail(`contracts.out must be a file inside the app`);
1185
+ if (path30.isAbsolute(contracts.out) || contracts.out.replace(/\\/g, "/").split("/").includes("..")) fail(`contracts.out must be a file inside the app`);
1098
1186
  }
1099
1187
  if (contracts.schemas !== void 0 && !isStringList(contracts.schemas)) fail(`contracts.schemas must be a list of schema names`);
1100
1188
  if (contracts.databaseEnv !== void 0 && (typeof contracts.databaseEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(contracts.databaseEnv))) {
@@ -1230,12 +1318,104 @@ var init_config = __esm({
1230
1318
  HOST = /^(?=.{1,253}$)(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
1231
1319
  }
1232
1320
  });
1321
+ function databaseElsewhere(root) {
1322
+ const setting = readGenesisConfig(root)?.supabase;
1323
+ if (setting === void 0) return null;
1324
+ if (setting === false) return { app: null, dir: null, hasSupabase: false };
1325
+ const resolved = path30.resolve(root, setting.app);
1326
+ const real2 = (p) => existsSync(p) ? realpathSync(p) : p;
1327
+ const dir = real2(resolved);
1328
+ if (dir === real2(path30.resolve(root))) throw new GenesisConfigError(`${path30.join(root, "genesis.config.json")}: supabase.app "${setting.app}" is this app itself; leave "supabase" out instead`);
1329
+ return { app: setting.app, dir, hasSupabase: existsSync(path30.join(dir, "supabase")) };
1330
+ }
1331
+ function isSupabasePath(rel) {
1332
+ return rel === "supabase" || rel.startsWith("supabase/");
1333
+ }
1334
+ function elsewhereNote(home, command = "genesis migrate") {
1335
+ if (!home.app) return `This app has no database files (genesis.config.json "supabase": false), so no Supabase files are written or planned here.`;
1336
+ return `This app's database files live in ${home.app}/supabase (genesis.config.json supabase.app), so no Supabase files are written or planned here: run ${command} in ${home.app}.`;
1337
+ }
1338
+ function blocksMissingThere(home, ids, manifests) {
1339
+ const missing = migrationsMissingThere(home, ids, manifests);
1340
+ if (!missing) return null;
1341
+ return ids.filter((id) => missing.some((m) => m.block === id));
1342
+ }
1343
+ function migrationsMissingThere(home, ids, manifests) {
1344
+ if (!home.dir) return null;
1345
+ let copied;
1346
+ let app;
1347
+ try {
1348
+ copied = readLock(home.dir).migrations ?? {};
1349
+ app = readAppMigrations(home.dir);
1350
+ } catch {
1351
+ return null;
1352
+ }
1353
+ const has2 = (pkg, file) => {
1354
+ if (Object.hasOwn(copied, migrationKey(pkg, file))) return true;
1355
+ const stem = stemOrNull(file);
1356
+ return app.some((m) => !m.forward && (m.tracked ? m.tracked.package === pkg && m.tracked.file === file : stem !== null && m.name.replace(/^\d+_/, "") === `${stem}.sql`));
1357
+ };
1358
+ const providers = providingMigrations(manifests);
1359
+ const out = [];
1360
+ for (const id of ids) {
1361
+ const m = manifests.find((b) => b.id === id);
1362
+ if (!m) continue;
1363
+ const superseded = /* @__PURE__ */ new Set();
1364
+ for (const mig of m.migrations) {
1365
+ if (has2(mig.package, mig.file)) continue;
1366
+ const by = providers.find((p) => has2(p.package, p.file) && p.provides.some((x) => x.package === mig.package && x.file === mig.file));
1367
+ if (by) {
1368
+ for (const dir of by.provides.find((x) => x.package === mig.package && x.file === mig.file)?.functions ?? []) superseded.add(`${mig.package}:${dir}`);
1369
+ continue;
1370
+ }
1371
+ out.push({ block: id, what: `${mig.package} ${mig.file}`, kind: "migration" });
1372
+ }
1373
+ for (const fn of m.functions) {
1374
+ if (superseded.has(`${fn.package}:${fn.dir}`)) continue;
1375
+ if (!existsSync(path30.join(home.dir, "supabase", "functions", fn.dir.split("/").pop()))) out.push({ block: id, what: `${fn.package} ${fn.dir}`, kind: "function" });
1376
+ }
1377
+ }
1378
+ return out;
1379
+ }
1380
+ function orderForAdding(ids, manifests) {
1381
+ const byId = new Map(manifests.map((m) => [m.id, m]));
1382
+ const before = (id) => {
1383
+ const m = byId.get(id);
1384
+ if (!m) return [];
1385
+ const providers = manifests.filter((p) => p.id !== id && p.migrations.some((pm) => pm.provides?.some((x) => m.migrations.some((mm) => mm.package === x.package && mm.file === x.file))));
1386
+ return [...m.requires, ...providers.map((p) => p.id)].filter((x) => ids.includes(x));
1387
+ };
1388
+ const out = [];
1389
+ const visiting = /* @__PURE__ */ new Set();
1390
+ const visit = (id) => {
1391
+ if (out.includes(id) || visiting.has(id)) return;
1392
+ visiting.add(id);
1393
+ for (const b of before(id)) visit(b);
1394
+ out.push(id);
1395
+ };
1396
+ for (const id of ids) visit(id);
1397
+ return out;
1398
+ }
1399
+ function addThereCommand(id) {
1400
+ return `genesis add ${id} --database-only`;
1401
+ }
1402
+ function addThereLine(home, ids) {
1403
+ if (!home.app || !ids.length) return null;
1404
+ return `In ${home.app} (it holds this app's database), run: ${ids.map(addThereCommand).join(" && ")}`;
1405
+ }
1406
+ var init_database = __esm({
1407
+ "src/blocks/database.ts"() {
1408
+ init_config();
1409
+ init_lock();
1410
+ init_migrations();
1411
+ }
1412
+ });
1233
1413
  function findPackageDir(from, name) {
1234
- let dir = path29.resolve(from);
1414
+ let dir = path30.resolve(from);
1235
1415
  for (; ; ) {
1236
- const candidate = path29.join(dir, "node_modules", name);
1237
- if (existsSync(path29.join(candidate, "package.json"))) return candidate;
1238
- const parent = path29.dirname(dir);
1416
+ const candidate = path30.join(dir, "node_modules", name);
1417
+ if (existsSync(path30.join(candidate, "package.json"))) return candidate;
1418
+ const parent = path30.dirname(dir);
1239
1419
  if (parent === dir) return null;
1240
1420
  dir = parent;
1241
1421
  }
@@ -1287,7 +1467,7 @@ function loadCompanions(root, config, uiPackage) {
1287
1467
  function readPackageExports(root, uiPackage) {
1288
1468
  const uiDir = findPackageDir(root, uiPackage);
1289
1469
  if (!uiDir) return null;
1290
- const uiPkg = JSON.parse(readFileSync(path29.join(uiDir, "package.json"), "utf8"));
1470
+ const uiPkg = JSON.parse(readFileSync(path30.join(uiDir, "package.json"), "utf8"));
1291
1471
  const subpaths = Object.values(uiPkg.exports ?? {});
1292
1472
  const declared = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
1293
1473
  const fromSource = typeof declared !== "string" && !subpaths.some((t) => typeof exportTypes(t) === "string");
@@ -1314,23 +1494,23 @@ function readPackageExports(root, uiPackage) {
1314
1494
  }
1315
1495
  if (fromSource) {
1316
1496
  for (const m of code.matchAll(/export\s+\*\s+from\s*["'](\.[^"']*)["']/g)) {
1317
- const next = resolveSource(path29.dirname(file), m[1]);
1497
+ const next = resolveSource(path30.dirname(file), m[1]);
1318
1498
  if (next) readEntry(next);
1319
1499
  }
1320
1500
  }
1321
1501
  };
1322
- for (const entry of typeEntries) readEntry(path29.join(uiDir, entry));
1502
+ for (const entry of typeEntries) readEntry(path30.join(uiDir, entry));
1323
1503
  if (!readAny) {
1324
1504
  const what = fromSource ? "type declarations or TypeScript source" : "type declarations";
1325
1505
  throw new DoctorConfigError(`${uiPackage} has no ${what} to read (is it built?). Looked for: ${[...typeEntries].join(", ") || "none"}`);
1326
1506
  }
1327
1507
  const valueDecls = /* @__PURE__ */ new Set();
1328
1508
  const typeDecls = /* @__PURE__ */ new Set();
1329
- const declRoot = typeof mainTypes === "string" ? path29.dirname(path29.join(uiDir, mainTypes)) : uiDir;
1509
+ const declRoot = typeof mainTypes === "string" ? path30.dirname(path30.join(uiDir, mainTypes)) : uiDir;
1330
1510
  const declFiles = fromSource ? walkSource(declRoot) : walkDts(declRoot);
1331
1511
  for (const pkg of reexportedPackages) {
1332
1512
  const dir = findPackageDir(uiDir, pkg);
1333
- if (dir) walkDts(path29.join(dir, "dist"), declFiles);
1513
+ if (dir) walkDts(path30.join(dir, "dist"), declFiles);
1334
1514
  }
1335
1515
  for (const file of declFiles) {
1336
1516
  const text = readFileSync(file, "utf8");
@@ -1378,13 +1558,13 @@ function exportSource(target) {
1378
1558
  return void 0;
1379
1559
  }
1380
1560
  function resolveSource(dir, spec) {
1381
- const base = path29.resolve(dir, spec.replace(/\.js$/, ""));
1382
- const candidates = [base, ...[".ts", ".tsx", ".mts", ".cts"].map((e) => base + e), ...["index.ts", "index.tsx"].map((i) => path29.join(base, i))];
1561
+ const base = path30.resolve(dir, spec.replace(/\.js$/, ""));
1562
+ const candidates = [base, ...[".ts", ".tsx", ".mts", ".cts"].map((e) => base + e), ...["index.ts", "index.tsx"].map((i) => path30.join(base, i))];
1383
1563
  return candidates.find((f) => TS_SOURCE.test(f) && existsSync(f) && statSync(f).isFile()) ?? null;
1384
1564
  }
1385
1565
  function insidePackage(dir, file) {
1386
- const rel = path29.relative(path29.resolve(dir), path29.resolve(file));
1387
- return rel === "" || !rel.startsWith("..") && !path29.isAbsolute(rel);
1566
+ const rel = path30.relative(path30.resolve(dir), path30.resolve(file));
1567
+ return rel === "" || !rel.startsWith("..") && !path30.isAbsolute(rel);
1388
1568
  }
1389
1569
  function stripComments(code) {
1390
1570
  let out = "";
@@ -1420,7 +1600,7 @@ function walkSource(dir, out = []) {
1420
1600
  if (!existsSync(dir)) return out;
1421
1601
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1422
1602
  if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
1423
- const p = path29.join(dir, entry.name);
1603
+ const p = path30.join(dir, entry.name);
1424
1604
  if (entry.isDirectory()) walkSource(p, out);
1425
1605
  else if (isTsSource(entry.name) || /\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
1426
1606
  }
@@ -1440,7 +1620,7 @@ function walkDts(dir, out = []) {
1440
1620
  if (!existsSync(dir)) return out;
1441
1621
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1442
1622
  if (entry.name === "node_modules") continue;
1443
- const p = path29.join(dir, entry.name);
1623
+ const p = path30.join(dir, entry.name);
1444
1624
  if (entry.isDirectory()) walkDts(p, out);
1445
1625
  else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
1446
1626
  }
@@ -1457,27 +1637,27 @@ function resolveThemeFiles(root, config, uiDir) {
1457
1637
  }
1458
1638
  const files = [];
1459
1639
  const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
1460
- const themes = ds && path29.join(ds, "dist", "themes");
1640
+ const themes = ds && path30.join(ds, "dist", "themes");
1461
1641
  if (themes && existsSync(themes)) {
1462
- for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path29.join(themes, name));
1642
+ for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path30.join(themes, name));
1463
1643
  }
1464
1644
  if (files.length === 0) {
1465
1645
  throw new DoctorConfigError(
1466
1646
  `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
1467
1647
  );
1468
1648
  }
1469
- const uiStyles = path29.join(uiDir, "dist", "styles.css");
1649
+ const uiStyles = path30.join(uiDir, "dist", "styles.css");
1470
1650
  if (existsSync(uiStyles)) files.push(uiStyles);
1471
1651
  return files;
1472
1652
  }
1473
1653
  function resolveSpec(root, spec) {
1474
- const local = path29.resolve(root, spec);
1475
- if (spec.startsWith(".") || path29.isAbsolute(spec)) return existsSync(local) ? local : null;
1654
+ const local = path30.resolve(root, spec);
1655
+ if (spec.startsWith(".") || path30.isAbsolute(spec)) return existsSync(local) ? local : null;
1476
1656
  const parts = spec.split("/");
1477
1657
  const nameLength = spec.startsWith("@") ? 2 : 1;
1478
1658
  const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
1479
1659
  if (dir) {
1480
- const file = path29.join(dir, ...parts.slice(nameLength));
1660
+ const file = path30.join(dir, ...parts.slice(nameLength));
1481
1661
  if (existsSync(file) && statSync(file).isFile()) return file;
1482
1662
  }
1483
1663
  return existsSync(local) ? local : null;
@@ -1485,7 +1665,7 @@ function resolveSpec(root, spec) {
1485
1665
  function loadPalette(root) {
1486
1666
  const names = new Set(TAILWIND_PALETTE);
1487
1667
  try {
1488
- const req = createRequire(path29.join(root, "package.json"));
1668
+ const req = createRequire(path30.join(root, "package.json"));
1489
1669
  const colors = req("tailwindcss/colors");
1490
1670
  for (const key2 of Object.keys(colors?.default ?? colors ?? {})) {
1491
1671
  if (/^[a-z]+$/.test(key2) && !["inherit", "current", "transparent"].includes(key2)) names.add(key2);
@@ -1730,7 +1910,7 @@ function globToRegExp(glob) {
1730
1910
  }
1731
1911
  function globMatcher(globs) {
1732
1912
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1733
- return (path51) => res.some((re) => re.test(path51));
1913
+ return (path53) => res.some((re) => re.test(path53));
1734
1914
  }
1735
1915
  var init_glob = __esm({
1736
1916
  "src/doctor/glob.ts"() {
@@ -1742,9 +1922,9 @@ function scanFiles(root, config) {
1742
1922
  const files = [];
1743
1923
  const seen = /* @__PURE__ */ new Set();
1744
1924
  const visit = (abs) => {
1745
- const rel = toPosix(path29.relative(root, abs));
1925
+ const rel = toPosix(path30.relative(root, abs));
1746
1926
  if (seen.has(rel) || ignored(rel)) return;
1747
- const ext = path29.extname(abs);
1927
+ const ext = path30.extname(abs);
1748
1928
  if (!extensions.has(ext)) return;
1749
1929
  if (statSync(abs).size > MAX_FILE_BYTES) return;
1750
1930
  seen.add(rel);
@@ -1754,14 +1934,14 @@ function scanFiles(root, config) {
1754
1934
  const walk3 = (dir) => {
1755
1935
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1756
1936
  if (entry.isDirectory()) {
1757
- if (!SKIP_DIRS.has(entry.name)) walk3(path29.join(dir, entry.name));
1937
+ if (!SKIP_DIRS.has(entry.name)) walk3(path30.join(dir, entry.name));
1758
1938
  } else if (entry.isFile()) {
1759
- visit(path29.join(dir, entry.name));
1939
+ visit(path30.join(dir, entry.name));
1760
1940
  }
1761
1941
  }
1762
1942
  };
1763
1943
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
1764
- const abs = path29.resolve(root, src);
1944
+ const abs = path30.resolve(root, src);
1765
1945
  if (!existsSync(abs)) continue;
1766
1946
  if (statSync(abs).isDirectory()) walk3(abs);
1767
1947
  else visit(abs);
@@ -1800,7 +1980,7 @@ var init_scan = __esm({
1800
1980
  ];
1801
1981
  SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
1802
1982
  MAX_FILE_BYTES = 2 * 1024 * 1024;
1803
- toPosix = (p) => p.split(path29.sep).join("/");
1983
+ toPosix = (p) => p.split(path30.sep).join("/");
1804
1984
  }
1805
1985
  });
1806
1986
 
@@ -1938,7 +2118,7 @@ function overlayState(name, json) {
1938
2118
  function overlaySetupProblems(root, config, dir, name, json) {
1939
2119
  const problems = [];
1940
2120
  if (json.private !== true) problems.push(`${name}: an overlay is the app's own copy and never publishes; set "private": true`);
1941
- const rel = path29.relative(path29.resolve(root), path29.resolve(dir)).split(path29.sep).join("/");
2121
+ const rel = path30.relative(path30.resolve(root), path30.resolve(dir)).split(path30.sep).join("/");
1942
2122
  const sources = (config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)).map((s) => s.replace(/^\.\//, "").replace(/\/+$/, ""));
1943
2123
  const holds = sources.find((s) => rel === "" || s === rel || s.startsWith(`${rel}/`));
1944
2124
  if (holds !== void 0) problems.push(`${name}: an overlay lives in a package folder of its own, not in ${rel || "the app root"}, which holds the app's source (${holds})`);
@@ -1974,7 +2154,7 @@ function pinnedVersion(root, name, manifests = ["package.json"]) {
1974
2154
  for (const file of manifests) {
1975
2155
  let json;
1976
2156
  try {
1977
- json = JSON.parse(readFileSync(path29.join(root, file), "utf8"));
2157
+ json = JSON.parse(readFileSync(path30.join(root, file), "utf8"));
1978
2158
  } catch {
1979
2159
  continue;
1980
2160
  }
@@ -1999,7 +2179,7 @@ function checkOverlays(ctx, now = /* @__PURE__ */ new Date()) {
1999
2179
  const file = `${pkg.rel}/package.json`;
2000
2180
  let json;
2001
2181
  try {
2002
- json = JSON.parse(readFileSync(path29.join(pkg.dir, "package.json"), "utf8"));
2182
+ json = JSON.parse(readFileSync(path30.join(pkg.dir, "package.json"), "utf8"));
2003
2183
  } catch {
2004
2184
  continue;
2005
2185
  }
@@ -2072,7 +2252,7 @@ var init_overlays = __esm({
2072
2252
  });
2073
2253
  function readReleaseManifest(root) {
2074
2254
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
2075
- const file = dir && path29.join(dir, "dist", "versions.json");
2255
+ const file = dir && path30.join(dir, "dist", "versions.json");
2076
2256
  if (!file || !existsSync(file)) return null;
2077
2257
  return JSON.parse(readFileSync(file, "utf8"));
2078
2258
  }
@@ -2098,7 +2278,7 @@ function checkVersionSkew(ctx) {
2098
2278
  }
2099
2279
  const dir = findPackageDir(ctx.root, name);
2100
2280
  if (!dir) continue;
2101
- const have = JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8")).version;
2281
+ const have = JSON.parse(readFileSync(path30.join(dir, "package.json"), "utf8")).version;
2102
2282
  if (have === want) continue;
2103
2283
  ctx.report({
2104
2284
  rule: "version-skew",
@@ -2119,13 +2299,13 @@ var init_versions = __esm({
2119
2299
  }
2120
2300
  });
2121
2301
  function findLockfile(root) {
2122
- let dir = path29.resolve(root);
2302
+ let dir = path30.resolve(root);
2123
2303
  for (; ; ) {
2124
- if (existsSync(path29.join(dir, "pnpm-lock.yaml"))) return { pm: "pnpm", dir };
2125
- if (existsSync(path29.join(dir, "bun.lock")) || existsSync(path29.join(dir, "bun.lockb"))) return { pm: "bun", dir };
2126
- if (existsSync(path29.join(dir, "yarn.lock"))) return { pm: "yarn", dir };
2127
- if (existsSync(path29.join(dir, "package-lock.json"))) return { pm: "npm", dir };
2128
- const parent = path29.dirname(dir);
2304
+ if (existsSync(path30.join(dir, "pnpm-lock.yaml"))) return { pm: "pnpm", dir };
2305
+ if (existsSync(path30.join(dir, "bun.lock")) || existsSync(path30.join(dir, "bun.lockb"))) return { pm: "bun", dir };
2306
+ if (existsSync(path30.join(dir, "yarn.lock"))) return { pm: "yarn", dir };
2307
+ if (existsSync(path30.join(dir, "package-lock.json"))) return { pm: "npm", dir };
2308
+ const parent = path30.dirname(dir);
2129
2309
  if (parent === dir) return null;
2130
2310
  dir = parent;
2131
2311
  }
@@ -2169,10 +2349,10 @@ var init_pm = __esm({
2169
2349
  function walk(dir, exclude = []) {
2170
2350
  const out = [];
2171
2351
  const visit = (rel) => {
2172
- for (const name of readdirSync(path29.join(dir, rel)).sort()) {
2352
+ for (const name of readdirSync(path30.join(dir, rel)).sort()) {
2173
2353
  const child = rel ? `${rel}/${name}` : name;
2174
2354
  if (exclude.some((r) => r.test(child))) continue;
2175
- const stat = statSync(path29.join(dir, child));
2355
+ const stat = statSync(path30.join(dir, child));
2176
2356
  if (stat.isDirectory()) visit(child);
2177
2357
  else if (stat.isFile()) out.push(child);
2178
2358
  }
@@ -2201,17 +2381,17 @@ var init_walk = __esm({
2201
2381
  });
2202
2382
  function starterDir() {
2203
2383
  const workspace = workspacePackagesDir();
2204
- const live = workspace && path29.join(workspace, "..", "apps", "genesis-rn-starter");
2205
- if (live && existsSync(path29.join(live, "package.json"))) return live;
2206
- const packaged = path29.join(cliPackageDir(), "dist", "starter");
2207
- if (existsSync(path29.join(packaged, "package.json"))) return packaged;
2384
+ const live = workspace && path30.join(workspace, "..", "apps", "genesis-rn-starter");
2385
+ if (live && existsSync(path30.join(live, "package.json"))) return live;
2386
+ const packaged = path30.join(cliPackageDir(), "dist", "starter");
2387
+ if (existsSync(path30.join(packaged, "package.json"))) return packaged;
2208
2388
  throw new Error("This genesis-cli has no starter (dist/starter is missing): reinstall @marktiderman/genesis-cli.");
2209
2389
  }
2210
2390
  function templatesDir(cliDir = cliPackageDir()) {
2211
2391
  const workspace = workspacePackagesDir();
2212
- const live = workspace && cliDir === cliPackageDir() ? path29.join(workspace, "..", "templates") : null;
2213
- if (live && existsSync(path29.join(live, "eas"))) return live;
2214
- const packaged = path29.join(cliDir, "dist", "templates");
2392
+ const live = workspace && cliDir === cliPackageDir() ? path30.join(workspace, "..", "templates") : null;
2393
+ if (live && existsSync(path30.join(live, "eas"))) return live;
2394
+ const packaged = path30.join(cliDir, "dist", "templates");
2215
2395
  if (existsSync(packaged)) return packaged;
2216
2396
  throw new Error(`${cliDir} has no templates (dist/templates is missing).`);
2217
2397
  }
@@ -2236,8 +2416,25 @@ function featuresBody(text) {
2236
2416
  const m = /\bfeatures:\s*\{/.exec(text);
2237
2417
  if (!m) return null;
2238
2418
  const start = m.index + m[0].length;
2239
- const end = text.indexOf("}", start);
2240
- return end < 0 ? null : { start, body: text.slice(start, end) };
2419
+ let depth = 1;
2420
+ for (let i = start; i < text.length; i++) {
2421
+ const c = text[i];
2422
+ if (c === "/" && text[i + 1] === "/") {
2423
+ const nl = text.indexOf("\n", i);
2424
+ if (nl < 0) return null;
2425
+ i = nl;
2426
+ } else if (c === "/" && text[i + 1] === "*") {
2427
+ const close = text.indexOf("*/", i + 2);
2428
+ if (close < 0) return null;
2429
+ i = close + 1;
2430
+ } else if (c === '"' || c === "'" || c === "`") {
2431
+ let j = i + 1;
2432
+ while (j < text.length && text[j] !== c) j += text[j] === "\\" ? 2 : 1;
2433
+ i = j;
2434
+ } else if (c === "{") depth++;
2435
+ else if (c === "}" && --depth === 0) return { start, body: text.slice(start, i) };
2436
+ }
2437
+ return null;
2241
2438
  }
2242
2439
  function parseStarterFeatures(text) {
2243
2440
  const found = featuresBody(text);
@@ -2270,6 +2467,7 @@ function parseStarterBlocks(json, source = GENESIS_CONFIG) {
2270
2467
  const starter = raw?.starter;
2271
2468
  if (starter === void 0) return null;
2272
2469
  const blocks = starter?.blocks;
2470
+ if (blocks === void 0 && typeof starter === "object" && starter !== null && !Array.isArray(starter)) return null;
2273
2471
  if (typeof blocks !== "object" || blocks === null || Array.isArray(blocks)) throw new Error(`${source}: starter.blocks must map each feature switch to a list of block ids`);
2274
2472
  const out = {};
2275
2473
  for (const [name, ids] of Object.entries(blocks)) {
@@ -2290,7 +2488,7 @@ function readText(file) {
2290
2488
  }
2291
2489
  function starterBlockMap(root) {
2292
2490
  if (root) {
2293
- const file = path29.join(root, GENESIS_CONFIG);
2491
+ const file = path30.join(root, GENESIS_CONFIG);
2294
2492
  const text2 = readText(file);
2295
2493
  const own = text2 === null ? null : parseStarterBlocks(text2, file);
2296
2494
  if (own) return own;
@@ -2301,7 +2499,7 @@ function starterBlockMap(root) {
2301
2499
  } catch {
2302
2500
  return {};
2303
2501
  }
2304
- const text = readText(path29.join(dir, GENESIS_CONFIG));
2502
+ const text = readText(path30.join(dir, GENESIS_CONFIG));
2305
2503
  return (text === null ? null : parseStarterBlocks(text)) ?? {};
2306
2504
  }
2307
2505
  function blocksSwitchedOff(switches, map, manifests, present) {
@@ -2321,10 +2519,10 @@ function blocksSwitchedOff(switches, map, manifests, present) {
2321
2519
  return off;
2322
2520
  }
2323
2521
  function appBlocksSwitchedOff(root, manifests, present) {
2324
- const text = readText(path29.join(root, STARTER_CONFIG));
2522
+ const text = readText(path30.join(root, STARTER_CONFIG));
2325
2523
  const switches = text === null ? null : parseStarterFeatures(text);
2326
2524
  if (!switches) return /* @__PURE__ */ new Map();
2327
- return blocksSwitchedOff(switches, starterBlockMap(existsSync(path29.join(root, GENESIS_CONFIG)) ? root : void 0), manifests, present);
2525
+ return blocksSwitchedOff(switches, starterBlockMap(existsSync(path30.join(root, GENESIS_CONFIG)) ? root : void 0), manifests, present);
2328
2526
  }
2329
2527
  function switchedOffNote(id, feature) {
2330
2528
  return `${id}: features.${feature} is off in ${STARTER_CONFIG}, so it's left out (turn it on to have it again)`;
@@ -2375,7 +2573,7 @@ var init_eas_placeholders = __esm({
2375
2573
  EAS_PLACEHOLDERS = {
2376
2574
  REPLACE_WITH_APP_STORE_CONNECT_APP_ID: "the app's Apple ID from App Store Connect (create the app there, then App Information \u2192 General Information \u2192 Apple ID, a number)",
2377
2575
  REPLACE_WITH_APPLE_TEAM_ID: "your Apple Developer Team ID (developer.apple.com \u2192 Account \u2192 Membership details, 10 characters)",
2378
- REPLACE_WITH_PATH_TO_GOOGLE_SERVICE_ACCOUNT_JSON: "the path to your Google Play service account key, a JSON file kept out of git (Play Console \u2192 Setup \u2192 API access); or delete submit.production.android until you ship to Google Play",
2576
+ REPLACE_WITH_PATH_TO_GOOGLE_SERVICE_ACCOUNT_JSON: "the Google Play service account key uploaded to EAS, not a local path (deploy-production.yml submits on EAS, where a local file isn't there): create a Google Cloud service account and its JSON key, invite it in Play Console \u2192 Users and permissions, upload the key with `eas credentials` (Android \u2192 Google Service Account), then remove only this serviceAccountKeyPath line (https://docs.expo.dev/submit/android/). Until you ship to Google Play, remove the submit_android job from deploy-production.yml instead, and keep submit.production.android as it is (the internal track, as a draft)",
2379
2577
  REPLACE_WITH_APP_FOLDER: "the app's code folder (src, or apps/<name> in a monorepo)"
2380
2578
  };
2381
2579
  }
@@ -2385,7 +2583,9 @@ var init_eas_placeholders = __esm({
2385
2583
  var init_native_exports = {};
2386
2584
  __export(init_native_exports, {
2387
2585
  APP_FOLDER_PLACEHOLDER: () => APP_FOLDER_PLACEHOLDER,
2586
+ DATABASE_TEMPLATES: () => DATABASE_TEMPLATES,
2388
2587
  appPnpmSettings: () => appPnpmSettings,
2588
+ besideConfig: () => besideConfig,
2389
2589
  initNative: () => initNative,
2390
2590
  runInitNative: () => runInitNative,
2391
2591
  starterIdentity: () => starterIdentity
@@ -2414,14 +2614,15 @@ function appPnpmSettings(text) {
2414
2614
  return `# pnpm settings for this app, from the Genesis monorepo it was made from.
2415
2615
  ${out.join("\n").replace(/^\n+/, "")}`;
2416
2616
  }
2417
- function readme(display, slug) {
2617
+ function readme(display, slug, database) {
2618
+ const apply = database ? `The database is ${database}'s: this app has no supabase/ folder. Add blocks' database files there (\`genesis add <block>\` in ${database}) and apply its migrations from there.` : `Apply \`supabase/migrations\` (\`supabase db push\`, or \`supabase start\` for a local stack).`;
2418
2619
  return `# ${display}
2419
2620
 
2420
2621
  An Expo app made with \`genesis init ${slug} --template native\` from the Genesis RN starter.
2421
2622
 
2422
- 1. \`cp .env.example .env\` and fill in your Supabase project's URL and publishable key.
2623
+ 1. \`cp .env.example .env\` and fill in your Supabase project's URL and publishable key${database ? ` (${database}'s project)` : ""}.
2423
2624
  2. Install: \`pnpm install\` (or your package manager).
2424
- 3. Apply \`supabase/migrations\` (\`supabase db push\`, or \`supabase start\` for a local stack).
2625
+ 3. ${apply}
2425
2626
  4. \`pnpm ios\` or \`pnpm android\`.
2426
2627
 
2427
2628
  - Turn features off in \`starter.config.ts\`.
@@ -2441,10 +2642,18 @@ function initNative(options) {
2441
2642
  if (!BUNDLE.test(bundleId)) throw new Error(`"${bundleId}" isn't a bundle id like com.example.app.`);
2442
2643
  if (!SCHEME.test(scheme)) throw new Error(`"${scheme}" isn't a URL scheme.`);
2443
2644
  if (/["\\\n]/.test(display)) throw new Error("The display name can't contain quotes, backslashes or new lines.");
2444
- const target = path29.resolve(options.target);
2645
+ const target = path30.resolve(options.target);
2445
2646
  if (existsSync(target) && readdirSync(target).length) throw new Error(`${target} isn't empty; init writes into a new folder and never overwrites.`);
2647
+ let beside;
2648
+ if (options.beside !== void 0) {
2649
+ const dir = path30.resolve(options.beside);
2650
+ if (!existsSync(dir)) throw new Error(`--beside: ${options.beside} doesn't exist; name the web app's folder.`);
2651
+ if (dir === target) throw new Error("--beside names the new app's own folder; name the web app's folder.");
2652
+ beside = { dir, app: path30.relative(target, dir).split(path30.sep).join("/"), shared: existsSync(path30.join(dir, "supabase")) };
2653
+ }
2654
+ const shared = beside?.shared === true;
2446
2655
  const source = starterDir();
2447
- const read2 = (rel) => readFileSync(path29.join(source, rel), "utf8");
2656
+ const read2 = (rel) => readFileSync(path30.join(source, rel), "utf8");
2448
2657
  const was = starterIdentity(read2(STARTER_CONFIG));
2449
2658
  const switches = parseStarterFeatures(read2(STARTER_CONFIG)) ?? {};
2450
2659
  const without = [...new Set(options.without ?? [])];
@@ -2487,22 +2696,28 @@ function initNative(options) {
2487
2696
  files.set("package.json", `${JSON.stringify(pkg, null, 2)}
2488
2697
  `);
2489
2698
  files.set("metro.config.js", METRO);
2490
- const pnpmSettings = [path29.join(source, "pnpm-workspace.yaml"), path29.join(source, "..", "..", "pnpm-workspace.yaml")].find((f) => existsSync(f));
2699
+ const pnpmSettings = [path30.join(source, "pnpm-workspace.yaml"), path30.join(source, "..", "..", "pnpm-workspace.yaml")].find((f) => existsSync(f));
2491
2700
  if (pnpmSettings) files.set("pnpm-workspace.yaml", appPnpmSettings(readFileSync(pnpmSettings, "utf8")));
2492
- files.set("README.md", readme(display, slug));
2701
+ files.set("README.md", readme(display, slug, shared ? beside.app : void 0));
2493
2702
  if (without.length) files.set(STARTER_CONFIG, setStarterFeatures(files.get(STARTER_CONFIG), Object.fromEntries(without.map((w) => [w, false]))));
2494
2703
  const carried = options.blocks.filter((b) => carriedBy(files, b)).map((b) => b.id);
2495
2704
  const switchedOff = blocksSwitchedOff(features2, parseStarterBlocks(read2("genesis.config.json")) ?? {}, options.blocks, carried);
2496
2705
  const leftOut = options.blocks.filter((b) => switchedOff.has(b.id)).map((b) => b.id);
2497
2706
  if (leftOut.length) leaveOut(files, options.blocks.filter((b) => switchedOff.has(b.id)));
2498
- const since = sinceAfter(files);
2499
- const config = files.get("genesis.config.json");
2500
- if (since && config && !/"since"\s*:/.test(config)) files.set("genesis.config.json", config.replace(/("supabase"\s*:\s*\{[^}]*?)(\s*\})/, `$1, "since": "${since}"$2`));
2707
+ if (shared) {
2708
+ for (const rel of [...files.keys()]) if (isSupabasePath(rel)) files.delete(rel);
2709
+ files.set("genesis.config.json", besideConfig(files.get("genesis.config.json"), beside.app));
2710
+ } else {
2711
+ const since = sinceAfter(files);
2712
+ const config = files.get("genesis.config.json");
2713
+ if (since && config && !/"since"\s*:/.test(config)) files.set("genesis.config.json", config.replace(/("supabase"\s*:\s*\{[^}]*?)(\s*\})/, `$1, "since": "${since}"$2`));
2714
+ }
2501
2715
  const lock = { ...emptyLock(), substitutions };
2502
2716
  const cliVersion2 = pinnedVersion2(target, CLI_PACKAGE)?.version;
2503
2717
  const templates = templatesDir();
2504
2718
  for (const rel of walk(templates)) {
2505
- const text = substitute(readFileSync(path29.join(templates, rel), "utf8"), substitutions);
2719
+ if (shared && DATABASE_TEMPLATES.has(rel)) continue;
2720
+ const text = substitute(readFileSync(path30.join(templates, rel), "utf8"), substitutions);
2506
2721
  const to = templateTarget(rel, text);
2507
2722
  files.set(to, text);
2508
2723
  lock.files[to] = { source: `${CLI_PACKAGE}:templates/${rel}`, sha256: sha256(text), ...cliVersion2 ? { version: cliVersion2 } : {} };
@@ -2513,15 +2728,22 @@ function initNative(options) {
2513
2728
  const blocks = [];
2514
2729
  for (const block of options.blocks) {
2515
2730
  if (switchedOff.has(block.id)) continue;
2731
+ if (shared) {
2732
+ if (carried.includes(block.id)) {
2733
+ blocks.push(block.id);
2734
+ lock.blocks[block.id] = { package: block.package, ...block.version ? { version: block.version } : {} };
2735
+ }
2736
+ continue;
2737
+ }
2516
2738
  const stems = block.migrations.map((m) => stemOf(m.file));
2517
- const copies = stems.map((s) => migrations.find((f) => path29.posix.basename(f).replace(/^\d+_/, "") === `${s}.sql`));
2739
+ const copies = stems.map((s) => migrations.find((f) => path30.posix.basename(f).replace(/^\d+_/, "") === `${s}.sql`));
2518
2740
  if (!stems.length || copies.some((c) => !c)) continue;
2519
2741
  blocks.push(block.id);
2520
2742
  lock.blocks[block.id] = { package: block.package, ...block.version ? { version: block.version } : {} };
2521
2743
  block.migrations.forEach((m, i) => {
2522
2744
  lock.migrations = { ...lock.migrations, [migrationKey(m.package, m.file)]: copies[i] };
2523
2745
  if (m.test) {
2524
- const test2 = `${TESTS_DIR}/${path29.posix.basename(m.test).replace(/^\d{4}_/, "")}`;
2746
+ const test2 = `${TESTS_DIR}/${path30.posix.basename(m.test).replace(/^\d{4}_/, "")}`;
2525
2747
  if (files.has(test2)) lock.files[test2] = { source: `${m.package}:${m.test}`, sha256: sha256(files.get(test2)) };
2526
2748
  }
2527
2749
  });
@@ -2534,8 +2756,8 @@ function initNative(options) {
2534
2756
  }
2535
2757
  mkdirSync(target, { recursive: true });
2536
2758
  for (const [rel, content] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
2537
- const file = path29.join(target, ...rel.split("/"));
2538
- mkdirSync(path29.dirname(file), { recursive: true });
2759
+ const file = path30.join(target, ...rel.split("/"));
2760
+ mkdirSync(path30.dirname(file), { recursive: true });
2539
2761
  writeFileSync(file, content, { encoding: "utf8", flag: "wx" });
2540
2762
  }
2541
2763
  writeLock(target, lock);
@@ -2545,17 +2767,40 @@ function initNative(options) {
2545
2767
  "Set links.hosts in genesis.config.json to your web domain, or delete the links block (no app links then).",
2546
2768
  ...[...files].flatMap(([rel, text]) => rel === "eas.json" || rel.startsWith(".eas/") ? findPlaceholders(rel, text).map((p) => placeholderStep(rel, p.text, p.placeholder)) : [])
2547
2769
  );
2548
- return { target, files: [...files.keys(), "genesis.lock.json"].sort(), dependencies: dependencies2, unpinned, blocks, leftOut, steps };
2770
+ let besideResult;
2771
+ if (beside) {
2772
+ const home = { app: beside.app, dir: beside.dir, hasSupabase: beside.shared };
2773
+ const missing = shared ? orderForAdding(blocksMissingThere(home, blocks, options.blocks) ?? blocks, options.blocks) : [];
2774
+ const line = !shared ? `${beside.app} has no supabase folder, so this app keeps its own supabase/ (as without --beside).` : addThereLine(home, missing) ?? `${beside.app} already has the database side of every block this app uses (${blocks.join(", ") || "none"}).`;
2775
+ besideResult = { app: beside.app, shared, missing, line };
2776
+ steps.unshift(line);
2777
+ }
2778
+ return { target, files: [...files.keys(), "genesis.lock.json"].sort(), dependencies: dependencies2, unpinned, blocks, leftOut, steps, ...besideResult ? { beside: besideResult } : {} };
2549
2779
  }
2550
2780
  }
2781
+ function besideConfig(text, app) {
2782
+ const json = JSON.parse(text);
2783
+ const out = {};
2784
+ for (const [key2, value] of Object.entries(json)) {
2785
+ if (key2 === "doctor" && value && typeof value === "object") {
2786
+ const { supabase: _settings, contracts: _contracts, ...rest } = value;
2787
+ if (Array.isArray(rest.packs)) rest.packs = rest.packs.filter((p) => p !== "supabase");
2788
+ out[key2] = rest;
2789
+ } else out[key2] = value;
2790
+ if (key2 === "doctor") out["supabase"] = { $comment: "This app has no supabase/ folder: its database files (migrations, pgTAP tests, Edge Functions) are in the supabase/ folder of the app named here. Run genesis add and migrate there.", app };
2791
+ }
2792
+ if (!("supabase" in out)) out["supabase"] = { app };
2793
+ return `${JSON.stringify(out, null, 2)}
2794
+ `;
2795
+ }
2551
2796
  function carriedBy(files, block) {
2552
- const names = [...files.keys()].filter((f) => f.startsWith(`${MIGRATIONS_DIR}/`) && f.endsWith(".sql")).map((f) => path29.posix.basename(f).replace(/^\d+_/, ""));
2797
+ const names = [...files.keys()].filter((f) => f.startsWith(`${MIGRATIONS_DIR}/`) && f.endsWith(".sql")).map((f) => path30.posix.basename(f).replace(/^\d+_/, ""));
2553
2798
  return block.migrations.length > 0 && block.migrations.every((m) => names.includes(`${stemOf(m.file)}.sql`));
2554
2799
  }
2555
2800
  function sinceAfter(files) {
2556
- const versions = [...files.keys()].filter((f) => f.startsWith(`${MIGRATIONS_DIR}/`) && f.endsWith(".sql")).map((f) => /^(\d{14})_/.exec(path29.posix.basename(f))?.[1]).filter((v) => Boolean(v)).sort();
2801
+ const versions = [...files.keys()].filter((f) => f.startsWith(`${MIGRATIONS_DIR}/`) && f.endsWith(".sql")).map((f) => /^(\d{14})_/.exec(path30.posix.basename(f))?.[1]).filter((v) => Boolean(v)).sort();
2557
2802
  const last = versions.at(-1);
2558
- return last ? String(BigInt(last) + 1n).padStart(14, "0") : null;
2803
+ return last ? nextStamp(last) : null;
2559
2804
  }
2560
2805
  function featTags(text) {
2561
2806
  return [...(text.split("\n", 1)[0] ?? "").matchAll(/@feat:([a-z0-9][a-z0-9-]*)/g)].map((m) => m[1]);
@@ -2568,12 +2813,12 @@ function leaveOut(files, blocks) {
2568
2813
  for (const block of blocks) {
2569
2814
  for (const m of block.migrations) {
2570
2815
  const stem = stemOf(m.file);
2571
- for (const copy of migrations.filter((f) => path29.posix.basename(f).replace(/^\d+_/, "") === `${stem}.sql`)) {
2816
+ for (const copy of migrations.filter((f) => path30.posix.basename(f).replace(/^\d+_/, "") === `${stem}.sql`)) {
2572
2817
  for (const s of files.get(copy).matchAll(/\bcreate\s+schema\s+(?:if\s+not\s+exists\s+)?"?([a-z_][a-z0-9_]*)"?/gi)) schemas.add(s[1].toLowerCase());
2573
2818
  files.delete(copy);
2574
2819
  }
2575
2820
  files.delete(`${TESTS_DIR}/${stem}.test.sql`);
2576
- if (m.test) files.delete(`${TESTS_DIR}/${path29.posix.basename(m.test).replace(/^\d{4}_/, "")}`);
2821
+ if (m.test) files.delete(`${TESTS_DIR}/${path30.posix.basename(m.test).replace(/^\d{4}_/, "")}`);
2577
2822
  }
2578
2823
  for (const fn of block.functions) {
2579
2824
  const name = fn.dir.split("/").pop();
@@ -2615,18 +2860,20 @@ function leaveOut(files, blocks) {
2615
2860
  async function runInitNative(options) {
2616
2861
  return initNative({ ...options, blocks: catalogBlocks() });
2617
2862
  }
2618
- var APP_FOLDER_PLACEHOLDER, SLUG, BUNDLE, SCHEME, METRO;
2863
+ var DATABASE_TEMPLATES, APP_FOLDER_PLACEHOLDER, SLUG, BUNDLE, SCHEME, METRO;
2619
2864
  var init_init_native = __esm({
2620
2865
  "src/blocks/init-native.ts"() {
2621
2866
  init_discover();
2622
2867
  init_files();
2623
2868
  init_lock();
2624
2869
  init_migrations();
2870
+ init_database();
2625
2871
  init_pm();
2626
2872
  init_starter_features();
2627
2873
  init_eas_placeholders();
2628
2874
  init_templates();
2629
2875
  init_walk();
2876
+ DATABASE_TEMPLATES = /* @__PURE__ */ new Set(["ci/supabase-ci.yml"]);
2630
2877
  APP_FOLDER_PLACEHOLDER = "REPLACE_WITH_APP_FOLDER";
2631
2878
  SLUG = /^[a-z][a-z0-9-]{1,40}$/;
2632
2879
  BUNDLE = /^[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)+$/;
@@ -3077,14 +3324,14 @@ function inherit(own, source) {
3077
3324
  }
3078
3325
  function resolveViews(relations) {
3079
3326
  const done = /* @__PURE__ */ new Set();
3080
- const resolve26 = (relation, depth) => {
3327
+ const resolve27 = (relation, depth) => {
3081
3328
  if (done.has(relation.oid) || !relation.origins || depth > MAX_VIEW_DEPTH) return;
3082
3329
  done.add(relation.oid);
3083
3330
  const sources = new Set([...relation.origins.values()].map((o) => o.relation));
3084
3331
  if (sources.size !== 1) return;
3085
3332
  const source = relations.get([...sources][0]);
3086
3333
  if (!source) return;
3087
- resolve26(source, depth + 1);
3334
+ resolve27(source, depth + 1);
3088
3335
  const viewAttnumOf = /* @__PURE__ */ new Map();
3089
3336
  for (const [attnum, origin] of relation.origins) {
3090
3337
  const own = relation.columns.get(attnum);
@@ -3107,7 +3354,7 @@ function resolveViews(relations) {
3107
3354
  };
3108
3355
  if (Object.keys(inherited).length) relation.table.settings = { ...inherited, ...relation.table.settings };
3109
3356
  };
3110
- for (const relation of relations.values()) resolve26(relation, 0);
3357
+ for (const relation of relations.values()) resolve27(relation, 0);
3111
3358
  }
3112
3359
  async function introspectPostgres(sql, schemas, options = {}) {
3113
3360
  const relations = /* @__PURE__ */ new Map();
@@ -3379,7 +3626,7 @@ async function checkContracts(ctx, read2 = postgresContract) {
3379
3626
  const env = settings2.databaseEnv ?? DEFAULT_DATABASE_ENV;
3380
3627
  let current = null;
3381
3628
  try {
3382
- current = lf(readFileSync(path29.join(ctx.root, out), "utf8"));
3629
+ current = lf(readFileSync(path30.join(ctx.root, out), "utf8"));
3383
3630
  } catch {
3384
3631
  current = null;
3385
3632
  }
@@ -3403,7 +3650,7 @@ async function checkContracts(ctx, read2 = postgresContract) {
3403
3650
  ctx.report({ rule: "contracts-stale", level: generation ? "error" : "warn", file: out, message: generation ? `couldn't be generated: ${message}` : `couldn't read the database through ${env}: ${message}` });
3404
3651
  return;
3405
3652
  }
3406
- const target = path29.relative(process.cwd(), path29.join(ctx.root, out)) || out;
3653
+ const target = path30.relative(process.cwd(), path30.join(ctx.root, out)) || out;
3407
3654
  const command = `genesis introspect -o ${shellArg(target)} -s ${shellArg(schemas.join(","))}${env === DEFAULT_DATABASE_ENV ? "" : ` --database-env ${shellArg(env)}`}`;
3408
3655
  if (current !== expected) {
3409
3656
  ctx.report({
@@ -3431,7 +3678,7 @@ __export(settings_exports, {
3431
3678
  });
3432
3679
  function introspectSettings(flags, root, contracts, readCurrent = () => null) {
3433
3680
  const out = flags.out ?? contracts?.out ?? DEFAULT_CONTRACT_OUT;
3434
- const target = path29.resolve(root, out);
3681
+ const target = path30.resolve(root, out);
3435
3682
  return { target, label: out, schemas: schemasFor(flags, target, contracts, readCurrent), databaseEnv: flags.databaseEnv ?? contracts?.databaseEnv ?? DEFAULT_DATABASE_ENV };
3436
3683
  }
3437
3684
  function schemasFor(flags, target, contracts, readCurrent) {
@@ -3447,19 +3694,19 @@ var init_settings = __esm({
3447
3694
  });
3448
3695
  function buildCommands(root, config) {
3449
3696
  if (config.build) return config.build;
3450
- const pkgFile = path29.join(root, "package.json");
3697
+ const pkgFile = path30.join(root, "package.json");
3451
3698
  const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
3452
3699
  const pm = packageManager(root);
3453
3700
  return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
3454
3701
  }
3455
3702
  function packageManager(root) {
3456
- let dir = path29.resolve(root);
3703
+ let dir = path30.resolve(root);
3457
3704
  for (; ; ) {
3458
- if (existsSync(path29.join(dir, "pnpm-lock.yaml"))) return "pnpm";
3459
- if (existsSync(path29.join(dir, "bun.lock")) || existsSync(path29.join(dir, "bun.lockb"))) return "bun";
3460
- if (existsSync(path29.join(dir, "yarn.lock"))) return "yarn";
3461
- if (existsSync(path29.join(dir, "package-lock.json"))) return "npm";
3462
- const parent = path29.dirname(dir);
3705
+ if (existsSync(path30.join(dir, "pnpm-lock.yaml"))) return "pnpm";
3706
+ if (existsSync(path30.join(dir, "bun.lock")) || existsSync(path30.join(dir, "bun.lockb"))) return "bun";
3707
+ if (existsSync(path30.join(dir, "yarn.lock"))) return "yarn";
3708
+ if (existsSync(path30.join(dir, "package-lock.json"))) return "npm";
3709
+ const parent = path30.dirname(dir);
3463
3710
  if (parent === dir) return "npm";
3464
3711
  dir = parent;
3465
3712
  }
@@ -3557,7 +3804,7 @@ function loadPatternRules(root, patterns, rulesDoc) {
3557
3804
  const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
3558
3805
  let all = compiled;
3559
3806
  if (rulesDoc) {
3560
- const file = path29.resolve(root, rulesDoc);
3807
+ const file = path30.resolve(root, rulesDoc);
3561
3808
  if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
3562
3809
  const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
3563
3810
  const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
@@ -3625,14 +3872,14 @@ async function loadPlugins(specs, configDir) {
3625
3872
  }
3626
3873
  function resolvePlugin(id, configDir) {
3627
3874
  try {
3628
- if (id.startsWith(".") || path29.isAbsolute(id)) return resolveFrom(path29.resolve(configDir, id), configDir);
3875
+ if (id.startsWith(".") || path30.isAbsolute(id)) return resolveFrom(path30.resolve(configDir, id), configDir);
3629
3876
  return resolveFrom(id, configDir);
3630
3877
  } catch {
3631
3878
  throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
3632
3879
  }
3633
3880
  }
3634
3881
  function resolveFrom(id, from) {
3635
- return createRequire(path29.join(from, "noop.js")).resolve(id);
3882
+ return createRequire(path30.join(from, "noop.js")).resolve(id);
3636
3883
  }
3637
3884
  var init_plugins = __esm({
3638
3885
  "src/doctor/plugins.ts"() {
@@ -3650,7 +3897,7 @@ function importSpecifiers(file) {
3650
3897
  }
3651
3898
  function checkProjectLayout(ctx) {
3652
3899
  for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
3653
- if (existsSync(path29.join(ctx.root, dir))) {
3900
+ if (existsSync(path30.join(ctx.root, dir))) {
3654
3901
  ctx.report({
3655
3902
  rule: "local-primitives",
3656
3903
  file: dir,
@@ -3660,7 +3907,7 @@ function checkProjectLayout(ctx) {
3660
3907
  }
3661
3908
  }
3662
3909
  for (const file of STARTER_LEFTOVERS) {
3663
- if (existsSync(path29.join(ctx.root, file))) {
3910
+ if (existsSync(path30.join(ctx.root, file))) {
3664
3911
  ctx.report({
3665
3912
  rule: "starter-leftover",
3666
3913
  level: "warn",
@@ -3748,7 +3995,7 @@ function checkTokens(ctx) {
3748
3995
  }
3749
3996
  for (const pattern of ctx.config.tokenFiles ?? []) {
3750
3997
  if (/[*?]/.test(pattern)) continue;
3751
- const abs = path29.join(ctx.root, pattern);
3998
+ const abs = path30.join(ctx.root, pattern);
3752
3999
  if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
3753
4000
  for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
3754
4001
  }
@@ -3870,7 +4117,9 @@ var init_rules = __esm({
3870
4117
  // supabase pack: contracts (contracts.ts)
3871
4118
  "contracts-stale",
3872
4119
  // genesis.lock.json against the files (lock-files.ts)
3873
- "lock-files"
4120
+ "lock-files",
4121
+ // an app whose database files live in another app (database.ts)
4122
+ "database-elsewhere"
3874
4123
  ];
3875
4124
  DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
3876
4125
  STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -3955,10 +4204,10 @@ var init_expo = __esm({
3955
4204
  }
3956
4205
  });
3957
4206
  function resolveLocal(root, fromFile, spec) {
3958
- const bases = spec.startsWith(".") ? [path29.resolve(path29.dirname(fromFile), spec)] : [path29.join(root, spec.slice(2)), path29.join(root, "src", spec.slice(2))];
4207
+ const bases = spec.startsWith(".") ? [path30.resolve(path30.dirname(fromFile), spec)] : [path30.join(root, spec.slice(2)), path30.join(root, "src", spec.slice(2))];
3959
4208
  for (const base of bases) {
3960
- const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path29.join(base, `index${e}`))].find(
3961
- (p) => SCRIPT_EXTS2.has(path29.extname(p)) && existsSync(p)
4209
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path30.join(base, `index${e}`))].find(
4210
+ (p) => SCRIPT_EXTS2.has(path30.extname(p)) && existsSync(p)
3962
4211
  );
3963
4212
  if (hit) return hit;
3964
4213
  }
@@ -4079,13 +4328,13 @@ function checkNativePack(ctx) {
4079
4328
  }
4080
4329
  function checkEasPlaceholders(ctx) {
4081
4330
  const files = [];
4082
- if (existsSync(path29.join(ctx.root, "eas.json"))) files.push("eas.json");
4083
- const workflows = path29.join(ctx.root, ".eas", "workflows");
4331
+ if (existsSync(path30.join(ctx.root, "eas.json"))) files.push("eas.json");
4332
+ const workflows = path30.join(ctx.root, ".eas", "workflows");
4084
4333
  if (existsSync(workflows)) {
4085
4334
  for (const name of readdirSync(workflows).sort()) if (/\.ya?ml$/.test(name)) files.push(`.eas/workflows/${name}`);
4086
4335
  }
4087
4336
  for (const file of files) {
4088
- for (const hit of findPlaceholders(file, readFileSync(path29.join(ctx.root, file), "utf8"))) {
4337
+ for (const hit of findPlaceholders(file, readFileSync(path30.join(ctx.root, file), "utf8"))) {
4089
4338
  const key2 = placeholderKey(hit.text, hit.placeholder);
4090
4339
  const what = EAS_PLACEHOLDERS[hit.placeholder];
4091
4340
  ctx.report({
@@ -4163,7 +4412,7 @@ function checkCustomHeaders(ctx, pkg) {
4163
4412
  if (!JSX_EXTS3.has(file.ext)) continue;
4164
4413
  const code = file.code;
4165
4414
  const hidden = HIDES_HEADER.exec(code);
4166
- if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path29.posix.dirname(file.path), file.path);
4415
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path30.posix.dirname(file.path), file.path);
4167
4416
  const own = hidden ? ownHeader(code, pkg) : null;
4168
4417
  if (hidden && own) {
4169
4418
  reported.add(file.path);
@@ -4191,7 +4440,7 @@ function checkCustomHeaders(ctx, pkg) {
4191
4440
  }
4192
4441
  for (const file of ctx.files) {
4193
4442
  if (!JSX_EXTS3.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
4194
- const layout = hidingLayouts.get(path29.posix.dirname(file.path));
4443
+ const layout = hidingLayouts.get(path30.posix.dirname(file.path));
4195
4444
  const own = layout ? ownHeader(file.code, pkg) : null;
4196
4445
  if (!layout || !own) continue;
4197
4446
  ctx.report({
@@ -4212,13 +4461,13 @@ function isLoadingOnlyRoute(code) {
4212
4461
  }
4213
4462
  function routerRoot(ctx) {
4214
4463
  if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
4215
- return existsSync(path29.join(ctx.root, "src", "app")) ? "src/app" : "app";
4464
+ return existsSync(path30.join(ctx.root, "src", "app")) ? "src/app" : "app";
4216
4465
  }
4217
4466
  function checkScreenLayouts(ctx, pkg) {
4218
4467
  const layouts = nativeLayouts(pkg);
4219
4468
  if (layouts.length === 0) return;
4220
4469
  const rootDir = routerRoot(ctx);
4221
- if (!existsSync(path29.join(ctx.root, rootDir))) {
4470
+ if (!existsSync(path30.join(ctx.root, rootDir))) {
4222
4471
  ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
4223
4472
  return;
4224
4473
  }
@@ -4255,7 +4504,7 @@ function checkScreenLayouts(ctx, pkg) {
4255
4504
  function readExpoConfigs(root) {
4256
4505
  const out = [];
4257
4506
  for (const name of EXPO_CONFIGS) {
4258
- const abs = path29.join(root, name);
4507
+ const abs = path30.join(root, name);
4259
4508
  if (!existsSync(abs)) continue;
4260
4509
  const text = readFileSync(abs, "utf8");
4261
4510
  let json = null;
@@ -4289,13 +4538,13 @@ function pluginOptions(json, module) {
4289
4538
  return null;
4290
4539
  }
4291
4540
  function dependencies(root) {
4292
- const file = path29.join(root, "package.json");
4541
+ const file = path30.join(root, "package.json");
4293
4542
  if (!existsSync(file)) return /* @__PURE__ */ new Set();
4294
4543
  const pkg = JSON.parse(readFileSync(file, "utf8"));
4295
4544
  return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
4296
4545
  }
4297
4546
  function runtimeDependencies(root) {
4298
- const file = path29.join(root, "package.json");
4547
+ const file = path30.join(root, "package.json");
4299
4548
  if (!existsSync(file)) return {};
4300
4549
  return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
4301
4550
  }
@@ -4584,14 +4833,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
4584
4833
  seen.add(file);
4585
4834
  const json = readJsonc(file);
4586
4835
  if (!json) return {};
4587
- const dir = path29.dirname(file);
4836
+ const dir = path30.dirname(file);
4588
4837
  let merged = {};
4589
4838
  const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
4590
4839
  for (const ext of parents) {
4591
4840
  if (typeof ext !== "string") continue;
4592
4841
  let target = null;
4593
- if (ext.startsWith(".") || path29.isAbsolute(ext)) {
4594
- const abs = path29.resolve(dir, ext);
4842
+ if (ext.startsWith(".") || path30.isAbsolute(ext)) {
4843
+ const abs = path30.resolve(dir, ext);
4595
4844
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
4596
4845
  } else {
4597
4846
  const parts = ext.split("/");
@@ -4599,14 +4848,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
4599
4848
  const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
4600
4849
  if (pkgDir) {
4601
4850
  const sub = parts.slice(nameLength).join("/");
4602
- const abs = path29.join(pkgDir, sub || "tsconfig.json");
4851
+ const abs = path30.join(pkgDir, sub || "tsconfig.json");
4603
4852
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
4604
4853
  }
4605
4854
  }
4606
4855
  if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
4607
4856
  }
4608
4857
  const opts = json.compilerOptions ?? {};
4609
- if (typeof opts.baseUrl === "string") merged.baseUrl = path29.resolve(dir, opts.baseUrl);
4858
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path30.resolve(dir, opts.baseUrl);
4610
4859
  if (opts.paths && typeof opts.paths === "object") {
4611
4860
  merged.paths = opts.paths;
4612
4861
  merged.pathsDir = dir;
@@ -4617,7 +4866,7 @@ function aliases(root) {
4617
4866
  const table = [];
4618
4867
  let baseUrl = null;
4619
4868
  for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
4620
- const file = path29.join(root, name);
4869
+ const file = path30.join(root, name);
4621
4870
  if (!existsSync(file)) continue;
4622
4871
  const config = readTsconfig(root, file);
4623
4872
  baseUrl ??= config.baseUrl ?? null;
@@ -4625,22 +4874,22 @@ function aliases(root) {
4625
4874
  for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
4626
4875
  if (!Array.isArray(targets)) continue;
4627
4876
  const exact = !pattern.endsWith("*");
4628
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path29.join(base, String(t).replace(/\*$/, ""))) });
4877
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path30.join(base, String(t).replace(/\*$/, ""))) });
4629
4878
  }
4630
4879
  }
4631
- const pkg = readJsonc(path29.join(root, "package.json"));
4880
+ const pkg = readJsonc(path30.join(root, "package.json"));
4632
4881
  for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
4633
4882
  if (typeof target !== "string") continue;
4634
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path29.join(root, target.replace(/\*.*$/, ""))] });
4883
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path30.join(root, target.replace(/\*.*$/, ""))] });
4635
4884
  }
4636
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path29.join(root, "src") + path29.sep, root + path29.sep] });
4885
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path30.join(root, "src") + path30.sep, root + path30.sep] });
4637
4886
  return { table, baseUrl };
4638
4887
  }
4639
4888
  function resolveFile(base) {
4640
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path29.join(base, `index${e}`))];
4889
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path30.join(base, `index${e}`))];
4641
4890
  if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
4642
4891
  for (const p of tries) {
4643
- if (SCRIPT_EXTS2.has(path29.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
4892
+ if (SCRIPT_EXTS2.has(path30.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
4644
4893
  }
4645
4894
  return null;
4646
4895
  }
@@ -4653,7 +4902,7 @@ function createTrail(ctx) {
4653
4902
  const { table, baseUrl } = aliases(ctx.root);
4654
4903
  let declared = null;
4655
4904
  try {
4656
- const pkg = JSON.parse(readFileSync(path29.join(ctx.root, "package.json"), "utf8"));
4905
+ const pkg = JSON.parse(readFileSync(path30.join(ctx.root, "package.json"), "utf8"));
4657
4906
  declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
4658
4907
  } catch {
4659
4908
  declared = null;
@@ -4684,17 +4933,17 @@ function createTrail(ctx) {
4684
4933
  if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
4685
4934
  let resolved = null;
4686
4935
  if (spec.startsWith(".")) {
4687
- resolved = resolveFile(path29.resolve(path29.dirname(file.absolutePath), spec));
4936
+ resolved = resolveFile(path30.resolve(path30.dirname(file.absolutePath), spec));
4688
4937
  if (!resolved) lost = true;
4689
4938
  } else {
4690
4939
  const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
4691
4940
  if (alias) {
4692
4941
  for (const t of alias.targets) {
4693
- resolved = resolveFile(alias.exact ? t : path29.join(t, spec.slice(alias.prefix.length)));
4942
+ resolved = resolveFile(alias.exact ? t : path30.join(t, spec.slice(alias.prefix.length)));
4694
4943
  if (resolved) break;
4695
4944
  }
4696
4945
  }
4697
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path29.join(baseUrl, spec));
4946
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path30.join(baseUrl, spec));
4698
4947
  if (!resolved) {
4699
4948
  const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
4700
4949
  if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
@@ -4780,7 +5029,7 @@ var init_trail = __esm({
4780
5029
  });
4781
5030
  function routesDir(ctx) {
4782
5031
  if (ctx.config.routesDir) return ctx.config.routesDir;
4783
- return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path29.join(ctx.root, d))) ?? null;
5032
+ return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path30.join(ctx.root, d))) ?? null;
4784
5033
  }
4785
5034
  function flavorOf(dir, rels) {
4786
5035
  const stems = rels.map((r) => r.split("/").pop());
@@ -4921,7 +5170,7 @@ function validateDeclaration(raw, packageName3, packageDir2, ignored) {
4921
5170
  });
4922
5171
  if (typeof raw === "string") {
4923
5172
  if (!packageDir2) fail(`points at ${raw}, but the package folder is unknown`);
4924
- const file = path29.resolve(packageDir2, raw);
5173
+ const file = path30.resolve(packageDir2, raw);
4925
5174
  if (!inside(packageDir2, file)) fail(`points outside the package (${raw})`);
4926
5175
  if (!existsSync(file)) fail(`points at ${raw}, which doesn't exist (is it in package.json "files"?)`);
4927
5176
  let parsed;
@@ -4970,7 +5219,7 @@ function validateDeclaration(raw, packageName3, packageDir2, ignored) {
4970
5219
  if (typeof c.plugin === "string") {
4971
5220
  if (!packageDir2) plugin = c.plugin;
4972
5221
  else {
4973
- plugin = path29.resolve(packageDir2, c.plugin);
5222
+ plugin = path30.resolve(packageDir2, c.plugin);
4974
5223
  if (!inside(packageDir2, plugin)) fail(`plugin points outside the package (${c.plugin})`);
4975
5224
  }
4976
5225
  }
@@ -5019,7 +5268,7 @@ function checkPattern(v, where2, fail) {
5019
5268
  }
5020
5269
  }
5021
5270
  function readDeclaringPackage(dir, local) {
5022
- const file = path29.join(dir, "package.json");
5271
+ const file = path30.join(dir, "package.json");
5023
5272
  let stamp;
5024
5273
  let real2;
5025
5274
  try {
@@ -5042,7 +5291,7 @@ ${local}`;
5042
5291
  const pkg = {
5043
5292
  name: json.name,
5044
5293
  version: typeof json.version === "string" ? json.version : "0.0.0",
5045
- dir: path29.resolve(dir),
5294
+ dir: path30.resolve(dir),
5046
5295
  namespace: ruleNamespace(json.name),
5047
5296
  local,
5048
5297
  private: json.private === true,
@@ -5056,7 +5305,7 @@ ${local}`;
5056
5305
  if (raw !== void 0) {
5057
5306
  const ignored = [];
5058
5307
  try {
5059
- pkg.declaration = validateDeclaration(raw, json.name, path29.resolve(dir), ignored);
5308
+ pkg.declaration = validateDeclaration(raw, json.name, path30.resolve(dir), ignored);
5060
5309
  if (ignored.length) pkg.ignored = ignored;
5061
5310
  } catch (err) {
5062
5311
  pkg.error = err.message;
@@ -5075,14 +5324,14 @@ function discoverPackages(root) {
5075
5324
  for (const dir of installed) {
5076
5325
  let scope;
5077
5326
  try {
5078
- scope = path29.dirname(realpathSync(dir));
5327
+ scope = path30.dirname(realpathSync(dir));
5079
5328
  } catch {
5080
5329
  continue;
5081
5330
  }
5082
- if (path29.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
5331
+ if (path30.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
5083
5332
  for (const entry of readdirSync(scope)) {
5084
5333
  if (byName.has(`@marktiderman/${entry}`) || !GENESIS.test(`@marktiderman/${entry}`)) continue;
5085
- const pkg = readDeclaringPackage(path29.join(scope, entry), false);
5334
+ const pkg = readDeclaringPackage(path30.join(scope, entry), false);
5086
5335
  if (pkg) byName.set(pkg.name, pkg);
5087
5336
  }
5088
5337
  }
@@ -5292,10 +5541,10 @@ var init_package_rules = __esm({
5292
5541
  });
5293
5542
  function sourceFiles(dir, rel = "") {
5294
5543
  const out = [];
5295
- for (const entry of readdirSync(path29.join(dir, rel)).sort()) {
5544
+ for (const entry of readdirSync(path30.join(dir, rel)).sort()) {
5296
5545
  if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
5297
5546
  const child = rel ? `${rel}/${entry}` : entry;
5298
- const stat = lstatSync(path29.join(dir, child));
5547
+ const stat = lstatSync(path30.join(dir, child));
5299
5548
  if (stat.isSymbolicLink()) continue;
5300
5549
  if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
5301
5550
  else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
@@ -5318,13 +5567,13 @@ function matchPattern(pattern, spec) {
5318
5567
  return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
5319
5568
  }
5320
5569
  function tsconfigPaths(dir) {
5321
- const file = path29.join(dir, "tsconfig.json");
5570
+ const file = path30.join(dir, "tsconfig.json");
5322
5571
  if (!existsSync(file)) return [];
5323
5572
  try {
5324
5573
  const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
5325
5574
  const options = JSON.parse(text).compilerOptions ?? {};
5326
- const base = path29.resolve(dir, options.baseUrl ?? ".");
5327
- return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path29.resolve(base, t)) }));
5575
+ const base = path30.resolve(dir, options.baseUrl ?? ".");
5576
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path30.resolve(base, t)) }));
5328
5577
  } catch {
5329
5578
  return [];
5330
5579
  }
@@ -5338,8 +5587,8 @@ function checkImports2(ctx, pkg, json) {
5338
5587
  const hit = matchPattern(pattern, spec);
5339
5588
  if (hit === null) continue;
5340
5589
  return targets.some((t) => {
5341
- const rel = path29.relative(pkg.dir, t.replace("*", hit));
5342
- return !rel.startsWith("..") && !path29.isAbsolute(rel);
5590
+ const rel = path30.relative(pkg.dir, t.replace("*", hit));
5591
+ return !rel.startsWith("..") && !path30.isAbsolute(rel);
5343
5592
  });
5344
5593
  }
5345
5594
  return null;
@@ -5352,7 +5601,7 @@ function checkImports2(ctx, pkg, json) {
5352
5601
  ...Object.keys(json.optionalDependencies ?? {})
5353
5602
  ]);
5354
5603
  for (const file of sourceFiles(pkg.dir)) {
5355
- const code = stripForImports(readFileSync(path29.join(pkg.dir, file), "utf8"));
5604
+ const code = stripForImports(readFileSync(path30.join(pkg.dir, file), "utf8"));
5356
5605
  if (code === null) continue;
5357
5606
  const at = `${pkg.rel}/${file}`;
5358
5607
  const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
@@ -5377,9 +5626,9 @@ function checkImports2(ctx, pkg, json) {
5377
5626
  continue;
5378
5627
  }
5379
5628
  if (spec.startsWith(".")) {
5380
- const target = path29.resolve(pkg.dir, path29.dirname(file), spec);
5381
- const rel = path29.relative(pkg.dir, target);
5382
- if (rel.startsWith("..") || path29.isAbsolute(rel)) {
5629
+ const target = path30.resolve(pkg.dir, path30.dirname(file), spec);
5630
+ const rel = path30.relative(pkg.dir, target);
5631
+ if (rel.startsWith("..") || path30.isAbsolute(rel)) {
5383
5632
  ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} reaches outside its folder (${spec}); move what it needs into the package or a dependency` });
5384
5633
  }
5385
5634
  continue;
@@ -5415,12 +5664,12 @@ function checkMigrations(ctx, pkg, json, locals) {
5415
5664
  const from = own ? "" : ` (in ${m.package})`;
5416
5665
  if (typeof m.file === "string" && typeof m.test !== "string") {
5417
5666
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.file, message: `${pkg.name} block ${id}: ${m.file}${from} has no pgTAP test; declare one as "test" beside it` });
5418
- } else if (typeof m.test === "string" && !existsSync(path29.join(home, m.test))) {
5667
+ } else if (typeof m.test === "string" && !existsSync(path30.join(home, m.test))) {
5419
5668
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.test, message: `${pkg.name} block ${id}: its test ${m.test}${from} doesn't exist` });
5420
5669
  }
5421
5670
  }
5422
5671
  }
5423
- const dir = path29.join(pkg.dir, "migrations");
5672
+ const dir = path30.join(pkg.dir, "migrations");
5424
5673
  if (!existsSync(dir)) return;
5425
5674
  const seen = /* @__PURE__ */ new Map();
5426
5675
  for (const name of readdirSync(dir).sort()) {
@@ -5429,7 +5678,7 @@ function checkMigrations(ctx, pkg, json, locals) {
5429
5678
  const other = seen.get(m[1]);
5430
5679
  if (other) ctx.report({ rule: "package-migration-number", file: `${pkg.rel}/migrations/${name}`, subject: m[1], message: `${pkg.name}: ${name} and ${other} share the number ${m[1]}; give each migration its own` });
5431
5680
  else seen.set(m[1], name);
5432
- if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path29.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
5681
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path30.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
5433
5682
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/migrations/${name}`, subject: name, message: `${pkg.name}: ${name} has no pgTAP test (migrations/tests/${name.replace(/\.sql$/, ".test.sql")})` });
5434
5683
  }
5435
5684
  }
@@ -5443,7 +5692,7 @@ function checkExports(ctx, pkg, json) {
5443
5692
  walk3(json.exports);
5444
5693
  for (const t of targets) {
5445
5694
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
5446
- if (!existsSync(path29.join(pkg.dir, t))) {
5695
+ if (!existsSync(path30.join(pkg.dir, t))) {
5447
5696
  ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
5448
5697
  }
5449
5698
  }
@@ -5461,11 +5710,11 @@ function checkBlocks(ctx, pkg, json) {
5461
5710
  function checkTaggedTests(ctx, pkg) {
5462
5711
  const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
5463
5712
  if (!tests.length) return;
5464
- const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path29.join(pkg.dir, f), "utf8")));
5713
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path30.join(pkg.dir, f), "utf8")));
5465
5714
  if (!tagged) ctx.report({ rule: "package-untagged-tests", level: "warn", file: pkg.rel, message: `${pkg.name}'s tests name no feature; tag them with // @feat:<feature id>` });
5466
5715
  }
5467
5716
  function checkRegistered(ctx, pkg) {
5468
- const file = path29.join(ctx.root, "features.json");
5717
+ const file = path30.join(ctx.root, "features.json");
5469
5718
  if (!existsSync(file)) return;
5470
5719
  let doc;
5471
5720
  try {
@@ -5475,7 +5724,7 @@ function checkRegistered(ctx, pkg) {
5475
5724
  }
5476
5725
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
5477
5726
  const forms = /* @__PURE__ */ new Set([pkg.rel]);
5478
- if (top) forms.add(path29.relative(top, realpathSync(pkg.dir)).split(path29.sep).join("/"));
5727
+ if (top) forms.add(path30.relative(top, realpathSync(pkg.dir)).split(path30.sep).join("/"));
5479
5728
  const covered = (doc.features ?? []).some(
5480
5729
  (f) => (f.links?.code ?? []).some((c) => {
5481
5730
  const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -5505,8 +5754,8 @@ function mergeBaseOf(root, base) {
5505
5754
  function checkChanges(ctx, pkg, json, base, mergeBase) {
5506
5755
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
5507
5756
  if (!top) return;
5508
- const appRelative = (fromTop) => path29.relative(realpathSync(ctx.root), path29.join(top, fromTop)).split(path29.sep).join("/");
5509
- const inRepo = path29.relative(top, realpathSync(pkg.dir)).split(path29.sep).join("/");
5757
+ const appRelative = (fromTop) => path30.relative(realpathSync(ctx.root), path30.join(top, fromTop)).split(path30.sep).join("/");
5758
+ const inRepo = path30.relative(top, realpathSync(pkg.dir)).split(path30.sep).join("/");
5510
5759
  const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell2, i) => i === 0 ? cell2 : appRelative(cell2)).join(" ")).join("\n");
5511
5760
  const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
5512
5761
  const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
@@ -5529,11 +5778,11 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
5529
5778
  const now = typeof json.version === "string" ? parseVersion(json.version) : null;
5530
5779
  const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
5531
5780
  const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
5532
- const changesets = top ? (git(top, ["diff", "--name-only", "--diff-filter=A", mergeBase, "--", ".changeset"]) ?? "").split("\n").concat((git(top, ["ls-files", "--others", "--exclude-standard", "--", ".changeset"]) ?? "").split("\n")).filter((f) => f.endsWith(".md")).map((f) => path29.join(top, f)) : [];
5781
+ const changesets = top ? (git(top, ["diff", "--name-only", "--diff-filter=A", mergeBase, "--", ".changeset"]) ?? "").split("\n").concat((git(top, ["ls-files", "--others", "--exclude-standard", "--", ".changeset"]) ?? "").split("\n")).filter((f) => f.endsWith(".md")).map((f) => path30.join(top, f)) : [];
5533
5782
  const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
5534
5783
  const named = naming.length > 0;
5535
5784
  if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
5536
- ctx.report({ rule: "package-unversioned-change", level: "warn", file: path29.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
5785
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: path30.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
5537
5786
  }
5538
5787
  let jsonBefore = null;
5539
5788
  try {
@@ -5543,7 +5792,7 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
5543
5792
  }
5544
5793
  const raw = json;
5545
5794
  if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
5546
- const appInRepo = path29.relative(top, realpathSync(ctx.root)).split(path29.sep).join("/");
5795
+ const appInRepo = path30.relative(top, realpathSync(ctx.root)).split(path30.sep).join("/");
5547
5796
  const candidates = [.../* @__PURE__ */ new Set(["features.ts", "src/features.ts", ...appInRepo ? [`${appInRepo}/features.ts`, `${appInRepo}/src/features.ts`] : []])];
5548
5797
  const registry = (git(top, ["diff", "--name-only", mergeBase, "--", ...candidates]) ?? "").trim();
5549
5798
  if (!registry) ctx.report({ rule: "package-unversioned-change", level: "warn", file: `${pkg.rel}/package.json`, message: `${pkg.name}'s blocks or exports changed but features.ts didn't; update the features they belong to` });
@@ -5594,7 +5843,7 @@ function checkPackagesPack(ctx) {
5594
5843
  ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
5595
5844
  }
5596
5845
  for (const pkg of packages) {
5597
- const json = JSON.parse(readFileSync(path29.join(pkg.dir, "package.json"), "utf8"));
5846
+ const json = JSON.parse(readFileSync(path30.join(pkg.dir, "package.json"), "utf8"));
5598
5847
  checkImports2(ctx, pkg, json);
5599
5848
  checkExports(ctx, pkg, json);
5600
5849
  checkBlocks(ctx, pkg, json);
@@ -5790,11 +6039,12 @@ function gitView(root, dir, base) {
5790
6039
  return { touched: touched2, edited };
5791
6040
  }
5792
6041
  function checkSupabasePack(ctx) {
6042
+ if (databaseElsewhere(ctx.root)) return;
5793
6043
  const settings2 = ctx.config.supabase ?? {};
5794
6044
  const dir = settings2.migrations ?? DEFAULT_MIGRATIONS;
5795
- const abs = path29.join(ctx.root, dir);
6045
+ const abs = path30.join(ctx.root, dir);
5796
6046
  if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
5797
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path29.join(abs, n), "utf8")) }));
6047
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path30.join(abs, n), "utf8")) }));
5798
6048
  const exposed = new Set((settings2.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
5799
6049
  const base = settings2.base ?? DEFAULT_BASE;
5800
6050
  const view = gitView(ctx.root, dir, base);
@@ -5811,7 +6061,7 @@ function checkSupabasePack(ctx) {
5811
6061
  }
5812
6062
  }
5813
6063
  const since = settings2.since;
5814
- const afterSince = (file) => since === void 0 || path29.posix.basename(file) >= since;
6064
+ const afterSince = (file) => since === void 0 || path30.posix.basename(file) >= since;
5815
6065
  if ("reason" in view && since === void 0) {
5816
6066
  ctx.report({
5817
6067
  rule: "migration-grants",
@@ -6093,6 +6343,7 @@ var DEFAULT_MIGRATIONS, DEFAULT_BASE, DEFAULT_EXPOSED, schemaOf, TYPE_ALIASES, M
6093
6343
  var init_supabase = __esm({
6094
6344
  "src/doctor/supabase.ts"() {
6095
6345
  init_config();
6346
+ init_database();
6096
6347
  DEFAULT_MIGRATIONS = "supabase/migrations";
6097
6348
  DEFAULT_BASE = "origin/main";
6098
6349
  DEFAULT_EXPOSED = ["public"];
@@ -6111,18 +6362,18 @@ var init_supabase = __esm({
6111
6362
  }
6112
6363
  });
6113
6364
  function nodeModulesOf(dir) {
6114
- const parent = path29.dirname(dir);
6115
- return path29.basename(parent).startsWith("@") ? path29.dirname(parent) : parent;
6365
+ const parent = path30.dirname(dir);
6366
+ return path30.basename(parent).startsWith("@") ? path30.dirname(parent) : parent;
6116
6367
  }
6117
6368
  function packagesIn(nodeModules) {
6118
6369
  if (!existsSync(nodeModules)) return [];
6119
6370
  const out = [];
6120
6371
  for (const entry of readdirSync(nodeModules)) {
6121
6372
  if (entry.startsWith(".")) continue;
6122
- const p = path29.join(nodeModules, entry);
6373
+ const p = path30.join(nodeModules, entry);
6123
6374
  if (entry.startsWith("@")) {
6124
6375
  try {
6125
- for (const sub of readdirSync(p)) out.push(path29.join(p, sub));
6376
+ for (const sub of readdirSync(p)) out.push(path30.join(p, sub));
6126
6377
  } catch {
6127
6378
  }
6128
6379
  } else {
@@ -6134,7 +6385,7 @@ function packagesIn(nodeModules) {
6134
6385
  function genesisInstalls(root) {
6135
6386
  const copies = /* @__PURE__ */ new Map();
6136
6387
  const realRoot = real(root);
6137
- const rel = (abs) => path29.relative(realRoot, abs).split(path29.sep).join("/") || ".";
6388
+ const rel = (abs) => path30.relative(realRoot, abs).split(path30.sep).join("/") || ".";
6138
6389
  const via = /* @__PURE__ */ new Map();
6139
6390
  const record = (real2, manifest, by, range, root2) => {
6140
6391
  let copy = copies.get(real2);
@@ -6179,7 +6430,7 @@ function genesisInstalls(root) {
6179
6430
  if (!dir) return null;
6180
6431
  if (!ownInstall || name in declared) return dir;
6181
6432
  const realDir = real(dir);
6182
- if (realDir.startsWith(realRoot + path29.sep)) return dir;
6433
+ if (realDir.startsWith(realRoot + path30.sep)) return dir;
6183
6434
  return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
6184
6435
  };
6185
6436
  const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
@@ -6187,7 +6438,7 @@ function genesisInstalls(root) {
6187
6438
  return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
6188
6439
  });
6189
6440
  const app = readManifest(root);
6190
- const ownInstall = LOCKFILES.some((f) => existsSync(path29.join(root, f)));
6441
+ const ownInstall = LOCKFILES.some((f) => existsSync(path30.join(root, f)));
6191
6442
  const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
6192
6443
  const declaredDev = Object.entries(app?.devDependencies ?? {});
6193
6444
  const runtimeDeps = {
@@ -6198,11 +6449,11 @@ function genesisInstalls(root) {
6198
6449
  };
6199
6450
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
6200
6451
  walk3("runtime", rootsOf(runtimeDeps, "the app"));
6201
- const top = path29.join(root, "node_modules");
6452
+ const top = path30.join(root, "node_modules");
6202
6453
  walk3(
6203
6454
  "hoisted",
6204
6455
  packagesIn(top).filter((dir) => {
6205
- const name = path29.relative(top, dir).split(path29.sep).join("/");
6456
+ const name = path30.relative(top, dir).split(path30.sep).join("/");
6206
6457
  return !(name in runtimeDeps) && !(name in devDeps);
6207
6458
  }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
6208
6459
  );
@@ -6244,7 +6495,7 @@ function checkDuplicatePackages(ctx) {
6244
6495
  }
6245
6496
  }
6246
6497
  function checkPeerRanges(ctx) {
6247
- const rel = (abs) => path29.relative(ctx.root, abs).split(path29.sep).join("/");
6498
+ const rel = (abs) => path30.relative(ctx.root, abs).split(path30.sep).join("/");
6248
6499
  for (const copies of genesisInstalls(ctx.root).values()) {
6249
6500
  for (const copy of copies) {
6250
6501
  const dir = copy.absolutePath;
@@ -6277,7 +6528,7 @@ var init_installs = __esm({
6277
6528
  NON_SHIPPING = /^(?:@marktiderman\/genesis-cli|vitest|@vitest\/.+|jest|jest-.+|@jest\/.+|ts-jest|babel-jest|mocha|ava|c8|nyc|@playwright\/test|playwright|cypress|@testing-library\/.+|happy-dom|jsdom|msw|@types\/.+|typescript|tsx|ts-node|eslint|eslint-.+|@eslint\/.+|@typescript-eslint\/.+|typescript-eslint|prettier|prettier-.+|@biomejs\/.+|oxlint|vite|@vitejs\/.+|vite-plugin-.+|webpack|webpack-.+|rollup|@rollup\/.+|esbuild|tsup|turbo|@storybook\/.+|storybook|@changesets\/.+|husky|lint-staged|wrangler|knip|concurrently|npm-run-all2?|rimraf|cross-env|dotenv-cli)$/;
6278
6529
  readManifest = (dir) => {
6279
6530
  try {
6280
- return JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8"));
6531
+ return JSON.parse(readFileSync(path30.join(dir, "package.json"), "utf8"));
6281
6532
  } catch {
6282
6533
  return null;
6283
6534
  }
@@ -6920,11 +7171,11 @@ function appScripts(root) {
6920
7171
  const out = [];
6921
7172
  const walk3 = (dir) => {
6922
7173
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
6923
- const abs = path29.join(dir, entry.name);
7174
+ const abs = path30.join(dir, entry.name);
6924
7175
  if (entry.isDirectory()) {
6925
7176
  if (!SKIP_DIRS3.has(entry.name)) walk3(abs);
6926
7177
  } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
6927
- out.push(path29.relative(root, abs).split(path29.sep).join("/"));
7178
+ out.push(path30.relative(root, abs).split(path30.sep).join("/"));
6928
7179
  }
6929
7180
  }
6930
7181
  };
@@ -6964,7 +7215,7 @@ var init_codemods = __esm({
6964
7215
  let readsId = false;
6965
7216
  let augmented = false;
6966
7217
  for (const rel of appScripts(root)) {
6967
- const abs = path29.join(root, rel);
7218
+ const abs = path30.join(root, rel);
6968
7219
  const text = readFileSync(abs, "utf8");
6969
7220
  if (augmentsResourceScope(text)) augmented = true;
6970
7221
  if (!IMPORTS_GENESIS.test(text)) continue;
@@ -7060,7 +7311,7 @@ function checkTreeViews(ctx) {
7060
7311
  function moduleFiles(ctx) {
7061
7312
  const scanned = new Set(ctx.files.map((f) => f.path));
7062
7313
  const ignored = globMatcher([...DEFAULT_IGNORE, ...ctx.config.ignore ?? []]);
7063
- const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path29.join(ctx.root, rel), "utf8"), true) }));
7314
+ const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path30.join(ctx.root, rel), "utf8"), true) }));
7064
7315
  return [...ctx.files.filter((f) => SCRIPT_EXTS5.has(f.ext)), ...extra];
7065
7316
  }
7066
7317
  function checkStudioServerImports(ctx) {
@@ -7090,7 +7341,7 @@ function checkStudioServerImports(ctx) {
7090
7341
  }
7091
7342
  function checkRemovedScopeNames(ctx) {
7092
7343
  let augmentedMemo;
7093
- const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path29.join(ctx.root, rel), "utf8")));
7344
+ const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path30.join(ctx.root, rel), "utf8")));
7094
7345
  for (const file of ctx.files) {
7095
7346
  if (!SCRIPT_EXTS5.has(file.ext)) continue;
7096
7347
  for (const hit of findRemovedScopeNames(file.code)) {
@@ -7179,16 +7430,16 @@ function genesisNamedImports(source) {
7179
7430
  }
7180
7431
  function declarationFiles(dir, out = []) {
7181
7432
  for (const name of readdirSync(dir)) {
7182
- const full = path29.join(dir, name);
7433
+ const full = path30.join(dir, name);
7183
7434
  if (statSync(full).isDirectory()) declarationFiles(full, out);
7184
7435
  else if (/\.d\.[cm]?ts$/.test(name)) out.push(full);
7185
7436
  }
7186
7437
  return out;
7187
7438
  }
7188
7439
  function readPackageTags(dir) {
7189
- const pkg = JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8"));
7440
+ const pkg = JSON.parse(readFileSync(path30.join(dir, "package.json"), "utf8"));
7190
7441
  const tags = { dir, byFile: /* @__PURE__ */ new Map(), declaredIn: /* @__PURE__ */ new Map(), exports: typeof pkg.exports === "object" && pkg.exports ? pkg.exports : {} };
7191
- const dist = path29.join(dir, "dist");
7442
+ const dist = path30.join(dir, "dist");
7192
7443
  if (!existsSync(dist)) return tags;
7193
7444
  for (const file of declarationFiles(dist)) {
7194
7445
  const text = readFileSync(file, "utf8");
@@ -7206,7 +7457,7 @@ function entryFile(tags, pkg, specifier) {
7206
7457
  const subpath = `.${specifier.slice(pkg.length)}` || ".";
7207
7458
  const target = tags.exports[subpath === "." ? "." : subpath];
7208
7459
  const types = typeof target === "object" && target ? target.types : null;
7209
- return typeof types === "string" ? path29.join(tags.dir, types) : null;
7460
+ return typeof types === "string" ? path30.join(tags.dir, types) : null;
7210
7461
  }
7211
7462
  function tagFor(tags, entry, name) {
7212
7463
  if (entry && tags.declaredIn.get(name)?.includes(entry)) return tags.byFile.get(entry)?.get(name);
@@ -7270,7 +7521,7 @@ function showAt(dir, rev, file) {
7270
7521
  function configAtBase(root, base, explicitFile) {
7271
7522
  const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
7272
7523
  if (!mergeBase) return null;
7273
- const candidates = explicitFile ? [{ dir: path29.dirname(explicitFile), file: path29.basename(explicitFile), explicit: true }] : [
7524
+ const candidates = explicitFile ? [{ dir: path30.dirname(explicitFile), file: path30.basename(explicitFile), explicit: true }] : [
7274
7525
  { dir: root, file: "genesis.config.json", explicit: false },
7275
7526
  { dir: root, file: "package.json", explicit: false }
7276
7527
  ];
@@ -7460,13 +7711,13 @@ function currentAgentsBlock(agents) {
7460
7711
  function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
7461
7712
  const rows = primitivesCatalog(packages);
7462
7713
  const changed = [];
7463
- const agents = path29.join(root, agentsFile);
7714
+ const agents = path30.join(root, agentsFile);
7464
7715
  const before = read(agents);
7465
7716
  const after = mergeAgentsBlock(before, renderAgentsBlock(rows));
7466
- const skill = path29.join(root, SKILL_PATH);
7717
+ const skill = path30.join(root, SKILL_PATH);
7467
7718
  const skillText = renderSkill(rows);
7468
7719
  if (read(skill)?.replace(/\r\n/g, "\n") !== skillText) {
7469
- mkdirSync(path29.dirname(skill), { recursive: true });
7720
+ mkdirSync(path30.dirname(skill), { recursive: true });
7470
7721
  writeFileSync(skill, skillText);
7471
7722
  changed.push(SKILL_PATH);
7472
7723
  }
@@ -7478,8 +7729,8 @@ function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
7478
7729
  }
7479
7730
  function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
7480
7731
  const rows = primitivesCatalog(packages);
7481
- const skill = read(path29.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
7482
- const block = currentAgentsBlock(read(path29.join(root, agentsFile)));
7732
+ const skill = read(path30.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
7733
+ const block = currentAgentsBlock(read(path30.join(root, agentsFile)));
7483
7734
  return {
7484
7735
  skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
7485
7736
  agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
@@ -7595,9 +7846,9 @@ function ownedKeyProblem(key2, source, localNames = /* @__PURE__ */ new Set()) {
7595
7846
  return `${key2} doesn't match its source ${source}`;
7596
7847
  }
7597
7848
  function mergeThreeWay(mine, base, theirs) {
7598
- const dir = mkdtempSync(path29.join(tmpdir(), "genesis-merge-"));
7849
+ const dir = mkdtempSync(path30.join(tmpdir(), "genesis-merge-"));
7599
7850
  try {
7600
- const [m, b, t] = ["mine", "base", "theirs"].map((n) => path29.join(dir, n));
7851
+ const [m, b, t] = ["mine", "base", "theirs"].map((n) => path30.join(dir, n));
7601
7852
  writeFileSync(m, mine);
7602
7853
  writeFileSync(b, base);
7603
7854
  writeFileSync(t, theirs);
@@ -7680,7 +7931,7 @@ var init_owned = __esm({
7680
7931
  }
7681
7932
  });
7682
7933
  async function checkLockFiles(ctx) {
7683
- if (!existsSync(path29.join(ctx.root, LOCK_FILE))) return;
7934
+ if (!existsSync(path30.join(ctx.root, LOCK_FILE))) return;
7684
7935
  let lock;
7685
7936
  try {
7686
7937
  lock = readLock(ctx.root);
@@ -7708,15 +7959,44 @@ async function checkLockFiles(ctx) {
7708
7959
  });
7709
7960
  }
7710
7961
  const local = localPackageNames(ctx.root);
7962
+ let home = null;
7963
+ try {
7964
+ home = databaseElsewhere(ctx.root);
7965
+ } catch {
7966
+ }
7967
+ const elsewhere = home ? Object.keys(lock.files).filter(isSupabasePath) : [];
7968
+ if (home && elsewhere.length) {
7969
+ ctx.report({
7970
+ rule: "lock-files",
7971
+ level: "info",
7972
+ file: LOCK_FILE,
7973
+ subject: "supabase/",
7974
+ message: `lists ${elsewhere.length} file${elsewhere.length === 1 ? "" : "s"} under supabase/, but this app's database files live ${home.app ? `in ${home.app}` : "nowhere"} (genesis.config.json supabase): genesis upgrade leaves them alone, so delete those entries`
7975
+ });
7976
+ }
7711
7977
  for (const [rel, entry] of Object.entries(lock.files)) {
7978
+ if (home && isSupabasePath(rel)) continue;
7712
7979
  if (ownedKeyProblem(rel, entry.source, local)) continue;
7713
7980
  if (offManifests.length && blockOfSource(entry.source, offManifests)) continue;
7714
- let text;
7981
+ let file;
7715
7982
  try {
7716
- text = readApp(ctx.root, rel);
7983
+ file = appPath(ctx.root, rel);
7717
7984
  } catch {
7718
7985
  continue;
7719
7986
  }
7987
+ let text;
7988
+ try {
7989
+ text = existsSync(file) ? readFileSync(file, "utf8") : null;
7990
+ } catch (err) {
7991
+ ctx.report({
7992
+ rule: "lock-files",
7993
+ level: "warn",
7994
+ file: rel,
7995
+ subject: rel,
7996
+ message: `is in ${LOCK_FILE} (from ${entry.source}) but can't be read (${err instanceof Error ? err.message : String(err)}), so genesis upgrade can't refresh it. Make it a file again, or remove its entry from ${LOCK_FILE}`
7997
+ });
7998
+ continue;
7999
+ }
7720
8000
  if (text === null) {
7721
8001
  if (entry.deleted) continue;
7722
8002
  ctx.report({
@@ -7749,6 +8029,34 @@ var init_lock_files = __esm({
7749
8029
  init_local();
7750
8030
  init_owned();
7751
8031
  init_starter_features();
8032
+ init_database();
8033
+ }
8034
+ });
8035
+ function checkDatabaseHome(ctx) {
8036
+ const home = databaseElsewhere(ctx.root);
8037
+ if (!home) return;
8038
+ if (home.app && !home.hasSupabase) {
8039
+ ctx.report({
8040
+ rule: "database-elsewhere",
8041
+ level: "warn",
8042
+ file: "genesis.config.json",
8043
+ subject: home.app,
8044
+ message: `supabase.app is ${home.app}, which has no supabase folder; name the app that holds this app's database (its migrations, tests and Edge Functions)`
8045
+ });
8046
+ }
8047
+ if (existsSync(path30.join(ctx.root, "supabase"))) {
8048
+ ctx.report({
8049
+ rule: "database-elsewhere",
8050
+ level: "warn",
8051
+ file: "supabase",
8052
+ subject: "supabase/",
8053
+ message: `is here, but genesis.config.json says this app's database files live ${home.app ? `in ${home.app}/supabase` : "nowhere"}: genesis add, migrate and upgrade never plan it, so it is a second, unused copy. Delete it`
8054
+ });
8055
+ }
8056
+ }
8057
+ var init_database2 = __esm({
8058
+ "src/doctor/database.ts"() {
8059
+ init_database();
7752
8060
  }
7753
8061
  });
7754
8062
 
@@ -7801,7 +8109,7 @@ __export(doctor_exports, {
7801
8109
  writeAgentGuide: () => writeAgentGuide
7802
8110
  });
7803
8111
  async function runDoctor(options = {}) {
7804
- const root = path29.resolve(options.root ?? process.cwd());
8112
+ const root = path30.resolve(options.root ?? process.cwd());
7805
8113
  const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
7806
8114
  const config = loaded.config;
7807
8115
  const genesis = options.genesis ?? loadGenesis(root, config);
@@ -7855,7 +8163,7 @@ async function runDoctor(options = {}) {
7855
8163
  }
7856
8164
  let findings = applyConfig(raw, config, packageRuleIds(packages));
7857
8165
  if (options.base && changed) {
7858
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path29.join(root, f)) });
8166
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path30.join(root, f)) });
7859
8167
  }
7860
8168
  const errors = findings.filter((f) => f.level === "error").length;
7861
8169
  const warnings = findings.filter((f) => f.level === "warn").length;
@@ -7901,6 +8209,7 @@ function builtinChecks(config, options = {}) {
7901
8209
  { name: "agent-guide", check: checkAgentGuide },
7902
8210
  { name: "overlays", check: (ctx) => checkOverlays(ctx) },
7903
8211
  { name: "lock-files", check: checkLockFiles },
8212
+ { name: "database-elsewhere", check: checkDatabaseHome },
7904
8213
  ...(config.packs ?? []).map((p) => packs[p]),
7905
8214
  ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
7906
8215
  ];
@@ -8016,6 +8325,7 @@ var init_doctor = __esm({
8016
8325
  init_primitives();
8017
8326
  init_overlays();
8018
8327
  init_lock_files();
8328
+ init_database2();
8019
8329
  init_config();
8020
8330
  init_genesis();
8021
8331
  init_patterns();
@@ -8045,12 +8355,12 @@ __export(agent_rules_exports, {
8045
8355
  runsOnPullRequestsInto: () => runsOnPullRequestsInto
8046
8356
  });
8047
8357
  function changesetBumps(root) {
8048
- const dir = path29.join(root, ".changeset");
8358
+ const dir = path30.join(root, ".changeset");
8049
8359
  const bumps = /* @__PURE__ */ new Map();
8050
8360
  if (!existsSync(dir)) return bumps;
8051
8361
  for (const name of readdirSync(dir)) {
8052
8362
  if (!name.endsWith(".md") || name === "README.md") continue;
8053
- const text = readFileSync(path29.join(dir, name), "utf8");
8363
+ const text = readFileSync(path30.join(dir, name), "utf8");
8054
8364
  const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? "";
8055
8365
  for (const line of front.split(/\r?\n/)) {
8056
8366
  const m = /^\s*["']?([^"':]+)["']?\s*:\s*(major|minor|patch)\s*$/.exec(line);
@@ -8063,13 +8373,13 @@ function changesetBumps(root) {
8063
8373
  return bumps;
8064
8374
  }
8065
8375
  function firstVersionProblems(root) {
8066
- const packagesDir = path29.join(root, "packages");
8376
+ const packagesDir = path30.join(root, "packages");
8067
8377
  if (!existsSync(packagesDir)) return [];
8068
8378
  const bumps = changesetBumps(root);
8069
8379
  const problems = [];
8070
8380
  for (const dir of readdirSync(packagesDir)) {
8071
- const file = path29.join(packagesDir, dir, "package.json");
8072
- if (!existsSync(file) || existsSync(path29.join(packagesDir, dir, "CHANGELOG.md"))) continue;
8381
+ const file = path30.join(packagesDir, dir, "package.json");
8382
+ if (!existsSync(file) || existsSync(path30.join(packagesDir, dir, "CHANGELOG.md"))) continue;
8073
8383
  const pkg = JSON.parse(readFileSync(file, "utf8"));
8074
8384
  if (pkg.private || !pkg.name) continue;
8075
8385
  if (pkg.version !== FIRST_VERSION) {
@@ -8140,12 +8450,12 @@ function runsOnPullRequestsInto(workflow, branch) {
8140
8450
  return ignore ? !ignore.some((p) => globMatches(p, branch)) : void 0;
8141
8451
  }
8142
8452
  function batchCiProblems(root, batch) {
8143
- const dir = path29.join(root, ".github", "workflows");
8453
+ const dir = path30.join(root, ".github", "workflows");
8144
8454
  if (!existsSync(dir)) return [];
8145
8455
  const problems = [];
8146
8456
  for (const name of readdirSync(dir)) {
8147
8457
  if (!/\.ya?ml$/.test(name)) continue;
8148
- const workflow = readFileSync(path29.join(dir, name), "utf8");
8458
+ const workflow = readFileSync(path30.join(dir, name), "utf8");
8149
8459
  const main = runsOnPullRequestsInto(workflow, "main");
8150
8460
  if (main && !runsOnPullRequestsInto(workflow, sampleBranch(batch))) {
8151
8461
  problems.push({ rule: "batch-ci", message: `.github/workflows/${name}: runs on pull requests into main but not into ${batch}; let pull_request's branch filter include it` });
@@ -8190,20 +8500,20 @@ function readObject(file, key2) {
8190
8500
  }
8191
8501
  }
8192
8502
  function settings(root, options) {
8193
- const fromPackage = readObject(path29.join(root, "package.json"), "genesisFeatures");
8194
- const fromConfig = readObject(path29.join(root, "genesis.config.json"), "features");
8503
+ const fromPackage = readObject(path30.join(root, "package.json"), "genesisFeatures");
8504
+ const fromConfig = readObject(path30.join(root, "genesis.config.json"), "features");
8195
8505
  const given = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== void 0));
8196
8506
  return { ...fromPackage, ...fromConfig, ...given };
8197
8507
  }
8198
8508
  async function loadRegistry(input) {
8199
- const root = path29.resolve(input.dir);
8509
+ const root = path30.resolve(input.dir);
8200
8510
  const options = settings(root, input);
8201
- const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path29.join(root, p)));
8202
- if (!registry || !existsSync(path29.join(root, registry))) {
8511
+ const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path30.join(root, p)));
8512
+ if (!registry || !existsSync(path30.join(root, registry))) {
8203
8513
  throw new Error(`No feature registry found. Looked for ${options.registry ?? DEFAULT_REGISTRIES.join(" and ")}; pass --registry.`);
8204
8514
  }
8205
- const jiti = createJiti(path29.join(root, "package.json"), { moduleCache: false });
8206
- const load = async (file) => await jiti.import(path29.join(root, file));
8515
+ const jiti = createJiti(path30.join(root, "package.json"), { moduleCache: false });
8516
+ const load = async (file) => await jiti.import(path30.join(root, file));
8207
8517
  const mod = await load(registry);
8208
8518
  const features2 = mod.features ?? mod.default;
8209
8519
  if (!isObject4(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
@@ -8215,7 +8525,7 @@ async function loadRegistry(input) {
8215
8525
  const project = {
8216
8526
  ...rest,
8217
8527
  root,
8218
- source: options.source ?? registry.split(path29.sep).join("/"),
8528
+ source: options.source ?? registry.split(path30.sep).join("/"),
8219
8529
  features: features2,
8220
8530
  flags
8221
8531
  };
@@ -8266,23 +8576,23 @@ async function runFeaturesCheck(options) {
8266
8576
  function readFeaturePackages(root) {
8267
8577
  const found = [];
8268
8578
  const read2 = (dir, inRepo) => {
8269
- const file = path29.join(dir, "package.json");
8579
+ const file = path30.join(dir, "package.json");
8270
8580
  if (!existsSync(file)) return;
8271
8581
  try {
8272
8582
  const pkg = JSON.parse(readFileSync(file, "utf8"));
8273
8583
  const layer = pkg.genesis?.layer;
8274
8584
  if (typeof pkg.name !== "string" || !PACKAGE_LAYERS.includes(layer)) return;
8275
8585
  if (found.some((p) => p.name === pkg.name)) return;
8276
- found.push({ name: pkg.name, layer, ...inRepo ? { dir: path29.relative(root, dir).split(path29.sep).join("/") } : {} });
8586
+ found.push({ name: pkg.name, layer, ...inRepo ? { dir: path30.relative(root, dir).split(path30.sep).join("/") } : {} });
8277
8587
  } catch {
8278
8588
  }
8279
8589
  };
8280
8590
  for (const [base, inRepo] of [
8281
- [path29.join(root, "packages"), true],
8282
- [path29.join(root, "node_modules", "@marktiderman"), false]
8591
+ [path30.join(root, "packages"), true],
8592
+ [path30.join(root, "node_modules", "@marktiderman"), false]
8283
8593
  ]) {
8284
8594
  if (!existsSync(base)) continue;
8285
- for (const name of readdirSync(base)) read2(path29.join(base, name), inRepo);
8595
+ for (const name of readdirSync(base)) read2(path30.join(base, name), inRepo);
8286
8596
  }
8287
8597
  return found;
8288
8598
  }
@@ -8399,7 +8709,7 @@ function readRegister(markdown) {
8399
8709
  const need = at(row, "need");
8400
8710
  if (!need || need === "-") problems.push(`${where2}: say the need in one line`);
8401
8711
  const local = at(row, "local");
8402
- if (local && local !== "-" && localPaths(local).some((p) => path29.isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p) || p.split(/[\\/]/).includes(".."))) {
8712
+ if (local && local !== "-" && localPaths(local).some((p) => path30.isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p) || p.split(/[\\/]/).includes(".."))) {
8403
8713
  problems.push(`${where2}: local must be paths inside the app, relative to its root`);
8404
8714
  }
8405
8715
  const opt = (c) => at(row, c) && at(row, c) !== "-" ? at(row, c) : void 0;
@@ -8411,13 +8721,13 @@ function localPaths(local) {
8411
8721
  return (local ?? "").split(/,\s+|<br\s*\/?>/i).map((p) => p.trim()).filter((p) => p && p !== "-");
8412
8722
  }
8413
8723
  function checkUpstream(root) {
8414
- const found = REGISTER_PATHS.find((p) => existsSync(path29.join(root, p)));
8724
+ const found = REGISTER_PATHS.find((p) => existsSync(path30.join(root, p)));
8415
8725
  if (!found) return { entries: [], problems: [], warnings: [`no ${REGISTER_PATHS.join(" or ")}: nothing to check (add one when the app first needs something Genesis lacks)`], missing: true };
8416
- const { entries, problems } = readRegister(readFileSync(path29.join(root, found), "utf8"));
8726
+ const { entries, problems } = readRegister(readFileSync(path30.join(root, found), "utf8"));
8417
8727
  const warnings = [];
8418
8728
  for (const e of entries) {
8419
8729
  const paths = localPaths(e.local);
8420
- const absent = paths.filter((p) => !existsSync(path29.join(root, p)));
8730
+ const absent = paths.filter((p) => !existsSync(path30.join(root, p)));
8421
8731
  const present = paths.filter((p) => !absent.includes(p));
8422
8732
  if (absent.length && e.status !== "promoted" && e.status !== "declined") problems.push(`${e.id}: local ${absent.join(", ")} doesn't exist`);
8423
8733
  if (present.length && e.status === "promoted") {
@@ -8482,8 +8792,8 @@ function routeTags(source) {
8482
8792
  }
8483
8793
  function wireStudioRoute(source, route, pageImportPath) {
8484
8794
  const tags = routeTags(source);
8485
- const relative14 = route.replace(/^\//, "");
8486
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative14.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
8795
+ const relative15 = route.replace(/^\//, "");
8796
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative15.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
8487
8797
  if (existing) {
8488
8798
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
8489
8799
  }
@@ -8491,17 +8801,17 @@ function wireStudioRoute(source, route, pageImportPath) {
8491
8801
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
8492
8802
  if (roots.length !== 1) {
8493
8803
  return {
8494
- 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="${relative14}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
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.`
8495
8805
  };
8496
8806
  }
8497
8807
  const layout = roots[0];
8498
8808
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
8499
- if (base && !relative14.startsWith(`${base}/`)) {
8809
+ if (base && !relative15.startsWith(`${base}/`)) {
8500
8810
  return {
8501
8811
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
8502
8812
  };
8503
8813
  }
8504
- const childPath = base ? relative14.slice(base.length + 1) : relative14;
8814
+ const childPath = base ? relative15.slice(base.length + 1) : relative15;
8505
8815
  const guard = GUARD.exec(source)?.[1];
8506
8816
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
8507
8817
  const before = source.slice(0, layout.close);
@@ -8875,8 +9185,8 @@ ${indent}}`;
8875
9185
  return JSON.stringify(value);
8876
9186
  }
8877
9187
  function featureKindField(root) {
8878
- for (let dir = path29.resolve(root); ; dir = path29.dirname(dir)) {
8879
- for (const file of [path29.join(dir, "node_modules/@marktiderman/genesis-features/package.json"), path29.join(dir, "packages/features/package.json")]) {
9188
+ for (let dir = path30.resolve(root); ; dir = path30.dirname(dir)) {
9189
+ for (const file of [path30.join(dir, "node_modules/@marktiderman/genesis-features/package.json"), path30.join(dir, "packages/features/package.json")]) {
8880
9190
  try {
8881
9191
  const pkg = JSON.parse(readFileSync(file, "utf8"));
8882
9192
  if (pkg.name !== "@marktiderman/genesis-features" || !pkg.version) continue;
@@ -8885,7 +9195,7 @@ function featureKindField(root) {
8885
9195
  } catch {
8886
9196
  }
8887
9197
  }
8888
- if (path29.dirname(dir) === dir) return "layer";
9198
+ if (path30.dirname(dir) === dir) return "layer";
8889
9199
  }
8890
9200
  }
8891
9201
  function featureSnippet(manifest, owner, kindField = "kind") {
@@ -8963,12 +9273,12 @@ var init_registry_edit = __esm({
8963
9273
  });
8964
9274
  function routerRoot2(root) {
8965
9275
  try {
8966
- const config = JSON.parse(readFileSync(path29.join(root, "genesis.config.json"), "utf8"));
9276
+ const config = JSON.parse(readFileSync(path30.join(root, "genesis.config.json"), "utf8"));
8967
9277
  const configured = config.doctor?.native?.routerRoot;
8968
- if (configured && existsSync(path29.join(root, configured, "_layout.tsx"))) return configured.replace(/\/+$/, "");
9278
+ if (configured && existsSync(path30.join(root, configured, "_layout.tsx"))) return configured.replace(/\/+$/, "");
8969
9279
  } catch {
8970
9280
  }
8971
- for (const dir of ["src/app", "app"]) if (existsSync(path29.join(root, dir, "_layout.tsx"))) return dir;
9281
+ for (const dir of ["src/app", "app"]) if (existsSync(path30.join(root, dir, "_layout.tsx"))) return dir;
8972
9282
  return null;
8973
9283
  }
8974
9284
  function routeOf(file) {
@@ -9030,7 +9340,7 @@ __export(add_exports, {
9030
9340
  });
9031
9341
  function appDependencies(root) {
9032
9342
  try {
9033
- const pkg = JSON.parse(readFileSync(path29.join(root, "package.json"), "utf8"));
9343
+ const pkg = JSON.parse(readFileSync(path30.join(root, "package.json"), "utf8"));
9034
9344
  return { ...pkg["dependencies"], ...pkg["devDependencies"], ...pkg["optionalDependencies"] };
9035
9345
  } catch {
9036
9346
  return {};
@@ -9039,14 +9349,14 @@ function appDependencies(root) {
9039
9349
  function registryFile(root) {
9040
9350
  const read2 = (file, key2) => {
9041
9351
  try {
9042
- const v = JSON.parse(readFileSync(path29.join(root, file), "utf8"))[key2]?.registry;
9352
+ const v = JSON.parse(readFileSync(path30.join(root, file), "utf8"))[key2]?.registry;
9043
9353
  return typeof v === "string" ? v : void 0;
9044
9354
  } catch {
9045
9355
  return void 0;
9046
9356
  }
9047
9357
  };
9048
9358
  const named = read2("genesis.config.json", "features") ?? read2("package.json", "genesisFeatures");
9049
- for (const candidate of named ? [named] : ["src/features.ts", "features.ts"]) if (existsSync(path29.join(root, candidate))) return candidate;
9359
+ for (const candidate of named ? [named] : ["src/features.ts", "features.ts"]) if (existsSync(path30.join(root, candidate))) return candidate;
9050
9360
  return null;
9051
9361
  }
9052
9362
  async function registryIds(root, file) {
@@ -9134,23 +9444,28 @@ verify_jwt = false
9134
9444
  return { content: `${config.replace(/\s*$/, "\n")}${add}`, names };
9135
9445
  }
9136
9446
  async function runAdd(options) {
9137
- const root = path29.resolve(options.root);
9447
+ const root = path30.resolve(options.root);
9138
9448
  const log = options.log ?? SILENT;
9139
9449
  const now = options.now ?? /* @__PURE__ */ new Date();
9140
9450
  const warnings = [];
9141
9451
  const install = options.install !== false;
9142
9452
  let found = await findBlock(root, options.block, { ...options.package ? { package: options.package } : {}, warnings });
9143
9453
  const lock = readLock(root);
9454
+ const home = databaseElsewhere(root);
9455
+ const databaseOnly = options.databaseOnly === true;
9456
+ if (databaseOnly && home) throw new Error(`--database-only adds a block's database files, and ${home.app ? `this app's are in ${home.app}` : "this app has none"} (genesis.config.json supabase): run it there.`);
9457
+ if (databaseOnly && !found.manifest.migrations.length && !found.manifest.functions.length) throw new Error(`${found.manifest.id} has no database files (migrations or Edge Functions); --database-only has nothing to add.`);
9144
9458
  const deps = appDependencies(root);
9145
9459
  const pm = detectPackageManager(root);
9146
9460
  const specs = [];
9147
9461
  const local = localPackageNames(root);
9148
- for (const name of found.manifest.packages) {
9462
+ const needed = databaseOnly ? [.../* @__PURE__ */ new Set([...found.manifest.migrations.map((m) => m.package), ...found.manifest.functions.map((f) => f.package)])] : found.manifest.packages;
9463
+ for (const name of needed) {
9149
9464
  if (deps[name] || local.has(name)) continue;
9150
9465
  const pin = pinnedVersion2(root, name);
9151
9466
  specs.push(pin ? `${name}@${pin.version}` : name);
9152
9467
  }
9153
- for (const spec of found.manifest.install) {
9468
+ for (const spec of databaseOnly ? [] : found.manifest.install) {
9154
9469
  const name = spec.startsWith("@") ? `@${spec.slice(1).split("@")[0]}` : spec.split("@")[0];
9155
9470
  if (!deps[name]) specs.push(spec);
9156
9471
  }
@@ -9158,7 +9473,7 @@ async function runAdd(options) {
9158
9473
  const registry = registryFile(root);
9159
9474
  const ids = registry ? await registryIds(root, registry) : null;
9160
9475
  const blockIds = new Set((await allBlocks(root)).map((b) => b.manifest.id));
9161
- for (const req of found.manifest.requires) {
9476
+ for (const req of databaseOnly ? [] : found.manifest.requires) {
9162
9477
  if (lock.blocks[req] || ids?.has(req)) continue;
9163
9478
  warnings.push(blockIds.has(req) ? `${options.block} requires the ${req} block: add it too (genesis add ${req}), unless the app already has it.` : `${options.block} requires the ${req} feature; make sure the app has it.`);
9164
9479
  }
@@ -9166,25 +9481,35 @@ async function runAdd(options) {
9166
9481
  const kept = [];
9167
9482
  const created = [];
9168
9483
  const edited = [];
9169
- const makePlan = (manifest2, from) => {
9484
+ const makePlan = (full, from) => {
9170
9485
  const planWarnings = [];
9171
- const migrations2 = planMigrations(root, sourceMigrations(root, manifest2), { now, ...lock.migrations ? { copied: lock.migrations } : {} });
9172
- const owned2 = ownedWrites(root, manifest2, planWarnings).map((w) => ({ ...w, content: substitute(w.content, lock.substitutions) }));
9173
- const fragment2 = agentsFragment(root, manifest2);
9174
- if (manifest2.agents && !fragment2) planWarnings.push(`${manifest2.agents.package} ${manifest2.agents.path}: can't read it; AGENTS.md wasn't changed.`);
9175
- const { routerRoot: routerRoot4, stubs: stubs2 } = planRouteStubs(root, manifest2.routes);
9176
- const toml2 = configTomlEdit(root, manifest2, planWarnings);
9486
+ const catalog = catalogBlocks();
9487
+ const providers = providingMigrations([full, ...catalog]);
9488
+ const migrations2 = home ? { rows: [], creates: [] } : planMigrations(root, sourceMigrations(root, full), { now, ...lock.migrations ? { copied: lock.migrations } : {}, providers });
9489
+ const superseded = supersededFunctions(migrations2.rows, providers);
9490
+ const replaced2 = full.functions.filter((fn) => superseded.has(`${fn.package}:${fn.dir}`)).map((fn) => {
9491
+ const by = superseded.get(`${fn.package}:${fn.dir}`);
9492
+ const block = providers.find((p) => p.package === by.package && p.file === by.file)?.block;
9493
+ const instead = (block ? catalog.find((b) => b.id === block)?.functions : void 0)?.map((f) => f.dir.split("/").pop()) ?? [];
9494
+ return { name: fn.dir.split("/").pop(), by, block, instead };
9495
+ });
9496
+ const manifest2 = { ...full, functions: full.functions.filter((fn) => !superseded.has(`${fn.package}:${fn.dir}`)) };
9497
+ const owned2 = ownedWrites(root, databaseOnly ? { ...manifest2, skills: [] } : manifest2, planWarnings).filter((w) => !home || !isSupabasePath(w.path)).map((w) => ({ ...w, content: substitute(w.content, lock.substitutions) }));
9498
+ const fragment2 = databaseOnly ? null : agentsFragment(root, manifest2);
9499
+ if (!databaseOnly && manifest2.agents && !fragment2) planWarnings.push(`${manifest2.agents.package} ${manifest2.agents.path}: can't read it; AGENTS.md wasn't changed.`);
9500
+ const { routerRoot: routerRoot4, stubs: stubs2 } = databaseOnly ? { routerRoot: null, stubs: [] } : planRouteStubs(root, manifest2.routes);
9501
+ const toml2 = home ? null : configTomlEdit(root, manifest2, planWarnings);
9177
9502
  let snippet2;
9178
9503
  let registryEdit2 = null;
9179
- if (!ids?.has(manifest2.id)) {
9504
+ if (!databaseOnly && !ids?.has(manifest2.id)) {
9180
9505
  const owner = JSON.parse(readApp(root, "package.json") ?? "{}").name ?? "app";
9181
9506
  snippet2 = featureSnippet(manifest2, owner, featureKindField(root));
9182
9507
  if (registry) registryEdit2 = addFeatureEntry(readApp(root, registry) ?? "", snippet2);
9183
9508
  }
9184
9509
  const print = (mark, p, note = "") => log.info(` ${mark} ${p}${note ? ` ${note}` : ""}`);
9185
- log.info(`${manifest2.id}: from ${manifest2.package}${manifest2.version ? ` ${manifest2.version}` : ""} (${from === "local" ? "local package" : from === "installed" ? "installed" : "not installed yet: files are read after the install"})`);
9510
+ log.info(`${manifest2.id}${databaseOnly ? " (database only)" : ""}: from ${manifest2.package}${manifest2.version ? ` ${manifest2.version}` : ""} (${from === "local" ? "local package" : from === "installed" ? "installed" : "not installed yet: files are read after the install"})`);
9186
9511
  if (command) log.info(` install: ${shellLine(command)}${install ? "" : " (skipped: --no-install)"}`);
9187
- log.info(formatMigrationRows(migrations2.rows).replace(/^/gm, " "));
9512
+ log.info(` ${home ? elsewhereNote(home, addThereCommand(manifest2.id)) : formatMigrationRows(migrations2.rows).replace(/^/gm, " ").trimStart()}`);
9188
9513
  for (const c of migrations2.creates) if (c.kind === "test") print("+", c.path, "(pgTAP test)");
9189
9514
  for (const w of owned2) {
9190
9515
  const existing = readApp(root, w.path);
@@ -9194,7 +9519,8 @@ async function runAdd(options) {
9194
9519
  if (toml2) print("~", "supabase/config.toml", `([functions.${toml2.names.join("], [functions.")}] verify_jwt = false)`);
9195
9520
  if (fragment2) print("~", "AGENTS.md", `(${fragmentMarkers(manifest2.id).start})`);
9196
9521
  if (registryEdit2 && registry) print("~", registry, `(adds ${manifest2.id})`);
9197
- return { manifest: manifest2, migrations: migrations2, owned: owned2, fragment: fragment2, routerRoot: routerRoot4, stubs: stubs2, toml: toml2, snippet: snippet2, registryEdit: registryEdit2, planWarnings };
9522
+ for (const r of replaced2) print("-", `supabase/functions/${r.name}`, `(superseded: ${r.by.package} ${r.by.file} provides its migration)`);
9523
+ return { manifest: manifest2, migrations: migrations2, owned: owned2, fragment: fragment2, routerRoot: routerRoot4, stubs: stubs2, toml: toml2, snippet: snippet2, registryEdit: registryEdit2, planWarnings, replaced: replaced2 };
9198
9524
  };
9199
9525
  let plan = makePlan(found.manifest, found.from);
9200
9526
  if (!options.dryRun && !options.yes) {
@@ -9209,7 +9535,7 @@ async function runAdd(options) {
9209
9535
  }
9210
9536
  warnings.push(...plan.planWarnings);
9211
9537
  if (found.from === "catalog") warnings.push(`${found.manifest.package} isn't installed, so its files can't be read yet: migrations, functions and skills are listed, not copied. Install it and run genesis add ${found.manifest.id} again.`);
9212
- const { manifest, migrations, owned, fragment, routerRoot: routerRoot3, stubs, toml, snippet, registryEdit } = plan;
9538
+ const { manifest, migrations, owned, fragment, routerRoot: routerRoot3, stubs, toml, snippet, registryEdit, replaced } = plan;
9213
9539
  for (const row of migrations.rows) {
9214
9540
  if (needsAttention(row)) kept.push({ path: row.copy ?? row.file, why: `${row.state}: ${row.detail}. Run genesis migrate --forward to add a forward migration.` });
9215
9541
  }
@@ -9217,14 +9543,28 @@ async function runAdd(options) {
9217
9543
  if (stub.existing) continue;
9218
9544
  if (!stub.file) steps.push(`Add a ${stub.route.path} screen to your router${stub.route.description ? ` (${stub.route.description})` : ""}${stub.route.signedIn ? ", for signed-in people only" : ""}.`);
9219
9545
  }
9220
- for (const fn of manifest.functions) {
9546
+ const database = manifest.migrations.length > 0 || manifest.functions.length > 0;
9547
+ if (home && database) {
9548
+ const there = blocksMissingThere(home, [manifest.id], [manifest, ...catalogBlocks()]);
9549
+ if (!home.app) steps.push(`${manifest.id} ships database files (migrations or Edge Functions); ${elsewhereNote(home)}`);
9550
+ else if (there && !there.length) steps.push(`${manifest.id}'s database files: ${home.app} already has every one of its migrations and Edge Functions, so nothing to add there.`);
9551
+ else {
9552
+ if (!there) warnings.push(`Can't read ${home.app}'s genesis.lock.json or migrations, so whether it has ${manifest.id}'s database files is unknown.`);
9553
+ steps.push(`Add ${manifest.id}'s database files in ${home.app}, which holds this app's database: ${addThereCommand(manifest.id)} there (genesis.config.json supabase.app).`);
9554
+ }
9555
+ }
9556
+ for (const fn of home ? [] : manifest.functions) {
9221
9557
  const name = fn.dir.split("/").pop();
9222
9558
  if (fn.verifyJwt === false && !readApp(root, "supabase/config.toml")) steps.push(`Deploy ${name} without the gateway's JWT check: supabase functions deploy ${name} --no-verify-jwt`);
9223
9559
  if (fn.secrets?.length) steps.push(`Set the ${name} function's secrets: supabase secrets set ${fn.secrets.map((s) => `${s}=\u2026`).join(" ")}`);
9224
9560
  }
9561
+ for (const r of home ? [] : replaced) {
9562
+ const instead = r.instead.length ? `${r.instead.join(" and ")} (the ${r.block} block's Edge Function${r.instead.length === 1 ? "" : "s"}) sends instead: deploy ${r.instead.length === 1 ? "it" : "them"} as its steps say` : `${r.by.package}'s own functions send instead`;
9563
+ steps.push(`${r.name} isn't copied or deployed: ${r.by.package} ${r.by.file} is in this app and provides the migration it needs, so ${instead}.`);
9564
+ }
9225
9565
  if (migrations.creates.some((c) => c.kind === "migration")) steps.push("Review the new migrations in supabase/migrations, then apply them (supabase db push, or open a pull request).");
9226
- steps.push(...manifest.steps);
9227
- if (manifest.privacy?.collects?.length) steps.push(`Update the App Store privacy label and Play data safety form: ${manifest.id} collects ${manifest.privacy.collects.map((c) => c.type).join(", ")}.`);
9566
+ if (!databaseOnly) steps.push(...manifest.steps);
9567
+ if (!databaseOnly && manifest.privacy?.collects?.length) steps.push(`Update the App Store privacy label and Play data safety form: ${manifest.id} collects ${manifest.privacy.collects.map((c) => c.type).join(", ")}.`);
9228
9568
  if (snippet && registry && !registryEdit) steps.push(`Add ${manifest.id} to ${registry} (the edit wasn't safe to make automatically):
9229
9569
  ${snippet}`);
9230
9570
  if (snippet && !registry) steps.push(`No feature registry (features.ts) here; when you add one, list ${manifest.id}:
@@ -9265,12 +9605,14 @@ ${snippet}`);
9265
9605
  ${snippet}`);
9266
9606
  } else edited.push(registry);
9267
9607
  }
9268
- if (found.from === "installed" || found.from === "local") lock.blocks[manifest.id] = { package: manifest.package, ...manifest.version ? { version: manifest.version } : {} };
9608
+ if (databaseOnly) {
9609
+ if (found.from === "catalog") steps.unshift(`Install ${needed.join(" and ")}, then run genesis add ${manifest.id} --database-only again to copy its files.`);
9610
+ } else if (found.from === "installed" || found.from === "local") lock.blocks[manifest.id] = { package: manifest.package, ...manifest.version ? { version: manifest.version } : {} };
9269
9611
  else steps.unshift(`Install ${manifest.packages.join(" and ")}, then run genesis add ${manifest.id} again to copy its files.`);
9270
9612
  const lockBefore = readApp(root, LOCK_FILE);
9271
9613
  writeLock(root, lock);
9272
9614
  if (readApp(root, LOCK_FILE) !== lockBefore) edited.push(LOCK_FILE);
9273
- if (registry && options.featuresBuild !== false) {
9615
+ if (!databaseOnly && registry && options.featuresBuild !== false) {
9274
9616
  try {
9275
9617
  const { runFeaturesBuild: runFeaturesBuild2 } = await Promise.resolve().then(() => (init_features(), features_exports));
9276
9618
  const changed = await runFeaturesBuild2({ dir: root });
@@ -9279,7 +9621,7 @@ ${snippet}`);
9279
9621
  warnings.push(`features build failed: ${err instanceof Error ? err.message : String(err)}`);
9280
9622
  }
9281
9623
  }
9282
- if (!routerRoot3 && manifest.routes.length) warnings.push("No Expo Router root (a _layout.tsx in src/app or app), so no route stubs were written; the steps list the screens.");
9624
+ if (!databaseOnly && !routerRoot3 && manifest.routes.length) warnings.push("No Expo Router root (a _layout.tsx in src/app or app), so no route stubs were written; the steps list the screens.");
9283
9625
  return { block: manifest, install: command, migrations, created, kept, edited, steps, ...snippet ? { featureSnippet: snippet } : {}, warnings };
9284
9626
  }
9285
9627
  function recordOwned(lock, appRel, source, content, root, pkg) {
@@ -9296,6 +9638,7 @@ var init_add = __esm({
9296
9638
  init_files();
9297
9639
  init_lock();
9298
9640
  init_migrations();
9641
+ init_database();
9299
9642
  init_owned();
9300
9643
  init_pm();
9301
9644
  init_registry_edit();
@@ -9339,7 +9682,7 @@ function notificationTypesSql(rows, registryFile2) {
9339
9682
  }
9340
9683
  function configuredRegistry(root) {
9341
9684
  try {
9342
- const raw = JSON.parse(readFileSync(path29.join(root, "genesis.config.json"), "utf8"));
9685
+ const raw = JSON.parse(readFileSync(path30.join(root, "genesis.config.json"), "utf8"));
9343
9686
  return typeof raw.notifications?.registry === "string" ? raw.notifications.registry : void 0;
9344
9687
  } catch {
9345
9688
  return void 0;
@@ -9358,14 +9701,14 @@ async function planNotificationTypes(root, options) {
9358
9701
  warnings.push(`Notification types: not checked on a dry run (loading ${file} runs app code).`);
9359
9702
  return { registry: file, warnings };
9360
9703
  }
9361
- const absolute = path29.resolve(root, file);
9704
+ const absolute = path30.resolve(root, file);
9362
9705
  if (!existsSync(absolute)) {
9363
9706
  warnings.push(`Notification types: ${file} doesn't exist (a relative path is resolved against the app's root, ${root}).`);
9364
9707
  return { registry: file, warnings };
9365
9708
  }
9366
9709
  let mod;
9367
9710
  try {
9368
- const jiti = createJiti(path29.join(root, "package.json"), { moduleCache: false });
9711
+ const jiti = createJiti(path30.join(root, "package.json"), { moduleCache: false });
9369
9712
  mod = await jiti.import(absolute);
9370
9713
  } catch (err) {
9371
9714
  warnings.push(`Notification types: couldn't load ${file} (${err instanceof Error ? err.message : String(err)}).`);
@@ -9376,8 +9719,8 @@ async function planNotificationTypes(root, options) {
9376
9719
  warnings.push(`Notification types: ${file} exports no defineNotifications registry (export it as \`notifications\`).`);
9377
9720
  return { registry: file, warnings };
9378
9721
  }
9379
- const shown = path29.isAbsolute(file) ? path29.relative(root, absolute) : file;
9380
- const content = notificationTypesSql(found.toTypeRows(), shown.split(path29.sep).join("/"));
9722
+ const shown = path30.isAbsolute(file) ? path30.relative(root, absolute) : file;
9723
+ const content = notificationTypesSql(found.toTypeRows(), shown.split(path30.sep).join("/"));
9381
9724
  const app = readAppMigrations(root);
9382
9725
  const latest = app.filter((m) => m.name.endsWith(`_${TYPES_STEM}.sql`)).sort((a, b) => a.name < b.name ? -1 : 1).pop();
9383
9726
  if (latest && payloadOf(latest.content) === payloadOf(content)) return { registry: file, warnings };
@@ -9409,18 +9752,32 @@ __export(migrate_exports, {
9409
9752
  runMigrate: () => runMigrate
9410
9753
  });
9411
9754
  async function runMigrate(options) {
9412
- const root = path29.resolve(options.root);
9755
+ const root = path30.resolve(options.root);
9413
9756
  const lock = readLock(root);
9414
9757
  const warnings = [];
9415
- const off = appBlocksSwitchedOff(root, catalogBlocks(), Object.keys(lock.blocks));
9758
+ const home = databaseElsewhere(root);
9759
+ const catalog = catalogBlocks();
9760
+ const off = appBlocksSwitchedOff(root, catalog, Object.keys(lock.blocks));
9416
9761
  const switchedOff = Object.keys(lock.blocks).filter((id) => off.has(id) && !options.blocks?.includes(id));
9762
+ if (home) {
9763
+ const ids2 = [.../* @__PURE__ */ new Set([...Object.keys(lock.blocks).filter((id) => !switchedOff.includes(id)), ...options.blocks ?? []])];
9764
+ const there = blocksMissingThere(home, ids2, catalog);
9765
+ if (home.app && !there) warnings.push(`Can't read ${home.app}'s genesis.lock.json or migrations, so every block is listed.`);
9766
+ const missing = orderForAdding(there ?? ids2, catalog);
9767
+ if (home.app && !home.hasSupabase) warnings.push(`${home.app} has no supabase folder: genesis.config.json supabase.app should name the app that holds it.`);
9768
+ const line = addThereLine(home, missing);
9769
+ const note = [elsewhereNote(home), ...line ? [line] : []].join(" ");
9770
+ return { plan: { rows: [], creates: [] }, written: [], warnings, switchedOff: switchedOff.map((id) => switchedOffNote(id, off.get(id))), attention: false, elsewhere: { app: home.app, note, missing } };
9771
+ }
9417
9772
  const ids = [.../* @__PURE__ */ new Set([...Object.keys(lock.blocks).filter((id) => !switchedOff.includes(id)), ...options.blocks ?? []])];
9418
9773
  const sources = [];
9419
9774
  const local = localPackageNames(root);
9775
+ const manifests = [];
9420
9776
  for (const id of ids) {
9421
9777
  const pkg = lock.blocks[id]?.package;
9422
9778
  try {
9423
9779
  const { manifest } = await findBlock(root, id, { ...pkg ? { package: pkg } : {}, warnings });
9780
+ manifests.push(manifest);
9424
9781
  sources.push(...sourceMigrations(root, manifest));
9425
9782
  } catch (err) {
9426
9783
  warnings.push(err instanceof Error ? err.message : String(err));
@@ -9443,7 +9800,7 @@ async function runMigrate(options) {
9443
9800
  sources.push({ package: t.package, file: t.file, source });
9444
9801
  }
9445
9802
  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.");
9446
- const plan = planMigrations(root, sources, { now: options.now ?? /* @__PURE__ */ new Date(), ...options.forward ? { forward: true } : {}, ...lock.migrations ? { copied: lock.migrations } : {} });
9803
+ const plan = planMigrations(root, sources, { now: options.now ?? /* @__PURE__ */ new Date(), ...options.forward ? { forward: true } : {}, ...lock.migrations ? { copied: lock.migrations } : {}, providers: providingMigrations([...manifests, ...catalog]) });
9447
9804
  const attention = plan.rows.some(needsAttention);
9448
9805
  const notifies = ids.some((id) => (lock.blocks[id]?.package ?? (id === "notifications" ? NOTIFICATIONS_PACKAGE : "")) === NOTIFICATIONS_PACKAGE);
9449
9806
  const types = notifies ? await planNotificationTypes(root, {
@@ -9474,17 +9831,18 @@ var init_migrate = __esm({
9474
9831
  init_lock();
9475
9832
  init_manifest();
9476
9833
  init_migrations();
9834
+ init_database();
9477
9835
  init_add();
9478
9836
  init_files();
9479
9837
  init_notification_types();
9480
9838
  }
9481
9839
  });
9482
9840
  function walk2(dir, rel = "", out = /* @__PURE__ */ new Map()) {
9483
- for (const entry of readdirSync(path29.join(dir, rel), { withFileTypes: true })) {
9841
+ for (const entry of readdirSync(path30.join(dir, rel), { withFileTypes: true })) {
9484
9842
  if (SKIP.has(entry.name)) continue;
9485
9843
  const child = rel ? `${rel}/${entry.name}` : entry.name;
9486
9844
  if (entry.isDirectory()) walk2(dir, child, out);
9487
- else if (entry.isFile()) out.set(child, readFileSync(path29.join(dir, child)));
9845
+ else if (entry.isFile()) out.set(child, readFileSync(path30.join(dir, child)));
9488
9846
  }
9489
9847
  return out;
9490
9848
  }
@@ -9507,7 +9865,7 @@ function gitUpstream(repository = GENESIS_REPOSITORY) {
9507
9865
  const tag = `${name}@${version}`;
9508
9866
  try {
9509
9867
  if (!clone) {
9510
- clone = mkdtempSync(path29.join(tmpdir(), "genesis-upstream-"));
9868
+ clone = mkdtempSync(path30.join(tmpdir(), "genesis-upstream-"));
9511
9869
  git4(["init", "-q"]);
9512
9870
  }
9513
9871
  git4(["fetch", "-q", "--no-tags", "--depth", "1", repository, `+refs/tags/${tag}:refs/tags/${tag}`]);
@@ -9524,7 +9882,7 @@ function gitUpstream(repository = GENESIS_REPOSITORY) {
9524
9882
  }
9525
9883
  });
9526
9884
  if (!manifest) return { error: `the tag ${tag} has no package named ${name}` };
9527
- const dir = path29.posix.dirname(manifest);
9885
+ const dir = path30.posix.dirname(manifest);
9528
9886
  const entries = git4(["ls-tree", "-r", "-z", tag, "--", `${dir}/`]).toString("utf8").split("\0").filter(Boolean).map((line) => /^\d+ blob ([0-9a-f]+)\t(.*)$/s.exec(line)).filter((m) => m !== null).map((m) => ({ sha: m[1], file: m[2].slice(dir.length + 1) })).filter((e) => !e.file.split("/").some((part) => SKIP.has(part)));
9529
9887
  const files = /* @__PURE__ */ new Map();
9530
9888
  if (entries.length) {
@@ -9550,10 +9908,10 @@ function gitUpstream(repository = GENESIS_REPOSITORY) {
9550
9908
  }
9551
9909
  function diffHunks(before, after) {
9552
9910
  if (before === after) return [];
9553
- const dir = mkdtempSync(path29.join(tmpdir(), "genesis-diff-"));
9911
+ const dir = mkdtempSync(path30.join(tmpdir(), "genesis-diff-"));
9554
9912
  try {
9555
- writeFileSync(path29.join(dir, "a"), before);
9556
- writeFileSync(path29.join(dir, "b"), after);
9913
+ writeFileSync(path30.join(dir, "a"), before);
9914
+ writeFileSync(path30.join(dir, "b"), after);
9557
9915
  let out = "";
9558
9916
  try {
9559
9917
  out = execFileSync("git", ["diff", "--no-index", "--no-color", "-U0", "a", "b"], { cwd: dir, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
@@ -9581,9 +9939,9 @@ function shippedBy(upstreamHunks) {
9581
9939
  return (h) => upstreamHunks.some((u) => u.start === h.start && u.count === h.count && u.added.length === h.added.length && u.added.every((l, i) => l === h.added[i]));
9582
9940
  }
9583
9941
  function promotions(root, name) {
9584
- const file = REGISTER_PATHS.find((p) => existsSync(path29.join(root, p)));
9942
+ const file = REGISTER_PATHS.find((p) => existsSync(path30.join(root, p)));
9585
9943
  if (!file) return [];
9586
- const text = readFileSync(path29.join(root, file), "utf8");
9944
+ const text = readFileSync(path30.join(root, file), "utf8");
9587
9945
  const rows = text.split("\n");
9588
9946
  return readRegister(text).entries.filter((e) => e.status === "promoted" && e.package === name).map((e) => {
9589
9947
  const row = rows.find((r) => r.split("|").map((c) => c.trim())[1] === e.id) ?? "";
@@ -9641,7 +9999,7 @@ function planOverlays(root, wanted, upstream2, manifests = ["package.json"]) {
9641
9999
  if (!GENESIS_PACKAGE_NAME.test(pkg.name)) continue;
9642
10000
  let json;
9643
10001
  try {
9644
- json = JSON.parse(readFileSync(path29.join(pkg.dir, "package.json"), "utf8"));
10002
+ json = JSON.parse(readFileSync(path30.join(pkg.dir, "package.json"), "utf8"));
9645
10003
  } catch {
9646
10004
  continue;
9647
10005
  }
@@ -9767,7 +10125,7 @@ function folderReferences(root, plan) {
9767
10125
  for (const file of candidates.sort()) {
9768
10126
  let text;
9769
10127
  try {
9770
- text = readFileSync(path29.join(root, file), "utf8");
10128
+ text = readFileSync(path30.join(root, file), "utf8");
9771
10129
  } catch {
9772
10130
  continue;
9773
10131
  }
@@ -9778,9 +10136,9 @@ function folderReferences(root, plan) {
9778
10136
  }
9779
10137
  function planPins(root, plan, manifests) {
9780
10138
  const pins = /* @__PURE__ */ new Map();
9781
- const overlay = path29.resolve(root, plan.rel);
10139
+ const overlay = path30.resolve(root, plan.rel);
9782
10140
  for (const file of manifests) {
9783
- const abs = path29.join(root, file);
10141
+ const abs = path30.join(root, file);
9784
10142
  if (!existsSync(abs)) continue;
9785
10143
  const text = readFileSync(abs, "utf8");
9786
10144
  let json;
@@ -9789,8 +10147,8 @@ function planPins(root, plan, manifests) {
9789
10147
  } catch {
9790
10148
  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`;
9791
10149
  }
9792
- const here = path29.dirname(abs);
9793
- const local = (spec) => typeof spec === "string" && (spec.startsWith("workspace:") || /^(file|link):/.test(spec) && path29.resolve(here, spec.slice(5)) === overlay);
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);
9794
10152
  let touched2 = false;
9795
10153
  for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
9796
10154
  const deps = json[section];
@@ -9815,10 +10173,10 @@ function applyOverlayPlans(root, plans) {
9815
10173
  const changed = [];
9816
10174
  for (const plan of plans) {
9817
10175
  if (plan.skipped || plan.conflicts.length) continue;
9818
- const dir = path29.join(root, plan.rel);
10176
+ const dir = path30.join(root, plan.rel);
9819
10177
  if (plan.remove) {
9820
10178
  for (const [file, text] of plan.pins) {
9821
- writeFileSync(path29.join(root, file), text);
10179
+ writeFileSync(path30.join(root, file), text);
9822
10180
  changed.push(file);
9823
10181
  }
9824
10182
  rmSync(dir, { recursive: true, force: true });
@@ -9826,10 +10184,10 @@ function applyOverlayPlans(root, plans) {
9826
10184
  continue;
9827
10185
  }
9828
10186
  for (const [file, bytes] of plan.writes) {
9829
- const target = path29.join(dir, file);
10187
+ const target = path30.join(dir, file);
9830
10188
  if (bytes === null) rmSync(target, { force: true });
9831
10189
  else {
9832
- mkdirSync(path29.dirname(target), { recursive: true });
10190
+ mkdirSync(path30.dirname(target), { recursive: true });
9833
10191
  writeFileSync(target, bytes);
9834
10192
  }
9835
10193
  changed.push(`${plan.rel}/${file}`);
@@ -9895,11 +10253,11 @@ function npmLookup(cwd) {
9895
10253
  if (!EXACT_OR_TAG.test(target)) throw new Error(`--version must be an exact version or a dist-tag, not "${target}"`);
9896
10254
  const version = JSON.parse(npm(["view", `${UMBRELLA}@${target}`, "version", "--json"], cwd) || "null");
9897
10255
  if (typeof version !== "string") throw new Error(`${UMBRELLA}@${target} is not one published version`);
9898
- const tmp = mkdtempSync(path29.join(tmpdir(), "genesis-umbrella-"));
10256
+ const tmp = mkdtempSync(path30.join(tmpdir(), "genesis-umbrella-"));
9899
10257
  try {
9900
10258
  const [packed] = JSON.parse(npm(["pack", `${UMBRELLA}@${version}`, "--pack-destination", tmp, "--json"], cwd));
9901
- execFileSync("tar", ["-xzf", path29.join(tmp, packed.filename), "-C", tmp, "package/dist/versions.json"]);
9902
- const manifest = JSON.parse(readFileSync(path29.join(tmp, "package/dist/versions.json"), "utf8"));
10259
+ execFileSync("tar", ["-xzf", path30.join(tmp, packed.filename), "-C", tmp, "package/dist/versions.json"]);
10260
+ const manifest = JSON.parse(readFileSync(path30.join(tmp, "package/dist/versions.json"), "utf8"));
9903
10261
  if (manifest.version !== version) throw new Error(`${UMBRELLA}@${version} ships a versions.json for ${manifest.version}`);
9904
10262
  return manifest;
9905
10263
  } finally {
@@ -9929,8 +10287,8 @@ function readText2(file) {
9929
10287
  function tidyReleaseAgeExcludes(file) {
9930
10288
  const before = readText2(file);
9931
10289
  if (before === null) return false;
9932
- const dir = path29.dirname(file);
9933
- const after = normaliseReleaseAgeExcludes(before, tidyLocked(before, readText2(path29.join(dir, "pnpm-lock.yaml")), readText2(path29.join(dir, ".npmrc"))));
10290
+ const dir = path30.dirname(file);
10291
+ const after = normaliseReleaseAgeExcludes(before, tidyLocked(before, readText2(path30.join(dir, "pnpm-lock.yaml")), readText2(path30.join(dir, ".npmrc"))));
9934
10292
  if (after === before) return false;
9935
10293
  writeFileSync(file, after);
9936
10294
  return true;
@@ -9948,7 +10306,7 @@ function pnpmWorkspaceFileFor(root) {
9948
10306
  const top = gitTopLevel(real2);
9949
10307
  const lockDir = findLockfile(real2)?.dir;
9950
10308
  const fallback = lockDir && (!top || inside2(top, lockDir)) ? lockDir : real2;
9951
- return pnpmWorkspaceFile(real2, fallback, { exists: existsSync, join: path29.join, dirname: path29.dirname }, top ?? void 0);
10309
+ return pnpmWorkspaceFile(real2, fallback, { exists: existsSync, join: path30.join, dirname: path30.dirname }, top ?? void 0);
9952
10310
  }
9953
10311
  function pnpmVersionIn(root) {
9954
10312
  try {
@@ -9975,7 +10333,7 @@ function releaseAgeError(output) {
9975
10333
  }
9976
10334
  function runInstall(root, argv) {
9977
10335
  const [cmd, ...args] = argv;
9978
- return new Promise((resolve26, reject) => {
10336
+ return new Promise((resolve27, reject) => {
9979
10337
  const child = spawn(cmd, args, { cwd: root, stdio: ["inherit", "pipe", "pipe"] });
9980
10338
  let output = "";
9981
10339
  const keep = (to) => (chunk) => {
@@ -9986,7 +10344,7 @@ function runInstall(root, argv) {
9986
10344
  child.stderr.on("data", keep(process.stderr));
9987
10345
  child.on("error", reject);
9988
10346
  child.on("close", (code, signal) => {
9989
- if (code === 0) return resolve26();
10347
+ if (code === 0) return resolve27();
9990
10348
  reject(releaseAgeError(output) ?? new Error(`${shellLine(argv)} failed (${signal ?? `exit code ${code}`})`));
9991
10349
  });
9992
10350
  });
@@ -9998,7 +10356,7 @@ function packageJsons(root) {
9998
10356
  if (files.length) return files;
9999
10357
  } catch {
10000
10358
  }
10001
- return existsSync(path29.join(root, "package.json")) ? ["package.json"] : [];
10359
+ return existsSync(path30.join(root, "package.json")) ? ["package.json"] : [];
10002
10360
  }
10003
10361
  function sourceText(root, source, substitutions) {
10004
10362
  const { package: pkg, path: rel } = parseSource(source);
@@ -10018,11 +10376,11 @@ function sourceText(root, source, substitutions) {
10018
10376
  }
10019
10377
  }
10020
10378
  async function runUpgrade(options) {
10021
- const root = path29.resolve(options.root);
10379
+ const root = path30.resolve(options.root);
10022
10380
  const log = options.log ?? (() => {
10023
10381
  });
10024
10382
  const lookup = options.lookup ?? npmLookup(root);
10025
- const release = options.manifest ? JSON.parse(readFileSync(path29.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
10383
+ const release = options.manifest ? JSON.parse(readFileSync(path30.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
10026
10384
  const pinned = { [UMBRELLA]: release.version, ...release.packages };
10027
10385
  const wanted = (name) => pinned[name] ?? lookup.latest(name);
10028
10386
  const prBase = options.pr && !options.dryRun ? checkPullRequest(root, release.version) : void 0;
@@ -10059,6 +10417,7 @@ async function runUpgrade(options) {
10059
10417
  }
10060
10418
  for (const o of overlays) if (!o.skipped) bumped.delete(`${o.rel}/package.json`);
10061
10419
  const lock = readLock(root);
10420
+ const home = databaseElsewhere(root);
10062
10421
  checkSubstitutions(lock.substitutions);
10063
10422
  const bases = /* @__PURE__ */ new Map();
10064
10423
  for (const [file, entry] of Object.entries(lock.files)) {
@@ -10086,7 +10445,7 @@ async function runUpgrade(options) {
10086
10445
  const excludeWarnings = [];
10087
10446
  if (!options.dryRun && options.install !== false && bumped.size) {
10088
10447
  const workspaceFile = pm === "pnpm" ? pnpmWorkspaceFileFor(root) : null;
10089
- const relWorkspace = workspaceFile ? path29.relative(realpathSync(root), workspaceFile) : null;
10448
+ const relWorkspace = workspaceFile ? path30.relative(realpathSync(root), workspaceFile) : null;
10090
10449
  const workspaceBefore = workspaceFile ? readText2(workspaceFile) : null;
10091
10450
  const tidy = () => {
10092
10451
  if (!workspaceFile || !tidyReleaseAgeExcludes(workspaceFile)) return;
@@ -10145,18 +10504,27 @@ async function runUpgrade(options) {
10145
10504
  try {
10146
10505
  const { manifest } = await findBlock(root, id, { package: entry.package, warnings });
10147
10506
  manifests.push(manifest);
10148
- for (const row of planMigrations(root, sourceMigrations(root, manifest), { now: /* @__PURE__ */ new Date(), tests: false, ...lock.migrations ? { copied: lock.migrations } : {} }).rows) {
10149
- if (row.state === "new") newMigrations.push(`${row.package} ${row.file}`);
10507
+ if (!home) {
10508
+ 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}`);
10510
+ }
10150
10511
  }
10151
10512
  if (manifest.version && manifest.version !== entry.version) lock.blocks[id] = { ...entry, version: manifest.version };
10152
10513
  } catch (err) {
10153
10514
  warnings.push(err instanceof Error ? err.message : String(err));
10154
10515
  }
10155
10516
  }
10517
+ if (home?.app) {
10518
+ const missing = migrationsMissingThere(home, manifests.map((m) => m.id), [...manifests, ...catalog]);
10519
+ if (!missing) warnings.push(`Can't read ${home.app}'s genesis.lock.json or migrations, so its new package migrations aren't listed.`);
10520
+ for (const m of missing ?? []) if (m.kind === "migration") newMigrations.push(`${m.what} (apply in ${home.app}: ${addThereCommand(m.block)})`);
10521
+ }
10156
10522
  const refreshed = [];
10523
+ const elsewhereEntries = home ? Object.keys(lock.files).filter(isSupabasePath) : [];
10157
10524
  for (const [file, entry] of Object.entries(lock.files)) {
10525
+ if (home && isSupabasePath(file)) continue;
10158
10526
  if (offManifests.length && blockOfSource(entry.source, offManifests)) continue;
10159
- if (newMigrations.length && file.startsWith(`${TESTS_DIR}/`)) {
10527
+ if (!home && newMigrations.length && file.startsWith(`${TESTS_DIR}/`)) {
10160
10528
  refreshed.push({ path: file, outcome: "deferred", detail: "new package migrations are waiting: run genesis migrate, then genesis upgrade again" });
10161
10529
  continue;
10162
10530
  }
@@ -10169,9 +10537,15 @@ async function runUpgrade(options) {
10169
10537
  if (outcome.outcome === "updated" || outcome.outcome === "merged") files.add(file);
10170
10538
  if ((outcome.outcome === "conflict" || outcome.outcome === "kept-mine") && !outcome.detail?.includes("already there")) next.add(`${file}.genesis-next`);
10171
10539
  }
10540
+ const functionsLeft = [];
10172
10541
  for (const manifest of manifests) {
10173
10542
  for (const w of ownedWrites(root, manifest, warnings)) {
10174
- if (lock.files[w.path]) continue;
10543
+ if (lock.files[w.path] || home && isSupabasePath(w.path)) continue;
10544
+ const fnDir = /^supabase\/functions\/([^/]+)\//.exec(w.path)?.[1];
10545
+ if (fnDir && !Object.keys(lock.files).some((f) => f.startsWith(`supabase/functions/${fnDir}/`))) {
10546
+ if (!functionsLeft.includes(`${fnDir} (${manifest.id})`)) functionsLeft.push(`${fnDir} (${manifest.id})`);
10547
+ continue;
10548
+ }
10175
10549
  const outcome = copyOwned(root, lock, { ...w, content: substitute(w.content, lock.substitutions) }, options.dryRun);
10176
10550
  if (outcome === "created") {
10177
10551
  added.push(w.path);
@@ -10215,7 +10589,12 @@ async function runUpgrade(options) {
10215
10589
  if (next.size) lines.push("", "Review and delete these before merging (not committed by --pr):", "", ...[...next].map((n) => `- ${n}`));
10216
10590
  if (lock.substitutions && Object.keys(lock.substitutions).length) lines.push("", `Templates renamed with genesis.lock.json's substitutions: ${Object.entries(lock.substitutions).map(([a, b]) => `${a} \u2192 ${b}`).join(", ")}.`);
10217
10591
  if (switchedOff.length) lines.push("", "Blocks switched off (left out):", "", ...switchedOff.map((s) => `- ${s}`));
10218
- if (newMigrations.length) lines.push("", "New package migrations (run `genesis migrate` to copy them):", "", ...newMigrations.map((m) => `- ${m}`));
10592
+ if (newMigrations.length) lines.push("", home ? `New package migrations (in ${home.app ?? "the app that holds the database"}, not here):` : "New package migrations (run `genesis migrate` to copy them):", "", ...newMigrations.map((m) => `- ${m}`));
10593
+ if (functionsLeft.length) lines.push("", "Edge Functions the app never had, not added (genesis add <block> adds one with its config.toml section, where it isn't superseded):", "", ...functionsLeft.map((f) => `- ${f}`));
10594
+ if (home) {
10595
+ lines.push("", `Database files: ${elsewhereNote(home, "genesis upgrade (then genesis migrate)")}`);
10596
+ 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
+ }
10219
10598
  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.`);
10220
10599
  lines.push(...overlayChecklist(overlays));
10221
10600
  if (warnings.length) lines.push("", "Warnings:", "", ...warnings.map((w) => `- ${w}`));
@@ -10229,8 +10608,8 @@ function checkSubstitutions(substitutions) {
10229
10608
  if (!substitutions || !Object.keys(substitutions).length) return;
10230
10609
  let allowed;
10231
10610
  try {
10232
- const was = starterIdentity(readFileSync(path29.join(starterDir(), "starter.config.ts"), "utf8"));
10233
- allowed = [was.name, was.slug, was.scheme, was.bundleId];
10611
+ const was = starterIdentity(readFileSync(path30.join(starterDir(), "starter.config.ts"), "utf8"));
10612
+ allowed = [was.name, was.slug, was.scheme, was.bundleId, APP_FOLDER_PLACEHOLDER];
10234
10613
  } catch {
10235
10614
  allowed = [];
10236
10615
  }
@@ -10262,17 +10641,17 @@ function openPullRequest(root, version, report, base) {
10262
10641
  git4("switch", "-c", branch);
10263
10642
  const top = git4("rev-parse", "--show-toplevel");
10264
10643
  const lockfiles = [];
10265
- for (let dir = path29.resolve(root); ; dir = path29.dirname(dir)) {
10266
- for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path29.join(dir, f))) lockfiles.push(path29.relative(root, path29.join(dir, f)));
10267
- if (lockfiles.length || dir === top || path29.dirname(dir) === dir) break;
10644
+ for (let dir = path30.resolve(root); ; dir = path30.dirname(dir)) {
10645
+ 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)));
10646
+ if (lockfiles.length || dir === top || path30.dirname(dir) === dir) break;
10268
10647
  }
10269
- const paths = [...report.files.filter((f) => existsSync(path29.join(root, f))), ...lockfiles];
10648
+ const paths = [...report.files.filter((f) => existsSync(path30.join(root, f))), ...lockfiles];
10270
10649
  git4("add", "--", ...paths);
10271
10650
  const overlayDirs = report.overlays.filter((o) => !o.skipped && !o.conflicts.length && (o.remove || [...o.writes.values()].includes(null))).map((o) => o.rel);
10272
10651
  if (overlayDirs.length) git4("add", "-A", "--", ...overlayDirs);
10273
10652
  git4("commit", "-q", "-m", `chore(deps): upgrade Genesis to ${version}`);
10274
10653
  git4("push", "-u", "origin", branch);
10275
- const body = path29.join(mkdtempSync(path29.join(tmpdir(), "genesis-pr-")), "body.md");
10654
+ const body = path30.join(mkdtempSync(path30.join(tmpdir(), "genesis-pr-")), "body.md");
10276
10655
  writeFileSync(body, `${report.summary}
10277
10656
 
10278
10657
  Opened by \`genesis upgrade --pr\`.
@@ -10290,6 +10669,7 @@ var init_upgrade = __esm({
10290
10669
  init_init_native();
10291
10670
  init_lock();
10292
10671
  init_migrations();
10672
+ init_database();
10293
10673
  init_owned();
10294
10674
  init_local();
10295
10675
  init_pm();
@@ -10299,8 +10679,8 @@ var init_upgrade = __esm({
10299
10679
  init_overlays2();
10300
10680
  EXACT_OR_TAG = /^[0-9A-Za-z][0-9A-Za-z.+-]*$/;
10301
10681
  inside2 = (dir, file) => {
10302
- const rel = path29.relative(dir, file);
10303
- return rel === "" || rel.split(path29.sep)[0] !== ".." && !path29.isAbsolute(rel);
10682
+ const rel = path30.relative(dir, file);
10683
+ return rel === "" || rel.split(path30.sep)[0] !== ".." && !path30.isAbsolute(rel);
10304
10684
  };
10305
10685
  NOT_MATURE = "ERR_PNPM_NO_MATURE_MATCHING_VERSION";
10306
10686
  SUBSTITUTION_VALUE = /^[A-Za-z0-9][A-Za-z0-9 .+-]{0,59}$/;
@@ -10403,9 +10783,9 @@ async function runScaffold(opts, fs2) {
10403
10783
  function joinPath(...parts) {
10404
10784
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
10405
10785
  }
10406
- function dirname(path51) {
10407
- const idx = path51.lastIndexOf("/");
10408
- return idx === -1 ? "." : path51.slice(0, idx);
10786
+ function dirname(path53) {
10787
+ const idx = path53.lastIndexOf("/");
10788
+ return idx === -1 ? "." : path53.slice(0, idx);
10409
10789
  }
10410
10790
  function brandPackageJson(consumer, genesisVersion) {
10411
10791
  return JSON.stringify(
@@ -10634,7 +11014,7 @@ program.name("genesis").description("Genesis CLI \u2014 scaffolders + workspace
10634
11014
  program.command("init").description("Scaffold a new Genesis consumer (brand package + tailwind + tokens), or with --template native a new Expo app from the Genesis RN starter").argument("<consumer>", "Consumer slug (lowercase, e.g., 'acme')").option("-t, --target <dir>", "Target directory (default: cwd; with --template, ./<consumer>)").option(
10635
11015
  "--genesis-version <v>",
10636
11016
  "Pin @marktiderman/genesis-* version (default: 'workspace:^' for monorepo)"
10637
- ).option("--native", "An Expo app: add NativeWind's preset and scan genesis-ui-native", false).option("--template <name>", "Make a whole app from a template: native (the Genesis RN starter)").option("--display-name <name>", "--template: the app's name on the home screen (default: from the slug)").option("--bundle-id <id>", "--template: iOS bundle id and Android package (default com.example.<slug>)").option("--scheme <scheme>", "--template: the URL scheme (default: the slug)").option("--without <switches>", "--template: starter.config.ts feature switches to turn off, comma-separated (e.g. chat,support); their blocks are left out").option(
11017
+ ).option("--native", "An Expo app: add NativeWind's preset and scan genesis-ui-native", false).option("--template <name>", "Make a whole app from a template: native (the Genesis RN starter)").option("--display-name <name>", "--template: the app's name on the home screen (default: from the slug)").option("--bundle-id <id>", "--template: iOS bundle id and Android package (default com.example.<slug>)").option("--scheme <scheme>", "--template: the URL scheme (default: the slug)").option("--without <switches>", "--template: starter.config.ts feature switches to turn off, comma-separated (e.g. chat,support); their blocks are left out").option("--beside <web-app>", "--template: a phone app that uses this web app's database: no supabase/ here when it has one, and genesis.config.json says where it is").option(
10638
11018
  "--emit-conflicts",
10639
11019
  "Emit `.genesis-next` siblings for files that already exist (so you can diff)",
10640
11020
  false
@@ -10644,19 +11024,21 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
10644
11024
  const { runInitNative: runInitNative2 } = await Promise.resolve().then(() => (init_init_native(), init_native_exports));
10645
11025
  const result2 = await runInitNative2({
10646
11026
  name: consumer,
10647
- target: path29.resolve(opts.target ?? consumer),
11027
+ target: path30.resolve(opts.target ?? consumer),
10648
11028
  ...opts.displayName ? { displayName: opts.displayName } : {},
10649
11029
  ...opts.bundleId ? { bundleId: opts.bundleId } : {},
10650
11030
  ...opts.scheme ? { scheme: opts.scheme } : {},
10651
- ...opts.without ? { without: opts.without.split(",").map((s) => s.trim()).filter(Boolean) } : {}
11031
+ ...opts.without ? { without: opts.without.split(",").map((s) => s.trim()).filter(Boolean) } : {},
11032
+ ...opts.beside ? { beside: opts.beside } : {}
10652
11033
  });
10653
11034
  console.log(`\u2714 Wrote ${result2.files.length} files to ${result2.target}`);
10654
11035
  if (result2.blocks.length) console.log(` blocks: ${result2.blocks.join(", ")}`);
10655
11036
  if (result2.leftOut.length) console.log(` left out (switched off): ${result2.leftOut.join(", ")}`);
11037
+ if (result2.beside?.shared) console.log(` database: ${result2.beside.app}/supabase (no supabase/ here)`);
10656
11038
  console.log(` Genesis packages: ${Object.entries(result2.dependencies).map(([n, v]) => `${n}@${v}`).join(", ")}`);
10657
11039
  console.log("");
10658
11040
  console.log("Next steps:");
10659
- [`cd ${path29.relative(process.cwd(), result2.target) || "."} && pnpm install (or your package manager)`, ...result2.steps].forEach((s, i) => console.log(` ${i + 1}. ${s}`));
11041
+ [`cd ${path30.relative(process.cwd(), result2.target) || "."} && pnpm install (or your package manager)`, ...result2.steps].forEach((s, i) => console.log(` ${i + 1}. ${s}`));
10660
11042
  return;
10661
11043
  }
10662
11044
  opts.target ??= process.cwd();
@@ -10741,7 +11123,7 @@ program.command("introspect").description("Write a checked-in contract (resource
10741
11123
  });
10742
11124
  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) => {
10743
11125
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
10744
- const root = path29.resolve(opts.dir);
11126
+ const root = path30.resolve(opts.dir);
10745
11127
  try {
10746
11128
  if (opts.printGenesis) {
10747
11129
  const { config } = doctor.loadConfig(root, opts.config);
@@ -10760,7 +11142,7 @@ program.command("doctor").description("Check this app against the installed Gene
10760
11142
  });
10761
11143
  program.command("catalog").description("Print the Genesis catalog: for each need, what to use, its import and docs, from every installed Genesis package's declarations").option("--json", "Print the catalog as JSON", false).option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
10762
11144
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
10763
- const packages = doctor.discoverPackages(path29.resolve(opts.dir));
11145
+ const packages = doctor.discoverPackages(path30.resolve(opts.dir));
10764
11146
  const rows = doctor.primitivesCatalog(packages);
10765
11147
  const broken = packages.filter((p) => p.error);
10766
11148
  if (opts.json) {
@@ -10775,7 +11157,7 @@ program.command("catalog").description("Print the Genesis catalog: for each need
10775
11157
  program.command("primitives").description("Deprecated name of `genesis catalog` (same output; JSON keeps the `primitives` key until the next major)").option("--json", "Print the catalog as JSON", false).option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
10776
11158
  console.error("! `genesis primitives` is now `genesis catalog`; the old name works until the next major.");
10777
11159
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
10778
- const packages = doctor.discoverPackages(path29.resolve(opts.dir));
11160
+ const packages = doctor.discoverPackages(path30.resolve(opts.dir));
10779
11161
  const rows = doctor.primitivesCatalog(packages);
10780
11162
  const broken = packages.filter((p) => p.error);
10781
11163
  if (opts.json) {
@@ -10788,10 +11170,10 @@ program.command("primitives").description("Deprecated name of `genesis catalog`
10788
11170
  if (broken.length) process.exitCode = 1;
10789
11171
  });
10790
11172
  program.command("agents").description(`Write the agent guide from the installed Genesis packages: .claude/skills/genesis/SKILL.md and a marked block in AGENTS.md`).option("--check", "Write nothing; exit 1 if either is missing or out of date (for CI)", false).option("--rules", "Check the repo against the agent rules of engagement a script can check (docs/agents/RULES.md); exit 1 on a break", false).option("--batch <pattern>", "With --rules: the branch pattern staging batches use in workflow filters", "staging/**").option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
10791
- const root = path29.resolve(opts.dir);
11173
+ const root = path30.resolve(opts.dir);
10792
11174
  if (opts.rules && opts.check) return program.error("--rules checks the repo, --check the agent guide: run them one at a time");
10793
11175
  if (opts.rules) {
10794
- if (!existsSync(path29.join(root, "packages")) && !existsSync(path29.join(root, ".github", "workflows"))) {
11176
+ if (!existsSync(path30.join(root, "packages")) && !existsSync(path30.join(root, ".github", "workflows"))) {
10795
11177
  return program.error(`--rules checks a repository: ${root} has no packages/ or .github/workflows/. Run it from the repo root or pass --dir.`);
10796
11178
  }
10797
11179
  const { checkAgentRules: checkAgentRules2 } = await Promise.resolve().then(() => (init_agent_rules(), agent_rules_exports));
@@ -10869,7 +11251,7 @@ featureOptions(
10869
11251
  var upstream = program.command("upstream").description("The app's register of what it needed from Genesis (docs/genesis-upstream.md)");
10870
11252
  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) => {
10871
11253
  const { checkUpstream: checkUpstream2 } = await Promise.resolve().then(() => (init_upstream(), upstream_exports));
10872
- const result = checkUpstream2(path29.resolve(opts.dir));
11254
+ const result = checkUpstream2(path30.resolve(opts.dir));
10873
11255
  for (const w of result.warnings) console.warn(`! ${w}`);
10874
11256
  for (const p of result.problems) console.error(`\u2717 ${p}`);
10875
11257
  if (result.problems.length) process.exitCode = 1;
@@ -10877,7 +11259,7 @@ upstream.command("check").description("Check docs/genesis-upstream.md: kinds, st
10877
11259
  });
10878
11260
  upstream.command("export").description("Print the link that files a register entry with Genesis through the gap form (sends nothing)").argument("<id>", "The entry's id").option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (id, opts) => {
10879
11261
  const { checkUpstream: checkUpstream2, exportIssueUrl: exportIssueUrl2 } = await Promise.resolve().then(() => (init_upstream(), upstream_exports));
10880
- const register = checkUpstream2(path29.resolve(opts.dir));
11262
+ const register = checkUpstream2(path30.resolve(opts.dir));
10881
11263
  if (register.missing) return program.error("There is no docs/genesis-upstream.md or genesis-upstream.md here; add the register first (see genesis upstream check).");
10882
11264
  const entry = register.entries.find((e) => e.id === id);
10883
11265
  if (!entry) return program.error(`No register entry "${id}" in ${register.file}.`);
@@ -10890,9 +11272,9 @@ ${exportIssueUrl2(entry)}`);
10890
11272
  var studio = program.command("studio").description("The Genesis Data Studio");
10891
11273
  studio.command("init").description("Turn the Data Studio on in this app: a server for every table, a page, and one migration to review").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--host <host>", "next, tanstack-start or supabase-function (default: detected)").option("--route <path>", "Where the page lives", "/admin/data").option("--login-role <name>", "The studio's database login", "genesis_studio_login").option("--force", "Overwrite files that already exist", false).action(async (opts) => {
10892
11274
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
10893
- const root = path29.resolve(opts.dir);
10894
- const packageJson = JSON.parse(await fs.readFile(path29.join(root, "package.json"), "utf-8").catch(() => "{}"));
10895
- const existsSync39 = (await import('fs')).existsSync;
11275
+ const root = path30.resolve(opts.dir);
11276
+ const packageJson = JSON.parse(await fs.readFile(path30.join(root, "package.json"), "utf-8").catch(() => "{}"));
11277
+ const existsSync41 = (await import('fs')).existsSync;
10896
11278
  const readSync = (await import('fs')).readFileSync;
10897
11279
  const readdirSync19 = (await import('fs')).readdirSync;
10898
11280
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
@@ -10901,13 +11283,13 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
10901
11283
  const plan = planStudioInit2(
10902
11284
  {
10903
11285
  packageJson,
10904
- exists: (p) => existsSync39(path29.join(root, p)),
10905
- read: (p) => existsSync39(path29.join(root, p)) ? readSync(path29.join(root, p), "utf-8") : null,
11286
+ exists: (p) => existsSync41(path30.join(root, p)),
11287
+ read: (p) => existsSync41(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
10906
11288
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
10907
11289
  listDeep: (p) => {
10908
11290
  const out = [];
10909
11291
  const walk3 = (rel) => {
10910
- for (const entry of readdirSync19(path29.join(root, rel), { withFileTypes: true })) {
11292
+ for (const entry of readdirSync19(path30.join(root, rel), { withFileTypes: true })) {
10911
11293
  const child = `${rel}/${entry.name}`;
10912
11294
  if (entry.isDirectory()) walk3(child);
10913
11295
  else out.push(child);
@@ -10921,7 +11303,7 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
10921
11303
  },
10922
11304
  list: (p) => {
10923
11305
  try {
10924
- return readdirSync19(path29.join(root, p));
11306
+ return readdirSync19(path30.join(root, p));
10925
11307
  } catch {
10926
11308
  return [];
10927
11309
  }
@@ -10930,8 +11312,8 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
10930
11312
  { host: opts.host, route: opts.route, loginRole: opts.loginRole }
10931
11313
  );
10932
11314
  for (const file of plan.files) {
10933
- const target = path29.join(root, file.path);
10934
- await fs.mkdir(path29.dirname(target), { recursive: true });
11315
+ const target = path30.join(root, file.path);
11316
+ await fs.mkdir(path30.dirname(target), { recursive: true });
10935
11317
  if (file.edit) {
10936
11318
  await fs.writeFile(target, file.content, "utf-8");
10937
11319
  console.log(`~ ${file.path} (${file.edit})`);
@@ -10942,14 +11324,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
10942
11324
  console.log(`+ ${file.path} (appended)`);
10943
11325
  continue;
10944
11326
  }
10945
- if (existsSync39(target) && !opts.force) {
11327
+ if (existsSync41(target) && !opts.force) {
10946
11328
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
10947
11329
  continue;
10948
11330
  }
10949
11331
  await fs.writeFile(target, file.content, "utf-8");
10950
11332
  console.log(`+ ${file.path}`);
10951
11333
  }
10952
- const pm = existsSync39(path29.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync39(path29.join(root, "yarn.lock")) ? "yarn add" : existsSync39(path29.join(root, "bun.lock")) || existsSync39(path29.join(root, "bun.lockb")) ? "bun add" : "npm install";
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";
10953
11335
  console.log("");
10954
11336
  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:`);
10955
11337
  console.log(` 1. ${pm} ${plan.install.map((p) => /[\s<>|]/.test(p) ? `"${p}"` : p).join(" ")}`);
@@ -10966,8 +11348,8 @@ async function confirm(question) {
10966
11348
  }
10967
11349
  }
10968
11350
  var logger = { info: (m) => console.log(m), warn: (m) => console.warn(`! ${m}`) };
10969
- program.command("add").description("Add a block (a feature an app adds whole) from the Genesis package that declares it: install, migrations, functions, skills, routes, registry entry").argument("[block]", "The block's id, e.g. tenant-features").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--package <name>", "The package that declares it, when two do").option("--list", "List the blocks this app can add, and exit", false).option("--dry-run", "Print the plan; write and install nothing", false).option("-y, --yes", "Don't ask before writing", false).option("--no-install", "Don't install packages (print the command instead)").option("--no-features-build", "Don't run features build after").action(async (block, opts) => {
10970
- const root = path29.resolve(opts.dir);
11351
+ program.command("add").description("Add a block (a feature an app adds whole) from the Genesis package that declares it: install, migrations, functions, skills, routes, registry entry").argument("[block]", "The block's id, e.g. tenant-features").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--package <name>", "The package that declares it, when two do").option("--list", "List the blocks this app can add, and exit", false).option("--dry-run", "Print the plan; write and install nothing", false).option("-y, --yes", "Don't ask before writing", false).option("--no-install", "Don't install packages (print the command instead)").option("--no-features-build", "Don't run features build after").option("--database-only", "Only the block's migrations, pgTAP tests, Edge Functions and config.toml sections: in the app that holds another app's database", false).action(async (block, opts) => {
11352
+ const root = path30.resolve(opts.dir);
10971
11353
  if (opts.list || !block) {
10972
11354
  const { allBlocks: allBlocks2 } = await Promise.resolve().then(() => (init_discover(), discover_exports));
10973
11355
  const { readLock: readLock2 } = await Promise.resolve().then(() => (init_lock(), lock_exports));
@@ -10980,7 +11362,7 @@ program.command("add").description("Add a block (a feature an app adds whole) fr
10980
11362
  return;
10981
11363
  }
10982
11364
  const { runAdd: runAdd2 } = await Promise.resolve().then(() => (init_add(), add_exports));
10983
- const report = await runAdd2({ root, block, ...opts.package ? { package: opts.package } : {}, dryRun: opts.dryRun, yes: opts.yes, install: opts.install, featuresBuild: opts.featuresBuild, log: logger, confirm });
11365
+ const report = await runAdd2({ root, block, ...opts.package ? { package: opts.package } : {}, dryRun: opts.dryRun, yes: opts.yes, install: opts.install, featuresBuild: opts.featuresBuild, ...opts.databaseOnly ? { databaseOnly: true } : {}, log: logger, confirm });
10984
11366
  for (const w of report.warnings) logger.warn(w);
10985
11367
  for (const k of report.kept) logger.warn(`${k.path}: ${k.why}`);
10986
11368
  console.log("");
@@ -10997,13 +11379,17 @@ program.command("migrate").description("Copy new package migrations of the app's
10997
11379
  const { runMigrate: runMigrate2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
10998
11380
  const { formatMigrationRows: formatMigrationRows2 } = await Promise.resolve().then(() => (init_migrations(), migrations_exports));
10999
11381
  const report = await runMigrate2({
11000
- root: path29.resolve(opts.dir),
11382
+ root: path30.resolve(opts.dir),
11001
11383
  ...opts.block ? { blocks: opts.block } : {},
11002
11384
  ...opts.notifications ? { notifications: opts.notifications } : {},
11003
11385
  dryRun: opts.dryRun,
11004
11386
  forward: opts.forward
11005
11387
  });
11006
11388
  for (const w of report.warnings) logger.warn(w);
11389
+ if (report.elsewhere) {
11390
+ console.log(report.elsewhere.note);
11391
+ return;
11392
+ }
11007
11393
  for (const s of report.switchedOff) console.log(`- skipped ${s}`);
11008
11394
  console.log(formatMigrationRows2(report.plan.rows));
11009
11395
  for (const c of report.plan.creates) if (c.kind !== "migration") console.log(`+ ${c.path} (${c.kind === "test" ? "pgTAP test" : "forward migration: fill it in"})`);
@@ -11019,7 +11405,7 @@ program.command("migrate").description("Copy new package migrations of the app's
11019
11405
  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) => {
11020
11406
  const { runUpgrade: runUpgrade2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
11021
11407
  const report = await runUpgrade2({
11022
- root: path29.resolve(opts.dir),
11408
+ root: path30.resolve(opts.dir),
11023
11409
  version: opts.version,
11024
11410
  ...opts.manifest ? { manifest: opts.manifest } : {},
11025
11411
  dryRun: opts.dryRun,
@@ -11046,7 +11432,7 @@ program.command("codemod [id]").description("Run one of Genesis's codemods by ha
11046
11432
  }
11047
11433
  const mod = codemodById2(id);
11048
11434
  if (!mod) throw new Error(`No codemod "${id}". Run genesis codemod to list them.`);
11049
- const changed = await mod.run({ root: path29.resolve(opts.dir), dryRun: opts.dryRun, log: (m) => console.log(m) });
11435
+ const changed = await mod.run({ root: path30.resolve(opts.dir), dryRun: opts.dryRun, log: (m) => console.log(m) });
11050
11436
  console.log(changed.length ? `${opts.dryRun ? "Would change" : "\u2714 Changed"} ${changed.length} file${changed.length === 1 ? "" : "s"}:
11051
11437
  ${changed.map((f) => ` ${f}`).join("\n")}` : "Nothing to change.");
11052
11438
  });
@@ -11097,7 +11483,7 @@ function redactUrl(location) {
11097
11483
  const url = new URL(location);
11098
11484
  return `${url.origin}${url.pathname}`;
11099
11485
  } catch {
11100
- return path29.basename(location);
11486
+ return path30.basename(location);
11101
11487
  }
11102
11488
  }
11103
11489
  //# sourceMappingURL=cli.js.map