@marktiderman/genesis-cli 1.11.3 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync, existsSync, readdirSync, mkdirSync, writeFileSync, mkdtempSync, rmSync, realpathSync, statSync, lstatSync } from 'fs';
3
- import * as path32 from 'path';
3
+ import * as path23 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';
7
7
  import { createJiti } from 'jiti';
8
- import { createRequire } from 'module';
8
+ import { createRequire, builtinModules } from 'module';
9
9
  import { execFileSync, spawnSync } from 'child_process';
10
10
  import { buildFeatureOutputs, checkFeatureOutputs, summarizeCheck } from '@marktiderman/genesis-features/node';
11
11
  import { findFeatures } from '@marktiderman/genesis-features';
@@ -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 = path32.join(packagesDir, dir, "package.json");
29
+ const file = path23.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;
@@ -45,16 +45,16 @@ function safeRelative(value) {
45
45
  if (segments.some((s) => s === "" || s === "." || s === ".." || s.startsWith("-"))) return null;
46
46
  return value;
47
47
  }
48
- function parseManifest(home, id, raw, version) {
48
+ function parseManifest(home, id, raw, version, options = {}) {
49
49
  const problems = [];
50
50
  const at = `${home} genesis.blocks.${id}`;
51
- if (!GENESIS_PACKAGE.test(home)) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) declare blocks`);
51
+ if (!GENESIS_PACKAGE.test(home) && !options.local) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) and the app's local packages declare blocks`);
52
52
  if (!BLOCK_ID.test(id)) problems.push(`${at}: "${id}" is not a feature id`);
53
53
  if (!isObject(raw)) throw new ManifestError([...problems, `${at}: must be an object`]);
54
54
  const pkgOf = (value, where) => {
55
55
  if (value === void 0) return home;
56
- if (typeof value !== "string" || !GENESIS_PACKAGE.test(value)) {
57
- problems.push(`${where}: package must be a Genesis package, not ${JSON.stringify(value)}`);
56
+ if (typeof value !== "string" || !(GENESIS_PACKAGE.test(value) || options.local && value === home)) {
57
+ problems.push(`${where}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
58
58
  return home;
59
59
  }
60
60
  return value;
@@ -234,14 +234,14 @@ ${problems.map((p) => ` - ${p}`).join("\n")}`);
234
234
  }
235
235
  });
236
236
  function inside(parent, child) {
237
- const rel = path32.relative(parent, child);
238
- return rel === "" || !rel.startsWith("..") && !path32.isAbsolute(rel);
237
+ const rel = path23.relative(parent, child);
238
+ return rel === "" || !rel.startsWith("..") && !path23.isAbsolute(rel);
239
239
  }
240
240
  function readPackageFile(packageDir2, rel) {
241
241
  const safe = safeRelative(rel);
242
242
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the package`);
243
243
  const root = realpathSync(packageDir2);
244
- const file = path32.join(root, ...safe.split("/"));
244
+ const file = path23.join(root, ...safe.split("/"));
245
245
  if (!existsSync(file)) return null;
246
246
  const real2 = realpathSync(file);
247
247
  if (!inside(root, real2)) throw new Error(`${rel} in ${packageDir2} points outside the package`);
@@ -252,7 +252,7 @@ function readPackageDir(packageDir2, rel, skipped = []) {
252
252
  const safe = safeRelative(rel);
253
253
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the package`);
254
254
  const root = realpathSync(packageDir2);
255
- const dir = path32.join(root, ...safe.split("/"));
255
+ const dir = path23.join(root, ...safe.split("/"));
256
256
  if (!existsSync(dir)) return null;
257
257
  const real2 = realpathSync(dir);
258
258
  if (!inside(root, real2) || !statSync(real2).isDirectory()) throw new Error(`${rel} in ${packageDir2} is not a folder inside the package`);
@@ -272,7 +272,7 @@ function appPath(root, rel) {
272
272
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the app`);
273
273
  if (safe.split("/").some((s) => s.toLowerCase() === ".git")) throw new Error(`"${rel}" is inside .git; refused`);
274
274
  const realRoot = realpathSync(root);
275
- const target = path32.join(realRoot, ...safe.split("/"));
275
+ const target = path23.join(realRoot, ...safe.split("/"));
276
276
  const there = (p) => {
277
277
  try {
278
278
  lstatSync(p);
@@ -281,13 +281,13 @@ function appPath(root, rel) {
281
281
  return false;
282
282
  }
283
283
  };
284
- let probe = path32.dirname(target);
285
- while (!there(probe)) probe = path32.dirname(probe);
284
+ let probe = path23.dirname(target);
285
+ while (!there(probe)) probe = path23.dirname(probe);
286
286
  let real2;
287
287
  try {
288
288
  real2 = realpathSync(probe);
289
289
  } catch {
290
- throw new Error(`${rel} goes through a broken symlink (${path32.relative(realRoot, probe)}); refused`);
290
+ throw new Error(`${rel} goes through a broken symlink (${path23.relative(realRoot, probe)}); refused`);
291
291
  }
292
292
  if (!inside(realRoot, real2)) throw new Error(`${rel} is outside the app (a symlinked folder?)`);
293
293
  if (there(target) && lstatSync(target).isSymbolicLink()) throw new Error(`${rel} is a symlink; left alone`);
@@ -299,20 +299,20 @@ function readApp(root, rel) {
299
299
  }
300
300
  function createApp(root, rel, content) {
301
301
  const file = appPath(root, rel);
302
- mkdirSync(path32.dirname(file), { recursive: true });
302
+ mkdirSync(path23.dirname(file), { recursive: true });
303
303
  writeFileSync(file, content, { encoding: "utf8", flag: "wx" });
304
304
  }
305
305
  function replaceApp(root, rel, content) {
306
306
  const file = appPath(root, rel);
307
- mkdirSync(path32.dirname(file), { recursive: true });
307
+ mkdirSync(path23.dirname(file), { recursive: true });
308
308
  writeFileSync(file, content, "utf8");
309
309
  }
310
310
  function listApp(root, rel, options = {}) {
311
- const dir = path32.join(root, rel);
311
+ const dir = path23.join(root, rel);
312
312
  if (!existsSync(dir)) return [];
313
313
  const out = [];
314
314
  const walk2 = (r) => {
315
- for (const entry of readdirSync(path32.join(root, r), { withFileTypes: true })) {
315
+ for (const entry of readdirSync(path23.join(root, r), { withFileTypes: true })) {
316
316
  const child = `${r}/${entry.name}`;
317
317
  if (entry.isDirectory()) walk2(child);
318
318
  else if (entry.isFile() || options.symlinks && entry.isSymbolicLink()) out.push(child);
@@ -328,6 +328,104 @@ var init_files = __esm({
328
328
  sha256 = (text) => createHash("sha256").update(text).digest("hex");
329
329
  }
330
330
  });
331
+ function validateLocalPackages(raw, source = "genesis.config.json") {
332
+ if (!Array.isArray(raw)) throw new LocalPackagesError(`${source}: ${LOCAL_PACKAGES_KEY} must be a list of folders`);
333
+ return raw.map((entry, i) => {
334
+ const where = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
335
+ if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where} must be a non-empty folder`);
336
+ if (path23.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where} must be relative to the app ("${entry}")`);
337
+ const norm = path23.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
338
+ if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where} must name a package folder, not the app or a parent of it ("${entry}")`);
339
+ const parts = norm.split("/");
340
+ if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
341
+ throw new LocalPackagesError(`${where}: only a final "/*" is supported ("${entry}")`);
342
+ }
343
+ if (parts.includes("node_modules")) throw new LocalPackagesError(`${where} can't point into node_modules ("${entry}")`);
344
+ return norm;
345
+ });
346
+ }
347
+ function localPackageGlobs(root) {
348
+ const file = path23.join(root, "genesis.config.json");
349
+ if (!existsSync(file)) return [];
350
+ let raw;
351
+ try {
352
+ raw = JSON.parse(readFileSync(file, "utf8"));
353
+ } catch (err) {
354
+ throw new LocalPackagesError(`${file} is not valid JSON: ${err.message}`);
355
+ }
356
+ const value = raw && typeof raw === "object" ? raw[LOCAL_PACKAGES_KEY] : void 0;
357
+ return value === void 0 ? [] : validateLocalPackages(value, file);
358
+ }
359
+ function repositoryRoot(appRoot) {
360
+ for (let dir = appRoot; ; ) {
361
+ if (existsSync(path23.join(dir, ".git"))) return dir;
362
+ const parent = path23.dirname(dir);
363
+ if (parent === dir) return appRoot;
364
+ dir = parent;
365
+ }
366
+ }
367
+ function localPackages(root) {
368
+ const appRoot = path23.resolve(root);
369
+ const globs = localPackageGlobs(appRoot);
370
+ const key2 = `${appRoot}
371
+ ${globs.join("\n")}`;
372
+ const hit = cache.get(key2);
373
+ if (hit) return hit;
374
+ const dirs = /* @__PURE__ */ new Set();
375
+ for (const glob of globs) {
376
+ if (glob.endsWith("/*") || glob === "*") {
377
+ const parent = path23.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
378
+ if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
379
+ for (const entry of readdirSync(parent).sort()) {
380
+ if (entry.startsWith(".") || entry === "node_modules") continue;
381
+ dirs.add(path23.join(parent, entry));
382
+ }
383
+ } else {
384
+ dirs.add(path23.join(appRoot, glob));
385
+ }
386
+ }
387
+ const real2 = realpathSync(repositoryRoot(appRoot));
388
+ const out = [];
389
+ const byName = /* @__PURE__ */ new Map();
390
+ for (const dir of [...dirs].sort()) {
391
+ const manifest = path23.join(dir, "package.json");
392
+ if (!existsSync(manifest)) continue;
393
+ if (!inside(real2, realpathSync(dir))) {
394
+ throw new LocalPackagesError(`${path23.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
395
+ }
396
+ let pkg;
397
+ try {
398
+ pkg = JSON.parse(readFileSync(manifest, "utf8"));
399
+ } catch {
400
+ continue;
401
+ }
402
+ if (typeof pkg.name !== "string" || !pkg.name) continue;
403
+ const rel = path23.relative(appRoot, dir).split(path23.sep).join("/");
404
+ const other = byName.get(pkg.name);
405
+ if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
406
+ byName.set(pkg.name, rel);
407
+ out.push({ name: pkg.name, dir, rel, ...typeof pkg.version === "string" ? { version: pkg.version } : {} });
408
+ }
409
+ cache.set(key2, out);
410
+ return out;
411
+ }
412
+ function localPackageNames(root) {
413
+ return new Set(localPackages(root).map((p) => p.name));
414
+ }
415
+ function localPackage(root, name) {
416
+ return localPackages(root).find((p) => p.name === name);
417
+ }
418
+ var LOCAL_PACKAGES_KEY, LocalPackagesError, cache;
419
+ var init_local = __esm({
420
+ "src/blocks/local.ts"() {
421
+ init_files();
422
+ LOCAL_PACKAGES_KEY = "localPackages";
423
+ LocalPackagesError = class extends Error {
424
+ name = "LocalPackagesError";
425
+ };
426
+ cache = /* @__PURE__ */ new Map();
427
+ }
428
+ });
331
429
 
332
430
  // src/blocks/discover.ts
333
431
  var discover_exports = {};
@@ -345,56 +443,58 @@ __export(discover_exports, {
345
443
  workspacePackagesDir: () => workspacePackagesDir
346
444
  });
347
445
  function cliPackageDir() {
348
- let dir = path32.dirname(fileURLToPath(import.meta.url));
446
+ let dir = path23.dirname(fileURLToPath(import.meta.url));
349
447
  for (; ; ) {
350
- const file = path32.join(dir, "package.json");
448
+ const file = path23.join(dir, "package.json");
351
449
  if (existsSync(file) && JSON.parse(readFileSync(file, "utf8")).name === CLI_PACKAGE) return dir;
352
- const parent = path32.dirname(dir);
450
+ const parent = path23.dirname(dir);
353
451
  if (parent === dir) throw new Error("Can't find the genesis-cli package folder.");
354
452
  dir = parent;
355
453
  }
356
454
  }
357
455
  function workspacePackagesDir() {
358
- const dir = path32.resolve(cliPackageDir(), "..");
359
- return existsSync(path32.join(dir, "features", "package.json")) && existsSync(path32.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
456
+ const dir = path23.resolve(cliPackageDir(), "..");
457
+ return existsSync(path23.join(dir, "features", "package.json")) && existsSync(path23.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
360
458
  }
361
459
  function readCatalog() {
362
460
  if (catalogCache) return catalogCache;
363
461
  const workspace = workspacePackagesDir();
364
462
  if (workspace) return catalogCache = buildCatalog(workspace);
365
- const file = path32.join(cliPackageDir(), "dist", "genesis-catalog.json");
463
+ const file = path23.join(cliPackageDir(), "dist", "genesis-catalog.json");
366
464
  catalogCache = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : { packages: {} };
367
465
  return catalogCache;
368
466
  }
369
467
  function installedGenesis(root) {
370
468
  const found = /* @__PURE__ */ new Map();
371
- let dir = path32.resolve(root);
469
+ let dir = path23.resolve(root);
372
470
  for (; ; ) {
373
- const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path32.join(dir, m)));
374
- const scope = path32.join(dir, "node_modules", "@marktiderman");
471
+ const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path23.join(dir, m)));
472
+ const scope = path23.join(dir, "node_modules", "@marktiderman");
375
473
  if (existsSync(scope)) {
376
474
  for (const entry of readdirSync(scope)) {
377
475
  const name = `@marktiderman/${entry}`;
378
476
  if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
379
- if (existsSync(path32.join(scope, entry, "package.json"))) found.set(name, path32.join(scope, entry));
477
+ if (existsSync(path23.join(scope, entry, "package.json"))) found.set(name, path23.join(scope, entry));
380
478
  }
381
479
  }
382
- const parent = path32.dirname(dir);
480
+ const parent = path23.dirname(dir);
383
481
  if (atInstallRoot || parent === dir) return found;
384
482
  dir = parent;
385
483
  }
386
484
  }
387
485
  function packageDir(root, name) {
486
+ const local = localPackage(root, name);
487
+ if (local) return local.dir;
388
488
  const installed = installedGenesis(root).get(name);
389
489
  if (installed) return installed;
390
490
  if (name === CLI_PACKAGE) return cliPackageDir();
391
491
  return null;
392
492
  }
393
493
  function packageVersion(dir) {
394
- return JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8")).version;
494
+ return JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8")).version;
395
495
  }
396
496
  function declarationsOf(dir, warnings) {
397
- const pkg = JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8"));
497
+ const pkg = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
398
498
  const key2 = `${realpathSync(dir)}@${pkg.version ?? ""}`;
399
499
  let cached = declarationCache.get(key2);
400
500
  if (!cached) {
@@ -404,15 +504,15 @@ function declarationsOf(dir, warnings) {
404
504
  return cached;
405
505
  }
406
506
  async function loadDeclarations(dir, warnings) {
407
- const pkg = JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8"));
507
+ const pkg = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
408
508
  const entry = pkg.exports?.["./blocks"];
409
509
  const target = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry["import"] ?? entry["default"] : void 0;
410
510
  if (typeof target !== "string") return {};
411
511
  const rel = safeRelative(target.replace(/^\.\//, ""));
412
- const file = rel && path32.join(dir, ...rel.split("/"));
512
+ const file = rel && path23.join(dir, ...rel.split("/"));
413
513
  if (!file || !inside(dir, file) || !existsSync(file)) return {};
414
514
  try {
415
- const jiti = createJiti(path32.join(dir, "package.json"), { moduleCache: false });
515
+ const jiti = createJiti(path23.join(dir, "package.json"), { moduleCache: false });
416
516
  const mod = await jiti.import(file);
417
517
  const out = {};
418
518
  for (const value of Object.values(mod)) if (isBlockDef(value)) out[value.id] = declarationFields(value);
@@ -422,21 +522,24 @@ async function loadDeclarations(dir, warnings) {
422
522
  return {};
423
523
  }
424
524
  }
425
- async function blocksOfInstalled(dir, warnings = []) {
426
- const pkg = JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8"));
525
+ async function blocksOfInstalled(dir, warnings = [], options = {}) {
526
+ const pkg = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
427
527
  const raw = rawBlocksOf(pkg);
428
528
  const declared = await declarationsOf(dir, warnings);
429
529
  const ids = /* @__PURE__ */ new Set([...Object.keys(raw), ...Object.keys(declared)]);
430
530
  const out = [];
431
531
  for (const id of [...ids].sort()) {
432
532
  const fromJson = raw[id] ?? {};
433
- const manifest = tryParse(() => parseManifest(pkg.name, id, { ...fromJson, ...declared[id] }, pkg.version), warnings);
533
+ const manifest = tryParse(() => parseManifest(pkg.name, id, { ...fromJson, ...declared[id] }, pkg.version, options), warnings);
434
534
  if (manifest) out.push(manifest);
435
535
  }
436
536
  return out;
437
537
  }
438
538
  async function allBlocks(root, warnings = []) {
439
539
  const out = [];
540
+ for (const local of localPackages(root)) {
541
+ for (const manifest of await blocksOfInstalled(local.dir, warnings, { local: true })) out.push({ manifest, from: "local" });
542
+ }
440
543
  const installed = installedGenesis(root);
441
544
  for (const [, dir] of installed) for (const manifest of await blocksOfInstalled(dir, warnings)) out.push({ manifest, from: "installed" });
442
545
  for (const [name, entry] of Object.entries(readCatalog().packages)) {
@@ -471,7 +574,7 @@ async function findBlock(root, id, options = {}) {
471
574
  const all = (await allBlocks(root, options.warnings)).filter((b) => b.manifest.id === id && (!options.package || b.manifest.package === options.package));
472
575
  if (all.length === 0) {
473
576
  const known = [...new Set((await allBlocks(root)).map((b) => b.manifest.id))].sort();
474
- throw new Error(`No Genesis package declares a block "${id}"${options.package ? ` in ${options.package}` : ""}. Known blocks: ${known.join(", ") || "none"}.`);
577
+ throw new Error(`No Genesis or local package declares a block "${id}"${options.package ? ` in ${options.package}` : ""}. Known blocks: ${known.join(", ") || "none"}.`);
475
578
  }
476
579
  if (all.length > 1) throw new Error(`"${id}" is declared by ${all.map((b) => b.manifest.package).join(" and ")}; pass --package to pick one.`);
477
580
  return all[0];
@@ -481,6 +584,7 @@ var init_discover = __esm({
481
584
  "src/blocks/discover.ts"() {
482
585
  init_catalog();
483
586
  init_files();
587
+ init_local();
484
588
  init_manifest();
485
589
  CLI_PACKAGE = "@marktiderman/genesis-cli";
486
590
  INSTALL_ROOT_MARKERS = [".git", "pnpm-lock.yaml", "pnpm-workspace.yaml", "bun.lock", "bun.lockb", "yarn.lock", "package-lock.json"];
@@ -502,7 +606,7 @@ function emptyLock() {
502
606
  return { version: 1, blocks: {}, files: {} };
503
607
  }
504
608
  function readLock(root) {
505
- const file = path32.join(root, LOCK_FILE);
609
+ const file = path23.join(root, LOCK_FILE);
506
610
  if (!existsSync(file)) return emptyLock();
507
611
  const raw = JSON.parse(readFileSync(file, "utf8"));
508
612
  if (raw.version !== 1) throw new Error(`${LOCK_FILE} has version ${String(raw.version)}; this CLI reads version 1.`);
@@ -557,7 +661,7 @@ function migrationHeader(pkg, file, source) {
557
661
  `;
558
662
  }
559
663
  function stemOrNull(file) {
560
- return MIGRATION_FILE.exec(path32.posix.basename(file))?.[2] ?? null;
664
+ return MIGRATION_FILE.exec(path23.posix.basename(file))?.[2] ?? null;
561
665
  }
562
666
  function stemOf(file) {
563
667
  const stem = stemOrNull(file);
@@ -567,7 +671,7 @@ function stemOf(file) {
567
671
  function readAppMigrations(root, dir = MIGRATIONS_DIR) {
568
672
  return listApp(root, dir, { symlinks: true }).filter((p) => p.endsWith(".sql")).map((p) => {
569
673
  const content = readApp(root, p) ?? "";
570
- const name = path32.posix.basename(p);
674
+ const name = path23.posix.basename(p);
571
675
  const m = HEADER.exec(content);
572
676
  if (m) return { path: p, name, content, tracked: { package: m[1], file: m[2], sha256: m[3], body: content.slice(m[0].length) } };
573
677
  const f = FORWARD.exec(content);
@@ -649,7 +753,7 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
649
753
  detail = copy.tracked ? renamed.trim() : "copied before headers; matches the package";
650
754
  } else if (copy.tracked) {
651
755
  state = "changed-upstream";
652
- detail = `${src.package} now ships a different ${path32.posix.basename(src.file)}; the applied copy is never rewritten`;
756
+ detail = `${src.package} now ships a different ${path23.posix.basename(src.file)}; the applied copy is never rewritten`;
653
757
  } else {
654
758
  state = "differs";
655
759
  detail = "has the package migration's name but other text and no header; treated as the app's own";
@@ -671,7 +775,7 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
671
775
  row.target = target2;
672
776
  creates.push({ path: target2, content: migrationHeader(src.package, src.file, src.source) + src.source, kind, source: { package: src.package, file: src.file } });
673
777
  if (options.tests !== false && src.test && src.testSource != null) {
674
- const test2 = `${TESTS_DIR}/${path32.posix.basename(src.test).replace(/^\d{4}_/, "")}`;
778
+ const test2 = `${TESTS_DIR}/${path23.posix.basename(src.test).replace(/^\d{4}_/, "")}`;
675
779
  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 } });
676
780
  }
677
781
  return;
@@ -731,25 +835,25 @@ function privacyDataType(type) {
731
835
  }
732
836
  function appPath2(v, where, fail) {
733
837
  if (typeof v !== "string" || !v.trim()) return fail(`${where} must be a non-empty path`);
734
- if (path32.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where} must be relative to the app, not absolute ("${v}")`);
735
- const norm = path32.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
838
+ if (path23.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where} must be relative to the app, not absolute ("${v}")`);
839
+ const norm = path23.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
736
840
  if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where} must be a folder inside the app ("${v}")`);
737
841
  return norm;
738
842
  }
739
843
  function loadConfig(root, configPath) {
740
844
  if (configPath) {
741
- const file = path32.resolve(root, configPath);
845
+ const file = path23.resolve(root, configPath);
742
846
  if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
743
847
  const json = readJson(file);
744
- const block = path32.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
745
- return { config: validateConfig(block ?? {}, file), file, dir: path32.dirname(file) };
848
+ const block = path23.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
849
+ return { config: validateConfig(block ?? {}, file), file, dir: path23.dirname(file) };
746
850
  }
747
- const own = path32.join(root, "genesis.config.json");
851
+ const own = path23.join(root, "genesis.config.json");
748
852
  if (existsSync(own)) {
749
853
  const block = readGenesisConfig(root)?.raw.doctor;
750
854
  return { config: validateConfig(block ?? {}, own), file: own, dir: root };
751
855
  }
752
- const pkg = path32.join(root, "package.json");
856
+ const pkg = path23.join(root, "package.json");
753
857
  if (existsSync(pkg)) {
754
858
  const block = readJson(pkg)?.genesis?.doctor;
755
859
  if (block !== void 0) return { config: validateConfig(block, pkg), file: pkg, dir: root };
@@ -764,7 +868,7 @@ function readJson(file) {
764
868
  }
765
869
  }
766
870
  function readGenesisConfig(root) {
767
- const file = path32.join(root, "genesis.config.json");
871
+ const file = path23.join(root, "genesis.config.json");
768
872
  if (!existsSync(file)) return null;
769
873
  const raw = readJson(file);
770
874
  if (!isObject2(raw)) throw new GenesisConfigError(`${file}: the config must be a JSON object`);
@@ -1005,16 +1109,18 @@ var init_config = __esm({
1005
1109
  "packs",
1006
1110
  "native",
1007
1111
  "supabase",
1112
+ "packages",
1008
1113
  "routesDir",
1009
1114
  "$schema",
1010
1115
  "$comment"
1011
1116
  ]);
1012
1117
  LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
1013
1118
  PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
1014
- PACKS = /* @__PURE__ */ new Set(["native", "supabase"]);
1119
+ PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
1015
1120
  PACK_KEYS = {
1016
1121
  native: { routerRoot: "path" },
1017
- supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" }
1122
+ supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
1123
+ packages: { base: "string" }
1018
1124
  };
1019
1125
  PRIVACY_KEYS = /* @__PURE__ */ new Set(["blocks", "collects", "tracking"]);
1020
1126
  DATA_USE_KEYS = /* @__PURE__ */ new Set(["type", "purposes", "linked", "tracking"]);
@@ -1023,11 +1129,11 @@ var init_config = __esm({
1023
1129
  }
1024
1130
  });
1025
1131
  function findPackageDir(from, name) {
1026
- let dir = path32.resolve(from);
1132
+ let dir = path23.resolve(from);
1027
1133
  for (; ; ) {
1028
- const candidate = path32.join(dir, "node_modules", name);
1029
- if (existsSync(path32.join(candidate, "package.json"))) return candidate;
1030
- const parent = path32.dirname(dir);
1134
+ const candidate = path23.join(dir, "node_modules", name);
1135
+ if (existsSync(path23.join(candidate, "package.json"))) return candidate;
1136
+ const parent = path23.dirname(dir);
1031
1137
  if (parent === dir) return null;
1032
1138
  dir = parent;
1033
1139
  }
@@ -1079,7 +1185,7 @@ function loadCompanions(root, config, uiPackage) {
1079
1185
  function readPackageExports(root, uiPackage) {
1080
1186
  const uiDir = findPackageDir(root, uiPackage);
1081
1187
  if (!uiDir) return null;
1082
- const uiPkg = JSON.parse(readFileSync(path32.join(uiDir, "package.json"), "utf8"));
1188
+ const uiPkg = JSON.parse(readFileSync(path23.join(uiDir, "package.json"), "utf8"));
1083
1189
  const typeEntries = /* @__PURE__ */ new Set();
1084
1190
  const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
1085
1191
  if (typeof mainTypes === "string") typeEntries.add(mainTypes);
@@ -1091,7 +1197,7 @@ function readPackageExports(root, uiPackage) {
1091
1197
  const reexportedPackages = /* @__PURE__ */ new Set();
1092
1198
  let readAny = false;
1093
1199
  for (const entry of typeEntries) {
1094
- const file = path32.join(uiDir, entry);
1200
+ const file = path23.join(uiDir, entry);
1095
1201
  if (!existsSync(file)) continue;
1096
1202
  readAny = true;
1097
1203
  const dts = readFileSync(file, "utf8");
@@ -1105,11 +1211,11 @@ function readPackageExports(root, uiPackage) {
1105
1211
  }
1106
1212
  const valueDecls = /* @__PURE__ */ new Set();
1107
1213
  const typeDecls = /* @__PURE__ */ new Set();
1108
- const declRoot = typeof mainTypes === "string" ? path32.dirname(path32.join(uiDir, mainTypes)) : uiDir;
1214
+ const declRoot = typeof mainTypes === "string" ? path23.dirname(path23.join(uiDir, mainTypes)) : uiDir;
1109
1215
  const declFiles = walkDts(declRoot);
1110
1216
  for (const pkg of reexportedPackages) {
1111
1217
  const dir = findPackageDir(uiDir, pkg);
1112
- if (dir) walkDts(path32.join(dir, "dist"), declFiles);
1218
+ if (dir) walkDts(path23.join(dir, "dist"), declFiles);
1113
1219
  }
1114
1220
  for (const file of declFiles) {
1115
1221
  const text = readFileSync(file, "utf8");
@@ -1155,7 +1261,7 @@ function walkDts(dir, out = []) {
1155
1261
  if (!existsSync(dir)) return out;
1156
1262
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1157
1263
  if (entry.name === "node_modules") continue;
1158
- const p = path32.join(dir, entry.name);
1264
+ const p = path23.join(dir, entry.name);
1159
1265
  if (entry.isDirectory()) walkDts(p, out);
1160
1266
  else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
1161
1267
  }
@@ -1172,27 +1278,27 @@ function resolveThemeFiles(root, config, uiDir) {
1172
1278
  }
1173
1279
  const files = [];
1174
1280
  const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
1175
- const themes = ds && path32.join(ds, "dist", "themes");
1281
+ const themes = ds && path23.join(ds, "dist", "themes");
1176
1282
  if (themes && existsSync(themes)) {
1177
- for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path32.join(themes, name));
1283
+ for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path23.join(themes, name));
1178
1284
  }
1179
1285
  if (files.length === 0) {
1180
1286
  throw new DoctorConfigError(
1181
1287
  `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
1182
1288
  );
1183
1289
  }
1184
- const uiStyles = path32.join(uiDir, "dist", "styles.css");
1290
+ const uiStyles = path23.join(uiDir, "dist", "styles.css");
1185
1291
  if (existsSync(uiStyles)) files.push(uiStyles);
1186
1292
  return files;
1187
1293
  }
1188
1294
  function resolveSpec(root, spec) {
1189
- const local = path32.resolve(root, spec);
1190
- if (spec.startsWith(".") || path32.isAbsolute(spec)) return existsSync(local) ? local : null;
1295
+ const local = path23.resolve(root, spec);
1296
+ if (spec.startsWith(".") || path23.isAbsolute(spec)) return existsSync(local) ? local : null;
1191
1297
  const parts = spec.split("/");
1192
1298
  const nameLength = spec.startsWith("@") ? 2 : 1;
1193
1299
  const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
1194
1300
  if (dir) {
1195
- const file = path32.join(dir, ...parts.slice(nameLength));
1301
+ const file = path23.join(dir, ...parts.slice(nameLength));
1196
1302
  if (existsSync(file) && statSync(file).isFile()) return file;
1197
1303
  }
1198
1304
  return existsSync(local) ? local : null;
@@ -1200,7 +1306,7 @@ function resolveSpec(root, spec) {
1200
1306
  function loadPalette(root) {
1201
1307
  const names = new Set(TAILWIND_PALETTE);
1202
1308
  try {
1203
- const req = createRequire(path32.join(root, "package.json"));
1309
+ const req = createRequire(path23.join(root, "package.json"));
1204
1310
  const colors = req("tailwindcss/colors");
1205
1311
  for (const key2 of Object.keys(colors?.default ?? colors ?? {})) {
1206
1312
  if (/^[a-z]+$/.test(key2) && !["inherit", "current", "transparent"].includes(key2)) names.add(key2);
@@ -1254,7 +1360,7 @@ var init_genesis = __esm({
1254
1360
  });
1255
1361
  function readReleaseManifest(root) {
1256
1362
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
1257
- const file = dir && path32.join(dir, "dist", "versions.json");
1363
+ const file = dir && path23.join(dir, "dist", "versions.json");
1258
1364
  if (!file || !existsSync(file)) return null;
1259
1365
  return JSON.parse(readFileSync(file, "utf8"));
1260
1366
  }
@@ -1264,7 +1370,7 @@ function checkVersionSkew(ctx) {
1264
1370
  for (const [name, want] of Object.entries(manifest.packages)) {
1265
1371
  const dir = findPackageDir(ctx.root, name);
1266
1372
  if (!dir) continue;
1267
- const have = JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8")).version;
1373
+ const have = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8")).version;
1268
1374
  if (have === want) continue;
1269
1375
  ctx.report({
1270
1376
  rule: "version-skew",
@@ -1283,13 +1389,13 @@ var init_versions = __esm({
1283
1389
  }
1284
1390
  });
1285
1391
  function detectPackageManager(root) {
1286
- let dir = path32.resolve(root);
1392
+ let dir = path23.resolve(root);
1287
1393
  for (; ; ) {
1288
- if (existsSync(path32.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1289
- if (existsSync(path32.join(dir, "bun.lock")) || existsSync(path32.join(dir, "bun.lockb"))) return "bun";
1290
- if (existsSync(path32.join(dir, "yarn.lock"))) return "yarn";
1291
- if (existsSync(path32.join(dir, "package-lock.json"))) return "npm";
1292
- const parent = path32.dirname(dir);
1394
+ if (existsSync(path23.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1395
+ if (existsSync(path23.join(dir, "bun.lock")) || existsSync(path23.join(dir, "bun.lockb"))) return "bun";
1396
+ if (existsSync(path23.join(dir, "yarn.lock"))) return "yarn";
1397
+ if (existsSync(path23.join(dir, "package-lock.json"))) return "npm";
1398
+ const parent = path23.dirname(dir);
1293
1399
  if (parent === dir) return "npm";
1294
1400
  dir = parent;
1295
1401
  }
@@ -1325,10 +1431,10 @@ var init_pm = __esm({
1325
1431
  function walk(dir, exclude = []) {
1326
1432
  const out = [];
1327
1433
  const visit = (rel) => {
1328
- for (const name of readdirSync(path32.join(dir, rel)).sort()) {
1434
+ for (const name of readdirSync(path23.join(dir, rel)).sort()) {
1329
1435
  const child = rel ? `${rel}/${name}` : name;
1330
1436
  if (exclude.some((r) => r.test(child))) continue;
1331
- const stat = statSync(path32.join(dir, child));
1437
+ const stat = statSync(path23.join(dir, child));
1332
1438
  if (stat.isDirectory()) visit(child);
1333
1439
  else if (stat.isFile()) out.push(child);
1334
1440
  }
@@ -1357,17 +1463,17 @@ var init_walk = __esm({
1357
1463
  });
1358
1464
  function starterDir() {
1359
1465
  const workspace = workspacePackagesDir();
1360
- const live = workspace && path32.join(workspace, "..", "apps", "genesis-rn-starter");
1361
- if (live && existsSync(path32.join(live, "package.json"))) return live;
1362
- const packaged = path32.join(cliPackageDir(), "dist", "starter");
1363
- if (existsSync(path32.join(packaged, "package.json"))) return packaged;
1466
+ const live = workspace && path23.join(workspace, "..", "apps", "genesis-rn-starter");
1467
+ if (live && existsSync(path23.join(live, "package.json"))) return live;
1468
+ const packaged = path23.join(cliPackageDir(), "dist", "starter");
1469
+ if (existsSync(path23.join(packaged, "package.json"))) return packaged;
1364
1470
  throw new Error("This genesis-cli has no starter (dist/starter is missing): reinstall @marktiderman/genesis-cli.");
1365
1471
  }
1366
1472
  function templatesDir(cliDir = cliPackageDir()) {
1367
1473
  const workspace = workspacePackagesDir();
1368
- const live = workspace && cliDir === cliPackageDir() ? path32.join(workspace, "..", "templates") : null;
1369
- if (live && existsSync(path32.join(live, "eas"))) return live;
1370
- const packaged = path32.join(cliDir, "dist", "templates");
1474
+ const live = workspace && cliDir === cliPackageDir() ? path23.join(workspace, "..", "templates") : null;
1475
+ if (live && existsSync(path23.join(live, "eas"))) return live;
1476
+ const packaged = path23.join(cliDir, "dist", "templates");
1371
1477
  if (existsSync(packaged)) return packaged;
1372
1478
  throw new Error(`${cliDir} has no templates (dist/templates is missing).`);
1373
1479
  }
@@ -1448,10 +1554,10 @@ function initNative(options) {
1448
1554
  if (!BUNDLE.test(bundleId)) throw new Error(`"${bundleId}" isn't a bundle id like com.example.app.`);
1449
1555
  if (!SCHEME.test(scheme)) throw new Error(`"${scheme}" isn't a URL scheme.`);
1450
1556
  if (/["\\\n]/.test(display)) throw new Error("The display name can't contain quotes, backslashes or new lines.");
1451
- const target = path32.resolve(options.target);
1557
+ const target = path23.resolve(options.target);
1452
1558
  if (existsSync(target) && readdirSync(target).length) throw new Error(`${target} isn't empty; init writes into a new folder and never overwrites.`);
1453
1559
  const source = starterDir();
1454
- const read = (rel) => readFileSync(path32.join(source, rel), "utf8");
1560
+ const read = (rel) => readFileSync(path23.join(source, rel), "utf8");
1455
1561
  const was = starterIdentity(read("starter.config.ts"));
1456
1562
  const substitutions = { [was.bundleId]: bundleId, [was.slug]: slug, [was.scheme]: scheme, [was.name]: display };
1457
1563
  const files = /* @__PURE__ */ new Map();
@@ -1482,14 +1588,14 @@ function initNative(options) {
1482
1588
  files.set("package.json", `${JSON.stringify(pkg, null, 2)}
1483
1589
  `);
1484
1590
  files.set("metro.config.js", METRO);
1485
- const pnpmSettings = [path32.join(source, "pnpm-workspace.yaml"), path32.join(source, "..", "..", "pnpm-workspace.yaml")].find((f) => existsSync(f));
1591
+ const pnpmSettings = [path23.join(source, "pnpm-workspace.yaml"), path23.join(source, "..", "..", "pnpm-workspace.yaml")].find((f) => existsSync(f));
1486
1592
  if (pnpmSettings) files.set("pnpm-workspace.yaml", appPnpmSettings(readFileSync(pnpmSettings, "utf8")));
1487
1593
  files.set("README.md", readme(display, slug));
1488
1594
  const lock = { ...emptyLock(), substitutions };
1489
1595
  const cliVersion2 = pinnedVersion(target, CLI_PACKAGE)?.version;
1490
1596
  const templates = templatesDir();
1491
1597
  for (const rel of walk(templates)) {
1492
- const text = substitute(readFileSync(path32.join(templates, rel), "utf8"), substitutions);
1598
+ const text = substitute(readFileSync(path23.join(templates, rel), "utf8"), substitutions);
1493
1599
  const to = templateTarget(rel, text);
1494
1600
  files.set(to, text);
1495
1601
  lock.files[to] = { source: `${CLI_PACKAGE}:templates/${rel}`, sha256: sha256(text), ...cliVersion2 ? { version: cliVersion2 } : {} };
@@ -1500,13 +1606,13 @@ function initNative(options) {
1500
1606
  const blocks = [];
1501
1607
  for (const block of options.blocks) {
1502
1608
  const stems = block.migrations.map((m) => stemOf(m.file));
1503
- const copies = stems.map((s) => migrations.find((f) => path32.posix.basename(f).replace(/^\d+_/, "") === `${s}.sql`));
1609
+ const copies = stems.map((s) => migrations.find((f) => path23.posix.basename(f).replace(/^\d+_/, "") === `${s}.sql`));
1504
1610
  if (!stems.length || copies.some((c) => !c)) continue;
1505
1611
  blocks.push(block.id);
1506
1612
  lock.blocks[block.id] = { package: block.package, ...block.version ? { version: block.version } : {} };
1507
1613
  block.migrations.forEach((m) => {
1508
1614
  if (m.test) {
1509
- const test2 = `${TESTS_DIR}/${path32.posix.basename(m.test).replace(/^\d{4}_/, "")}`;
1615
+ const test2 = `${TESTS_DIR}/${path23.posix.basename(m.test).replace(/^\d{4}_/, "")}`;
1510
1616
  if (files.has(test2)) lock.files[test2] = { source: `${m.package}:${m.test}`, sha256: sha256(files.get(test2)) };
1511
1617
  }
1512
1618
  });
@@ -1519,8 +1625,8 @@ function initNative(options) {
1519
1625
  }
1520
1626
  mkdirSync(target, { recursive: true });
1521
1627
  for (const [rel, content] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
1522
- const file = path32.join(target, ...rel.split("/"));
1523
- mkdirSync(path32.dirname(file), { recursive: true });
1628
+ const file = path23.join(target, ...rel.split("/"));
1629
+ mkdirSync(path23.dirname(file), { recursive: true });
1524
1630
  writeFileSync(file, content, { encoding: "utf8", flag: "wx" });
1525
1631
  }
1526
1632
  writeLock(target, lock);
@@ -1874,19 +1980,19 @@ var init_introspect = __esm({
1874
1980
  });
1875
1981
  function buildCommands(root, config) {
1876
1982
  if (config.build) return config.build;
1877
- const pkgFile = path32.join(root, "package.json");
1983
+ const pkgFile = path23.join(root, "package.json");
1878
1984
  const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
1879
1985
  const pm = packageManager(root);
1880
1986
  return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
1881
1987
  }
1882
1988
  function packageManager(root) {
1883
- let dir = path32.resolve(root);
1989
+ let dir = path23.resolve(root);
1884
1990
  for (; ; ) {
1885
- if (existsSync(path32.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1886
- if (existsSync(path32.join(dir, "bun.lock")) || existsSync(path32.join(dir, "bun.lockb"))) return "bun";
1887
- if (existsSync(path32.join(dir, "yarn.lock"))) return "yarn";
1888
- if (existsSync(path32.join(dir, "package-lock.json"))) return "npm";
1889
- const parent = path32.dirname(dir);
1991
+ if (existsSync(path23.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1992
+ if (existsSync(path23.join(dir, "bun.lock")) || existsSync(path23.join(dir, "bun.lockb"))) return "bun";
1993
+ if (existsSync(path23.join(dir, "yarn.lock"))) return "yarn";
1994
+ if (existsSync(path23.join(dir, "package-lock.json"))) return "npm";
1995
+ const parent = path23.dirname(dir);
1890
1996
  if (parent === dir) return "npm";
1891
1997
  dir = parent;
1892
1998
  }
@@ -1943,7 +2049,7 @@ function globToRegExp(glob) {
1943
2049
  }
1944
2050
  function globMatcher(globs) {
1945
2051
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1946
- return (path33) => res.some((re) => re.test(path33));
2052
+ return (path35) => res.some((re) => re.test(path35));
1947
2053
  }
1948
2054
  var init_glob = __esm({
1949
2055
  "src/doctor/glob.ts"() {
@@ -2120,9 +2226,9 @@ function scanFiles(root, config) {
2120
2226
  const files = [];
2121
2227
  const seen = /* @__PURE__ */ new Set();
2122
2228
  const visit = (abs) => {
2123
- const rel = toPosix(path32.relative(root, abs));
2229
+ const rel = toPosix(path23.relative(root, abs));
2124
2230
  if (seen.has(rel) || ignored(rel)) return;
2125
- const ext = path32.extname(abs);
2231
+ const ext = path23.extname(abs);
2126
2232
  if (!extensions.has(ext)) return;
2127
2233
  if (statSync(abs).size > MAX_FILE_BYTES) return;
2128
2234
  seen.add(rel);
@@ -2132,18 +2238,25 @@ function scanFiles(root, config) {
2132
2238
  const walk2 = (dir) => {
2133
2239
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
2134
2240
  if (entry.isDirectory()) {
2135
- if (!SKIP_DIRS.has(entry.name)) walk2(path32.join(dir, entry.name));
2241
+ if (!SKIP_DIRS.has(entry.name)) walk2(path23.join(dir, entry.name));
2136
2242
  } else if (entry.isFile()) {
2137
- visit(path32.join(dir, entry.name));
2243
+ visit(path23.join(dir, entry.name));
2138
2244
  }
2139
2245
  }
2140
2246
  };
2141
2247
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
2142
- const abs = path32.resolve(root, src);
2248
+ const abs = path23.resolve(root, src);
2143
2249
  if (!existsSync(abs)) continue;
2144
2250
  if (statSync(abs).isDirectory()) walk2(abs);
2145
2251
  else visit(abs);
2146
2252
  }
2253
+ let local = [];
2254
+ try {
2255
+ local = localPackages(root);
2256
+ } catch {
2257
+ local = [];
2258
+ }
2259
+ for (const pkg of local) walk2(pkg.dir);
2147
2260
  return files;
2148
2261
  }
2149
2262
  function lineAt(text, index) {
@@ -2154,6 +2267,7 @@ function lineAt(text, index) {
2154
2267
  var DEFAULT_SRC, DEFAULT_NATIVE_SRC, DEFAULT_EXTENSIONS, DEFAULT_IGNORE, SKIP_DIRS, MAX_FILE_BYTES, toPosix;
2155
2268
  var init_scan = __esm({
2156
2269
  "src/doctor/scan.ts"() {
2270
+ init_local();
2157
2271
  init_color_literals();
2158
2272
  init_glob();
2159
2273
  DEFAULT_SRC = ["src"];
@@ -2170,7 +2284,7 @@ var init_scan = __esm({
2170
2284
  ];
2171
2285
  SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
2172
2286
  MAX_FILE_BYTES = 2 * 1024 * 1024;
2173
- toPosix = (p) => p.split(path32.sep).join("/");
2287
+ toPosix = (p) => p.split(path23.sep).join("/");
2174
2288
  }
2175
2289
  });
2176
2290
  function parseRulesMarkdown(markdown) {
@@ -2236,7 +2350,7 @@ function loadPatternRules(root, patterns, rulesDoc) {
2236
2350
  const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
2237
2351
  let all = compiled;
2238
2352
  if (rulesDoc) {
2239
- const file = path32.resolve(root, rulesDoc);
2353
+ const file = path23.resolve(root, rulesDoc);
2240
2354
  if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
2241
2355
  const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
2242
2356
  const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
@@ -2302,14 +2416,14 @@ async function loadPlugins(specs, configDir) {
2302
2416
  }
2303
2417
  function resolvePlugin(id, configDir) {
2304
2418
  try {
2305
- if (id.startsWith(".") || path32.isAbsolute(id)) return resolveFrom(path32.resolve(configDir, id), configDir);
2419
+ if (id.startsWith(".") || path23.isAbsolute(id)) return resolveFrom(path23.resolve(configDir, id), configDir);
2306
2420
  return resolveFrom(id, configDir);
2307
2421
  } catch {
2308
2422
  throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
2309
2423
  }
2310
2424
  }
2311
2425
  function resolveFrom(id, from) {
2312
- return createRequire(path32.join(from, "noop.js")).resolve(id);
2426
+ return createRequire(path23.join(from, "noop.js")).resolve(id);
2313
2427
  }
2314
2428
  var init_plugins = __esm({
2315
2429
  "src/doctor/plugins.ts"() {
@@ -2327,7 +2441,7 @@ function importSpecifiers(file) {
2327
2441
  }
2328
2442
  function checkProjectLayout(ctx) {
2329
2443
  for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
2330
- if (existsSync(path32.join(ctx.root, dir))) {
2444
+ if (existsSync(path23.join(ctx.root, dir))) {
2331
2445
  ctx.report({
2332
2446
  rule: "local-primitives",
2333
2447
  file: dir,
@@ -2337,7 +2451,7 @@ function checkProjectLayout(ctx) {
2337
2451
  }
2338
2452
  }
2339
2453
  for (const file of STARTER_LEFTOVERS) {
2340
- if (existsSync(path32.join(ctx.root, file))) {
2454
+ if (existsSync(path23.join(ctx.root, file))) {
2341
2455
  ctx.report({
2342
2456
  rule: "starter-leftover",
2343
2457
  level: "warn",
@@ -2424,7 +2538,7 @@ function checkTokens(ctx) {
2424
2538
  }
2425
2539
  for (const pattern of ctx.config.tokenFiles ?? []) {
2426
2540
  if (/[*?]/.test(pattern)) continue;
2427
- const abs = path32.join(ctx.root, pattern);
2541
+ const abs = path23.join(ctx.root, pattern);
2428
2542
  if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
2429
2543
  for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
2430
2544
  }
@@ -2504,7 +2618,18 @@ var init_rules = __esm({
2504
2618
  "migration-definer-search-path",
2505
2619
  "migration-edited",
2506
2620
  "migration-testing-kit",
2507
- "migration-view-rls"
2621
+ "migration-view-rls",
2622
+ // packages pack
2623
+ "package-app-import",
2624
+ "package-undeclared-dependency",
2625
+ "package-migration-test",
2626
+ "package-migration-number",
2627
+ "package-migration-edited",
2628
+ "package-unregistered",
2629
+ "package-unversioned-change",
2630
+ "package-export-missing",
2631
+ "package-block-invalid",
2632
+ "package-untagged-tests"
2508
2633
  ];
2509
2634
  DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
2510
2635
  STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -2592,10 +2717,10 @@ function localImports(root, file) {
2592
2717
  const out = [];
2593
2718
  for (const m of file.code.matchAll(/\bfrom\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g)) {
2594
2719
  const spec = m[1];
2595
- const bases = spec.startsWith(".") ? [path32.resolve(path32.dirname(file.absolutePath), spec)] : [path32.join(root, spec.slice(2)), path32.join(root, "src", spec.slice(2))];
2720
+ const bases = spec.startsWith(".") ? [path23.resolve(path23.dirname(file.absolutePath), spec)] : [path23.join(root, spec.slice(2)), path23.join(root, "src", spec.slice(2))];
2596
2721
  for (const base of bases) {
2597
- const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path32.join(base, `index${e}`))].find(
2598
- (p) => SCRIPT_EXTS2.has(path32.extname(p)) && existsSync(p)
2722
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path23.join(base, `index${e}`))].find(
2723
+ (p) => SCRIPT_EXTS2.has(path23.extname(p)) && existsSync(p)
2599
2724
  );
2600
2725
  if (hit) {
2601
2726
  out.push(hit);
@@ -2758,7 +2883,7 @@ function checkCustomHeaders(ctx, pkg) {
2758
2883
  if (!JSX_EXTS3.has(file.ext)) continue;
2759
2884
  const code = file.code;
2760
2885
  const hidden = HIDES_HEADER.exec(code);
2761
- if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path32.posix.dirname(file.path), file.path);
2886
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path23.posix.dirname(file.path), file.path);
2762
2887
  const own = hidden ? ownHeader(code, pkg) : null;
2763
2888
  if (hidden && own) {
2764
2889
  reported.add(file.path);
@@ -2786,7 +2911,7 @@ function checkCustomHeaders(ctx, pkg) {
2786
2911
  }
2787
2912
  for (const file of ctx.files) {
2788
2913
  if (!JSX_EXTS3.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
2789
- const layout = hidingLayouts.get(path32.posix.dirname(file.path));
2914
+ const layout = hidingLayouts.get(path23.posix.dirname(file.path));
2790
2915
  const own = layout ? ownHeader(file.code, pkg) : null;
2791
2916
  if (!layout || !own) continue;
2792
2917
  ctx.report({
@@ -2807,13 +2932,13 @@ function isLoadingOnlyRoute(code) {
2807
2932
  }
2808
2933
  function routerRoot(ctx) {
2809
2934
  if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
2810
- return existsSync(path32.join(ctx.root, "src", "app")) ? "src/app" : "app";
2935
+ return existsSync(path23.join(ctx.root, "src", "app")) ? "src/app" : "app";
2811
2936
  }
2812
2937
  function checkScreenLayouts(ctx, pkg) {
2813
2938
  const layouts = nativeLayouts(pkg);
2814
2939
  if (layouts.length === 0) return;
2815
2940
  const rootDir = routerRoot(ctx);
2816
- if (!existsSync(path32.join(ctx.root, rootDir))) {
2941
+ if (!existsSync(path23.join(ctx.root, rootDir))) {
2817
2942
  ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
2818
2943
  return;
2819
2944
  }
@@ -2850,7 +2975,7 @@ function checkScreenLayouts(ctx, pkg) {
2850
2975
  function readExpoConfigs(root) {
2851
2976
  const out = [];
2852
2977
  for (const name of EXPO_CONFIGS) {
2853
- const abs = path32.join(root, name);
2978
+ const abs = path23.join(root, name);
2854
2979
  if (!existsSync(abs)) continue;
2855
2980
  const text = readFileSync(abs, "utf8");
2856
2981
  let json = null;
@@ -2884,13 +3009,13 @@ function pluginOptions(json, module) {
2884
3009
  return null;
2885
3010
  }
2886
3011
  function dependencies(root) {
2887
- const file = path32.join(root, "package.json");
3012
+ const file = path23.join(root, "package.json");
2888
3013
  if (!existsSync(file)) return /* @__PURE__ */ new Set();
2889
3014
  const pkg = JSON.parse(readFileSync(file, "utf8"));
2890
3015
  return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
2891
3016
  }
2892
3017
  function runtimeDependencies(root) {
2893
- const file = path32.join(root, "package.json");
3018
+ const file = path23.join(root, "package.json");
2894
3019
  if (!existsSync(file)) return {};
2895
3020
  return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
2896
3021
  }
@@ -3009,1134 +3134,1427 @@ var init_native = __esm({
3009
3134
  GENESIS_PLUGIN_IMPORT = /\bfrom\s*["']@marktiderman\/genesis-cli[^"']*["']|\b(?:require|import)\s*\(\s*["']@marktiderman\/genesis-cli[^"']*["']\s*\)/g;
3010
3135
  }
3011
3136
  });
3012
- function sqlStatements(text) {
3013
- const out = [];
3014
- let buf = "";
3015
- let bodies = [];
3016
- let line = 1;
3017
- let start = 0;
3018
- const flush = () => {
3019
- const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
3020
- if (sql) out.push({ sql, line: start, bodies });
3021
- buf = "";
3022
- bodies = [];
3023
- start = 0;
3024
- };
3025
- const put = (s) => {
3026
- if (!start && /\S/.test(s)) start = line;
3027
- buf += s;
3028
- };
3029
- let i = 0;
3030
- while (i < text.length) {
3031
- const ch = text[i];
3032
- const two = text.slice(i, i + 2);
3033
- if (ch === "\n") {
3034
- buf += " ";
3035
- line++;
3036
- i++;
3037
- } else if (two === "--") {
3038
- while (i < text.length && text[i] !== "\n") i++;
3039
- } else if (two === "/*") {
3040
- let depth = 0;
3041
- while (i < text.length) {
3042
- if (text.startsWith("/*", i)) {
3043
- depth++;
3044
- i += 2;
3045
- } else if (text.startsWith("*/", i)) {
3046
- depth--;
3047
- i += 2;
3048
- if (depth === 0) break;
3049
- } else {
3050
- if (text[i] === "\n") line++;
3051
- i++;
3052
- }
3053
- }
3054
- buf += " ";
3055
- } else if (ch === "'") {
3056
- const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
3057
- put("'");
3058
- i++;
3059
- while (i < text.length) {
3060
- if (escapes && text[i] === "\\") i += 2;
3061
- else if (text[i] === "'" && text[i + 1] === "'") i += 2;
3062
- else if (text[i] === "'") break;
3063
- else {
3064
- if (text[i] === "\n") line++;
3065
- i++;
3066
- }
3067
- }
3068
- put("'");
3069
- i++;
3070
- } else if (ch === '"') {
3071
- i++;
3072
- while (i < text.length && text[i] !== '"') put(text[i++]);
3073
- i++;
3074
- } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
3075
- const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
3076
- const end = text.indexOf(tag, i + tag.length);
3077
- const stop = end === -1 ? text.length : end + tag.length;
3078
- bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
3079
- for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
3080
- put(`${tag} ${tag}`);
3081
- i = stop;
3082
- } else if (ch === ";") {
3083
- flush();
3084
- i++;
3085
- } else {
3086
- put(ch);
3087
- i++;
3088
- }
3089
- }
3090
- flush();
3091
- return out;
3137
+
3138
+ // src/doctor/semver.ts
3139
+ function parseVersion(v) {
3140
+ const m = VERSION.exec(v.trim());
3141
+ return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
3092
3142
  }
3093
- function qualify(name) {
3094
- const n = name.trim().toLowerCase();
3095
- return n.includes(".") ? n : `public.${n}`;
3143
+ function compareVersions(a, b) {
3144
+ for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
3145
+ if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
3146
+ for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
3147
+ const x = a.pre[i];
3148
+ const y = b.pre[i];
3149
+ if (x === void 0) return -1;
3150
+ if (y === void 0) return 1;
3151
+ if (x === y) continue;
3152
+ const nx = /^\d+$/.test(x);
3153
+ const ny = /^\d+$/.test(y);
3154
+ if (nx && ny) return +x < +y ? -1 : 1;
3155
+ if (nx !== ny) return nx ? -1 : 1;
3156
+ return x < y ? -1 : 1;
3157
+ }
3158
+ return 0;
3096
3159
  }
3097
- function parenthesized(sql, open) {
3098
- let depth = 0;
3099
- for (let k = open; k < sql.length; k++) {
3100
- if (sql[k] === "(") depth++;
3101
- else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
3160
+ function partial(s) {
3161
+ const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
3162
+ if (!m) return null;
3163
+ const nums = [];
3164
+ let wild = false;
3165
+ for (const part of [m[1], m[2], m[3]]) {
3166
+ if (wild || part === void 0 || /^[xX*]$/.test(part)) {
3167
+ wild = true;
3168
+ nums.push(null);
3169
+ } else nums.push(+part);
3102
3170
  }
3103
- return { inner: sql.slice(open + 1), end: sql.length };
3171
+ return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
3104
3172
  }
3105
- function stripParens(s) {
3106
- let out = "";
3107
- let depth = 0;
3108
- for (const c of s) {
3109
- if (c === "(") depth++;
3110
- else if (c === ")") depth = Math.max(0, depth - 1);
3111
- else if (depth === 0) out += c;
3173
+ function comparators(token) {
3174
+ const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
3175
+ if (!m) return null;
3176
+ const op = m[1] ?? "";
3177
+ const p = partial(m[2]);
3178
+ if (!p) return null;
3179
+ const [major, mi, pa] = p.nums;
3180
+ if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
3181
+ const M = major;
3182
+ const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
3183
+ const next = (kind) => kind === "major" ? ver(M + 1, 0, 0, ["0"]) : kind === "minor" ? ver(M, (mi ?? 0) + 1, 0, ["0"]) : ver(M, mi ?? 0, (pa ?? 0) + 1, ["0"]);
3184
+ const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
3185
+ const out = switchOp();
3186
+ if (p.pre.length) {
3187
+ for (const c of out) if (c.v === lo) c.pre = true;
3112
3188
  }
3113
3189
  return out;
3114
- }
3115
- function splitTop(s) {
3116
- const parts = [];
3117
- let depth = 0;
3118
- let cur = "";
3119
- for (const c of s) {
3120
- if (c === "(") depth++;
3121
- if (c === ")") depth--;
3122
- if (c === "," && depth === 0) {
3123
- parts.push(cur);
3124
- cur = "";
3125
- } else cur += c;
3190
+ function switchOp() {
3191
+ switch (op) {
3192
+ case "^": {
3193
+ const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
3194
+ return [
3195
+ { op: ">=", v: lo },
3196
+ { op: "<", v: bound }
3197
+ ];
3198
+ }
3199
+ case "~":
3200
+ case "~>":
3201
+ return [
3202
+ { op: ">=", v: lo },
3203
+ { op: "<", v: mi === null ? next("major") : next("minor") }
3204
+ ];
3205
+ case ">":
3206
+ return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
3207
+ case ">=":
3208
+ return [{ op: ">=", v: lo }];
3209
+ case "<":
3210
+ return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
3211
+ case "<=":
3212
+ return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
3213
+ default:
3214
+ return upper ? [
3215
+ { op: ">=", v: lo },
3216
+ { op: "<", v: upper }
3217
+ ] : [{ op: "=", v: lo }];
3218
+ }
3126
3219
  }
3127
- if (cur.trim()) parts.push(cur);
3128
- return parts.map((p) => p.trim()).filter(Boolean);
3129
3220
  }
3130
- function argTypes(args) {
3131
- const types = [];
3132
- for (const raw of splitTop(args)) {
3133
- let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
3134
- const mode = tokens[0];
3135
- if (mode === "out") continue;
3136
- if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
3137
- const joined = tokens.join(" ");
3138
- const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
3139
- types.push(TYPE_ALIASES[type] ?? type);
3221
+ function test(c, v) {
3222
+ const d = compareVersions(v, c.v);
3223
+ return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
3224
+ }
3225
+ function parseRange(range) {
3226
+ const alts = [];
3227
+ for (const raw of range.trim().split("||")) {
3228
+ const alt = raw.trim();
3229
+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
3230
+ if (hyphen) {
3231
+ const from = comparators(`>=${hyphen[1]}`);
3232
+ const to = comparators(`<=${hyphen[2]}`);
3233
+ if (!from || !to) return null;
3234
+ alts.push([...from, ...to]);
3235
+ continue;
3236
+ }
3237
+ const set = [];
3238
+ for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
3239
+ const cs = comparators(token);
3240
+ if (!cs) return null;
3241
+ set.push(...cs);
3242
+ }
3243
+ alts.push(set);
3140
3244
  }
3141
- return types;
3245
+ return alts;
3142
3246
  }
3143
- function git(root, args) {
3144
- const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3145
- return r.status === 0 ? r.stdout : null;
3247
+ function satisfies(version, range) {
3248
+ const v = parseVersion(version);
3249
+ const alts = parseRange(range);
3250
+ if (!v || !alts) return null;
3251
+ return alts.some(
3252
+ (set) => set.every((c) => test(c, v)) && (!v.pre.length || set.some((c) => c.pre && c.v.major === v.major && c.v.minor === v.minor && c.v.patch === v.patch))
3253
+ );
3146
3254
  }
3147
- function gitView(root, dir, base) {
3148
- if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
3149
- if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
3150
- return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
3151
- }
3152
- const mergeBase = git(root, ["merge-base", "HEAD", base])?.trim();
3153
- if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
3154
- const diff = git(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
3155
- const untracked = git(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
3156
- if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
3157
- const sql = (p) => p !== void 0 && p.endsWith(".sql");
3158
- const touched = new Set(untracked.split("\n").filter(sql));
3159
- const edited = [];
3160
- for (const row of diff.split("\n").filter(Boolean)) {
3161
- const [status, a, b] = row.split(" ");
3162
- if (status.startsWith("R")) {
3163
- if (sql(b)) touched.add(b);
3164
- if (sql(a)) edited.push({ file: a, status: "renamed" });
3165
- continue;
3166
- }
3167
- if (!sql(a)) continue;
3168
- if (status.startsWith("A")) touched.add(a);
3169
- else if (status.startsWith("M") || status.startsWith("T")) {
3170
- touched.add(a);
3171
- edited.push({ file: a, status: "modified" });
3172
- } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
3255
+ var VERSION, ver;
3256
+ var init_semver = __esm({
3257
+ "src/doctor/semver.ts"() {
3258
+ VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
3259
+ ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
3173
3260
  }
3174
- return { touched, edited };
3175
- }
3176
- function checkSupabasePack(ctx) {
3177
- const settings2 = ctx.config.supabase ?? {};
3178
- const dir = settings2.migrations ?? DEFAULT_MIGRATIONS;
3179
- const abs = path32.join(ctx.root, dir);
3180
- if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
3181
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path32.join(abs, n), "utf8")) }));
3182
- const exposed = new Set((settings2.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
3183
- const base = settings2.base ?? DEFAULT_BASE;
3184
- const view = gitView(ctx.root, dir, base);
3185
- if ("reason" in view) {
3186
- if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
3187
- } else {
3188
- for (const e of view.edited) {
3189
- ctx.report({
3190
- rule: "migration-edited",
3191
- file: e.file,
3192
- subject: e.file,
3193
- message: `${e.status === "modified" ? "edits" : e.status === "deleted" ? "deletes" : "renames"} a migration that already exists on ${base}, so it has been applied; put the change in a new migration instead`
3194
- });
3261
+ });
3262
+ function stripForImports(code) {
3263
+ const out = [];
3264
+ const blank = (ch) => ch === "\n" ? "\n" : " ";
3265
+ const n = code.length;
3266
+ const templates = [];
3267
+ let depth = 0;
3268
+ let i = 0;
3269
+ let sure = true;
3270
+ const isSpecifier = () => /(?:\bfrom|(?:^|[;{}\n])\s*import|\bimport\s*\(|\brequire\s*\()\s*$/.test(out.slice(-40).join(""));
3271
+ const before = () => out.slice(-24).join("");
3272
+ const KEYWORD = /(?:^|[^\w$.])(?:return|typeof|instanceof|case|do|else|in|of|new|delete|void|throw|yield|await|from|import|export|default|require)\s*$/;
3273
+ const startsExpression = (b) => {
3274
+ const t = b.replace(/\s+$/, "");
3275
+ if (!t) return true;
3276
+ if (KEYWORD.test(b)) return true;
3277
+ return /[([{,;:=!&|?+\-*%<>~^}]$/.test(t);
3278
+ };
3279
+ const exprStart = () => startsExpression(before());
3280
+ const taggedTemplate = () => {
3281
+ const b = out.slice(-48).join("");
3282
+ const m = /([A-Za-z_$][\w$.]*)$/.exec(b);
3283
+ return m !== null && startsExpression(b.slice(0, b.length - m[1].length));
3284
+ };
3285
+ const templateBody = () => {
3286
+ while (i < n) {
3287
+ const ch = code[i];
3288
+ if (ch === "\\") {
3289
+ out.push(" ", blank(code[i + 1] ?? ""));
3290
+ i += 2;
3291
+ } else if (ch === "`") {
3292
+ out.push("`");
3293
+ i++;
3294
+ return;
3295
+ } else if (ch === "$" && code[i + 1] === "{") {
3296
+ out.push("${");
3297
+ i += 2;
3298
+ templates.push(depth);
3299
+ depth++;
3300
+ return;
3301
+ } else {
3302
+ out.push(blank(ch));
3303
+ i++;
3304
+ }
3195
3305
  }
3196
- }
3197
- const since = settings2.since;
3198
- const afterSince = (file) => since === void 0 || path32.posix.basename(file) >= since;
3199
- if ("reason" in view && since === void 0) {
3200
- ctx.report({
3201
- rule: "migration-grants",
3202
- level: "warn",
3203
- file: dir,
3204
- message: `skipped: can't tell new migrations from applied ones (${view.reason}); fetch the base ref (CI: fetch-depth 0) or set doctor.supabase.since`
3205
- });
3206
- } else {
3207
- const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
3208
- checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
3209
- }
3210
- checkRls(ctx, migrations, exposed);
3211
- checkViewInvoker(ctx, migrations, exposed);
3212
- checkDefinerSearchPath(ctx, migrations);
3213
- checkTestingKit(ctx, migrations);
3214
- }
3215
- function checkTestingKit(ctx, migrations) {
3216
- for (const { file, statements } of migrations) {
3217
- const hit = statements.find(({ sql }) => /\bgenesis_testing\b/.test(sql));
3218
- if (!hit) continue;
3219
- ctx.report({
3220
- rule: "migration-testing-kit",
3221
- file,
3222
- line: hit.line,
3223
- subject: "genesis_testing",
3224
- message: "a migration uses genesis_testing, the pgTAP kit for test databases only; move it to supabase/tests/database/000_genesis_testing.test.sql"
3225
- });
3226
- }
3227
- }
3228
- function granteesOf(s) {
3229
- return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
3230
- }
3231
- function checkGrants(ctx, migrations, exposed) {
3232
- const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
3233
- const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
3234
- const blanket = (roles) => {
3235
- const o = open(roles);
3236
- if (o.length) return { level: "error", who: o.join(" and ") };
3237
- if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
3238
- return null;
3306
+ sure = false;
3239
3307
  };
3240
- for (const { file, statements } of migrations) {
3241
- for (const { sql, line } of statements) {
3242
- const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
3243
- if (all) {
3244
- const hit = blanket(granteesOf(all[1]));
3245
- if (hit) {
3246
- ctx.report({ rule: "migration-grants", level: hit.level, file, line, subject: "on all functions", message: `grants every function in a schema to ${hit.who}, which re-grants functions an earlier migration revoked; ${fix}` });
3247
- }
3248
- continue;
3308
+ while (i < n && sure) {
3309
+ const ch = code[i];
3310
+ const next = code[i + 1];
3311
+ if (ch === "/" && next === "/") {
3312
+ while (i < n && code[i] !== "\n") {
3313
+ out.push(" ");
3314
+ i++;
3249
3315
  }
3250
- const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
3251
- if (defaults) {
3252
- const hit = blanket(granteesOf(defaults[1]));
3253
- if (hit) {
3254
- ctx.report({ rule: "migration-grants", level: hit.level, file, line, subject: "alter default privileges", message: `grants default privileges on functions to ${hit.who}, so every future function is callable by them; ${fix}` });
3255
- }
3256
- continue;
3316
+ } else if (ch === "/" && next === "*") {
3317
+ out.push(" ");
3318
+ i += 2;
3319
+ while (i < n && !(code[i] === "*" && code[i + 1] === "/")) {
3320
+ out.push(blank(code[i]));
3321
+ i++;
3257
3322
  }
3258
- const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
3259
- if (fn) {
3260
- const roles = open(granteesOf(fn[2]));
3261
- if (!roles.length) continue;
3262
- for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
3263
- if (exposed.has(schemaOf(name))) continue;
3264
- ctx.report({
3265
- rule: "migration-grants",
3266
- file,
3267
- line,
3268
- subject: name,
3269
- message: `grants ${name} to ${roles.join(" and ")}; a function outside the exposed schemas is never callable by anon or public (grant it to authenticated, or expose a wrapper)`
3270
- });
3271
- }
3272
- continue;
3323
+ if (i < n) {
3324
+ out.push(" ");
3325
+ i += 2;
3273
3326
  }
3274
- const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
3275
- if (schema) {
3276
- const roles = open(granteesOf(schema[2]));
3277
- if (!roles.length) continue;
3278
- for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
3279
- if (exposed.has(s)) continue;
3280
- ctx.report({
3281
- rule: "migration-grants",
3282
- file,
3283
- line,
3284
- subject: `schema ${s}`,
3285
- message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
3286
- });
3327
+ } else if (ch === "/" && next !== ">" && code[i - 1] !== "<" && exprStart()) {
3328
+ const afterBrace = /[}>]\s*$/.test(before());
3329
+ const start = i;
3330
+ const mark = out.length;
3331
+ out.push("/");
3332
+ i++;
3333
+ let inClass = false;
3334
+ for (; ; ) {
3335
+ const c = code[i];
3336
+ if (c === void 0 || c === "\n") {
3337
+ if (afterBrace) {
3338
+ out.length = mark;
3339
+ out.push("/");
3340
+ i = start + 1;
3341
+ } else sure = false;
3342
+ break;
3287
3343
  }
3344
+ if (c === "\\") {
3345
+ out.push(" ", blank(code[i + 1] ?? ""));
3346
+ i += 2;
3347
+ continue;
3348
+ }
3349
+ i++;
3350
+ if (c === "[") inClass = true;
3351
+ else if (c === "]") inClass = false;
3352
+ else if (c === "/" && !inClass) {
3353
+ if (afterBrace && /[<>]/.test(code.slice(start + 1, i - 1))) {
3354
+ out.length = mark;
3355
+ out.push("/");
3356
+ i = start + 1;
3357
+ break;
3358
+ }
3359
+ out.push("/");
3360
+ break;
3361
+ }
3362
+ out.push(" ");
3288
3363
  }
3289
- }
3290
- }
3291
- }
3292
- function checkRls(ctx, migrations, exposed) {
3293
- const tables = /* @__PURE__ */ new Map();
3294
- const name = String.raw`([\w$.]+)`;
3295
- const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
3296
- for (const { file, statements } of migrations) {
3297
- for (const { sql, line, bodies } of statements) {
3298
- if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
3299
- const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
3300
- if (create) {
3301
- if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
3302
- continue;
3303
- }
3304
- const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
3305
- const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
3306
- if (rename || move) {
3307
- const from = qualify((rename ?? move)[1]);
3308
- const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
3309
- const state = tables.get(from);
3310
- if (state) {
3311
- tables.delete(from);
3312
- tables.set(to, state);
3364
+ if (out.length > mark + 1 || i > start + 1) while (i < n && /[a-z]/.test(code[i])) out.push(code[i++]);
3365
+ } else if ((ch === '"' || ch === "'") && exprStart()) {
3366
+ const keep = isSpecifier();
3367
+ out.push(ch);
3368
+ i++;
3369
+ while (i < n && code[i] !== ch && code[i] !== "\n") {
3370
+ if (code[i] === "\\") {
3371
+ out.push(keep ? code[i] : " ", keep ? code[i + 1] ?? "" : blank(code[i + 1] ?? ""));
3372
+ i += 2;
3373
+ } else {
3374
+ out.push(keep ? code[i] : blank(code[i]));
3375
+ i++;
3313
3376
  }
3314
- continue;
3315
3377
  }
3316
- const alter = new RegExp(target).exec(sql);
3317
- if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
3318
- const t = qualify(alter[1]);
3319
- if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
3320
- else {
3321
- const state = tables.get(t);
3322
- if (state) state.rls = true;
3323
- }
3324
- continue;
3378
+ if (code[i] !== ch) sure = false;
3379
+ else {
3380
+ out.push(code[i]);
3381
+ i++;
3325
3382
  }
3326
- const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3327
- if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
3383
+ } else if (ch === "`" && (exprStart() || taggedTemplate())) {
3384
+ out.push("`");
3385
+ i++;
3386
+ templateBody();
3387
+ } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
3388
+ templates.pop();
3389
+ depth--;
3390
+ out.push("}");
3391
+ i++;
3392
+ templateBody();
3393
+ } else {
3394
+ if (ch === "{") depth++;
3395
+ else if (ch === "}") depth--;
3396
+ out.push(ch);
3397
+ i++;
3328
3398
  }
3329
3399
  }
3330
- for (const [t, at] of tables) {
3331
- if (at.rls || !exposed.has(schemaOf(t))) continue;
3332
- ctx.report({
3333
- rule: "migration-rls",
3334
- file: at.file,
3335
- line: at.line,
3336
- subject: t,
3337
- message: at.disabled ? `disables row level security on ${t}, and no later migration turns it back on; anyone with the API key can read and write it` : `creates ${t} without enabling row level security in any migration; add "alter table ${t} enable row level security;" and its policies`
3338
- });
3400
+ return sure && templates.length === 0 ? out.join("") : null;
3401
+ }
3402
+ function bindings(clause) {
3403
+ const out = [];
3404
+ const named = /\{([^}]*)\}/.exec(clause);
3405
+ for (const part of named?.[1].split(",") ?? []) {
3406
+ const p = part.trim();
3407
+ if (!p || p.startsWith("type ")) continue;
3408
+ out.push(p.split(/\s+as\s+/).pop().trim());
3339
3409
  }
3410
+ const rest = clause.replace(/\{[^}]*\}/, "");
3411
+ const ns = /\*\s*as\s+([\w$]+)/.exec(rest);
3412
+ if (ns) out.push(ns[1]);
3413
+ const def = /^\s*([\w$]+)/.exec(rest);
3414
+ if (def && def[1] !== "as") out.push(def[1]);
3415
+ return out;
3340
3416
  }
3341
- function checkViewInvoker(ctx, migrations, exposed) {
3342
- const views = /* @__PURE__ */ new Map();
3343
- const name = String.raw`([\w$.]+)`;
3344
- const invokerOn = /\bsecurity_invoker\s*(?:=\s*(?:true|on|yes|1|'true'|'on'))?\s*(?:,|\))/;
3345
- for (const { file, statements } of migrations) {
3346
- for (const { sql, line } of statements) {
3347
- const create = new RegExp(String.raw`^create (?:or replace )?(?:temp |temporary )?(?:recursive )?view ${name}`).exec(sql);
3348
- if (create) {
3349
- if (/^create (?:or replace )?(?:temp|temporary) /.test(sql)) continue;
3350
- const options = /^[^(]*?\bwith\s*(\([^)]*\))\s*as\b/.exec(sql)?.[1] ?? "";
3351
- views.set(qualify(create[1]), { invoker: invokerOn.test(options), file, line });
3352
- continue;
3417
+ function readJsonc(file) {
3418
+ try {
3419
+ const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? "").replace(/,(\s*[}\]])/g, "$1");
3420
+ return JSON.parse(text);
3421
+ } catch {
3422
+ return null;
3423
+ }
3424
+ }
3425
+ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3426
+ if (seen.has(file) || seen.size > 10) return {};
3427
+ seen.add(file);
3428
+ const json = readJsonc(file);
3429
+ if (!json) return {};
3430
+ const dir = path23.dirname(file);
3431
+ let merged = {};
3432
+ const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
3433
+ for (const ext of parents) {
3434
+ if (typeof ext !== "string") continue;
3435
+ let target = null;
3436
+ if (ext.startsWith(".") || path23.isAbsolute(ext)) {
3437
+ const abs = path23.resolve(dir, ext);
3438
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3439
+ } else {
3440
+ const parts = ext.split("/");
3441
+ const nameLength = ext.startsWith("@") ? 2 : 1;
3442
+ const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
3443
+ if (pkgDir) {
3444
+ const sub = parts.slice(nameLength).join("/");
3445
+ const abs = path23.join(pkgDir, sub || "tsconfig.json");
3446
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3353
3447
  }
3354
- const alter = new RegExp(String.raw`^alter view (?:if exists )?${name} (set|reset) (\([^)]*\))`).exec(sql);
3355
- if (alter && /\bsecurity_invoker\b/.test(alter[3])) {
3356
- const state = views.get(qualify(alter[1]));
3357
- if (state) state.invoker = alter[2] === "set" && invokerOn.test(alter[3]);
3358
- continue;
3448
+ }
3449
+ if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
3450
+ }
3451
+ const opts = json.compilerOptions ?? {};
3452
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path23.resolve(dir, opts.baseUrl);
3453
+ if (opts.paths && typeof opts.paths === "object") {
3454
+ merged.paths = opts.paths;
3455
+ merged.pathsDir = dir;
3456
+ }
3457
+ return merged;
3458
+ }
3459
+ function aliases(root) {
3460
+ const table = [];
3461
+ let baseUrl = null;
3462
+ for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
3463
+ const file = path23.join(root, name);
3464
+ if (!existsSync(file)) continue;
3465
+ const config = readTsconfig(root, file);
3466
+ baseUrl ??= config.baseUrl ?? null;
3467
+ const base = config.baseUrl ?? config.pathsDir ?? root;
3468
+ for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
3469
+ if (!Array.isArray(targets)) continue;
3470
+ const exact = !pattern.endsWith("*");
3471
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path23.join(base, String(t).replace(/\*$/, ""))) });
3472
+ }
3473
+ }
3474
+ const pkg = readJsonc(path23.join(root, "package.json"));
3475
+ for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
3476
+ if (typeof target !== "string") continue;
3477
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path23.join(root, target.replace(/\*.*$/, ""))] });
3478
+ }
3479
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path23.join(root, "src") + path23.sep, root + path23.sep] });
3480
+ return { table, baseUrl };
3481
+ }
3482
+ function resolveFile(base) {
3483
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path23.join(base, `index${e}`))];
3484
+ if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
3485
+ for (const p of tries) {
3486
+ if (SCRIPT_EXTS2.has(path23.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
3487
+ }
3488
+ return null;
3489
+ }
3490
+ function trailFor(ctx) {
3491
+ let t = trails.get(ctx.files);
3492
+ if (!t) trails.set(ctx.files, t = createTrail(ctx));
3493
+ return t;
3494
+ }
3495
+ function createTrail(ctx) {
3496
+ const { table, baseUrl } = aliases(ctx.root);
3497
+ let declared = null;
3498
+ try {
3499
+ const pkg = JSON.parse(readFileSync(path23.join(ctx.root, "package.json"), "utf8"));
3500
+ declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
3501
+ } catch {
3502
+ declared = null;
3503
+ }
3504
+ const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
3505
+ const read = (abs) => byPath.get(abs) ?? readSource(abs);
3506
+ const importsCache = /* @__PURE__ */ new Map();
3507
+ const importsOf = (file) => {
3508
+ const hit = importsCache.get(file.absolutePath);
3509
+ if (hit) return hit;
3510
+ const files = [];
3511
+ let lost = false;
3512
+ const code = stripped(file);
3513
+ if (code === null) {
3514
+ const out2 = { files: [], lost: true };
3515
+ importsCache.set(file.absolutePath, out2);
3516
+ return out2;
3517
+ }
3518
+ const used = new Set(renderedElements(code).map((e) => e.split(".")[0]));
3519
+ for (const m of code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
3520
+ for (const m of code.matchAll(/\bexport\s+default\s+([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
3521
+ for (const m of code.matchAll(/\bexport\s*\{([^}]*)\}\s*;/g)) for (const n of m[1].split(",")) used.add(n.trim().split(/\s+as\s+/)[0]);
3522
+ const specs = [];
3523
+ for (const m of code.matchAll(IMPORT_FROM)) if (!m[1] && bindings(m[2]).some((b) => used.has(b))) specs.push(m[3]);
3524
+ for (const m of code.matchAll(EXPORT_FROM)) if (!m[1]) specs.push(m[2]);
3525
+ for (const m of code.matchAll(DYNAMIC)) specs.push(m[1]);
3526
+ for (const spec of specs) {
3527
+ if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
3528
+ let resolved = null;
3529
+ if (spec.startsWith(".")) {
3530
+ resolved = resolveFile(path23.resolve(path23.dirname(file.absolutePath), spec));
3531
+ if (!resolved) lost = true;
3532
+ } else {
3533
+ const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
3534
+ if (alias) {
3535
+ for (const t of alias.targets) {
3536
+ resolved = resolveFile(alias.exact ? t : path23.join(t, spec.slice(alias.prefix.length)));
3537
+ if (resolved) break;
3538
+ }
3539
+ }
3540
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path23.join(baseUrl, spec));
3541
+ if (!resolved) {
3542
+ const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
3543
+ if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
3544
+ }
3359
3545
  }
3360
- const rename = new RegExp(String.raw`^alter view (?:if exists )?${name} rename to ([\w$]+)$`).exec(sql);
3361
- if (rename) {
3362
- const from = qualify(rename[1]);
3363
- const state = views.get(from);
3364
- if (state) {
3365
- views.delete(from);
3366
- views.set(`${schemaOf(from)}.${rename[2]}`, state);
3546
+ if (resolved && !files.includes(resolved)) files.push(resolved);
3547
+ }
3548
+ const out = { files, lost };
3549
+ importsCache.set(file.absolutePath, out);
3550
+ return out;
3551
+ };
3552
+ const strippedCache = /* @__PURE__ */ new Map();
3553
+ const stripped = (file) => {
3554
+ if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
3555
+ return strippedCache.get(file.absolutePath);
3556
+ };
3557
+ const memo = /* @__PURE__ */ new WeakMap();
3558
+ const reach = (file, test2, depth, seen) => {
3559
+ let cache2 = memo.get(test2);
3560
+ if (!cache2) memo.set(test2, cache2 = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
3561
+ const k = `${file.absolutePath}\0${depth}`;
3562
+ const free = cache2.free.get(k);
3563
+ if (free) return [free, /* @__PURE__ */ new Set()];
3564
+ const reusable = cache2.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
3565
+ if (reusable) return [reusable.result, new Set(reusable.cut)];
3566
+ let result;
3567
+ const cut = /* @__PURE__ */ new Set();
3568
+ const code = stripped(file);
3569
+ if (code === null) result = "unknown";
3570
+ else if (test2(code)) result = "yes";
3571
+ else {
3572
+ const { files, lost } = importsOf(file);
3573
+ let unknown = lost && depth > 0;
3574
+ result = "no";
3575
+ if (depth > 0) {
3576
+ seen.add(file.absolutePath);
3577
+ for (const abs of files) {
3578
+ if (seen.has(abs)) {
3579
+ cut.add(abs);
3580
+ continue;
3581
+ }
3582
+ const target = read(abs);
3583
+ if (!target) {
3584
+ unknown = true;
3585
+ continue;
3586
+ }
3587
+ const [r, c] = reach(target, test2, depth - 1, seen);
3588
+ for (const m of c) cut.add(m);
3589
+ if (r === "yes") {
3590
+ result = "yes";
3591
+ break;
3592
+ }
3593
+ if (r === "unknown") unknown = true;
3367
3594
  }
3368
- continue;
3595
+ seen.delete(file.absolutePath);
3596
+ cut.delete(file.absolutePath);
3369
3597
  }
3370
- const drop = /^drop view (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3371
- if (drop) for (const n of drop[1].split(",")) views.delete(qualify(n));
3598
+ if (result === "no" && unknown) result = "unknown";
3599
+ }
3600
+ if (result === "yes" || cut.size === 0) {
3601
+ cache2.free.set(k, result);
3602
+ return [result, /* @__PURE__ */ new Set()];
3372
3603
  }
3604
+ const entries = cache2.cut.get(k) ?? [];
3605
+ entries.push({ cut: [...cut], result });
3606
+ cache2.cut.set(k, entries);
3607
+ return [result, cut];
3608
+ };
3609
+ return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
3610
+ }
3611
+ var TRAIL_DEPTH, RESOLVE_EXTS2, IMPORT_FROM, EXPORT_FROM, DYNAMIC, trails;
3612
+ var init_trail = __esm({
3613
+ "src/doctor/trail.ts"() {
3614
+ init_genesis();
3615
+ init_source();
3616
+ TRAIL_DEPTH = 6;
3617
+ RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
3618
+ IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
3619
+ EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
3620
+ DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
3621
+ trails = /* @__PURE__ */ new WeakMap();
3373
3622
  }
3374
- for (const [v, at] of views) {
3375
- if (at.invoker || !exposed.has(schemaOf(v))) continue;
3376
- ctx.report({
3377
- rule: "migration-view-rls",
3378
- file: at.file,
3379
- line: at.line,
3380
- subject: v,
3381
- message: `${v} runs as its owner, so it reads past row level security; create it "with (security_invoker = true)" or add "alter view ${v} set (security_invoker = true);"`
3382
- });
3623
+ });
3624
+ function sourceFiles(dir, rel = "") {
3625
+ const out = [];
3626
+ for (const entry of readdirSync(path23.join(dir, rel)).sort()) {
3627
+ if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
3628
+ const child = rel ? `${rel}/${entry}` : entry;
3629
+ const stat = lstatSync(path23.join(dir, child));
3630
+ if (stat.isSymbolicLink()) continue;
3631
+ if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
3632
+ else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
3383
3633
  }
3634
+ return out;
3384
3635
  }
3385
- function checkDefinerSearchPath(ctx, migrations) {
3386
- const fns = /* @__PURE__ */ new Map();
3387
- const keysFor = (sql, nameEnd, fnName) => {
3388
- const rest = sql.slice(nameEnd).trimStart();
3389
- if (rest.startsWith("(")) {
3390
- const { inner } = parenthesized(rest, 0);
3391
- return [`${fnName}(${argTypes(inner).join(",")})`];
3636
+ function packageName2(specifier) {
3637
+ const parts = specifier.split("/");
3638
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3639
+ }
3640
+ function git(root, args) {
3641
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3642
+ return r.status === 0 ? r.stdout : null;
3643
+ }
3644
+ function matchPattern(pattern, spec) {
3645
+ const star = pattern.indexOf("*");
3646
+ if (star < 0) return pattern === spec ? "" : null;
3647
+ const head = pattern.slice(0, star);
3648
+ const tail = pattern.slice(star + 1);
3649
+ return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3650
+ }
3651
+ function tsconfigPaths(dir) {
3652
+ const file = path23.join(dir, "tsconfig.json");
3653
+ if (!existsSync(file)) return [];
3654
+ try {
3655
+ const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
3656
+ const options = JSON.parse(text).compilerOptions ?? {};
3657
+ const base = path23.resolve(dir, options.baseUrl ?? ".");
3658
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path23.resolve(base, t)) }));
3659
+ } catch {
3660
+ return [];
3661
+ }
3662
+ }
3663
+ function checkImports2(ctx, pkg, json) {
3664
+ const aliases2 = tsconfigPaths(pkg.dir);
3665
+ const subpathImports = Object.keys(json.imports ?? {});
3666
+ const viaAlias = (spec) => {
3667
+ if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
3668
+ for (const { pattern, targets } of aliases2) {
3669
+ const hit = matchPattern(pattern, spec);
3670
+ if (hit === null) continue;
3671
+ return targets.some((t) => {
3672
+ const rel = path23.relative(pkg.dir, t.replace("*", hit));
3673
+ return !rel.startsWith("..") && !path23.isAbsolute(rel);
3674
+ });
3392
3675
  }
3393
- return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
3676
+ return null;
3394
3677
  };
3395
- for (const { file, statements } of migrations) {
3396
- for (const { sql, line } of statements) {
3397
- const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
3398
- if (create) {
3399
- const [key2] = keysFor(sql, create[0].length, qualify(create[1]));
3400
- fns.set(key2, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
3401
- continue;
3402
- }
3403
- const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
3404
- if (alter) {
3405
- const fnName = qualify(alter[1]);
3406
- const keys = keysFor(sql, alter[0].length, fnName);
3407
- const rename = / rename to ([\w$]+)$/.exec(sql);
3408
- const move = / set schema ([\w$]+)$/.exec(sql);
3409
- for (const key2 of keys) {
3410
- const state = fns.get(key2);
3411
- if (rename || move) {
3412
- if (!state) continue;
3413
- fns.delete(key2);
3414
- const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
3415
- fns.set(newName + key2.slice(fnName.length), state);
3416
- continue;
3678
+ const declared = /* @__PURE__ */ new Set([
3679
+ json.name,
3680
+ ...Object.keys(json.dependencies ?? {}),
3681
+ ...Object.keys(json.peerDependencies ?? {}),
3682
+ ...Object.keys(json.devDependencies ?? {}),
3683
+ ...Object.keys(json.optionalDependencies ?? {})
3684
+ ]);
3685
+ for (const file of sourceFiles(pkg.dir)) {
3686
+ const code = stripForImports(readFileSync(path23.join(pkg.dir, file), "utf8"));
3687
+ if (code === null) continue;
3688
+ const at = `${pkg.rel}/${file}`;
3689
+ const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
3690
+ let offset = 0;
3691
+ code.split("\n").forEach((text, i) => {
3692
+ const lineStart = offset;
3693
+ offset += text.length + 1;
3694
+ for (const m of text.matchAll(IMPORT)) {
3695
+ const spec = m[1];
3696
+ const line = i + 1;
3697
+ const at0 = lineStart + m.index;
3698
+ if (typeOnly.some(([a, b]) => at0 >= a && at0 < b)) continue;
3699
+ const alias = viaAlias(spec);
3700
+ if (alias === true) continue;
3701
+ if (alias === false) {
3702
+ ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} imports ${spec}, an alias that points outside the package` });
3703
+ continue;
3704
+ }
3705
+ if (spec.startsWith("#")) continue;
3706
+ if (spec.startsWith("@/") || spec.startsWith("~/")) {
3707
+ ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} imports the app's own code (${spec}); a package may only use its own files and its declared dependencies` });
3708
+ continue;
3709
+ }
3710
+ if (spec.startsWith(".")) {
3711
+ const target = path23.resolve(pkg.dir, path23.dirname(file), spec);
3712
+ const rel = path23.relative(pkg.dir, target);
3713
+ if (rel.startsWith("..") || path23.isAbsolute(rel)) {
3714
+ 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` });
3417
3715
  }
3418
- const next = state ?? { definer: false, searchPath: false, file, line };
3419
- if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
3420
- if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
3421
- if (/\bset search_path\b/.test(sql)) next.searchPath = true;
3422
- if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
3423
- fns.set(key2, next);
3716
+ continue;
3424
3717
  }
3425
- continue;
3426
- }
3427
- const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3428
- if (drop) {
3429
- for (const part of splitTop(drop[1])) {
3430
- const m = /^([\w$.]+)\s*/.exec(part);
3431
- if (m) for (const key2 of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key2);
3718
+ if (BUILTINS.has(spec) || spec.startsWith("node:") || spec.startsWith("virtual:") || /^[a-z]+:/.test(spec)) continue;
3719
+ const name = packageName2(spec);
3720
+ if (!declared.has(name)) {
3721
+ ctx.report({ rule: "package-undeclared-dependency", file: at, line, subject: name, message: `${pkg.name} imports ${name}, which its package.json doesn't list; add it to dependencies or peerDependencies` });
3432
3722
  }
3433
3723
  }
3724
+ });
3725
+ }
3726
+ }
3727
+ function checkMigrations(ctx, pkg, json) {
3728
+ const declaredFiles = /* @__PURE__ */ new Set();
3729
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
3730
+ const migrations = raw.migrations ?? [];
3731
+ for (const m of migrations) {
3732
+ if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
3733
+ if (typeof m.file === "string" && typeof m.test !== "string") {
3734
+ ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.file, message: `${pkg.name} block ${id}: ${m.file} has no pgTAP test; declare one as "test" beside it` });
3735
+ } else if (typeof m.test === "string" && !existsSync(path23.join(pkg.dir, m.test))) {
3736
+ ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.test, message: `${pkg.name} block ${id}: its test ${m.test} doesn't exist` });
3737
+ }
3434
3738
  }
3435
3739
  }
3436
- for (const [key2, at] of fns) {
3437
- if (!at.definer || at.searchPath) continue;
3438
- ctx.report({
3439
- rule: "migration-definer-search-path",
3440
- file: at.file,
3441
- line: at.line,
3442
- subject: key2,
3443
- message: `${key2} is security definer without "set search_path"; add set search_path = '' and schema-qualify the names in its body, so a caller's objects can't stand in for yours`
3444
- });
3740
+ const dir = path23.join(pkg.dir, "migrations");
3741
+ if (!existsSync(dir)) return;
3742
+ const seen = /* @__PURE__ */ new Map();
3743
+ for (const name of readdirSync(dir).sort()) {
3744
+ const m = MIGRATION_FILE.exec(name);
3745
+ if (!m) continue;
3746
+ const other = seen.get(m[1]);
3747
+ 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` });
3748
+ else seen.set(m[1], name);
3749
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path23.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
3750
+ 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")})` });
3751
+ }
3445
3752
  }
3446
3753
  }
3447
- var DEFAULT_MIGRATIONS, DEFAULT_BASE, DEFAULT_EXPOSED, schemaOf, TYPE_ALIASES, MULTIWORD_TYPE;
3448
- var init_supabase = __esm({
3449
- "src/doctor/supabase.ts"() {
3450
- init_config();
3451
- DEFAULT_MIGRATIONS = "supabase/migrations";
3452
- DEFAULT_BASE = "origin/main";
3453
- DEFAULT_EXPOSED = ["public"];
3454
- schemaOf = (name) => name.split(".")[0];
3455
- TYPE_ALIASES = {
3456
- int: "integer",
3457
- int4: "integer",
3458
- int8: "bigint",
3459
- int2: "smallint",
3460
- bool: "boolean",
3461
- varchar: "character varying",
3462
- timestamptz: "timestamp with time zone",
3463
- float8: "double precision"
3464
- };
3465
- MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
3754
+ function checkExports(ctx, pkg, json) {
3755
+ const targets = [];
3756
+ const walk2 = (v) => {
3757
+ if (typeof v === "string") targets.push(v);
3758
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk2(x);
3759
+ };
3760
+ walk2(json.exports);
3761
+ for (const t of targets) {
3762
+ if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
3763
+ if (!existsSync(path23.join(pkg.dir, t))) {
3764
+ ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
3765
+ }
3466
3766
  }
3467
- });
3468
-
3469
- // src/doctor/semver.ts
3470
- function parseVersion(v) {
3471
- const m = VERSION.exec(v.trim());
3472
- return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
3473
3767
  }
3474
- function compareVersions(a, b) {
3475
- for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
3476
- if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
3477
- for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
3478
- const x = a.pre[i];
3479
- const y = b.pre[i];
3480
- if (x === void 0) return -1;
3481
- if (y === void 0) return 1;
3482
- if (x === y) continue;
3483
- const nx = /^\d+$/.test(x);
3484
- const ny = /^\d+$/.test(y);
3485
- if (nx && ny) return +x < +y ? -1 : 1;
3486
- if (nx !== ny) return nx ? -1 : 1;
3487
- return x < y ? -1 : 1;
3768
+ function checkBlocks(ctx, pkg, json) {
3769
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
3770
+ try {
3771
+ parseManifest(json.name, id, raw, json.version, { local: true });
3772
+ } catch (err) {
3773
+ if (!(err instanceof ManifestError)) throw err;
3774
+ for (const problem of err.problems) ctx.report({ rule: "package-block-invalid", file: `${pkg.rel}/package.json`, subject: id, message: problem });
3775
+ }
3488
3776
  }
3489
- return 0;
3490
3777
  }
3491
- function partial(s) {
3492
- const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
3493
- if (!m) return null;
3494
- const nums = [];
3495
- let wild = false;
3496
- for (const part of [m[1], m[2], m[3]]) {
3497
- if (wild || part === void 0 || /^[xX*]$/.test(part)) {
3498
- wild = true;
3499
- nums.push(null);
3500
- } else nums.push(+part);
3778
+ function checkTaggedTests(ctx, pkg) {
3779
+ const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
3780
+ if (!tests.length) return;
3781
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path23.join(pkg.dir, f), "utf8")));
3782
+ 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>` });
3783
+ }
3784
+ function checkRegistered(ctx, pkg) {
3785
+ const file = path23.join(ctx.root, "features.json");
3786
+ if (!existsSync(file)) return;
3787
+ let doc;
3788
+ try {
3789
+ doc = JSON.parse(readFileSync(file, "utf8"));
3790
+ } catch {
3791
+ return;
3792
+ }
3793
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3794
+ const forms = /* @__PURE__ */ new Set([pkg.rel]);
3795
+ if (top) forms.add(path23.relative(top, realpathSync(pkg.dir)).split(path23.sep).join("/"));
3796
+ const covered = (doc.features ?? []).some(
3797
+ (f) => (f.links?.code ?? []).some((c) => {
3798
+ const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
3799
+ return [...forms].some((rel) => norm === rel || norm.startsWith(`${rel}/`) || rel.startsWith(`${norm}/`));
3800
+ })
3801
+ );
3802
+ if (!covered) {
3803
+ ctx.report({ rule: "package-unregistered", level: "warn", file: pkg.rel, message: `no feature in features.ts lists ${pkg.rel} in links.code; add the package to the feature it implements` });
3501
3804
  }
3502
- return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
3503
3805
  }
3504
- function comparators(token) {
3505
- const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
3506
- if (!m) return null;
3507
- const op = m[1] ?? "";
3508
- const p = partial(m[2]);
3509
- if (!p) return null;
3510
- const [major, mi, pa] = p.nums;
3511
- if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
3512
- const M = major;
3513
- const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
3514
- const next = (kind) => kind === "major" ? ver(M + 1, 0, 0, ["0"]) : kind === "minor" ? ver(M, (mi ?? 0) + 1, 0, ["0"]) : ver(M, mi ?? 0, (pa ?? 0) + 1, ["0"]);
3515
- const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
3516
- const out = switchOp();
3517
- if (p.pre.length) {
3518
- for (const c of out) if (c.v === lo) c.pre = true;
3806
+ function changesetNames(text) {
3807
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
3808
+ const names = /* @__PURE__ */ new Set();
3809
+ if (!m) return names;
3810
+ for (const line of m[1].split(/\r?\n/)) {
3811
+ const entry = /^\s*(?:"([^"]+)"|'([^']+)'|([^\s:'"]+))\s*:\s*(major|minor|patch)\s*$/.exec(line);
3812
+ if (entry) names.add(entry[1] ?? entry[2] ?? entry[3]);
3519
3813
  }
3520
- return out;
3521
- function switchOp() {
3522
- switch (op) {
3523
- case "^": {
3524
- const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
3525
- return [
3526
- { op: ">=", v: lo },
3527
- { op: "<", v: bound }
3528
- ];
3814
+ return names;
3815
+ }
3816
+ function mergeBaseOf(root, base) {
3817
+ if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository" };
3818
+ if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) return { reason: `the git ref ${base} isn't available (fetch it)` };
3819
+ const sha = git(root, ["merge-base", "HEAD", base])?.trim();
3820
+ return sha ? { sha } : { reason: `HEAD has no merge base with ${base} (fetch with depth 0)` };
3821
+ }
3822
+ function checkChanges(ctx, pkg, json, base, mergeBase) {
3823
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3824
+ if (!top) return;
3825
+ const appRelative = (fromTop) => path23.relative(realpathSync(ctx.root), path23.join(top, fromTop)).split(path23.sep).join("/");
3826
+ const inRepo = path23.relative(top, realpathSync(pkg.dir)).split(path23.sep).join("/");
3827
+ const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell, i) => i === 0 ? cell : appRelative(cell)).join(" ")).join("\n");
3828
+ const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
3829
+ const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
3830
+ (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
3831
+ );
3832
+ for (const row of diff.split("\n").filter(Boolean)) {
3833
+ const [status, a] = row.split(" ");
3834
+ if (a && /\/migrations\/\d{4}_[a-z0-9_]+\.sql$/.test(a) && /^[MDRT]/.test(status)) {
3835
+ ctx.report({ rule: "package-migration-edited", level: "warn", file: a, message: `${a} existed on ${base} and was ${status.startsWith("D") ? "deleted" : "changed"}; once a migration may have been applied, add a new one instead` });
3836
+ }
3837
+ }
3838
+ if (!changed.length) return;
3839
+ const before = git(ctx.root, ["show", `${mergeBase}:./${pkg.rel}/package.json`]);
3840
+ let versionBefore;
3841
+ try {
3842
+ versionBefore = before ? JSON.parse(before).version : void 0;
3843
+ } catch {
3844
+ versionBefore = void 0;
3845
+ }
3846
+ const now = typeof json.version === "string" ? parseVersion(json.version) : null;
3847
+ const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
3848
+ const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
3849
+ 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) => path23.join(top, f)) : [];
3850
+ const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
3851
+ const named = naming.length > 0;
3852
+ if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
3853
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: path23.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
3854
+ }
3855
+ let jsonBefore = null;
3856
+ try {
3857
+ jsonBefore = before ? JSON.parse(before) : null;
3858
+ } catch {
3859
+ jsonBefore = null;
3860
+ }
3861
+ const raw = json;
3862
+ if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
3863
+ const registry = (git(ctx.root, ["diff", "--relative", "--name-only", mergeBase, "--", "features.ts", "src/features.ts"]) ?? "").trim();
3864
+ 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` });
3865
+ }
3866
+ if (bumped && !named && before !== null) {
3867
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: `${pkg.rel}/package.json`, message: `${pkg.name}'s version went up without a changeset; add one with a "Features:" line so the change is recorded` });
3868
+ }
3869
+ if (!bumped && !named) {
3870
+ ctx.report({
3871
+ rule: "package-unversioned-change",
3872
+ level: "warn",
3873
+ file: `${pkg.rel}/package.json`,
3874
+ message: `${pkg.name} changed since ${base} (${changed.length} file${changed.length === 1 ? "" : "s"}) but neither its version nor a new changeset naming it did; add a changeset (or bump "version") saying what changed`
3875
+ });
3876
+ }
3877
+ }
3878
+ function checkPackagesPack(ctx) {
3879
+ let packages;
3880
+ try {
3881
+ packages = localPackages(ctx.root);
3882
+ } catch (err) {
3883
+ ctx.report({ rule: "package-block-invalid", file: "genesis.config.json", message: err.message });
3884
+ return;
3885
+ }
3886
+ if (!packages.length) return;
3887
+ const base = ctx.base ?? ctx.config.packages?.base;
3888
+ const merge = base ? mergeBaseOf(ctx.root, base) : { reason: "no base ref (pass --base <ref>, e.g. --base origin/main)" };
3889
+ if ("reason" in merge) {
3890
+ ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
3891
+ }
3892
+ for (const pkg of packages) {
3893
+ const json = JSON.parse(readFileSync(path23.join(pkg.dir, "package.json"), "utf8"));
3894
+ checkImports2(ctx, pkg, json);
3895
+ checkExports(ctx, pkg, json);
3896
+ checkBlocks(ctx, pkg, json);
3897
+ checkMigrations(ctx, pkg, json);
3898
+ checkTaggedTests(ctx, pkg);
3899
+ checkRegistered(ctx, pkg);
3900
+ if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
3901
+ }
3902
+ }
3903
+ var SOURCE, SKIP_DIRS2, BUILTINS, IMPORT, TYPE_ONLY;
3904
+ var init_packages = __esm({
3905
+ "src/doctor/packages.ts"() {
3906
+ init_local();
3907
+ init_manifest();
3908
+ init_semver();
3909
+ init_trail();
3910
+ SOURCE = /\.(?:[cm]?[jt]sx?)$/;
3911
+ SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
3912
+ BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
3913
+ IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
3914
+ TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
3915
+ }
3916
+ });
3917
+ function sqlStatements(text) {
3918
+ const out = [];
3919
+ let buf = "";
3920
+ let bodies = [];
3921
+ let line = 1;
3922
+ let start = 0;
3923
+ const flush = () => {
3924
+ const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
3925
+ if (sql) out.push({ sql, line: start, bodies });
3926
+ buf = "";
3927
+ bodies = [];
3928
+ start = 0;
3929
+ };
3930
+ const put = (s) => {
3931
+ if (!start && /\S/.test(s)) start = line;
3932
+ buf += s;
3933
+ };
3934
+ let i = 0;
3935
+ while (i < text.length) {
3936
+ const ch = text[i];
3937
+ const two = text.slice(i, i + 2);
3938
+ if (ch === "\n") {
3939
+ buf += " ";
3940
+ line++;
3941
+ i++;
3942
+ } else if (two === "--") {
3943
+ while (i < text.length && text[i] !== "\n") i++;
3944
+ } else if (two === "/*") {
3945
+ let depth = 0;
3946
+ while (i < text.length) {
3947
+ if (text.startsWith("/*", i)) {
3948
+ depth++;
3949
+ i += 2;
3950
+ } else if (text.startsWith("*/", i)) {
3951
+ depth--;
3952
+ i += 2;
3953
+ if (depth === 0) break;
3954
+ } else {
3955
+ if (text[i] === "\n") line++;
3956
+ i++;
3957
+ }
3958
+ }
3959
+ buf += " ";
3960
+ } else if (ch === "'") {
3961
+ const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
3962
+ put("'");
3963
+ i++;
3964
+ while (i < text.length) {
3965
+ if (escapes && text[i] === "\\") i += 2;
3966
+ else if (text[i] === "'" && text[i + 1] === "'") i += 2;
3967
+ else if (text[i] === "'") break;
3968
+ else {
3969
+ if (text[i] === "\n") line++;
3970
+ i++;
3971
+ }
3529
3972
  }
3530
- case "~":
3531
- case "~>":
3532
- return [
3533
- { op: ">=", v: lo },
3534
- { op: "<", v: mi === null ? next("major") : next("minor") }
3535
- ];
3536
- case ">":
3537
- return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
3538
- case ">=":
3539
- return [{ op: ">=", v: lo }];
3540
- case "<":
3541
- return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
3542
- case "<=":
3543
- return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
3544
- default:
3545
- return upper ? [
3546
- { op: ">=", v: lo },
3547
- { op: "<", v: upper }
3548
- ] : [{ op: "=", v: lo }];
3973
+ put("'");
3974
+ i++;
3975
+ } else if (ch === '"') {
3976
+ i++;
3977
+ while (i < text.length && text[i] !== '"') put(text[i++]);
3978
+ i++;
3979
+ } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
3980
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
3981
+ const end = text.indexOf(tag, i + tag.length);
3982
+ const stop = end === -1 ? text.length : end + tag.length;
3983
+ bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
3984
+ for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
3985
+ put(`${tag} ${tag}`);
3986
+ i = stop;
3987
+ } else if (ch === ";") {
3988
+ flush();
3989
+ i++;
3990
+ } else {
3991
+ put(ch);
3992
+ i++;
3549
3993
  }
3550
3994
  }
3995
+ flush();
3996
+ return out;
3551
3997
  }
3552
- function test(c, v) {
3553
- const d = compareVersions(v, c.v);
3554
- return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
3998
+ function qualify(name) {
3999
+ const n = name.trim().toLowerCase();
4000
+ return n.includes(".") ? n : `public.${n}`;
3555
4001
  }
3556
- function parseRange(range) {
3557
- const alts = [];
3558
- for (const raw of range.trim().split("||")) {
3559
- const alt = raw.trim();
3560
- const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
3561
- if (hyphen) {
3562
- const from = comparators(`>=${hyphen[1]}`);
3563
- const to = comparators(`<=${hyphen[2]}`);
3564
- if (!from || !to) return null;
3565
- alts.push([...from, ...to]);
3566
- continue;
3567
- }
3568
- const set = [];
3569
- for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
3570
- const cs = comparators(token);
3571
- if (!cs) return null;
3572
- set.push(...cs);
3573
- }
3574
- alts.push(set);
4002
+ function parenthesized(sql, open) {
4003
+ let depth = 0;
4004
+ for (let k = open; k < sql.length; k++) {
4005
+ if (sql[k] === "(") depth++;
4006
+ else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
3575
4007
  }
3576
- return alts;
4008
+ return { inner: sql.slice(open + 1), end: sql.length };
3577
4009
  }
3578
- function satisfies(version, range) {
3579
- const v = parseVersion(version);
3580
- const alts = parseRange(range);
3581
- if (!v || !alts) return null;
3582
- return alts.some(
3583
- (set) => set.every((c) => test(c, v)) && (!v.pre.length || set.some((c) => c.pre && c.v.major === v.major && c.v.minor === v.minor && c.v.patch === v.patch))
3584
- );
4010
+ function stripParens(s) {
4011
+ let out = "";
4012
+ let depth = 0;
4013
+ for (const c of s) {
4014
+ if (c === "(") depth++;
4015
+ else if (c === ")") depth = Math.max(0, depth - 1);
4016
+ else if (depth === 0) out += c;
4017
+ }
4018
+ return out;
3585
4019
  }
3586
- var VERSION, ver;
3587
- var init_semver = __esm({
3588
- "src/doctor/semver.ts"() {
3589
- VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
3590
- ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
4020
+ function splitTop(s) {
4021
+ const parts = [];
4022
+ let depth = 0;
4023
+ let cur = "";
4024
+ for (const c of s) {
4025
+ if (c === "(") depth++;
4026
+ if (c === ")") depth--;
4027
+ if (c === "," && depth === 0) {
4028
+ parts.push(cur);
4029
+ cur = "";
4030
+ } else cur += c;
3591
4031
  }
3592
- });
3593
- function nodeModulesOf(dir) {
3594
- const parent = path32.dirname(dir);
3595
- return path32.basename(parent).startsWith("@") ? path32.dirname(parent) : parent;
4032
+ if (cur.trim()) parts.push(cur);
4033
+ return parts.map((p) => p.trim()).filter(Boolean);
3596
4034
  }
3597
- function packagesIn(nodeModules) {
3598
- if (!existsSync(nodeModules)) return [];
3599
- const out = [];
3600
- for (const entry of readdirSync(nodeModules)) {
3601
- if (entry.startsWith(".")) continue;
3602
- const p = path32.join(nodeModules, entry);
3603
- if (entry.startsWith("@")) {
3604
- try {
3605
- for (const sub of readdirSync(p)) out.push(path32.join(p, sub));
3606
- } catch {
3607
- }
3608
- } else {
3609
- out.push(p);
3610
- }
4035
+ function argTypes(args) {
4036
+ const types = [];
4037
+ for (const raw of splitTop(args)) {
4038
+ let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
4039
+ const mode = tokens[0];
4040
+ if (mode === "out") continue;
4041
+ if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
4042
+ const joined = tokens.join(" ");
4043
+ const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
4044
+ types.push(TYPE_ALIASES[type] ?? type);
3611
4045
  }
3612
- return out;
4046
+ return types;
3613
4047
  }
3614
- function genesisInstalls(root) {
3615
- const copies = /* @__PURE__ */ new Map();
3616
- const realRoot = real(root);
3617
- const rel = (abs) => path32.relative(realRoot, abs).split(path32.sep).join("/") || ".";
3618
- const via = /* @__PURE__ */ new Map();
3619
- const record = (real2, manifest, by, range, root2) => {
3620
- let copy = copies.get(real2);
3621
- if (!copy) {
3622
- copy = { name: manifest.name, version: String(manifest.version ?? "unknown"), dir: rel(real2), absolutePath: real2, requiredBy: [], devOnly: false, runtime: false };
3623
- copies.set(real2, copy);
3624
- via.set(real2, /* @__PURE__ */ new Set());
3625
- }
3626
- via.get(real2).add(root2);
3627
- if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
3628
- };
3629
- const walk2 = (kind, roots) => {
3630
- const expanded = /* @__PURE__ */ new Set();
3631
- const queue = [];
3632
- const visit = (dir, by, range) => {
3633
- const manifest = readManifest(dir);
3634
- if (!manifest?.name) return;
3635
- if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
3636
- const realDir = real(dir);
3637
- if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
3638
- if (expanded.has(realDir)) return;
3639
- expanded.add(realDir);
3640
- queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
3641
- };
3642
- for (const r of roots) visit(r.dir, r.by, r.range);
3643
- while (queue.length) {
3644
- const { real: from, manifest, label } = queue.shift();
3645
- const deps = { ...manifest.optionalDependencies, ...manifest.dependencies };
3646
- for (const [name, range] of Object.entries(deps)) {
3647
- const dir = findPackageDir(from, name);
3648
- if (dir) visit(dir, label, range);
3649
- }
3650
- for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
3651
- if (name in deps) continue;
3652
- const dir = peerOf(from, name);
3653
- if (dir) visit(dir, label, range);
3654
- }
4048
+ function git2(root, args) {
4049
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
4050
+ return r.status === 0 ? r.stdout : null;
4051
+ }
4052
+ function gitView(root, dir, base) {
4053
+ if (git2(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
4054
+ if (git2(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
4055
+ return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
4056
+ }
4057
+ const mergeBase = git2(root, ["merge-base", "HEAD", base])?.trim();
4058
+ if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
4059
+ const diff = git2(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
4060
+ const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
4061
+ if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
4062
+ const sql = (p) => p !== void 0 && p.endsWith(".sql");
4063
+ const touched = new Set(untracked.split("\n").filter(sql));
4064
+ const edited = [];
4065
+ for (const row of diff.split("\n").filter(Boolean)) {
4066
+ const [status, a, b] = row.split(" ");
4067
+ if (status.startsWith("R")) {
4068
+ if (sql(b)) touched.add(b);
4069
+ if (sql(a)) edited.push({ file: a, status: "renamed" });
4070
+ continue;
3655
4071
  }
3656
- };
3657
- const peerOf = (from, name) => {
3658
- const dir = findPackageDir(from, name);
3659
- if (!dir) return null;
3660
- if (!ownInstall || name in declared) return dir;
3661
- const realDir = real(dir);
3662
- if (realDir.startsWith(realRoot + path32.sep)) return dir;
3663
- return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
3664
- };
3665
- const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
3666
- const dir = findPackageDir(root, name);
3667
- return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
3668
- });
3669
- const app = readManifest(root);
3670
- const ownInstall = LOCKFILES.some((f) => existsSync(path32.join(root, f)));
3671
- const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
3672
- const declaredDev = Object.entries(app?.devDependencies ?? {});
3673
- const runtimeDeps = {
3674
- ...Object.fromEntries(declaredDev.filter(([n]) => !NON_SHIPPING.test(n))),
3675
- ...app?.peerDependencies,
3676
- ...app?.optionalDependencies,
3677
- ...app?.dependencies
3678
- };
3679
- const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
3680
- walk2("runtime", rootsOf(runtimeDeps, "the app"));
3681
- const top = path32.join(root, "node_modules");
3682
- walk2(
3683
- "hoisted",
3684
- packagesIn(top).filter((dir) => {
3685
- const name = path32.relative(top, dir).split(path32.sep).join("/");
3686
- return !(name in runtimeDeps) && !(name in devDeps);
3687
- }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
3688
- );
3689
- const devRoots = { ...devDeps };
3690
- for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
3691
- walk2("dev", rootsOf(devRoots, "the app (dev)"));
3692
- for (const [key2, copy] of copies) {
3693
- const kinds = via.get(key2);
3694
- copy.runtime = kinds.has("runtime");
3695
- copy.devOnly = kinds.size === 1 && kinds.has("dev");
4072
+ if (!sql(a)) continue;
4073
+ if (status.startsWith("A")) touched.add(a);
4074
+ else if (status.startsWith("M") || status.startsWith("T")) {
4075
+ touched.add(a);
4076
+ edited.push({ file: a, status: "modified" });
4077
+ } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
3696
4078
  }
3697
- const byName = /* @__PURE__ */ new Map();
3698
- for (const copy of copies.values()) byName.set(copy.name, [...byName.get(copy.name) ?? [], copy]);
3699
- for (const list of byName.values()) list.sort((a, b) => a.dir.split("/").length - b.dir.split("/").length || a.dir.localeCompare(b.dir));
3700
- return byName;
4079
+ return { touched, edited };
3701
4080
  }
3702
- function checkDuplicatePackages(ctx) {
3703
- const describe = (c) => `${c.version} at ${c.dir} (${c.requiredBy.map((r) => `${r.by}${r.range ? ` wants ${r.range}` : ""}`).join("; ")})`;
3704
- for (const [name, copies] of genesisInstalls(ctx.root)) {
3705
- if (copies.length < 2) continue;
3706
- const shipping = copies.filter((c) => c.runtime);
3707
- if (!(shipping.length === 1 && copies.every((c) => c === shipping[0] || c.devOnly))) {
4081
+ function checkSupabasePack(ctx) {
4082
+ const settings2 = ctx.config.supabase ?? {};
4083
+ const dir = settings2.migrations ?? DEFAULT_MIGRATIONS;
4084
+ const abs = path23.join(ctx.root, dir);
4085
+ if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
4086
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path23.join(abs, n), "utf8")) }));
4087
+ const exposed = new Set((settings2.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
4088
+ const base = settings2.base ?? DEFAULT_BASE;
4089
+ const view = gitView(ctx.root, dir, base);
4090
+ if ("reason" in view) {
4091
+ if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
4092
+ } else {
4093
+ for (const e of view.edited) {
3708
4094
  ctx.report({
3709
- rule: "duplicate-genesis-package",
3710
- level: "warn",
3711
- file: "package.json",
3712
- subject: name,
3713
- message: `${name} is installed ${copies.length} times: ${copies.map((c) => `${describe(c)}${c.devOnly ? " [dev only]" : ""}`).join(", ")}. Each copy is its own module, so a provider from one (DataProvider, the shell's contexts) is invisible to hooks from another. Align the ranges so one copy satisfies them all, or add an override/resolution`
4095
+ rule: "migration-edited",
4096
+ file: e.file,
4097
+ subject: e.file,
4098
+ message: `${e.status === "modified" ? "edits" : e.status === "deleted" ? "deletes" : "renames"} a migration that already exists on ${base}, so it has been applied; put the change in a new migration instead`
3714
4099
  });
3715
- continue;
3716
4100
  }
4101
+ }
4102
+ const since = settings2.since;
4103
+ const afterSince = (file) => since === void 0 || path23.posix.basename(file) >= since;
4104
+ if ("reason" in view && since === void 0) {
3717
4105
  ctx.report({
3718
- rule: "duplicate-genesis-package",
3719
- level: "info",
3720
- file: "package.json",
3721
- subject: name,
3722
- message: `${name} has dev-only copies beside the one the app loads: ${copies.filter((c) => c.devOnly).map(describe).join(", ")}. They run in tooling, not the app, so they can't split its contexts; upgrade the tool to drop them`
4106
+ rule: "migration-grants",
4107
+ level: "warn",
4108
+ file: dir,
4109
+ message: `skipped: can't tell new migrations from applied ones (${view.reason}); fetch the base ref (CI: fetch-depth 0) or set doctor.supabase.since`
3723
4110
  });
4111
+ } else {
4112
+ const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
4113
+ checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
3724
4114
  }
4115
+ checkRls(ctx, migrations, exposed);
4116
+ checkViewInvoker(ctx, migrations, exposed);
4117
+ checkDefinerSearchPath(ctx, migrations);
4118
+ checkTestingKit(ctx, migrations);
3725
4119
  }
3726
- function checkPeerRanges(ctx) {
3727
- const rel = (abs) => path32.relative(ctx.root, abs).split(path32.sep).join("/");
3728
- for (const copies of genesisInstalls(ctx.root).values()) {
3729
- for (const copy of copies) {
3730
- const dir = copy.absolutePath;
3731
- const peers = readManifest(dir)?.peerDependencies ?? {};
3732
- for (const [peer, range] of Object.entries(peers)) {
3733
- if (!GENESIS.test(peer)) continue;
3734
- const peerDir = findPackageDir(dir, peer);
3735
- const installed = peerDir && readManifest(peerDir)?.version;
3736
- if (!peerDir || !installed) continue;
3737
- if (satisfies(installed, range) !== false) continue;
3738
- ctx.report({
3739
- rule: "peer-range-mismatch",
3740
- // A dev tool's own tree (the CLI's) doesn't run in the app.
3741
- level: copy.devOnly ? "info" : "warn",
3742
- file: "package.json",
3743
- subject: `${copy.name}>${peer}`,
3744
- message: `${copy.name}@${copy.version} (${copy.dir}) wants ${peer} ${range}, but ${installed} is installed (${rel(peerDir)}). Install a ${peer} in that range, or a ${copy.name} release built against ${installed}`
3745
- });
4120
+ function checkTestingKit(ctx, migrations) {
4121
+ for (const { file, statements } of migrations) {
4122
+ const hit = statements.find(({ sql }) => /\bgenesis_testing\b/.test(sql));
4123
+ if (!hit) continue;
4124
+ ctx.report({
4125
+ rule: "migration-testing-kit",
4126
+ file,
4127
+ line: hit.line,
4128
+ subject: "genesis_testing",
4129
+ message: "a migration uses genesis_testing, the pgTAP kit for test databases only; move it to supabase/tests/database/000_genesis_testing.test.sql"
4130
+ });
4131
+ }
4132
+ }
4133
+ function granteesOf(s) {
4134
+ return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
4135
+ }
4136
+ function checkGrants(ctx, migrations, exposed) {
4137
+ const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
4138
+ const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
4139
+ const blanket = (roles) => {
4140
+ const o = open(roles);
4141
+ if (o.length) return { level: "error", who: o.join(" and ") };
4142
+ if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
4143
+ return null;
4144
+ };
4145
+ for (const { file, statements } of migrations) {
4146
+ for (const { sql, line } of statements) {
4147
+ const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
4148
+ if (all) {
4149
+ const hit = blanket(granteesOf(all[1]));
4150
+ if (hit) {
4151
+ ctx.report({ rule: "migration-grants", level: hit.level, file, line, subject: "on all functions", message: `grants every function in a schema to ${hit.who}, which re-grants functions an earlier migration revoked; ${fix}` });
4152
+ }
4153
+ continue;
4154
+ }
4155
+ const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
4156
+ if (defaults) {
4157
+ const hit = blanket(granteesOf(defaults[1]));
4158
+ if (hit) {
4159
+ ctx.report({ rule: "migration-grants", level: hit.level, file, line, subject: "alter default privileges", message: `grants default privileges on functions to ${hit.who}, so every future function is callable by them; ${fix}` });
4160
+ }
4161
+ continue;
4162
+ }
4163
+ const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
4164
+ if (fn) {
4165
+ const roles = open(granteesOf(fn[2]));
4166
+ if (!roles.length) continue;
4167
+ for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
4168
+ if (exposed.has(schemaOf(name))) continue;
4169
+ ctx.report({
4170
+ rule: "migration-grants",
4171
+ file,
4172
+ line,
4173
+ subject: name,
4174
+ message: `grants ${name} to ${roles.join(" and ")}; a function outside the exposed schemas is never callable by anon or public (grant it to authenticated, or expose a wrapper)`
4175
+ });
4176
+ }
4177
+ continue;
4178
+ }
4179
+ const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
4180
+ if (schema) {
4181
+ const roles = open(granteesOf(schema[2]));
4182
+ if (!roles.length) continue;
4183
+ for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
4184
+ if (exposed.has(s)) continue;
4185
+ ctx.report({
4186
+ rule: "migration-grants",
4187
+ file,
4188
+ line,
4189
+ subject: `schema ${s}`,
4190
+ message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
4191
+ });
4192
+ }
3746
4193
  }
3747
4194
  }
3748
4195
  }
3749
4196
  }
3750
- var GENESIS, DEV_TOOLS, NON_SHIPPING, readManifest, real, LOCKFILES;
3751
- var init_installs = __esm({
3752
- "src/doctor/installs.ts"() {
3753
- init_genesis();
3754
- init_semver();
3755
- GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
3756
- DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
3757
- 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)$/;
3758
- readManifest = (dir) => {
3759
- try {
3760
- return JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8"));
3761
- } catch {
3762
- return null;
4197
+ function checkRls(ctx, migrations, exposed) {
4198
+ const tables = /* @__PURE__ */ new Map();
4199
+ const name = String.raw`([\w$.]+)`;
4200
+ const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
4201
+ for (const { file, statements } of migrations) {
4202
+ for (const { sql, line, bodies } of statements) {
4203
+ if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
4204
+ const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
4205
+ if (create) {
4206
+ if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
4207
+ continue;
3763
4208
  }
3764
- };
3765
- real = (p) => {
3766
- try {
3767
- return realpathSync(p);
3768
- } catch {
3769
- return p;
4209
+ const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
4210
+ const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
4211
+ if (rename || move) {
4212
+ const from = qualify((rename ?? move)[1]);
4213
+ const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
4214
+ const state = tables.get(from);
4215
+ if (state) {
4216
+ tables.delete(from);
4217
+ tables.set(to, state);
4218
+ }
4219
+ continue;
3770
4220
  }
3771
- };
3772
- LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
4221
+ const alter = new RegExp(target).exec(sql);
4222
+ if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
4223
+ const t = qualify(alter[1]);
4224
+ if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
4225
+ else {
4226
+ const state = tables.get(t);
4227
+ if (state) state.rls = true;
4228
+ }
4229
+ continue;
4230
+ }
4231
+ const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
4232
+ if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
4233
+ }
3773
4234
  }
3774
- });
3775
- function stripForImports(code) {
3776
- const out = [];
3777
- const blank = (ch) => ch === "\n" ? "\n" : " ";
3778
- const n = code.length;
3779
- const templates = [];
3780
- let depth = 0;
3781
- let i = 0;
3782
- let sure = true;
3783
- const isSpecifier = () => /(?:\bfrom|(?:^|[;{}\n])\s*import|\bimport\s*\(|\brequire\s*\()\s*$/.test(out.slice(-40).join(""));
3784
- const before = () => out.slice(-24).join("");
3785
- const KEYWORD = /(?:^|[^\w$.])(?:return|typeof|instanceof|case|do|else|in|of|new|delete|void|throw|yield|await|from|import|export|default|require)\s*$/;
3786
- const startsExpression = (b) => {
3787
- const t = b.replace(/\s+$/, "");
3788
- if (!t) return true;
3789
- if (KEYWORD.test(b)) return true;
3790
- return /[([{,;:=!&|?+\-*%<>~^}]$/.test(t);
3791
- };
3792
- const exprStart = () => startsExpression(before());
3793
- const taggedTemplate = () => {
3794
- const b = out.slice(-48).join("");
3795
- const m = /([A-Za-z_$][\w$.]*)$/.exec(b);
3796
- return m !== null && startsExpression(b.slice(0, b.length - m[1].length));
3797
- };
3798
- const templateBody = () => {
3799
- while (i < n) {
3800
- const ch = code[i];
3801
- if (ch === "\\") {
3802
- out.push(" ", blank(code[i + 1] ?? ""));
3803
- i += 2;
3804
- } else if (ch === "`") {
3805
- out.push("`");
3806
- i++;
3807
- return;
3808
- } else if (ch === "$" && code[i + 1] === "{") {
3809
- out.push("${");
3810
- i += 2;
3811
- templates.push(depth);
3812
- depth++;
3813
- return;
3814
- } else {
3815
- out.push(blank(ch));
3816
- i++;
4235
+ for (const [t, at] of tables) {
4236
+ if (at.rls || !exposed.has(schemaOf(t))) continue;
4237
+ ctx.report({
4238
+ rule: "migration-rls",
4239
+ file: at.file,
4240
+ line: at.line,
4241
+ subject: t,
4242
+ message: at.disabled ? `disables row level security on ${t}, and no later migration turns it back on; anyone with the API key can read and write it` : `creates ${t} without enabling row level security in any migration; add "alter table ${t} enable row level security;" and its policies`
4243
+ });
4244
+ }
4245
+ }
4246
+ function checkViewInvoker(ctx, migrations, exposed) {
4247
+ const views = /* @__PURE__ */ new Map();
4248
+ const name = String.raw`([\w$.]+)`;
4249
+ const invokerOn = /\bsecurity_invoker\s*(?:=\s*(?:true|on|yes|1|'true'|'on'))?\s*(?:,|\))/;
4250
+ for (const { file, statements } of migrations) {
4251
+ for (const { sql, line } of statements) {
4252
+ const create = new RegExp(String.raw`^create (?:or replace )?(?:temp |temporary )?(?:recursive )?view ${name}`).exec(sql);
4253
+ if (create) {
4254
+ if (/^create (?:or replace )?(?:temp|temporary) /.test(sql)) continue;
4255
+ const options = /^[^(]*?\bwith\s*(\([^)]*\))\s*as\b/.exec(sql)?.[1] ?? "";
4256
+ views.set(qualify(create[1]), { invoker: invokerOn.test(options), file, line });
4257
+ continue;
4258
+ }
4259
+ const alter = new RegExp(String.raw`^alter view (?:if exists )?${name} (set|reset) (\([^)]*\))`).exec(sql);
4260
+ if (alter && /\bsecurity_invoker\b/.test(alter[3])) {
4261
+ const state = views.get(qualify(alter[1]));
4262
+ if (state) state.invoker = alter[2] === "set" && invokerOn.test(alter[3]);
4263
+ continue;
4264
+ }
4265
+ const rename = new RegExp(String.raw`^alter view (?:if exists )?${name} rename to ([\w$]+)$`).exec(sql);
4266
+ if (rename) {
4267
+ const from = qualify(rename[1]);
4268
+ const state = views.get(from);
4269
+ if (state) {
4270
+ views.delete(from);
4271
+ views.set(`${schemaOf(from)}.${rename[2]}`, state);
4272
+ }
4273
+ continue;
3817
4274
  }
4275
+ const drop = /^drop view (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
4276
+ if (drop) for (const n of drop[1].split(",")) views.delete(qualify(n));
3818
4277
  }
3819
- sure = false;
4278
+ }
4279
+ for (const [v, at] of views) {
4280
+ if (at.invoker || !exposed.has(schemaOf(v))) continue;
4281
+ ctx.report({
4282
+ rule: "migration-view-rls",
4283
+ file: at.file,
4284
+ line: at.line,
4285
+ subject: v,
4286
+ message: `${v} runs as its owner, so it reads past row level security; create it "with (security_invoker = true)" or add "alter view ${v} set (security_invoker = true);"`
4287
+ });
4288
+ }
4289
+ }
4290
+ function checkDefinerSearchPath(ctx, migrations) {
4291
+ const fns = /* @__PURE__ */ new Map();
4292
+ const keysFor = (sql, nameEnd, fnName) => {
4293
+ const rest = sql.slice(nameEnd).trimStart();
4294
+ if (rest.startsWith("(")) {
4295
+ const { inner } = parenthesized(rest, 0);
4296
+ return [`${fnName}(${argTypes(inner).join(",")})`];
4297
+ }
4298
+ return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
3820
4299
  };
3821
- while (i < n && sure) {
3822
- const ch = code[i];
3823
- const next = code[i + 1];
3824
- if (ch === "/" && next === "/") {
3825
- while (i < n && code[i] !== "\n") {
3826
- out.push(" ");
3827
- i++;
3828
- }
3829
- } else if (ch === "/" && next === "*") {
3830
- out.push(" ");
3831
- i += 2;
3832
- while (i < n && !(code[i] === "*" && code[i + 1] === "/")) {
3833
- out.push(blank(code[i]));
3834
- i++;
3835
- }
3836
- if (i < n) {
3837
- out.push(" ");
3838
- i += 2;
4300
+ for (const { file, statements } of migrations) {
4301
+ for (const { sql, line } of statements) {
4302
+ const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
4303
+ if (create) {
4304
+ const [key2] = keysFor(sql, create[0].length, qualify(create[1]));
4305
+ fns.set(key2, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
4306
+ continue;
3839
4307
  }
3840
- } else if (ch === "/" && next !== ">" && code[i - 1] !== "<" && exprStart()) {
3841
- const afterBrace = /[}>]\s*$/.test(before());
3842
- const start = i;
3843
- const mark = out.length;
3844
- out.push("/");
3845
- i++;
3846
- let inClass = false;
3847
- for (; ; ) {
3848
- const c = code[i];
3849
- if (c === void 0 || c === "\n") {
3850
- if (afterBrace) {
3851
- out.length = mark;
3852
- out.push("/");
3853
- i = start + 1;
3854
- } else sure = false;
3855
- break;
3856
- }
3857
- if (c === "\\") {
3858
- out.push(" ", blank(code[i + 1] ?? ""));
3859
- i += 2;
3860
- continue;
3861
- }
3862
- i++;
3863
- if (c === "[") inClass = true;
3864
- else if (c === "]") inClass = false;
3865
- else if (c === "/" && !inClass) {
3866
- if (afterBrace && /[<>]/.test(code.slice(start + 1, i - 1))) {
3867
- out.length = mark;
3868
- out.push("/");
3869
- i = start + 1;
3870
- break;
4308
+ const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
4309
+ if (alter) {
4310
+ const fnName = qualify(alter[1]);
4311
+ const keys = keysFor(sql, alter[0].length, fnName);
4312
+ const rename = / rename to ([\w$]+)$/.exec(sql);
4313
+ const move = / set schema ([\w$]+)$/.exec(sql);
4314
+ for (const key2 of keys) {
4315
+ const state = fns.get(key2);
4316
+ if (rename || move) {
4317
+ if (!state) continue;
4318
+ fns.delete(key2);
4319
+ const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
4320
+ fns.set(newName + key2.slice(fnName.length), state);
4321
+ continue;
3871
4322
  }
3872
- out.push("/");
3873
- break;
4323
+ const next = state ?? { definer: false, searchPath: false, file, line };
4324
+ if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
4325
+ if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
4326
+ if (/\bset search_path\b/.test(sql)) next.searchPath = true;
4327
+ if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
4328
+ fns.set(key2, next);
3874
4329
  }
3875
- out.push(" ");
4330
+ continue;
3876
4331
  }
3877
- if (out.length > mark + 1 || i > start + 1) while (i < n && /[a-z]/.test(code[i])) out.push(code[i++]);
3878
- } else if ((ch === '"' || ch === "'") && exprStart()) {
3879
- const keep = isSpecifier();
3880
- out.push(ch);
3881
- i++;
3882
- while (i < n && code[i] !== ch && code[i] !== "\n") {
3883
- if (code[i] === "\\") {
3884
- out.push(keep ? code[i] : " ", keep ? code[i + 1] ?? "" : blank(code[i + 1] ?? ""));
3885
- i += 2;
3886
- } else {
3887
- out.push(keep ? code[i] : blank(code[i]));
3888
- i++;
4332
+ const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
4333
+ if (drop) {
4334
+ for (const part of splitTop(drop[1])) {
4335
+ const m = /^([\w$.]+)\s*/.exec(part);
4336
+ if (m) for (const key2 of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key2);
3889
4337
  }
3890
4338
  }
3891
- if (code[i] !== ch) sure = false;
3892
- else {
3893
- out.push(code[i]);
3894
- i++;
3895
- }
3896
- } else if (ch === "`" && (exprStart() || taggedTemplate())) {
3897
- out.push("`");
3898
- i++;
3899
- templateBody();
3900
- } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
3901
- templates.pop();
3902
- depth--;
3903
- out.push("}");
3904
- i++;
3905
- templateBody();
3906
- } else {
3907
- if (ch === "{") depth++;
3908
- else if (ch === "}") depth--;
3909
- out.push(ch);
3910
- i++;
3911
4339
  }
3912
4340
  }
3913
- return sure && templates.length === 0 ? out.join("") : null;
3914
- }
3915
- function bindings(clause) {
3916
- const out = [];
3917
- const named = /\{([^}]*)\}/.exec(clause);
3918
- for (const part of named?.[1].split(",") ?? []) {
3919
- const p = part.trim();
3920
- if (!p || p.startsWith("type ")) continue;
3921
- out.push(p.split(/\s+as\s+/).pop().trim());
4341
+ for (const [key2, at] of fns) {
4342
+ if (!at.definer || at.searchPath) continue;
4343
+ ctx.report({
4344
+ rule: "migration-definer-search-path",
4345
+ file: at.file,
4346
+ line: at.line,
4347
+ subject: key2,
4348
+ message: `${key2} is security definer without "set search_path"; add set search_path = '' and schema-qualify the names in its body, so a caller's objects can't stand in for yours`
4349
+ });
3922
4350
  }
3923
- const rest = clause.replace(/\{[^}]*\}/, "");
3924
- const ns = /\*\s*as\s+([\w$]+)/.exec(rest);
3925
- if (ns) out.push(ns[1]);
3926
- const def = /^\s*([\w$]+)/.exec(rest);
3927
- if (def && def[1] !== "as") out.push(def[1]);
3928
- return out;
3929
4351
  }
3930
- function readJsonc(file) {
3931
- try {
3932
- const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? "").replace(/,(\s*[}\]])/g, "$1");
3933
- return JSON.parse(text);
3934
- } catch {
3935
- return null;
4352
+ var DEFAULT_MIGRATIONS, DEFAULT_BASE, DEFAULT_EXPOSED, schemaOf, TYPE_ALIASES, MULTIWORD_TYPE;
4353
+ var init_supabase = __esm({
4354
+ "src/doctor/supabase.ts"() {
4355
+ init_config();
4356
+ DEFAULT_MIGRATIONS = "supabase/migrations";
4357
+ DEFAULT_BASE = "origin/main";
4358
+ DEFAULT_EXPOSED = ["public"];
4359
+ schemaOf = (name) => name.split(".")[0];
4360
+ TYPE_ALIASES = {
4361
+ int: "integer",
4362
+ int4: "integer",
4363
+ int8: "bigint",
4364
+ int2: "smallint",
4365
+ bool: "boolean",
4366
+ varchar: "character varying",
4367
+ timestamptz: "timestamp with time zone",
4368
+ float8: "double precision"
4369
+ };
4370
+ MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
3936
4371
  }
4372
+ });
4373
+ function nodeModulesOf(dir) {
4374
+ const parent = path23.dirname(dir);
4375
+ return path23.basename(parent).startsWith("@") ? path23.dirname(parent) : parent;
3937
4376
  }
3938
- function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3939
- if (seen.has(file) || seen.size > 10) return {};
3940
- seen.add(file);
3941
- const json = readJsonc(file);
3942
- if (!json) return {};
3943
- const dir = path32.dirname(file);
3944
- let merged = {};
3945
- const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
3946
- for (const ext of parents) {
3947
- if (typeof ext !== "string") continue;
3948
- let target = null;
3949
- if (ext.startsWith(".") || path32.isAbsolute(ext)) {
3950
- const abs = path32.resolve(dir, ext);
3951
- target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
4377
+ function packagesIn(nodeModules) {
4378
+ if (!existsSync(nodeModules)) return [];
4379
+ const out = [];
4380
+ for (const entry of readdirSync(nodeModules)) {
4381
+ if (entry.startsWith(".")) continue;
4382
+ const p = path23.join(nodeModules, entry);
4383
+ if (entry.startsWith("@")) {
4384
+ try {
4385
+ for (const sub of readdirSync(p)) out.push(path23.join(p, sub));
4386
+ } catch {
4387
+ }
3952
4388
  } else {
3953
- const parts = ext.split("/");
3954
- const nameLength = ext.startsWith("@") ? 2 : 1;
3955
- const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
3956
- if (pkgDir) {
3957
- const sub = parts.slice(nameLength).join("/");
3958
- const abs = path32.join(pkgDir, sub || "tsconfig.json");
3959
- target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
4389
+ out.push(p);
4390
+ }
4391
+ }
4392
+ return out;
4393
+ }
4394
+ function genesisInstalls(root) {
4395
+ const copies = /* @__PURE__ */ new Map();
4396
+ const realRoot = real(root);
4397
+ const rel = (abs) => path23.relative(realRoot, abs).split(path23.sep).join("/") || ".";
4398
+ const via = /* @__PURE__ */ new Map();
4399
+ const record = (real2, manifest, by, range, root2) => {
4400
+ let copy = copies.get(real2);
4401
+ if (!copy) {
4402
+ copy = { name: manifest.name, version: String(manifest.version ?? "unknown"), dir: rel(real2), absolutePath: real2, requiredBy: [], devOnly: false, runtime: false };
4403
+ copies.set(real2, copy);
4404
+ via.set(real2, /* @__PURE__ */ new Set());
4405
+ }
4406
+ via.get(real2).add(root2);
4407
+ if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
4408
+ };
4409
+ const walk2 = (kind, roots) => {
4410
+ const expanded = /* @__PURE__ */ new Set();
4411
+ const queue = [];
4412
+ const visit = (dir, by, range) => {
4413
+ const manifest = readManifest(dir);
4414
+ if (!manifest?.name) return;
4415
+ if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
4416
+ const realDir = real(dir);
4417
+ if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
4418
+ if (expanded.has(realDir)) return;
4419
+ expanded.add(realDir);
4420
+ queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
4421
+ };
4422
+ for (const r of roots) visit(r.dir, r.by, r.range);
4423
+ while (queue.length) {
4424
+ const { real: from, manifest, label } = queue.shift();
4425
+ const deps = { ...manifest.optionalDependencies, ...manifest.dependencies };
4426
+ for (const [name, range] of Object.entries(deps)) {
4427
+ const dir = findPackageDir(from, name);
4428
+ if (dir) visit(dir, label, range);
4429
+ }
4430
+ for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
4431
+ if (name in deps) continue;
4432
+ const dir = peerOf(from, name);
4433
+ if (dir) visit(dir, label, range);
3960
4434
  }
3961
4435
  }
3962
- if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
3963
- }
3964
- const opts = json.compilerOptions ?? {};
3965
- if (typeof opts.baseUrl === "string") merged.baseUrl = path32.resolve(dir, opts.baseUrl);
3966
- if (opts.paths && typeof opts.paths === "object") {
3967
- merged.paths = opts.paths;
3968
- merged.pathsDir = dir;
4436
+ };
4437
+ const peerOf = (from, name) => {
4438
+ const dir = findPackageDir(from, name);
4439
+ if (!dir) return null;
4440
+ if (!ownInstall || name in declared) return dir;
4441
+ const realDir = real(dir);
4442
+ if (realDir.startsWith(realRoot + path23.sep)) return dir;
4443
+ return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
4444
+ };
4445
+ const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
4446
+ const dir = findPackageDir(root, name);
4447
+ return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
4448
+ });
4449
+ const app = readManifest(root);
4450
+ const ownInstall = LOCKFILES.some((f) => existsSync(path23.join(root, f)));
4451
+ const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
4452
+ const declaredDev = Object.entries(app?.devDependencies ?? {});
4453
+ const runtimeDeps = {
4454
+ ...Object.fromEntries(declaredDev.filter(([n]) => !NON_SHIPPING.test(n))),
4455
+ ...app?.peerDependencies,
4456
+ ...app?.optionalDependencies,
4457
+ ...app?.dependencies
4458
+ };
4459
+ const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
4460
+ walk2("runtime", rootsOf(runtimeDeps, "the app"));
4461
+ const top = path23.join(root, "node_modules");
4462
+ walk2(
4463
+ "hoisted",
4464
+ packagesIn(top).filter((dir) => {
4465
+ const name = path23.relative(top, dir).split(path23.sep).join("/");
4466
+ return !(name in runtimeDeps) && !(name in devDeps);
4467
+ }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
4468
+ );
4469
+ const devRoots = { ...devDeps };
4470
+ for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
4471
+ walk2("dev", rootsOf(devRoots, "the app (dev)"));
4472
+ for (const [key2, copy] of copies) {
4473
+ const kinds = via.get(key2);
4474
+ copy.runtime = kinds.has("runtime");
4475
+ copy.devOnly = kinds.size === 1 && kinds.has("dev");
3969
4476
  }
3970
- return merged;
4477
+ const byName = /* @__PURE__ */ new Map();
4478
+ for (const copy of copies.values()) byName.set(copy.name, [...byName.get(copy.name) ?? [], copy]);
4479
+ for (const list of byName.values()) list.sort((a, b) => a.dir.split("/").length - b.dir.split("/").length || a.dir.localeCompare(b.dir));
4480
+ return byName;
3971
4481
  }
3972
- function aliases(root) {
3973
- const table = [];
3974
- let baseUrl = null;
3975
- for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
3976
- const file = path32.join(root, name);
3977
- if (!existsSync(file)) continue;
3978
- const config = readTsconfig(root, file);
3979
- baseUrl ??= config.baseUrl ?? null;
3980
- const base = config.baseUrl ?? config.pathsDir ?? root;
3981
- for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
3982
- if (!Array.isArray(targets)) continue;
3983
- const exact = !pattern.endsWith("*");
3984
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path32.join(base, String(t).replace(/\*$/, ""))) });
4482
+ function checkDuplicatePackages(ctx) {
4483
+ const describe = (c) => `${c.version} at ${c.dir} (${c.requiredBy.map((r) => `${r.by}${r.range ? ` wants ${r.range}` : ""}`).join("; ")})`;
4484
+ for (const [name, copies] of genesisInstalls(ctx.root)) {
4485
+ if (copies.length < 2) continue;
4486
+ const shipping = copies.filter((c) => c.runtime);
4487
+ if (!(shipping.length === 1 && copies.every((c) => c === shipping[0] || c.devOnly))) {
4488
+ ctx.report({
4489
+ rule: "duplicate-genesis-package",
4490
+ level: "warn",
4491
+ file: "package.json",
4492
+ subject: name,
4493
+ message: `${name} is installed ${copies.length} times: ${copies.map((c) => `${describe(c)}${c.devOnly ? " [dev only]" : ""}`).join(", ")}. Each copy is its own module, so a provider from one (DataProvider, the shell's contexts) is invisible to hooks from another. Align the ranges so one copy satisfies them all, or add an override/resolution`
4494
+ });
4495
+ continue;
3985
4496
  }
4497
+ ctx.report({
4498
+ rule: "duplicate-genesis-package",
4499
+ level: "info",
4500
+ file: "package.json",
4501
+ subject: name,
4502
+ message: `${name} has dev-only copies beside the one the app loads: ${copies.filter((c) => c.devOnly).map(describe).join(", ")}. They run in tooling, not the app, so they can't split its contexts; upgrade the tool to drop them`
4503
+ });
3986
4504
  }
3987
- const pkg = readJsonc(path32.join(root, "package.json"));
3988
- for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
3989
- if (typeof target !== "string") continue;
3990
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path32.join(root, target.replace(/\*.*$/, ""))] });
3991
- }
3992
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path32.join(root, "src") + path32.sep, root + path32.sep] });
3993
- return { table, baseUrl };
3994
- }
3995
- function resolveFile(base) {
3996
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path32.join(base, `index${e}`))];
3997
- if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
3998
- for (const p of tries) {
3999
- if (SCRIPT_EXTS2.has(path32.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
4000
- }
4001
- return null;
4002
- }
4003
- function trailFor(ctx) {
4004
- let t = trails.get(ctx.files);
4005
- if (!t) trails.set(ctx.files, t = createTrail(ctx));
4006
- return t;
4007
4505
  }
4008
- function createTrail(ctx) {
4009
- const { table, baseUrl } = aliases(ctx.root);
4010
- let declared = null;
4011
- try {
4012
- const pkg = JSON.parse(readFileSync(path32.join(ctx.root, "package.json"), "utf8"));
4013
- declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
4014
- } catch {
4015
- declared = null;
4016
- }
4017
- const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
4018
- const read = (abs) => byPath.get(abs) ?? readSource(abs);
4019
- const importsCache = /* @__PURE__ */ new Map();
4020
- const importsOf = (file) => {
4021
- const hit = importsCache.get(file.absolutePath);
4022
- if (hit) return hit;
4023
- const files = [];
4024
- let lost = false;
4025
- const code = stripped(file);
4026
- if (code === null) {
4027
- const out2 = { files: [], lost: true };
4028
- importsCache.set(file.absolutePath, out2);
4029
- return out2;
4030
- }
4031
- const used = new Set(renderedElements(code).map((e) => e.split(".")[0]));
4032
- for (const m of code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
4033
- for (const m of code.matchAll(/\bexport\s+default\s+([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
4034
- for (const m of code.matchAll(/\bexport\s*\{([^}]*)\}\s*;/g)) for (const n of m[1].split(",")) used.add(n.trim().split(/\s+as\s+/)[0]);
4035
- const specs = [];
4036
- for (const m of code.matchAll(IMPORT_FROM)) if (!m[1] && bindings(m[2]).some((b) => used.has(b))) specs.push(m[3]);
4037
- for (const m of code.matchAll(EXPORT_FROM)) if (!m[1]) specs.push(m[2]);
4038
- for (const m of code.matchAll(DYNAMIC)) specs.push(m[1]);
4039
- for (const spec of specs) {
4040
- if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
4041
- let resolved = null;
4042
- if (spec.startsWith(".")) {
4043
- resolved = resolveFile(path32.resolve(path32.dirname(file.absolutePath), spec));
4044
- if (!resolved) lost = true;
4045
- } else {
4046
- const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
4047
- if (alias) {
4048
- for (const t of alias.targets) {
4049
- resolved = resolveFile(alias.exact ? t : path32.join(t, spec.slice(alias.prefix.length)));
4050
- if (resolved) break;
4051
- }
4052
- }
4053
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path32.join(baseUrl, spec));
4054
- if (!resolved) {
4055
- const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
4056
- if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
4057
- }
4058
- }
4059
- if (resolved && !files.includes(resolved)) files.push(resolved);
4060
- }
4061
- const out = { files, lost };
4062
- importsCache.set(file.absolutePath, out);
4063
- return out;
4064
- };
4065
- const strippedCache = /* @__PURE__ */ new Map();
4066
- const stripped = (file) => {
4067
- if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
4068
- return strippedCache.get(file.absolutePath);
4069
- };
4070
- const memo = /* @__PURE__ */ new WeakMap();
4071
- const reach = (file, test2, depth, seen) => {
4072
- let cache = memo.get(test2);
4073
- if (!cache) memo.set(test2, cache = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
4074
- const k = `${file.absolutePath}\0${depth}`;
4075
- const free = cache.free.get(k);
4076
- if (free) return [free, /* @__PURE__ */ new Set()];
4077
- const reusable = cache.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
4078
- if (reusable) return [reusable.result, new Set(reusable.cut)];
4079
- let result;
4080
- const cut = /* @__PURE__ */ new Set();
4081
- const code = stripped(file);
4082
- if (code === null) result = "unknown";
4083
- else if (test2(code)) result = "yes";
4084
- else {
4085
- const { files, lost } = importsOf(file);
4086
- let unknown = lost && depth > 0;
4087
- result = "no";
4088
- if (depth > 0) {
4089
- seen.add(file.absolutePath);
4090
- for (const abs of files) {
4091
- if (seen.has(abs)) {
4092
- cut.add(abs);
4093
- continue;
4094
- }
4095
- const target = read(abs);
4096
- if (!target) {
4097
- unknown = true;
4098
- continue;
4099
- }
4100
- const [r, c] = reach(target, test2, depth - 1, seen);
4101
- for (const m of c) cut.add(m);
4102
- if (r === "yes") {
4103
- result = "yes";
4104
- break;
4105
- }
4106
- if (r === "unknown") unknown = true;
4107
- }
4108
- seen.delete(file.absolutePath);
4109
- cut.delete(file.absolutePath);
4506
+ function checkPeerRanges(ctx) {
4507
+ const rel = (abs) => path23.relative(ctx.root, abs).split(path23.sep).join("/");
4508
+ for (const copies of genesisInstalls(ctx.root).values()) {
4509
+ for (const copy of copies) {
4510
+ const dir = copy.absolutePath;
4511
+ const peers = readManifest(dir)?.peerDependencies ?? {};
4512
+ for (const [peer, range] of Object.entries(peers)) {
4513
+ if (!GENESIS.test(peer)) continue;
4514
+ const peerDir = findPackageDir(dir, peer);
4515
+ const installed = peerDir && readManifest(peerDir)?.version;
4516
+ if (!peerDir || !installed) continue;
4517
+ if (satisfies(installed, range) !== false) continue;
4518
+ ctx.report({
4519
+ rule: "peer-range-mismatch",
4520
+ // A dev tool's own tree (the CLI's) doesn't run in the app.
4521
+ level: copy.devOnly ? "info" : "warn",
4522
+ file: "package.json",
4523
+ subject: `${copy.name}>${peer}`,
4524
+ message: `${copy.name}@${copy.version} (${copy.dir}) wants ${peer} ${range}, but ${installed} is installed (${rel(peerDir)}). Install a ${peer} in that range, or a ${copy.name} release built against ${installed}`
4525
+ });
4110
4526
  }
4111
- if (result === "no" && unknown) result = "unknown";
4112
- }
4113
- if (result === "yes" || cut.size === 0) {
4114
- cache.free.set(k, result);
4115
- return [result, /* @__PURE__ */ new Set()];
4116
4527
  }
4117
- const entries = cache.cut.get(k) ?? [];
4118
- entries.push({ cut: [...cut], result });
4119
- cache.cut.set(k, entries);
4120
- return [result, cut];
4121
- };
4122
- return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
4528
+ }
4123
4529
  }
4124
- var TRAIL_DEPTH, RESOLVE_EXTS2, IMPORT_FROM, EXPORT_FROM, DYNAMIC, trails;
4125
- var init_trail = __esm({
4126
- "src/doctor/trail.ts"() {
4530
+ var GENESIS, DEV_TOOLS, NON_SHIPPING, readManifest, real, LOCKFILES;
4531
+ var init_installs = __esm({
4532
+ "src/doctor/installs.ts"() {
4127
4533
  init_genesis();
4128
- init_source();
4129
- TRAIL_DEPTH = 6;
4130
- RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
4131
- IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
4132
- EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
4133
- DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
4134
- trails = /* @__PURE__ */ new WeakMap();
4534
+ init_semver();
4535
+ GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
4536
+ DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
4537
+ 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)$/;
4538
+ readManifest = (dir) => {
4539
+ try {
4540
+ return JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
4541
+ } catch {
4542
+ return null;
4543
+ }
4544
+ };
4545
+ real = (p) => {
4546
+ try {
4547
+ return realpathSync(p);
4548
+ } catch {
4549
+ return p;
4550
+ }
4551
+ };
4552
+ LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
4135
4553
  }
4136
4554
  });
4137
4555
  function routesDir(ctx) {
4138
4556
  if (ctx.config.routesDir) return ctx.config.routesDir;
4139
- return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path32.join(ctx.root, d))) ?? null;
4557
+ return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path23.join(ctx.root, d))) ?? null;
4140
4558
  }
4141
4559
  function flavorOf(dir, rels) {
4142
4560
  const stems = rels.map((r) => r.split("/").pop());
@@ -4358,10 +4776,10 @@ function checkPageLayouts(ctx) {
4358
4776
  for (const n of namedImportsFrom(code, GENESIS_PACKAGE2)) if (PACKAGE_SCREEN.test(n)) names.add(n);
4359
4777
  return rendersRe(names)?.test(code) ?? false;
4360
4778
  };
4361
- const cache = /* @__PURE__ */ new Map();
4779
+ const cache2 = /* @__PURE__ */ new Map();
4362
4780
  const provides = (r) => {
4363
- if (!cache.has(r)) cache.set(r, routeReach(ctx, r, rendersLayout));
4364
- return cache.get(r);
4781
+ if (!cache2.has(r)) cache2.set(r, routeReach(ctx, r, rendersLayout));
4782
+ return cache2.get(r);
4365
4783
  };
4366
4784
  const list = [...layouts].sort();
4367
4785
  const named = list.length > 4 ? `${list.slice(0, 4).join(", ")}, \u2026` : list.join(", ");
@@ -4455,7 +4873,7 @@ __export(doctor_exports, {
4455
4873
  webRoutes: () => webRoutes
4456
4874
  });
4457
4875
  async function runDoctor(options = {}) {
4458
- const root = path32.resolve(options.root ?? process.cwd());
4876
+ const root = path23.resolve(options.root ?? process.cwd());
4459
4877
  const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
4460
4878
  const config = loaded.config;
4461
4879
  const genesis = options.genesis ?? loadGenesis(root, config);
@@ -4467,7 +4885,7 @@ async function runDoctor(options = {}) {
4467
4885
  if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
4468
4886
  }
4469
4887
  const raw = [];
4470
- const ctx = { root, files, genesis, config, report: (f) => raw.push(f) };
4888
+ const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
4471
4889
  for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
4472
4890
  try {
4473
4891
  await plugin.check(ctx);
@@ -4499,7 +4917,8 @@ async function runDoctor(options = {}) {
4499
4917
  function builtinChecks(config) {
4500
4918
  const packs = {
4501
4919
  native: { name: "native", check: checkNativePack },
4502
- supabase: { name: "supabase", check: checkSupabasePack }
4920
+ supabase: { name: "supabase", check: checkSupabasePack },
4921
+ packages: { name: "packages", check: checkPackagesPack }
4503
4922
  };
4504
4923
  return [
4505
4924
  { name: "layout", check: checkProjectLayout },
@@ -4601,6 +5020,7 @@ var init_doctor = __esm({
4601
5020
  init_rules();
4602
5021
  init_native();
4603
5022
  init_scan();
5023
+ init_packages();
4604
5024
  init_supabase();
4605
5025
  init_versions();
4606
5026
  init_installs();
@@ -4643,20 +5063,20 @@ function readObject(file, key2) {
4643
5063
  }
4644
5064
  }
4645
5065
  function settings(root, options) {
4646
- const fromPackage = readObject(path32.join(root, "package.json"), "genesisFeatures");
4647
- const fromConfig = readObject(path32.join(root, "genesis.config.json"), "features");
5066
+ const fromPackage = readObject(path23.join(root, "package.json"), "genesisFeatures");
5067
+ const fromConfig = readObject(path23.join(root, "genesis.config.json"), "features");
4648
5068
  const given = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== void 0));
4649
5069
  return { ...fromPackage, ...fromConfig, ...given };
4650
5070
  }
4651
5071
  async function loadRegistry(input) {
4652
- const root = path32.resolve(input.dir);
5072
+ const root = path23.resolve(input.dir);
4653
5073
  const options = settings(root, input);
4654
- const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path32.join(root, p)));
4655
- if (!registry || !existsSync(path32.join(root, registry))) {
5074
+ const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path23.join(root, p)));
5075
+ if (!registry || !existsSync(path23.join(root, registry))) {
4656
5076
  throw new Error(`No feature registry found. Looked for ${options.registry ?? DEFAULT_REGISTRIES.join(" and ")}; pass --registry.`);
4657
5077
  }
4658
- const jiti = createJiti(path32.join(root, "package.json"), { moduleCache: false });
4659
- const load = async (file) => await jiti.import(path32.join(root, file));
5078
+ const jiti = createJiti(path23.join(root, "package.json"), { moduleCache: false });
5079
+ const load = async (file) => await jiti.import(path23.join(root, file));
4660
5080
  const mod = await load(registry);
4661
5081
  const features2 = mod.features ?? mod.default;
4662
5082
  if (!isObject3(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
@@ -4668,7 +5088,7 @@ async function loadRegistry(input) {
4668
5088
  const project = {
4669
5089
  ...rest,
4670
5090
  root,
4671
- source: options.source ?? registry.split(path32.sep).join("/"),
5091
+ source: options.source ?? registry.split(path23.sep).join("/"),
4672
5092
  features: features2,
4673
5093
  flags
4674
5094
  };
@@ -4778,8 +5198,8 @@ function routeTags(source) {
4778
5198
  }
4779
5199
  function wireStudioRoute(source, route, pageImportPath) {
4780
5200
  const tags = routeTags(source);
4781
- const relative6 = route.replace(/^\//, "");
4782
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative6.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
5201
+ const relative8 = route.replace(/^\//, "");
5202
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative8.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
4783
5203
  if (existing) {
4784
5204
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
4785
5205
  }
@@ -4787,17 +5207,17 @@ function wireStudioRoute(source, route, pageImportPath) {
4787
5207
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
4788
5208
  if (roots.length !== 1) {
4789
5209
  return {
4790
- 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="${relative6}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
5210
+ 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="${relative8}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
4791
5211
  };
4792
5212
  }
4793
5213
  const layout = roots[0];
4794
5214
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
4795
- if (base && !relative6.startsWith(`${base}/`)) {
5215
+ if (base && !relative8.startsWith(`${base}/`)) {
4796
5216
  return {
4797
5217
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
4798
5218
  };
4799
5219
  }
4800
- const childPath = base ? relative6.slice(base.length + 1) : relative6;
5220
+ const childPath = base ? relative8.slice(base.length + 1) : relative8;
4801
5221
  const guard = GUARD.exec(source)?.[1];
4802
5222
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
4803
5223
  const before = source.slice(0, layout.close);
@@ -5175,7 +5595,7 @@ function copyOwned(root, lock, write, dryRun = false) {
5175
5595
  }
5176
5596
  return "kept";
5177
5597
  }
5178
- function ownedKeyProblem(key2, source) {
5598
+ function ownedKeyProblem(key2, source, localNames = /* @__PURE__ */ new Set()) {
5179
5599
  let parsed;
5180
5600
  try {
5181
5601
  parsed = parseSource(source);
@@ -5183,7 +5603,7 @@ function ownedKeyProblem(key2, source) {
5183
5603
  return err instanceof Error ? err.message : String(err);
5184
5604
  }
5185
5605
  const { package: pkg, path: rel } = parsed;
5186
- if (!GENESIS_PACKAGE.test(pkg)) return `${key2}'s source ${pkg} isn't a Genesis package`;
5606
+ if (!GENESIS_PACKAGE.test(pkg) && !localNames.has(pkg)) return `${key2}'s source ${pkg} isn't a Genesis or local package`;
5187
5607
  if (!safeRelative(rel) || !safeRelative(key2)) return `${key2} or its source isn't a plain path`;
5188
5608
  if (key2.startsWith("supabase/migrations/")) return `${key2} is a migration; migrations are never refreshed`;
5189
5609
  const base = rel.split("/").pop();
@@ -5197,9 +5617,9 @@ function ownedKeyProblem(key2, source) {
5197
5617
  return `${key2} doesn't match its source ${source}`;
5198
5618
  }
5199
5619
  function mergeThreeWay(mine, base, theirs) {
5200
- const dir = mkdtempSync(path32.join(tmpdir(), "genesis-merge-"));
5620
+ const dir = mkdtempSync(path23.join(tmpdir(), "genesis-merge-"));
5201
5621
  try {
5202
- const [m, b, t] = ["mine", "base", "theirs"].map((n) => path32.join(dir, n));
5622
+ const [m, b, t] = ["mine", "base", "theirs"].map((n) => path23.join(dir, n));
5203
5623
  writeFileSync(m, mine);
5204
5624
  writeFileSync(b, base);
5205
5625
  writeFileSync(t, theirs);
@@ -5218,7 +5638,7 @@ function mergeThreeWay(mine, base, theirs) {
5218
5638
  function refreshOwned(root, lock, input, options = {}) {
5219
5639
  const entry = lock.files[input.path];
5220
5640
  if (!entry) throw new Error(`${input.path} isn't in genesis.lock.json`);
5221
- const problem = ownedKeyProblem(input.path, entry.source);
5641
+ const problem = ownedKeyProblem(input.path, entry.source, localPackageNames(root));
5222
5642
  if (problem) return { path: input.path, outcome: "refused", detail: `genesis.lock.json: ${problem}; left alone` };
5223
5643
  const write = (rel, text) => {
5224
5644
  if (!options.dryRun) replaceApp(root, rel, text);
@@ -5276,6 +5696,7 @@ var init_owned = __esm({
5276
5696
  "src/blocks/owned.ts"() {
5277
5697
  init_files();
5278
5698
  init_lock();
5699
+ init_local();
5279
5700
  init_manifest();
5280
5701
  CLI = "@marktiderman/genesis-cli";
5281
5702
  }
@@ -5368,12 +5789,12 @@ var init_registry_edit = __esm({
5368
5789
  });
5369
5790
  function routerRoot2(root) {
5370
5791
  try {
5371
- const config = JSON.parse(readFileSync(path32.join(root, "genesis.config.json"), "utf8"));
5792
+ const config = JSON.parse(readFileSync(path23.join(root, "genesis.config.json"), "utf8"));
5372
5793
  const configured = config.doctor?.native?.routerRoot;
5373
- if (configured && existsSync(path32.join(root, configured, "_layout.tsx"))) return configured.replace(/\/+$/, "");
5794
+ if (configured && existsSync(path23.join(root, configured, "_layout.tsx"))) return configured.replace(/\/+$/, "");
5374
5795
  } catch {
5375
5796
  }
5376
- for (const dir of ["src/app", "app"]) if (existsSync(path32.join(root, dir, "_layout.tsx"))) return dir;
5797
+ for (const dir of ["src/app", "app"]) if (existsSync(path23.join(root, dir, "_layout.tsx"))) return dir;
5377
5798
  return null;
5378
5799
  }
5379
5800
  function routeOf(file) {
@@ -5434,7 +5855,7 @@ __export(add_exports, {
5434
5855
  });
5435
5856
  function appDependencies(root) {
5436
5857
  try {
5437
- const pkg = JSON.parse(readFileSync(path32.join(root, "package.json"), "utf8"));
5858
+ const pkg = JSON.parse(readFileSync(path23.join(root, "package.json"), "utf8"));
5438
5859
  return { ...pkg["dependencies"], ...pkg["devDependencies"], ...pkg["optionalDependencies"] };
5439
5860
  } catch {
5440
5861
  return {};
@@ -5443,14 +5864,14 @@ function appDependencies(root) {
5443
5864
  function registryFile(root) {
5444
5865
  const read = (file, key2) => {
5445
5866
  try {
5446
- const v = JSON.parse(readFileSync(path32.join(root, file), "utf8"))[key2]?.registry;
5867
+ const v = JSON.parse(readFileSync(path23.join(root, file), "utf8"))[key2]?.registry;
5447
5868
  return typeof v === "string" ? v : void 0;
5448
5869
  } catch {
5449
5870
  return void 0;
5450
5871
  }
5451
5872
  };
5452
5873
  const named = read("genesis.config.json", "features") ?? read("package.json", "genesisFeatures");
5453
- for (const candidate of named ? [named] : ["src/features.ts", "features.ts"]) if (existsSync(path32.join(root, candidate))) return candidate;
5874
+ for (const candidate of named ? [named] : ["src/features.ts", "features.ts"]) if (existsSync(path23.join(root, candidate))) return candidate;
5454
5875
  return null;
5455
5876
  }
5456
5877
  async function registryIds(root, file) {
@@ -5527,7 +5948,7 @@ verify_jwt = false
5527
5948
  return { content: `${config.replace(/\s*$/, "\n")}${add}`, names };
5528
5949
  }
5529
5950
  async function runAdd(options) {
5530
- const root = path32.resolve(options.root);
5951
+ const root = path23.resolve(options.root);
5531
5952
  const log = options.log ?? SILENT;
5532
5953
  const now = options.now ?? /* @__PURE__ */ new Date();
5533
5954
  const warnings = [];
@@ -5537,8 +5958,9 @@ async function runAdd(options) {
5537
5958
  const deps = appDependencies(root);
5538
5959
  const pm = detectPackageManager(root);
5539
5960
  const specs = [];
5961
+ const local = localPackageNames(root);
5540
5962
  for (const name of found.manifest.packages) {
5541
- if (deps[name]) continue;
5963
+ if (deps[name] || local.has(name)) continue;
5542
5964
  const pin = pinnedVersion(root, name);
5543
5965
  specs.push(pin ? `${name}@${pin.version}` : name);
5544
5966
  }
@@ -5574,7 +5996,7 @@ async function runAdd(options) {
5574
5996
  if (registry) registryEdit2 = addFeatureEntry(readApp(root, registry) ?? "", snippet2);
5575
5997
  }
5576
5998
  const print = (mark, p, note = "") => log.info(` ${mark} ${p}${note ? ` ${note}` : ""}`);
5577
- log.info(`${manifest2.id}: from ${manifest2.package}${manifest2.version ? ` ${manifest2.version}` : ""} (${from === "installed" ? "installed" : "not installed yet: files are read after the install"})`);
5999
+ 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"})`);
5578
6000
  if (command) log.info(` install: ${shellLine(command)}${install ? "" : " (skipped: --no-install)"}`);
5579
6001
  log.info(formatMigrationRows(migrations2.rows).replace(/^/gm, " "));
5580
6002
  for (const c of migrations2.creates) if (c.kind === "test") print("+", c.path, "(pgTAP test)");
@@ -5656,7 +6078,7 @@ ${snippet}`);
5656
6078
  ${snippet}`);
5657
6079
  } else edited.push(registry);
5658
6080
  }
5659
- if (found.from === "installed") lock.blocks[manifest.id] = { package: manifest.package, ...manifest.version ? { version: manifest.version } : {} };
6081
+ if (found.from === "installed" || found.from === "local") lock.blocks[manifest.id] = { package: manifest.package, ...manifest.version ? { version: manifest.version } : {} };
5660
6082
  else steps.unshift(`Install ${manifest.packages.join(" and ")}, then run genesis add ${manifest.id} again to copy its files.`);
5661
6083
  const lockBefore = readApp(root, LOCK_FILE);
5662
6084
  writeLock(root, lock);
@@ -5681,6 +6103,7 @@ function recordOwned(lock, appRel, source, content, root, pkg) {
5681
6103
  var SILENT;
5682
6104
  var init_add = __esm({
5683
6105
  "src/blocks/add.ts"() {
6106
+ init_local();
5684
6107
  init_agents();
5685
6108
  init_discover();
5686
6109
  init_files();
@@ -5702,11 +6125,12 @@ __export(migrate_exports, {
5702
6125
  runMigrate: () => runMigrate
5703
6126
  });
5704
6127
  async function runMigrate(options) {
5705
- const root = path32.resolve(options.root);
6128
+ const root = path23.resolve(options.root);
5706
6129
  const lock = readLock(root);
5707
6130
  const warnings = [];
5708
6131
  const ids = [.../* @__PURE__ */ new Set([...Object.keys(lock.blocks), ...options.blocks ?? []])];
5709
6132
  const sources = [];
6133
+ const local = localPackageNames(root);
5710
6134
  for (const id of ids) {
5711
6135
  const pkg = lock.blocks[id]?.package;
5712
6136
  try {
@@ -5719,8 +6143,8 @@ async function runMigrate(options) {
5719
6143
  for (const copy of readAppMigrations(root)) {
5720
6144
  const t = copy.tracked;
5721
6145
  if (!t || sources.some((s) => s.package === t.package && s.file === t.file)) continue;
5722
- if (!GENESIS_PACKAGE.test(t.package) || !validHeaderFile(t.file)) {
5723
- warnings.push(`${copy.path}: its genesis-migration header names ${t.package} ${t.file}, which isn't a Genesis package's NNNN_name.sql; skipped.`);
6146
+ if (!(GENESIS_PACKAGE.test(t.package) || local.has(t.package)) || !validHeaderFile(t.file)) {
6147
+ warnings.push(`${copy.path}: its genesis-migration header names ${t.package} ${t.file}, which isn't a Genesis or local package's NNNN_name.sql; skipped.`);
5724
6148
  continue;
5725
6149
  }
5726
6150
  const dir = packageDir(root, t.package);
@@ -5744,6 +6168,7 @@ async function runMigrate(options) {
5744
6168
  var init_migrate = __esm({
5745
6169
  "src/blocks/migrate.ts"() {
5746
6170
  init_discover();
6171
+ init_local();
5747
6172
  init_files();
5748
6173
  init_lock();
5749
6174
  init_manifest();
@@ -5862,11 +6287,11 @@ function npmLookup(cwd) {
5862
6287
  if (!EXACT_OR_TAG.test(target)) throw new Error(`--version must be an exact version or a dist-tag, not "${target}"`);
5863
6288
  const version = JSON.parse(npm(["view", `${UMBRELLA}@${target}`, "version", "--json"], cwd) || "null");
5864
6289
  if (typeof version !== "string") throw new Error(`${UMBRELLA}@${target} is not one published version`);
5865
- const tmp = mkdtempSync(path32.join(tmpdir(), "genesis-umbrella-"));
6290
+ const tmp = mkdtempSync(path23.join(tmpdir(), "genesis-umbrella-"));
5866
6291
  try {
5867
6292
  const [packed] = JSON.parse(npm(["pack", `${UMBRELLA}@${version}`, "--pack-destination", tmp, "--json"], cwd));
5868
- execFileSync("tar", ["-xzf", path32.join(tmp, packed.filename), "-C", tmp, "package/dist/versions.json"]);
5869
- const manifest = JSON.parse(readFileSync(path32.join(tmp, "package/dist/versions.json"), "utf8"));
6293
+ execFileSync("tar", ["-xzf", path23.join(tmp, packed.filename), "-C", tmp, "package/dist/versions.json"]);
6294
+ const manifest = JSON.parse(readFileSync(path23.join(tmp, "package/dist/versions.json"), "utf8"));
5870
6295
  if (manifest.version !== version) throw new Error(`${UMBRELLA}@${version} ships a versions.json for ${manifest.version}`);
5871
6296
  return manifest;
5872
6297
  } finally {
@@ -5893,7 +6318,7 @@ function packageJsons(root) {
5893
6318
  if (files.length) return files;
5894
6319
  } catch {
5895
6320
  }
5896
- return existsSync(path32.join(root, "package.json")) ? ["package.json"] : [];
6321
+ return existsSync(path23.join(root, "package.json")) ? ["package.json"] : [];
5897
6322
  }
5898
6323
  function sourceText(root, source, substitutions) {
5899
6324
  const { package: pkg, path: rel } = parseSource(source);
@@ -5912,11 +6337,11 @@ function sourceText(root, source, substitutions) {
5912
6337
  }
5913
6338
  }
5914
6339
  async function runUpgrade(options) {
5915
- const root = path32.resolve(options.root);
6340
+ const root = path23.resolve(options.root);
5916
6341
  const log = options.log ?? (() => {
5917
6342
  });
5918
6343
  const lookup = options.lookup ?? npmLookup(root);
5919
- const release = options.manifest ? JSON.parse(readFileSync(path32.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
6344
+ const release = options.manifest ? JSON.parse(readFileSync(path23.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
5920
6345
  const pinned = { [UMBRELLA]: release.version, ...release.packages };
5921
6346
  const wanted = (name) => pinned[name] ?? lookup.latest(name);
5922
6347
  const prBase = options.pr && !options.dryRun ? checkPullRequest(root, release.version) : void 0;
@@ -5938,7 +6363,7 @@ async function runUpgrade(options) {
5938
6363
  checkSubstitutions(lock.substitutions);
5939
6364
  const bases = /* @__PURE__ */ new Map();
5940
6365
  for (const [file, entry] of Object.entries(lock.files)) {
5941
- if (ownedKeyProblem(file, entry.source)) continue;
6366
+ if (ownedKeyProblem(file, entry.source, localPackageNames(root))) continue;
5942
6367
  const text = sourceText(root, entry.source, lock.substitutions);
5943
6368
  if (text !== null && sha256(text) === entry.sha256) bases.set(file, text);
5944
6369
  }
@@ -5986,7 +6411,7 @@ async function runUpgrade(options) {
5986
6411
  refreshed.push({ path: file, outcome: "deferred", detail: "new package migrations are waiting: run genesis migrate, then genesis upgrade again" });
5987
6412
  continue;
5988
6413
  }
5989
- const problem = ownedKeyProblem(file, entry.source);
6414
+ const problem = ownedKeyProblem(file, entry.source, localPackageNames(root));
5990
6415
  const theirs = problem ? null : sourceText(root, entry.source, lock.substitutions);
5991
6416
  const dir = problem ? null : packageDir(root, parseSource(entry.source).package);
5992
6417
  const version = dir ? packageVersion(dir) : void 0;
@@ -6052,7 +6477,7 @@ function checkSubstitutions(substitutions) {
6052
6477
  if (!substitutions || !Object.keys(substitutions).length) return;
6053
6478
  let allowed;
6054
6479
  try {
6055
- const was = starterIdentity(readFileSync(path32.join(starterDir(), "starter.config.ts"), "utf8"));
6480
+ const was = starterIdentity(readFileSync(path23.join(starterDir(), "starter.config.ts"), "utf8"));
6056
6481
  allowed = [was.name, was.slug, was.scheme, was.bundleId];
6057
6482
  } catch {
6058
6483
  allowed = [];
@@ -6064,15 +6489,15 @@ function checkSubstitutions(substitutions) {
6064
6489
  }
6065
6490
  }
6066
6491
  function checkPullRequest(root, version) {
6067
- const git2 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
6068
- if (git2("status", "--porcelain")) throw new Error("--pr needs a clean working tree (commit or stash your changes first).");
6069
- const base = git2("rev-parse", "--abbrev-ref", "HEAD");
6492
+ const git3 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
6493
+ if (git3("status", "--porcelain")) throw new Error("--pr needs a clean working tree (commit or stash your changes first).");
6494
+ const base = git3("rev-parse", "--abbrev-ref", "HEAD");
6070
6495
  if (base === "HEAD") throw new Error("--pr needs a branch checked out, not a detached HEAD.");
6071
6496
  const branch = `genesis-upgrade/${version}`;
6072
- git2("check-ref-format", "--branch", branch);
6497
+ git3("check-ref-format", "--branch", branch);
6073
6498
  let exists = true;
6074
6499
  try {
6075
- git2("rev-parse", "--verify", "--quiet", `refs/heads/${branch}`);
6500
+ git3("rev-parse", "--verify", "--quiet", `refs/heads/${branch}`);
6076
6501
  } catch {
6077
6502
  exists = false;
6078
6503
  }
@@ -6080,20 +6505,20 @@ function checkPullRequest(root, version) {
6080
6505
  return base;
6081
6506
  }
6082
6507
  function openPullRequest(root, version, report, base) {
6083
- const git2 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
6508
+ const git3 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
6084
6509
  const branch = `genesis-upgrade/${version}`;
6085
- git2("switch", "-c", branch);
6086
- const top = git2("rev-parse", "--show-toplevel");
6510
+ git3("switch", "-c", branch);
6511
+ const top = git3("rev-parse", "--show-toplevel");
6087
6512
  const lockfiles = [];
6088
- for (let dir = path32.resolve(root); ; dir = path32.dirname(dir)) {
6089
- for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path32.join(dir, f))) lockfiles.push(path32.relative(root, path32.join(dir, f)));
6090
- if (lockfiles.length || dir === top || path32.dirname(dir) === dir) break;
6091
- }
6092
- const paths = [...report.files.filter((f) => existsSync(path32.join(root, f))), ...lockfiles];
6093
- git2("add", "--", ...paths);
6094
- git2("commit", "-q", "-m", `chore(deps): upgrade Genesis to ${version}`);
6095
- git2("push", "-u", "origin", branch);
6096
- const body = path32.join(mkdtempSync(path32.join(tmpdir(), "genesis-pr-")), "body.md");
6513
+ for (let dir = path23.resolve(root); ; dir = path23.dirname(dir)) {
6514
+ for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path23.join(dir, f))) lockfiles.push(path23.relative(root, path23.join(dir, f)));
6515
+ if (lockfiles.length || dir === top || path23.dirname(dir) === dir) break;
6516
+ }
6517
+ const paths = [...report.files.filter((f) => existsSync(path23.join(root, f))), ...lockfiles];
6518
+ git3("add", "--", ...paths);
6519
+ git3("commit", "-q", "-m", `chore(deps): upgrade Genesis to ${version}`);
6520
+ git3("push", "-u", "origin", branch);
6521
+ const body = path23.join(mkdtempSync(path23.join(tmpdir(), "genesis-pr-")), "body.md");
6097
6522
  writeFileSync(body, `${report.summary}
6098
6523
 
6099
6524
  Opened by \`genesis upgrade --pr\`.
@@ -6111,6 +6536,7 @@ var init_upgrade = __esm({
6111
6536
  init_lock();
6112
6537
  init_migrations();
6113
6538
  init_owned();
6539
+ init_local();
6114
6540
  init_pm();
6115
6541
  init_templates();
6116
6542
  init_bump_core();
@@ -6216,9 +6642,9 @@ async function runScaffold(opts, fs2) {
6216
6642
  function joinPath(...parts) {
6217
6643
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
6218
6644
  }
6219
- function dirname(path33) {
6220
- const idx = path33.lastIndexOf("/");
6221
- return idx === -1 ? "." : path33.slice(0, idx);
6645
+ function dirname(path35) {
6646
+ const idx = path35.lastIndexOf("/");
6647
+ return idx === -1 ? "." : path35.slice(0, idx);
6222
6648
  }
6223
6649
  function brandPackageJson(consumer, genesisVersion) {
6224
6650
  return JSON.stringify(
@@ -6457,7 +6883,7 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
6457
6883
  const { runInitNative: runInitNative2 } = await Promise.resolve().then(() => (init_init_native(), init_native_exports));
6458
6884
  const result2 = await runInitNative2({
6459
6885
  name: consumer,
6460
- target: path32.resolve(opts.target ?? consumer),
6886
+ target: path23.resolve(opts.target ?? consumer),
6461
6887
  ...opts.displayName ? { displayName: opts.displayName } : {},
6462
6888
  ...opts.bundleId ? { bundleId: opts.bundleId } : {},
6463
6889
  ...opts.scheme ? { scheme: opts.scheme } : {}
@@ -6467,7 +6893,7 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
6467
6893
  console.log(` Genesis packages: ${Object.entries(result2.dependencies).map(([n, v]) => `${n}@${v}`).join(", ")}`);
6468
6894
  console.log("");
6469
6895
  console.log("Next steps:");
6470
- [`cd ${path32.relative(process.cwd(), result2.target) || "."} && pnpm install (or your package manager)`, ...result2.steps].forEach((s, i) => console.log(` ${i + 1}. ${s}`));
6896
+ [`cd ${path23.relative(process.cwd(), result2.target) || "."} && pnpm install (or your package manager)`, ...result2.steps].forEach((s, i) => console.log(` ${i + 1}. ${s}`));
6471
6897
  return;
6472
6898
  }
6473
6899
  opts.target ??= process.cwd();
@@ -6533,7 +6959,7 @@ program.command("introspect").description("Write a checked-in contract (resource
6533
6959
  source = `Postgres (${schemas.join(", ")})`;
6534
6960
  }
6535
6961
  const content = emitContracts2(tables, { source });
6536
- const target = path32.resolve(opts.out);
6962
+ const target = path23.resolve(opts.out);
6537
6963
  if (opts.check) {
6538
6964
  const current = await fs.readFile(target, "utf-8").catch(() => null);
6539
6965
  if (current !== content) {
@@ -6546,16 +6972,16 @@ program.command("introspect").description("Write a checked-in contract (resource
6546
6972
  await fs.writeFile(target, content, "utf-8");
6547
6973
  console.log(`\u2714 Wrote ${opts.out}: ${tables.length} tables.`);
6548
6974
  });
6549
- 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).action(async (opts) => {
6975
+ 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), e.g. origin/main").action(async (opts) => {
6550
6976
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
6551
- const root = path32.resolve(opts.dir);
6977
+ const root = path23.resolve(opts.dir);
6552
6978
  try {
6553
6979
  if (opts.printGenesis) {
6554
6980
  const { config } = doctor.loadConfig(root, opts.config);
6555
6981
  console.log(JSON.stringify(doctor.genesisSummary(doctor.loadGenesis(root, config)), null, 2));
6556
6982
  return;
6557
6983
  }
6558
- const result = await doctor.runDoctor({ root, configPath: opts.config, strict: opts.strict, build: opts.build, quietBuild: opts.json });
6984
+ const result = await doctor.runDoctor({ root, configPath: opts.config, strict: opts.strict, build: opts.build, quietBuild: opts.json, ...opts.base ? { base: opts.base } : {} });
6559
6985
  console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result));
6560
6986
  process.exitCode = result.ok ? 0 : 1;
6561
6987
  } catch (err) {
@@ -6613,24 +7039,24 @@ featureOptions(
6613
7039
  var studio = program.command("studio").description("The Genesis Data Studio");
6614
7040
  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) => {
6615
7041
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
6616
- const root = path32.resolve(opts.dir);
6617
- const packageJson = JSON.parse(await fs.readFile(path32.join(root, "package.json"), "utf-8").catch(() => "{}"));
6618
- const existsSync26 = (await import('fs')).existsSync;
7042
+ const root = path23.resolve(opts.dir);
7043
+ const packageJson = JSON.parse(await fs.readFile(path23.join(root, "package.json"), "utf-8").catch(() => "{}"));
7044
+ const existsSync28 = (await import('fs')).existsSync;
6619
7045
  const readSync = (await import('fs')).readFileSync;
6620
- const readdirSync10 = (await import('fs')).readdirSync;
7046
+ const readdirSync12 = (await import('fs')).readdirSync;
6621
7047
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
6622
7048
  throw new Error("--host must be next, tanstack-start or supabase-function.");
6623
7049
  }
6624
7050
  const plan = planStudioInit2(
6625
7051
  {
6626
7052
  packageJson,
6627
- exists: (p) => existsSync26(path32.join(root, p)),
6628
- read: (p) => existsSync26(path32.join(root, p)) ? readSync(path32.join(root, p), "utf-8") : null,
7053
+ exists: (p) => existsSync28(path23.join(root, p)),
7054
+ read: (p) => existsSync28(path23.join(root, p)) ? readSync(path23.join(root, p), "utf-8") : null,
6629
7055
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
6630
7056
  listDeep: (p) => {
6631
7057
  const out = [];
6632
7058
  const walk2 = (rel) => {
6633
- for (const entry of readdirSync10(path32.join(root, rel), { withFileTypes: true })) {
7059
+ for (const entry of readdirSync12(path23.join(root, rel), { withFileTypes: true })) {
6634
7060
  const child = `${rel}/${entry.name}`;
6635
7061
  if (entry.isDirectory()) walk2(child);
6636
7062
  else out.push(child);
@@ -6644,7 +7070,7 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
6644
7070
  },
6645
7071
  list: (p) => {
6646
7072
  try {
6647
- return readdirSync10(path32.join(root, p));
7073
+ return readdirSync12(path23.join(root, p));
6648
7074
  } catch {
6649
7075
  return [];
6650
7076
  }
@@ -6653,8 +7079,8 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
6653
7079
  { host: opts.host, route: opts.route, loginRole: opts.loginRole }
6654
7080
  );
6655
7081
  for (const file of plan.files) {
6656
- const target = path32.join(root, file.path);
6657
- await fs.mkdir(path32.dirname(target), { recursive: true });
7082
+ const target = path23.join(root, file.path);
7083
+ await fs.mkdir(path23.dirname(target), { recursive: true });
6658
7084
  if (file.edit) {
6659
7085
  await fs.writeFile(target, file.content, "utf-8");
6660
7086
  console.log(`~ ${file.path} (${file.edit})`);
@@ -6665,14 +7091,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
6665
7091
  console.log(`+ ${file.path} (appended)`);
6666
7092
  continue;
6667
7093
  }
6668
- if (existsSync26(target) && !opts.force) {
7094
+ if (existsSync28(target) && !opts.force) {
6669
7095
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
6670
7096
  continue;
6671
7097
  }
6672
7098
  await fs.writeFile(target, file.content, "utf-8");
6673
7099
  console.log(`+ ${file.path}`);
6674
7100
  }
6675
- const pm = existsSync26(path32.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync26(path32.join(root, "yarn.lock")) ? "yarn add" : existsSync26(path32.join(root, "bun.lock")) || existsSync26(path32.join(root, "bun.lockb")) ? "bun add" : "npm install";
7101
+ const pm = existsSync28(path23.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync28(path23.join(root, "yarn.lock")) ? "yarn add" : existsSync28(path23.join(root, "bun.lock")) || existsSync28(path23.join(root, "bun.lockb")) ? "bun add" : "npm install";
6676
7102
  console.log("");
6677
7103
  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:`);
6678
7104
  console.log(` 1. ${pm} ${plan.install.join(" ")}`);
@@ -6690,7 +7116,7 @@ async function confirm(question) {
6690
7116
  }
6691
7117
  var logger = { info: (m) => console.log(m), warn: (m) => console.warn(`! ${m}`) };
6692
7118
  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) => {
6693
- const root = path32.resolve(opts.dir);
7119
+ const root = path23.resolve(opts.dir);
6694
7120
  if (opts.list || !block) {
6695
7121
  const { allBlocks: allBlocks2 } = await Promise.resolve().then(() => (init_discover(), discover_exports));
6696
7122
  const { readLock: readLock2 } = await Promise.resolve().then(() => (init_lock(), lock_exports));
@@ -6719,7 +7145,7 @@ program.command("add").description("Add a block (a feature an app adds whole) fr
6719
7145
  program.command("migrate").description("Copy new package migrations of the app's blocks in as new timestamped files; report edited or changed ones (never rewritten)").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--block <id...>", "Also check these blocks (beyond genesis.lock.json's)").option("--dry-run", "Report only", false).option("--forward", "Write a forward migration stub for each edited or changed migration", false).action(async (opts) => {
6720
7146
  const { runMigrate: runMigrate2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
6721
7147
  const { formatMigrationRows: formatMigrationRows2 } = await Promise.resolve().then(() => (init_migrations(), migrations_exports));
6722
- const report = await runMigrate2({ root: path32.resolve(opts.dir), ...opts.block ? { blocks: opts.block } : {}, dryRun: opts.dryRun, forward: opts.forward });
7148
+ const report = await runMigrate2({ root: path23.resolve(opts.dir), ...opts.block ? { blocks: opts.block } : {}, dryRun: opts.dryRun, forward: opts.forward });
6723
7149
  for (const w of report.warnings) logger.warn(w);
6724
7150
  console.log(formatMigrationRows2(report.plan.rows));
6725
7151
  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"})`);
@@ -6734,7 +7160,7 @@ program.command("migrate").description("Copy new package migrations of the app's
6734
7160
  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).action(async (opts) => {
6735
7161
  const { runUpgrade: runUpgrade2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
6736
7162
  const report = await runUpgrade2({
6737
- root: path32.resolve(opts.dir),
7163
+ root: path23.resolve(opts.dir),
6738
7164
  version: opts.version,
6739
7165
  ...opts.manifest ? { manifest: opts.manifest } : {},
6740
7166
  dryRun: opts.dryRun,
@@ -6798,7 +7224,7 @@ function redactUrl(location) {
6798
7224
  const url = new URL(location);
6799
7225
  return `${url.origin}${url.pathname}`;
6800
7226
  } catch {
6801
- return path32.basename(location);
7227
+ return path23.basename(location);
6802
7228
  }
6803
7229
  }
6804
7230
  //# sourceMappingURL=cli.js.map