@marktiderman/genesis-cli 1.11.2 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
- import { createRequire } from 'module';
1
+ import { createRequire, builtinModules } from 'module';
2
2
  import { studioSetupSql } from '@marktiderman/genesis-studio-server';
3
3
  import * as path14 from 'path';
4
4
  import { spawnSync } from 'child_process';
5
- import { existsSync, readFileSync, statSync, readdirSync, realpathSync } from 'fs';
5
+ import { existsSync, readFileSync, statSync, readdirSync, realpathSync, lstatSync } from 'fs';
6
+ import 'crypto';
7
+ import { FEATURE_PLATFORMS, defineBlock, BlockError } from '@marktiderman/genesis-features/blocks';
6
8
  import { pathToFileURL } from 'url';
7
9
 
8
10
  // src/scaffolder.ts
@@ -101,9 +103,9 @@ async function runScaffold(opts, fs) {
101
103
  function joinPath(...parts) {
102
104
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
103
105
  }
104
- function dirname(path17) {
105
- const idx = path17.lastIndexOf("/");
106
- return idx === -1 ? "." : path17.slice(0, idx);
106
+ function dirname(path20) {
107
+ const idx = path20.lastIndexOf("/");
108
+ return idx === -1 ? "." : path20.slice(0, idx);
107
109
  }
108
110
  function brandPackageJson(consumer, genesisVersion) {
109
111
  return JSON.stringify(
@@ -297,7 +299,7 @@ This consumer was bootstrapped with \`@marktiderman/genesis-cli init ${consumer}
297
299
 
298
300
  ## Workflow
299
301
 
300
- - **Reuse before extend, extend before create.** Before building anything,
302
+ - **Reuse, then extend, then invent** (the Genesis way). Before building anything,
301
303
  run \`npx @marktiderman/genesis-cli features find <term>\` and read
302
304
  https://github.com/marktiderman/genesis/blob/main/docs/FRAMEWORK.md
303
305
  - **Brand changes live in \`packages/${consumer}-brand\`.** Don't fork Genesis
@@ -627,8 +629,8 @@ function routeTags(source) {
627
629
  var GUARD = /<((?:[A-Z]\w*)?(?:Admin|Staff)\w*(?:Guard|Route|Only)|RequireAdmin|RequireStaff)>/;
628
630
  function wireStudioRoute(source, route, pageImportPath) {
629
631
  const tags = routeTags(source);
630
- const relative3 = route.replace(/^\//, "");
631
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
632
+ const relative6 = route.replace(/^\//, "");
633
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative6.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
632
634
  if (existing) {
633
635
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
634
636
  }
@@ -636,17 +638,17 @@ function wireStudioRoute(source, route, pageImportPath) {
636
638
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
637
639
  if (roots.length !== 1) {
638
640
  return {
639
- 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="${relative3}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
641
+ 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.`
640
642
  };
641
643
  }
642
644
  const layout = roots[0];
643
645
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
644
- if (base && !relative3.startsWith(`${base}/`)) {
646
+ if (base && !relative6.startsWith(`${base}/`)) {
645
647
  return {
646
648
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
647
649
  };
648
650
  }
649
- const childPath = base ? relative3.slice(base.length + 1) : relative3;
651
+ const childPath = base ? relative6.slice(base.length + 1) : relative6;
650
652
  const guard = GUARD.exec(source)?.[1];
651
653
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
652
654
  const before = source.slice(0, layout.close);
@@ -1066,16 +1068,18 @@ var KNOWN = /* @__PURE__ */ new Set([
1066
1068
  "packs",
1067
1069
  "native",
1068
1070
  "supabase",
1071
+ "packages",
1069
1072
  "routesDir",
1070
1073
  "$schema",
1071
1074
  "$comment"
1072
1075
  ]);
1073
1076
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
1074
1077
  var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
1075
- var PACKS = /* @__PURE__ */ new Set(["native", "supabase"]);
1078
+ var PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
1076
1079
  var PACK_KEYS = {
1077
1080
  native: { routerRoot: "path" },
1078
- supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" }
1081
+ supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
1082
+ packages: { base: "string" }
1079
1083
  };
1080
1084
  function appPath(v, where, fail) {
1081
1085
  if (typeof v !== "string" || !v.trim()) return fail(`${where} must be a non-empty path`);
@@ -1314,7 +1318,7 @@ function globToRegExp(glob) {
1314
1318
  }
1315
1319
  function globMatcher(globs) {
1316
1320
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1317
- return (path17) => res.some((re) => re.test(path17));
1321
+ return (path20) => res.some((re) => re.test(path20));
1318
1322
  }
1319
1323
  var DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
1320
1324
  var NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
@@ -1540,6 +1544,274 @@ function loadPalette(root) {
1540
1544
  }
1541
1545
  return [...names].sort();
1542
1546
  }
1547
+ var GENESIS_PACKAGE = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
1548
+ var BLOCK_ID = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
1549
+ var MIGRATION_FILE = /^(\d{4})_([a-z0-9_]+)\.sql$/;
1550
+ var FUNCTION_NAME = /^[a-z0-9][a-z0-9_-]*$/;
1551
+ var ROUTE = /^\/(?:[A-Za-z0-9_\-[\]().]+\/?)*$/;
1552
+ var INSTALL_SPEC = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9.^~<>=|* -]+)?$/;
1553
+ var SECRET = /^[A-Z][A-Z0-9_]*$/;
1554
+ var ManifestError = class extends Error {
1555
+ constructor(problems) {
1556
+ super(`Invalid block manifest:
1557
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1558
+ this.problems = problems;
1559
+ this.name = "ManifestError";
1560
+ }
1561
+ problems;
1562
+ };
1563
+ function safeRelative(value) {
1564
+ if (typeof value !== "string" || !value || value.length > 300) return null;
1565
+ if (/[\0\\:]/.test(value) || value.startsWith("/") || value.startsWith("~")) return null;
1566
+ const segments = value.split("/");
1567
+ if (segments.some((s) => s === "" || s === "." || s === ".." || s.startsWith("-"))) return null;
1568
+ return value;
1569
+ }
1570
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1571
+ var strings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
1572
+ function parseManifest(home, id, raw, version, options = {}) {
1573
+ const problems = [];
1574
+ const at = `${home} genesis.blocks.${id}`;
1575
+ if (!GENESIS_PACKAGE.test(home) && !options.local) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) and the app's local packages declare blocks`);
1576
+ if (!BLOCK_ID.test(id)) problems.push(`${at}: "${id}" is not a feature id`);
1577
+ if (!isObject2(raw)) throw new ManifestError([...problems, `${at}: must be an object`]);
1578
+ const pkgOf = (value, where) => {
1579
+ if (value === void 0) return home;
1580
+ if (typeof value !== "string" || !(GENESIS_PACKAGE.test(value) || options.local && value === home)) {
1581
+ problems.push(`${where}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
1582
+ return home;
1583
+ }
1584
+ return value;
1585
+ };
1586
+ const pathOf = (value, where) => {
1587
+ const safe = safeRelative(value);
1588
+ if (!safe) problems.push(`${where}: ${JSON.stringify(value)} is not a plain path inside the package`);
1589
+ return safe ?? "";
1590
+ };
1591
+ const list = (key2) => {
1592
+ const v = raw[key2];
1593
+ if (v === void 0) return [];
1594
+ if (!Array.isArray(v)) {
1595
+ problems.push(`${at}.${key2}: must be a list`);
1596
+ return [];
1597
+ }
1598
+ return v;
1599
+ };
1600
+ const requires = list("requires").filter((r) => {
1601
+ const ok = typeof r === "string" && BLOCK_ID.test(r);
1602
+ if (!ok) problems.push(`${at}.requires: ${JSON.stringify(r)} is not a feature id`);
1603
+ return ok;
1604
+ });
1605
+ let platforms;
1606
+ if (raw["platforms"] !== void 0) {
1607
+ platforms = list("platforms").filter((p) => {
1608
+ const ok = typeof p === "string" && FEATURE_PLATFORMS.includes(p);
1609
+ if (!ok) problems.push(`${at}.platforms: ${JSON.stringify(p)} is not one of ${FEATURE_PLATFORMS.join(", ")}`);
1610
+ return ok;
1611
+ });
1612
+ }
1613
+ const packages = list("packages").map((p, i) => pkgOf(p, `${at}.packages[${i}]`));
1614
+ const install = list("install").filter((s) => {
1615
+ const ok = typeof s === "string" && INSTALL_SPEC.test(s) && !s.startsWith("-");
1616
+ if (!ok) problems.push(`${at}.install: ${JSON.stringify(s)} is not a package name with an optional range`);
1617
+ return ok;
1618
+ });
1619
+ const migrations = list("migrations").map((m, i) => {
1620
+ const where = `${at}.migrations[${i}]`;
1621
+ if (!isObject2(m)) {
1622
+ problems.push(`${where}: must be an object`);
1623
+ return { package: home, file: "" };
1624
+ }
1625
+ const file = pathOf(m["file"], `${where}.file`);
1626
+ if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
1627
+ const out = { package: pkgOf(m["package"], where), file };
1628
+ if (m["test"] !== void 0) {
1629
+ out.test = pathOf(m["test"], `${where}.test`);
1630
+ if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
1631
+ }
1632
+ return out;
1633
+ });
1634
+ const functions = list("functions").map((f, i) => {
1635
+ const where = `${at}.functions[${i}]`;
1636
+ if (!isObject2(f)) {
1637
+ problems.push(`${where}: must be an object`);
1638
+ return { package: home, dir: "" };
1639
+ }
1640
+ const dir = pathOf(f["dir"], `${where}.dir`);
1641
+ if (dir && !FUNCTION_NAME.test(dir.split("/").pop())) problems.push(`${where}.dir: the folder's name "${dir.split("/").pop()}" is not a function name`);
1642
+ const out = { package: pkgOf(f["package"], where), dir };
1643
+ if (f["verifyJwt"] !== void 0) {
1644
+ if (typeof f["verifyJwt"] !== "boolean") problems.push(`${where}.verifyJwt: must be true or false`);
1645
+ else out.verifyJwt = f["verifyJwt"];
1646
+ }
1647
+ if (f["secrets"] !== void 0) {
1648
+ if (!strings(f["secrets"]) || f["secrets"].some((s) => !SECRET.test(s))) problems.push(`${where}.secrets: must be a list of UPPER_CASE names`);
1649
+ else out.secrets = f["secrets"];
1650
+ }
1651
+ return out;
1652
+ });
1653
+ const routes = list("routes").map((r, i) => {
1654
+ const where = `${at}.routes[${i}]`;
1655
+ if (!isObject2(r) || typeof r["path"] !== "string" || !ROUTE.test(r["path"]) || r["path"].split("/").includes("..")) {
1656
+ problems.push(`${where}: needs a path like /settings/notifications`);
1657
+ return { path: "/" };
1658
+ }
1659
+ const out = { path: r["path"] };
1660
+ if (typeof r["description"] === "string") out.description = r["description"];
1661
+ if (typeof r["signedIn"] === "boolean") out.signedIn = r["signedIn"];
1662
+ return out;
1663
+ });
1664
+ const skills = list("skills").map((s, i) => {
1665
+ if (isObject2(s)) return { package: pkgOf(s["package"], `${at}.skills[${i}]`), path: pathOf(s["path"], `${at}.skills[${i}].path`) };
1666
+ return { package: home, path: pathOf(s, `${at}.skills[${i}]`) };
1667
+ });
1668
+ for (const s of skills) if (s.path && !s.path.endsWith("SKILL.md")) problems.push(`${at}.skills: "${s.path}" must point at a SKILL.md`);
1669
+ let agents;
1670
+ if (raw["agents"] !== void 0) {
1671
+ const a = raw["agents"];
1672
+ agents = isObject2(a) ? { package: pkgOf(a["package"], `${at}.agents`), path: pathOf(a["path"], `${at}.agents.path`) } : { package: home, path: pathOf(a, `${at}.agents`) };
1673
+ if (agents.path && !agents.path.endsWith(".md")) problems.push(`${at}.agents: "${agents.path}" must be a Markdown file`);
1674
+ }
1675
+ let feature;
1676
+ if (raw["feature"] !== void 0) {
1677
+ const f = raw["feature"];
1678
+ if (!isObject2(f) || typeof f["name"] !== "string" || typeof f["summary"] !== "string") problems.push(`${at}.feature: needs a name and a summary`);
1679
+ else {
1680
+ feature = { name: f["name"], summary: f["summary"] };
1681
+ if (typeof f["layer"] === "string") feature.layer = f["layer"];
1682
+ if (strings(f["keywords"])) feature.keywords = f["keywords"];
1683
+ if (strings(f["audience"])) feature.audience = f["audience"];
1684
+ }
1685
+ }
1686
+ const steps = list("steps").filter((s) => {
1687
+ if (typeof s !== "string") problems.push(`${at}.steps: every step is a sentence`);
1688
+ return typeof s === "string";
1689
+ });
1690
+ const privacy = isObject2(raw["privacy"]) ? raw["privacy"] : void 0;
1691
+ try {
1692
+ const def = { id, requires, contributes: { routes, migrations: migrations.filter((m) => m.file), skills: skills.map((s) => s.path).filter(Boolean), ...privacy ? { privacy } : {} } };
1693
+ if (platforms) def.platforms = platforms;
1694
+ defineBlock(def);
1695
+ } catch (err) {
1696
+ if (err instanceof BlockError) problems.push(...err.problems.map((p) => `${at}: ${p}`));
1697
+ else throw err;
1698
+ }
1699
+ if (problems.length) throw new ManifestError(problems);
1700
+ return {
1701
+ id,
1702
+ package: home,
1703
+ ...version ? { version } : {},
1704
+ requires,
1705
+ ...platforms ? { platforms } : {},
1706
+ packages: packages.length ? [...new Set(packages)] : [home],
1707
+ install,
1708
+ migrations,
1709
+ functions,
1710
+ routes,
1711
+ skills,
1712
+ ...agents ? { agents } : {},
1713
+ ...feature ? { feature } : {},
1714
+ steps,
1715
+ ...privacy ? { privacy } : {}
1716
+ };
1717
+ }
1718
+ function rawBlocksOf(packageJson) {
1719
+ if (!isObject2(packageJson) || !isObject2(packageJson["genesis"])) return {};
1720
+ const blocks = packageJson["genesis"]["blocks"];
1721
+ return isObject2(blocks) ? blocks : {};
1722
+ }
1723
+
1724
+ // src/blocks/files.ts
1725
+ function inside(parent, child) {
1726
+ const rel = path14.relative(parent, child);
1727
+ return rel === "" || !rel.startsWith("..") && !path14.isAbsolute(rel);
1728
+ }
1729
+
1730
+ // src/blocks/local.ts
1731
+ var LOCAL_PACKAGES_KEY = "localPackages";
1732
+ var LocalPackagesError = class extends Error {
1733
+ name = "LocalPackagesError";
1734
+ };
1735
+ function validateLocalPackages(raw, source = "genesis.config.json") {
1736
+ if (!Array.isArray(raw)) throw new LocalPackagesError(`${source}: ${LOCAL_PACKAGES_KEY} must be a list of folders`);
1737
+ return raw.map((entry, i) => {
1738
+ const where = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
1739
+ if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where} must be a non-empty folder`);
1740
+ if (path14.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where} must be relative to the app ("${entry}")`);
1741
+ const norm = path14.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
1742
+ if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where} must name a package folder, not the app or a parent of it ("${entry}")`);
1743
+ const parts = norm.split("/");
1744
+ if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
1745
+ throw new LocalPackagesError(`${where}: only a final "/*" is supported ("${entry}")`);
1746
+ }
1747
+ if (parts.includes("node_modules")) throw new LocalPackagesError(`${where} can't point into node_modules ("${entry}")`);
1748
+ return norm;
1749
+ });
1750
+ }
1751
+ function localPackageGlobs(root) {
1752
+ const file = path14.join(root, "genesis.config.json");
1753
+ if (!existsSync(file)) return [];
1754
+ let raw;
1755
+ try {
1756
+ raw = JSON.parse(readFileSync(file, "utf8"));
1757
+ } catch (err) {
1758
+ throw new LocalPackagesError(`${file} is not valid JSON: ${err.message}`);
1759
+ }
1760
+ const value = raw && typeof raw === "object" ? raw[LOCAL_PACKAGES_KEY] : void 0;
1761
+ return value === void 0 ? [] : validateLocalPackages(value, file);
1762
+ }
1763
+ var cache = /* @__PURE__ */ new Map();
1764
+ function repositoryRoot(appRoot) {
1765
+ for (let dir = appRoot; ; ) {
1766
+ if (existsSync(path14.join(dir, ".git"))) return dir;
1767
+ const parent = path14.dirname(dir);
1768
+ if (parent === dir) return appRoot;
1769
+ dir = parent;
1770
+ }
1771
+ }
1772
+ function localPackages(root) {
1773
+ const appRoot = path14.resolve(root);
1774
+ const globs = localPackageGlobs(appRoot);
1775
+ const key2 = `${appRoot}
1776
+ ${globs.join("\n")}`;
1777
+ const hit = cache.get(key2);
1778
+ if (hit) return hit;
1779
+ const dirs = /* @__PURE__ */ new Set();
1780
+ for (const glob of globs) {
1781
+ if (glob.endsWith("/*") || glob === "*") {
1782
+ const parent = path14.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
1783
+ if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
1784
+ for (const entry of readdirSync(parent).sort()) {
1785
+ if (entry.startsWith(".") || entry === "node_modules") continue;
1786
+ dirs.add(path14.join(parent, entry));
1787
+ }
1788
+ } else {
1789
+ dirs.add(path14.join(appRoot, glob));
1790
+ }
1791
+ }
1792
+ const real2 = realpathSync(repositoryRoot(appRoot));
1793
+ const out = [];
1794
+ const byName = /* @__PURE__ */ new Map();
1795
+ for (const dir of [...dirs].sort()) {
1796
+ const manifest = path14.join(dir, "package.json");
1797
+ if (!existsSync(manifest)) continue;
1798
+ if (!inside(real2, realpathSync(dir))) continue;
1799
+ let pkg;
1800
+ try {
1801
+ pkg = JSON.parse(readFileSync(manifest, "utf8"));
1802
+ } catch {
1803
+ continue;
1804
+ }
1805
+ if (typeof pkg.name !== "string" || !pkg.name) continue;
1806
+ const rel = path14.relative(appRoot, dir).split(path14.sep).join("/");
1807
+ const other = byName.get(pkg.name);
1808
+ if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
1809
+ byName.set(pkg.name, rel);
1810
+ out.push({ name: pkg.name, dir, rel, ...typeof pkg.version === "string" ? { version: pkg.version } : {} });
1811
+ }
1812
+ cache.set(key2, out);
1813
+ return out;
1814
+ }
1543
1815
 
1544
1816
  // ../../scripts/lib/color-literals.mjs
1545
1817
  var LINE_COMMENT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".jsx", ".js", ".mjs", ".cjs", ".scss", ".less"]);
@@ -1747,6 +2019,13 @@ function scanFiles(root, config) {
1747
2019
  if (statSync(abs).isDirectory()) walk(abs);
1748
2020
  else visit(abs);
1749
2021
  }
2022
+ let local = [];
2023
+ try {
2024
+ local = localPackages(root);
2025
+ } catch {
2026
+ local = [];
2027
+ }
2028
+ for (const pkg of local) walk(pkg.dir);
1750
2029
  return files;
1751
2030
  }
1752
2031
  function lineAt(text, index) {
@@ -1919,7 +2198,18 @@ var BUILTIN_RULES = [
1919
2198
  "migration-definer-search-path",
1920
2199
  "migration-edited",
1921
2200
  "migration-testing-kit",
1922
- "migration-view-rls"
2201
+ "migration-view-rls",
2202
+ // packages pack
2203
+ "package-app-import",
2204
+ "package-undeclared-dependency",
2205
+ "package-migration-test",
2206
+ "package-migration-number",
2207
+ "package-migration-edited",
2208
+ "package-unregistered",
2209
+ "package-unversioned-change",
2210
+ "package-export-missing",
2211
+ "package-block-invalid",
2212
+ "package-untagged-tests"
1923
2213
  ];
1924
2214
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
1925
2215
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -2542,1134 +2832,1407 @@ function checkStoreReadiness(ctx) {
2542
2832
  });
2543
2833
  }
2544
2834
  }
2545
- var DEFAULT_MIGRATIONS = "supabase/migrations";
2546
- var DEFAULT_BASE = "origin/main";
2547
- var DEFAULT_EXPOSED = ["public"];
2548
- function sqlStatements(text) {
2549
- const out = [];
2550
- let buf = "";
2551
- let bodies = [];
2552
- let line = 1;
2553
- let start = 0;
2554
- const flush = () => {
2555
- const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
2556
- if (sql) out.push({ sql, line: start, bodies });
2557
- buf = "";
2558
- bodies = [];
2559
- start = 0;
2560
- };
2561
- const put = (s) => {
2562
- if (!start && /\S/.test(s)) start = line;
2563
- buf += s;
2564
- };
2565
- let i = 0;
2566
- while (i < text.length) {
2567
- const ch = text[i];
2568
- const two = text.slice(i, i + 2);
2569
- if (ch === "\n") {
2570
- buf += " ";
2571
- line++;
2572
- i++;
2573
- } else if (two === "--") {
2574
- while (i < text.length && text[i] !== "\n") i++;
2575
- } else if (two === "/*") {
2576
- let depth = 0;
2577
- while (i < text.length) {
2578
- if (text.startsWith("/*", i)) {
2579
- depth++;
2580
- i += 2;
2581
- } else if (text.startsWith("*/", i)) {
2582
- depth--;
2583
- i += 2;
2584
- if (depth === 0) break;
2585
- } else {
2586
- if (text[i] === "\n") line++;
2587
- i++;
2588
- }
2589
- }
2590
- buf += " ";
2591
- } else if (ch === "'") {
2592
- const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
2593
- put("'");
2594
- i++;
2595
- while (i < text.length) {
2596
- if (escapes && text[i] === "\\") i += 2;
2597
- else if (text[i] === "'" && text[i + 1] === "'") i += 2;
2598
- else if (text[i] === "'") break;
2599
- else {
2600
- if (text[i] === "\n") line++;
2601
- i++;
2602
- }
2603
- }
2604
- put("'");
2605
- i++;
2606
- } else if (ch === '"') {
2607
- i++;
2608
- while (i < text.length && text[i] !== '"') put(text[i++]);
2609
- i++;
2610
- } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
2611
- const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
2612
- const end = text.indexOf(tag, i + tag.length);
2613
- const stop = end === -1 ? text.length : end + tag.length;
2614
- bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
2615
- for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
2616
- put(`${tag} ${tag}`);
2617
- i = stop;
2618
- } else if (ch === ";") {
2619
- flush();
2620
- i++;
2621
- } else {
2622
- put(ch);
2623
- i++;
2624
- }
2625
- }
2626
- flush();
2627
- return out;
2835
+
2836
+ // src/doctor/semver.ts
2837
+ var VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
2838
+ function parseVersion(v) {
2839
+ const m = VERSION.exec(v.trim());
2840
+ return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
2628
2841
  }
2629
- function qualify(name) {
2630
- const n = name.trim().toLowerCase();
2631
- return n.includes(".") ? n : `public.${n}`;
2842
+ function compareVersions(a, b) {
2843
+ for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
2844
+ if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
2845
+ for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
2846
+ const x = a.pre[i];
2847
+ const y = b.pre[i];
2848
+ if (x === void 0) return -1;
2849
+ if (y === void 0) return 1;
2850
+ if (x === y) continue;
2851
+ const nx = /^\d+$/.test(x);
2852
+ const ny = /^\d+$/.test(y);
2853
+ if (nx && ny) return +x < +y ? -1 : 1;
2854
+ if (nx !== ny) return nx ? -1 : 1;
2855
+ return x < y ? -1 : 1;
2856
+ }
2857
+ return 0;
2632
2858
  }
2633
- var schemaOf = (name) => name.split(".")[0];
2634
- function parenthesized(sql, open) {
2635
- let depth = 0;
2636
- for (let k = open; k < sql.length; k++) {
2637
- if (sql[k] === "(") depth++;
2638
- else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
2859
+ function partial(s) {
2860
+ const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
2861
+ if (!m) return null;
2862
+ const nums = [];
2863
+ let wild = false;
2864
+ for (const part of [m[1], m[2], m[3]]) {
2865
+ if (wild || part === void 0 || /^[xX*]$/.test(part)) {
2866
+ wild = true;
2867
+ nums.push(null);
2868
+ } else nums.push(+part);
2639
2869
  }
2640
- return { inner: sql.slice(open + 1), end: sql.length };
2870
+ return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
2641
2871
  }
2642
- function stripParens(s) {
2643
- let out = "";
2644
- let depth = 0;
2645
- for (const c of s) {
2646
- if (c === "(") depth++;
2647
- else if (c === ")") depth = Math.max(0, depth - 1);
2648
- else if (depth === 0) out += c;
2872
+ var ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
2873
+ function comparators(token) {
2874
+ const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
2875
+ if (!m) return null;
2876
+ const op = m[1] ?? "";
2877
+ const p = partial(m[2]);
2878
+ if (!p) return null;
2879
+ const [major, mi, pa] = p.nums;
2880
+ if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
2881
+ const M = major;
2882
+ const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
2883
+ 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"]);
2884
+ const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
2885
+ const out = switchOp();
2886
+ if (p.pre.length) {
2887
+ for (const c of out) if (c.v === lo) c.pre = true;
2649
2888
  }
2650
2889
  return out;
2651
- }
2652
- function splitTop(s) {
2653
- const parts = [];
2654
- let depth = 0;
2655
- let cur = "";
2656
- for (const c of s) {
2657
- if (c === "(") depth++;
2658
- if (c === ")") depth--;
2659
- if (c === "," && depth === 0) {
2660
- parts.push(cur);
2661
- cur = "";
2662
- } else cur += c;
2890
+ function switchOp() {
2891
+ switch (op) {
2892
+ case "^": {
2893
+ const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
2894
+ return [
2895
+ { op: ">=", v: lo },
2896
+ { op: "<", v: bound }
2897
+ ];
2898
+ }
2899
+ case "~":
2900
+ case "~>":
2901
+ return [
2902
+ { op: ">=", v: lo },
2903
+ { op: "<", v: mi === null ? next("major") : next("minor") }
2904
+ ];
2905
+ case ">":
2906
+ return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
2907
+ case ">=":
2908
+ return [{ op: ">=", v: lo }];
2909
+ case "<":
2910
+ return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
2911
+ case "<=":
2912
+ return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
2913
+ default:
2914
+ return upper ? [
2915
+ { op: ">=", v: lo },
2916
+ { op: "<", v: upper }
2917
+ ] : [{ op: "=", v: lo }];
2918
+ }
2663
2919
  }
2664
- if (cur.trim()) parts.push(cur);
2665
- return parts.map((p) => p.trim()).filter(Boolean);
2666
2920
  }
2667
- var TYPE_ALIASES = {
2668
- int: "integer",
2669
- int4: "integer",
2670
- int8: "bigint",
2671
- int2: "smallint",
2672
- bool: "boolean",
2673
- varchar: "character varying",
2674
- timestamptz: "timestamp with time zone",
2675
- float8: "double precision"
2676
- };
2677
- var MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
2678
- function argTypes(args) {
2679
- const types = [];
2680
- for (const raw of splitTop(args)) {
2681
- let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
2682
- const mode = tokens[0];
2683
- if (mode === "out") continue;
2684
- if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
2685
- const joined = tokens.join(" ");
2686
- const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
2687
- types.push(TYPE_ALIASES[type] ?? type);
2688
- }
2689
- return types;
2690
- }
2691
- function git(root, args) {
2692
- const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
2693
- return r.status === 0 ? r.stdout : null;
2921
+ function test(c, v) {
2922
+ const d = compareVersions(v, c.v);
2923
+ return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
2694
2924
  }
2695
- function gitView(root, dir, base) {
2696
- if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
2697
- if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
2698
- return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
2699
- }
2700
- const mergeBase = git(root, ["merge-base", "HEAD", base])?.trim();
2701
- if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
2702
- const diff = git(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
2703
- const untracked = git(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
2704
- if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
2705
- const sql = (p) => p !== void 0 && p.endsWith(".sql");
2706
- const touched = new Set(untracked.split("\n").filter(sql));
2707
- const edited = [];
2708
- for (const row of diff.split("\n").filter(Boolean)) {
2709
- const [status, a, b] = row.split(" ");
2710
- if (status.startsWith("R")) {
2711
- if (sql(b)) touched.add(b);
2712
- if (sql(a)) edited.push({ file: a, status: "renamed" });
2925
+ function parseRange(range) {
2926
+ const alts = [];
2927
+ for (const raw of range.trim().split("||")) {
2928
+ const alt = raw.trim();
2929
+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
2930
+ if (hyphen) {
2931
+ const from = comparators(`>=${hyphen[1]}`);
2932
+ const to = comparators(`<=${hyphen[2]}`);
2933
+ if (!from || !to) return null;
2934
+ alts.push([...from, ...to]);
2713
2935
  continue;
2714
2936
  }
2715
- if (!sql(a)) continue;
2716
- if (status.startsWith("A")) touched.add(a);
2717
- else if (status.startsWith("M") || status.startsWith("T")) {
2718
- touched.add(a);
2719
- edited.push({ file: a, status: "modified" });
2720
- } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
2721
- }
2722
- return { touched, edited };
2723
- }
2724
- function checkSupabasePack(ctx) {
2725
- const settings = ctx.config.supabase ?? {};
2726
- const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
2727
- const abs = path14.join(ctx.root, dir);
2728
- if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
2729
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path14.join(abs, n), "utf8")) }));
2730
- const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
2731
- const base = settings.base ?? DEFAULT_BASE;
2732
- const view = gitView(ctx.root, dir, base);
2733
- if ("reason" in view) {
2734
- if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
2735
- } else {
2736
- for (const e of view.edited) {
2737
- ctx.report({
2738
- rule: "migration-edited",
2739
- file: e.file,
2740
- subject: e.file,
2741
- 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`
2742
- });
2937
+ const set = [];
2938
+ for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
2939
+ const cs = comparators(token);
2940
+ if (!cs) return null;
2941
+ set.push(...cs);
2743
2942
  }
2943
+ alts.push(set);
2744
2944
  }
2745
- const since = settings.since;
2746
- const afterSince = (file) => since === void 0 || path14.posix.basename(file) >= since;
2747
- if ("reason" in view && since === void 0) {
2748
- ctx.report({
2749
- rule: "migration-grants",
2750
- level: "warn",
2751
- file: dir,
2752
- 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`
2753
- });
2754
- } else {
2755
- const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
2756
- checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
2757
- }
2758
- checkRls(ctx, migrations, exposed);
2759
- checkViewInvoker(ctx, migrations, exposed);
2760
- checkDefinerSearchPath(ctx, migrations);
2761
- checkTestingKit(ctx, migrations);
2762
- }
2763
- function checkTestingKit(ctx, migrations) {
2764
- for (const { file, statements } of migrations) {
2765
- const hit = statements.find(({ sql }) => /\bgenesis_testing\b/.test(sql));
2766
- if (!hit) continue;
2767
- ctx.report({
2768
- rule: "migration-testing-kit",
2769
- file,
2770
- line: hit.line,
2771
- subject: "genesis_testing",
2772
- message: "a migration uses genesis_testing, the pgTAP kit for test databases only; move it to supabase/tests/database/000_genesis_testing.test.sql"
2773
- });
2774
- }
2945
+ return alts;
2775
2946
  }
2776
- function granteesOf(s) {
2777
- return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
2947
+ function satisfies(version, range) {
2948
+ const v = parseVersion(version);
2949
+ const alts = parseRange(range);
2950
+ if (!v || !alts) return null;
2951
+ return alts.some(
2952
+ (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))
2953
+ );
2778
2954
  }
2779
- function checkGrants(ctx, migrations, exposed) {
2780
- const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
2781
- const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
2782
- const blanket = (roles) => {
2783
- const o = open(roles);
2784
- if (o.length) return { level: "error", who: o.join(" and ") };
2785
- if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
2786
- return null;
2955
+ var TRAIL_DEPTH = 6;
2956
+ var RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
2957
+ var IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
2958
+ var EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
2959
+ var DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
2960
+ function stripForImports(code) {
2961
+ const out = [];
2962
+ const blank = (ch) => ch === "\n" ? "\n" : " ";
2963
+ const n = code.length;
2964
+ const templates = [];
2965
+ let depth = 0;
2966
+ let i = 0;
2967
+ let sure = true;
2968
+ const isSpecifier = () => /(?:\bfrom|(?:^|[;{}\n])\s*import|\bimport\s*\(|\brequire\s*\()\s*$/.test(out.slice(-40).join(""));
2969
+ const before = () => out.slice(-24).join("");
2970
+ const KEYWORD = /(?:^|[^\w$.])(?:return|typeof|instanceof|case|do|else|in|of|new|delete|void|throw|yield|await|from|import|export|default|require)\s*$/;
2971
+ const startsExpression = (b) => {
2972
+ const t = b.replace(/\s+$/, "");
2973
+ if (!t) return true;
2974
+ if (KEYWORD.test(b)) return true;
2975
+ return /[([{,;:=!&|?+\-*%<>~^}]$/.test(t);
2787
2976
  };
2788
- for (const { file, statements } of migrations) {
2789
- for (const { sql, line } of statements) {
2790
- const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
2791
- if (all) {
2792
- const hit = blanket(granteesOf(all[1]));
2793
- if (hit) {
2794
- 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}` });
2795
- }
2796
- continue;
2977
+ const exprStart = () => startsExpression(before());
2978
+ const taggedTemplate = () => {
2979
+ const b = out.slice(-48).join("");
2980
+ const m = /([A-Za-z_$][\w$.]*)$/.exec(b);
2981
+ return m !== null && startsExpression(b.slice(0, b.length - m[1].length));
2982
+ };
2983
+ const templateBody = () => {
2984
+ while (i < n) {
2985
+ const ch = code[i];
2986
+ if (ch === "\\") {
2987
+ out.push(" ", blank(code[i + 1] ?? ""));
2988
+ i += 2;
2989
+ } else if (ch === "`") {
2990
+ out.push("`");
2991
+ i++;
2992
+ return;
2993
+ } else if (ch === "$" && code[i + 1] === "{") {
2994
+ out.push("${");
2995
+ i += 2;
2996
+ templates.push(depth);
2997
+ depth++;
2998
+ return;
2999
+ } else {
3000
+ out.push(blank(ch));
3001
+ i++;
2797
3002
  }
2798
- const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
2799
- if (defaults) {
2800
- const hit = blanket(granteesOf(defaults[1]));
2801
- if (hit) {
2802
- 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}` });
2803
- }
2804
- continue;
3003
+ }
3004
+ sure = false;
3005
+ };
3006
+ while (i < n && sure) {
3007
+ const ch = code[i];
3008
+ const next = code[i + 1];
3009
+ if (ch === "/" && next === "/") {
3010
+ while (i < n && code[i] !== "\n") {
3011
+ out.push(" ");
3012
+ i++;
2805
3013
  }
2806
- const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
2807
- if (fn) {
2808
- const roles = open(granteesOf(fn[2]));
2809
- if (!roles.length) continue;
2810
- for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
2811
- if (exposed.has(schemaOf(name))) continue;
2812
- ctx.report({
2813
- rule: "migration-grants",
2814
- file,
2815
- line,
2816
- subject: name,
2817
- 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)`
2818
- });
2819
- }
2820
- continue;
3014
+ } else if (ch === "/" && next === "*") {
3015
+ out.push(" ");
3016
+ i += 2;
3017
+ while (i < n && !(code[i] === "*" && code[i + 1] === "/")) {
3018
+ out.push(blank(code[i]));
3019
+ i++;
2821
3020
  }
2822
- const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
2823
- if (schema) {
2824
- const roles = open(granteesOf(schema[2]));
2825
- if (!roles.length) continue;
2826
- for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
2827
- if (exposed.has(s)) continue;
2828
- ctx.report({
2829
- rule: "migration-grants",
2830
- file,
2831
- line,
2832
- subject: `schema ${s}`,
2833
- message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
2834
- });
2835
- }
3021
+ if (i < n) {
3022
+ out.push(" ");
3023
+ i += 2;
2836
3024
  }
2837
- }
2838
- }
2839
- }
2840
- function checkRls(ctx, migrations, exposed) {
2841
- const tables = /* @__PURE__ */ new Map();
2842
- const name = String.raw`([\w$.]+)`;
2843
- const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
2844
- for (const { file, statements } of migrations) {
2845
- for (const { sql, line, bodies } of statements) {
2846
- if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
2847
- const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
2848
- if (create) {
2849
- if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
2850
- continue;
2851
- }
2852
- const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
2853
- const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
2854
- if (rename || move) {
2855
- const from = qualify((rename ?? move)[1]);
2856
- const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
2857
- const state = tables.get(from);
2858
- if (state) {
2859
- tables.delete(from);
2860
- tables.set(to, state);
3025
+ } else if (ch === "/" && next !== ">" && code[i - 1] !== "<" && exprStart()) {
3026
+ const afterBrace = /[}>]\s*$/.test(before());
3027
+ const start = i;
3028
+ const mark = out.length;
3029
+ out.push("/");
3030
+ i++;
3031
+ let inClass = false;
3032
+ for (; ; ) {
3033
+ const c = code[i];
3034
+ if (c === void 0 || c === "\n") {
3035
+ if (afterBrace) {
3036
+ out.length = mark;
3037
+ out.push("/");
3038
+ i = start + 1;
3039
+ } else sure = false;
3040
+ break;
2861
3041
  }
2862
- continue;
3042
+ if (c === "\\") {
3043
+ out.push(" ", blank(code[i + 1] ?? ""));
3044
+ i += 2;
3045
+ continue;
3046
+ }
3047
+ i++;
3048
+ if (c === "[") inClass = true;
3049
+ else if (c === "]") inClass = false;
3050
+ else if (c === "/" && !inClass) {
3051
+ if (afterBrace && /[<>]/.test(code.slice(start + 1, i - 1))) {
3052
+ out.length = mark;
3053
+ out.push("/");
3054
+ i = start + 1;
3055
+ break;
3056
+ }
3057
+ out.push("/");
3058
+ break;
3059
+ }
3060
+ out.push(" ");
2863
3061
  }
2864
- const alter = new RegExp(target).exec(sql);
2865
- if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
2866
- const t = qualify(alter[1]);
2867
- if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
2868
- else {
2869
- const state = tables.get(t);
2870
- if (state) state.rls = true;
3062
+ if (out.length > mark + 1 || i > start + 1) while (i < n && /[a-z]/.test(code[i])) out.push(code[i++]);
3063
+ } else if ((ch === '"' || ch === "'") && exprStart()) {
3064
+ const keep = isSpecifier();
3065
+ out.push(ch);
3066
+ i++;
3067
+ while (i < n && code[i] !== ch && code[i] !== "\n") {
3068
+ if (code[i] === "\\") {
3069
+ out.push(keep ? code[i] : " ", keep ? code[i + 1] ?? "" : blank(code[i + 1] ?? ""));
3070
+ i += 2;
3071
+ } else {
3072
+ out.push(keep ? code[i] : blank(code[i]));
3073
+ i++;
2871
3074
  }
2872
- continue;
2873
3075
  }
2874
- const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
2875
- if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
3076
+ if (code[i] !== ch) sure = false;
3077
+ else {
3078
+ out.push(code[i]);
3079
+ i++;
3080
+ }
3081
+ } else if (ch === "`" && (exprStart() || taggedTemplate())) {
3082
+ out.push("`");
3083
+ i++;
3084
+ templateBody();
3085
+ } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
3086
+ templates.pop();
3087
+ depth--;
3088
+ out.push("}");
3089
+ i++;
3090
+ templateBody();
3091
+ } else {
3092
+ if (ch === "{") depth++;
3093
+ else if (ch === "}") depth--;
3094
+ out.push(ch);
3095
+ i++;
2876
3096
  }
2877
3097
  }
2878
- for (const [t, at] of tables) {
2879
- if (at.rls || !exposed.has(schemaOf(t))) continue;
2880
- ctx.report({
2881
- rule: "migration-rls",
2882
- file: at.file,
2883
- line: at.line,
2884
- subject: t,
2885
- 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`
2886
- });
2887
- }
3098
+ return sure && templates.length === 0 ? out.join("") : null;
2888
3099
  }
2889
- function checkViewInvoker(ctx, migrations, exposed) {
2890
- const views = /* @__PURE__ */ new Map();
2891
- const name = String.raw`([\w$.]+)`;
2892
- const invokerOn = /\bsecurity_invoker\s*(?:=\s*(?:true|on|yes|1|'true'|'on'))?\s*(?:,|\))/;
2893
- for (const { file, statements } of migrations) {
2894
- for (const { sql, line } of statements) {
2895
- const create = new RegExp(String.raw`^create (?:or replace )?(?:temp |temporary )?(?:recursive )?view ${name}`).exec(sql);
2896
- if (create) {
2897
- if (/^create (?:or replace )?(?:temp|temporary) /.test(sql)) continue;
2898
- const options = /^[^(]*?\bwith\s*(\([^)]*\))\s*as\b/.exec(sql)?.[1] ?? "";
2899
- views.set(qualify(create[1]), { invoker: invokerOn.test(options), file, line });
2900
- continue;
2901
- }
2902
- const alter = new RegExp(String.raw`^alter view (?:if exists )?${name} (set|reset) (\([^)]*\))`).exec(sql);
2903
- if (alter && /\bsecurity_invoker\b/.test(alter[3])) {
2904
- const state = views.get(qualify(alter[1]));
2905
- if (state) state.invoker = alter[2] === "set" && invokerOn.test(alter[3]);
2906
- continue;
2907
- }
2908
- const rename = new RegExp(String.raw`^alter view (?:if exists )?${name} rename to ([\w$]+)$`).exec(sql);
2909
- if (rename) {
2910
- const from = qualify(rename[1]);
2911
- const state = views.get(from);
2912
- if (state) {
2913
- views.delete(from);
2914
- views.set(`${schemaOf(from)}.${rename[2]}`, state);
2915
- }
2916
- continue;
2917
- }
2918
- const drop = /^drop view (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
2919
- if (drop) for (const n of drop[1].split(",")) views.delete(qualify(n));
2920
- }
3100
+ function bindings(clause) {
3101
+ const out = [];
3102
+ const named = /\{([^}]*)\}/.exec(clause);
3103
+ for (const part of named?.[1].split(",") ?? []) {
3104
+ const p = part.trim();
3105
+ if (!p || p.startsWith("type ")) continue;
3106
+ out.push(p.split(/\s+as\s+/).pop().trim());
2921
3107
  }
2922
- for (const [v, at] of views) {
2923
- if (at.invoker || !exposed.has(schemaOf(v))) continue;
2924
- ctx.report({
2925
- rule: "migration-view-rls",
2926
- file: at.file,
2927
- line: at.line,
2928
- subject: v,
2929
- 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);"`
2930
- });
3108
+ const rest = clause.replace(/\{[^}]*\}/, "");
3109
+ const ns = /\*\s*as\s+([\w$]+)/.exec(rest);
3110
+ if (ns) out.push(ns[1]);
3111
+ const def = /^\s*([\w$]+)/.exec(rest);
3112
+ if (def && def[1] !== "as") out.push(def[1]);
3113
+ return out;
3114
+ }
3115
+ function readJsonc(file) {
3116
+ try {
3117
+ const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? "").replace(/,(\s*[}\]])/g, "$1");
3118
+ return JSON.parse(text);
3119
+ } catch {
3120
+ return null;
2931
3121
  }
2932
3122
  }
2933
- function checkDefinerSearchPath(ctx, migrations) {
2934
- const fns = /* @__PURE__ */ new Map();
2935
- const keysFor = (sql, nameEnd, fnName) => {
2936
- const rest = sql.slice(nameEnd).trimStart();
2937
- if (rest.startsWith("(")) {
2938
- const { inner } = parenthesized(rest, 0);
2939
- return [`${fnName}(${argTypes(inner).join(",")})`];
2940
- }
2941
- return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
2942
- };
2943
- for (const { file, statements } of migrations) {
2944
- for (const { sql, line } of statements) {
2945
- const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
2946
- if (create) {
2947
- const [key2] = keysFor(sql, create[0].length, qualify(create[1]));
2948
- fns.set(key2, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
2949
- continue;
2950
- }
2951
- const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
2952
- if (alter) {
2953
- const fnName = qualify(alter[1]);
2954
- const keys = keysFor(sql, alter[0].length, fnName);
2955
- const rename = / rename to ([\w$]+)$/.exec(sql);
2956
- const move = / set schema ([\w$]+)$/.exec(sql);
2957
- for (const key2 of keys) {
2958
- const state = fns.get(key2);
2959
- if (rename || move) {
2960
- if (!state) continue;
2961
- fns.delete(key2);
2962
- const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
2963
- fns.set(newName + key2.slice(fnName.length), state);
2964
- continue;
2965
- }
2966
- const next = state ?? { definer: false, searchPath: false, file, line };
2967
- if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
2968
- if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
2969
- if (/\bset search_path\b/.test(sql)) next.searchPath = true;
2970
- if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
2971
- fns.set(key2, next);
2972
- }
2973
- continue;
2974
- }
2975
- const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
2976
- if (drop) {
2977
- for (const part of splitTop(drop[1])) {
2978
- const m = /^([\w$.]+)\s*/.exec(part);
2979
- if (m) for (const key2 of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key2);
2980
- }
3123
+ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3124
+ if (seen.has(file) || seen.size > 10) return {};
3125
+ seen.add(file);
3126
+ const json = readJsonc(file);
3127
+ if (!json) return {};
3128
+ const dir = path14.dirname(file);
3129
+ let merged = {};
3130
+ const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
3131
+ for (const ext of parents) {
3132
+ if (typeof ext !== "string") continue;
3133
+ let target = null;
3134
+ if (ext.startsWith(".") || path14.isAbsolute(ext)) {
3135
+ const abs = path14.resolve(dir, ext);
3136
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3137
+ } else {
3138
+ const parts = ext.split("/");
3139
+ const nameLength = ext.startsWith("@") ? 2 : 1;
3140
+ const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
3141
+ if (pkgDir) {
3142
+ const sub = parts.slice(nameLength).join("/");
3143
+ const abs = path14.join(pkgDir, sub || "tsconfig.json");
3144
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2981
3145
  }
2982
3146
  }
3147
+ if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
2983
3148
  }
2984
- for (const [key2, at] of fns) {
2985
- if (!at.definer || at.searchPath) continue;
2986
- ctx.report({
2987
- rule: "migration-definer-search-path",
2988
- file: at.file,
2989
- line: at.line,
2990
- subject: key2,
2991
- 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`
2992
- });
3149
+ const opts = json.compilerOptions ?? {};
3150
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path14.resolve(dir, opts.baseUrl);
3151
+ if (opts.paths && typeof opts.paths === "object") {
3152
+ merged.paths = opts.paths;
3153
+ merged.pathsDir = dir;
2993
3154
  }
3155
+ return merged;
2994
3156
  }
2995
- var UMBRELLA_PACKAGE = "@marktiderman/genesis";
2996
- function readReleaseManifest(root) {
2997
- const dir = findPackageDir(root, UMBRELLA_PACKAGE);
2998
- const file = dir && path14.join(dir, "dist", "versions.json");
2999
- if (!file || !existsSync(file)) return null;
3000
- return JSON.parse(readFileSync(file, "utf8"));
3001
- }
3002
- function checkVersionSkew(ctx) {
3003
- const manifest = readReleaseManifest(ctx.root);
3004
- if (!manifest) return;
3005
- for (const [name, want] of Object.entries(manifest.packages)) {
3006
- const dir = findPackageDir(ctx.root, name);
3007
- if (!dir) continue;
3008
- const have = JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8")).version;
3009
- if (have === want) continue;
3010
- ctx.report({
3011
- rule: "version-skew",
3012
- level: "warn",
3013
- file: "package.json",
3014
- subject: name,
3015
- message: `${name} is ${have}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Install ${name}@${want}, or move every Genesis package to one release.`
3016
- });
3157
+ function aliases(root) {
3158
+ const table = [];
3159
+ let baseUrl = null;
3160
+ for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
3161
+ const file = path14.join(root, name);
3162
+ if (!existsSync(file)) continue;
3163
+ const config = readTsconfig(root, file);
3164
+ baseUrl ??= config.baseUrl ?? null;
3165
+ const base = config.baseUrl ?? config.pathsDir ?? root;
3166
+ for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
3167
+ if (!Array.isArray(targets)) continue;
3168
+ const exact = !pattern.endsWith("*");
3169
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path14.join(base, String(t).replace(/\*$/, ""))) });
3170
+ }
3017
3171
  }
3018
- }
3019
-
3020
- // src/doctor/semver.ts
3021
- var VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
3022
- function parseVersion(v) {
3023
- const m = VERSION.exec(v.trim());
3024
- return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
3025
- }
3026
- function compareVersions(a, b) {
3027
- for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
3028
- if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
3029
- for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
3030
- const x = a.pre[i];
3031
- const y = b.pre[i];
3032
- if (x === void 0) return -1;
3033
- if (y === void 0) return 1;
3034
- if (x === y) continue;
3035
- const nx = /^\d+$/.test(x);
3036
- const ny = /^\d+$/.test(y);
3037
- if (nx && ny) return +x < +y ? -1 : 1;
3038
- if (nx !== ny) return nx ? -1 : 1;
3039
- return x < y ? -1 : 1;
3172
+ const pkg = readJsonc(path14.join(root, "package.json"));
3173
+ for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
3174
+ if (typeof target !== "string") continue;
3175
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path14.join(root, target.replace(/\*.*$/, ""))] });
3040
3176
  }
3041
- return 0;
3177
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
3178
+ return { table, baseUrl };
3042
3179
  }
3043
- function partial(s) {
3044
- const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
3045
- if (!m) return null;
3046
- const nums = [];
3047
- let wild = false;
3048
- for (const part of [m[1], m[2], m[3]]) {
3049
- if (wild || part === void 0 || /^[xX*]$/.test(part)) {
3050
- wild = true;
3051
- nums.push(null);
3052
- } else nums.push(+part);
3180
+ function resolveFile(base) {
3181
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path14.join(base, `index${e}`))];
3182
+ if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
3183
+ for (const p of tries) {
3184
+ if (SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
3053
3185
  }
3054
- return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
3186
+ return null;
3055
3187
  }
3056
- var ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
3057
- function comparators(token) {
3058
- const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
3059
- if (!m) return null;
3060
- const op = m[1] ?? "";
3061
- const p = partial(m[2]);
3062
- if (!p) return null;
3063
- const [major, mi, pa] = p.nums;
3064
- if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
3065
- const M = major;
3066
- const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
3067
- 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"]);
3068
- const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
3069
- const out = switchOp();
3070
- if (p.pre.length) {
3071
- for (const c of out) if (c.v === lo) c.pre = true;
3188
+ var trails = /* @__PURE__ */ new WeakMap();
3189
+ function trailFor(ctx) {
3190
+ let t = trails.get(ctx.files);
3191
+ if (!t) trails.set(ctx.files, t = createTrail(ctx));
3192
+ return t;
3193
+ }
3194
+ function createTrail(ctx) {
3195
+ const { table, baseUrl } = aliases(ctx.root);
3196
+ let declared = null;
3197
+ try {
3198
+ const pkg = JSON.parse(readFileSync(path14.join(ctx.root, "package.json"), "utf8"));
3199
+ declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
3200
+ } catch {
3201
+ declared = null;
3072
3202
  }
3073
- return out;
3074
- function switchOp() {
3075
- switch (op) {
3076
- case "^": {
3077
- const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
3078
- return [
3079
- { op: ">=", v: lo },
3080
- { op: "<", v: bound }
3081
- ];
3203
+ const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
3204
+ const read = (abs) => byPath.get(abs) ?? readSource(abs);
3205
+ const importsCache = /* @__PURE__ */ new Map();
3206
+ const importsOf = (file) => {
3207
+ const hit = importsCache.get(file.absolutePath);
3208
+ if (hit) return hit;
3209
+ const files = [];
3210
+ let lost = false;
3211
+ const code = stripped(file);
3212
+ if (code === null) {
3213
+ const out2 = { files: [], lost: true };
3214
+ importsCache.set(file.absolutePath, out2);
3215
+ return out2;
3216
+ }
3217
+ const used = new Set(renderedElements(code).map((e) => e.split(".")[0]));
3218
+ for (const m of code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
3219
+ for (const m of code.matchAll(/\bexport\s+default\s+([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
3220
+ 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]);
3221
+ const specs = [];
3222
+ for (const m of code.matchAll(IMPORT_FROM)) if (!m[1] && bindings(m[2]).some((b) => used.has(b))) specs.push(m[3]);
3223
+ for (const m of code.matchAll(EXPORT_FROM)) if (!m[1]) specs.push(m[2]);
3224
+ for (const m of code.matchAll(DYNAMIC)) specs.push(m[1]);
3225
+ for (const spec of specs) {
3226
+ if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
3227
+ let resolved = null;
3228
+ if (spec.startsWith(".")) {
3229
+ resolved = resolveFile(path14.resolve(path14.dirname(file.absolutePath), spec));
3230
+ if (!resolved) lost = true;
3231
+ } else {
3232
+ const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
3233
+ if (alias) {
3234
+ for (const t of alias.targets) {
3235
+ resolved = resolveFile(alias.exact ? t : path14.join(t, spec.slice(alias.prefix.length)));
3236
+ if (resolved) break;
3237
+ }
3238
+ }
3239
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path14.join(baseUrl, spec));
3240
+ if (!resolved) {
3241
+ const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
3242
+ if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
3243
+ }
3082
3244
  }
3083
- case "~":
3084
- case "~>":
3085
- return [
3086
- { op: ">=", v: lo },
3087
- { op: "<", v: mi === null ? next("major") : next("minor") }
3088
- ];
3089
- case ">":
3090
- return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
3091
- case ">=":
3092
- return [{ op: ">=", v: lo }];
3093
- case "<":
3094
- return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
3095
- case "<=":
3096
- return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
3097
- default:
3098
- return upper ? [
3099
- { op: ">=", v: lo },
3100
- { op: "<", v: upper }
3101
- ] : [{ op: "=", v: lo }];
3245
+ if (resolved && !files.includes(resolved)) files.push(resolved);
3102
3246
  }
3103
- }
3104
- }
3105
- function test(c, v) {
3106
- const d = compareVersions(v, c.v);
3107
- return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
3108
- }
3109
- function parseRange(range) {
3110
- const alts = [];
3111
- for (const raw of range.trim().split("||")) {
3112
- const alt = raw.trim();
3113
- const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
3114
- if (hyphen) {
3115
- const from = comparators(`>=${hyphen[1]}`);
3116
- const to = comparators(`<=${hyphen[2]}`);
3117
- if (!from || !to) return null;
3118
- alts.push([...from, ...to]);
3119
- continue;
3247
+ const out = { files, lost };
3248
+ importsCache.set(file.absolutePath, out);
3249
+ return out;
3250
+ };
3251
+ const strippedCache = /* @__PURE__ */ new Map();
3252
+ const stripped = (file) => {
3253
+ if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
3254
+ return strippedCache.get(file.absolutePath);
3255
+ };
3256
+ const memo = /* @__PURE__ */ new WeakMap();
3257
+ const reach = (file, test2, depth, seen) => {
3258
+ let cache2 = memo.get(test2);
3259
+ if (!cache2) memo.set(test2, cache2 = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
3260
+ const k = `${file.absolutePath}\0${depth}`;
3261
+ const free = cache2.free.get(k);
3262
+ if (free) return [free, /* @__PURE__ */ new Set()];
3263
+ const reusable = cache2.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
3264
+ if (reusable) return [reusable.result, new Set(reusable.cut)];
3265
+ let result;
3266
+ const cut = /* @__PURE__ */ new Set();
3267
+ const code = stripped(file);
3268
+ if (code === null) result = "unknown";
3269
+ else if (test2(code)) result = "yes";
3270
+ else {
3271
+ const { files, lost } = importsOf(file);
3272
+ let unknown = lost && depth > 0;
3273
+ result = "no";
3274
+ if (depth > 0) {
3275
+ seen.add(file.absolutePath);
3276
+ for (const abs of files) {
3277
+ if (seen.has(abs)) {
3278
+ cut.add(abs);
3279
+ continue;
3280
+ }
3281
+ const target = read(abs);
3282
+ if (!target) {
3283
+ unknown = true;
3284
+ continue;
3285
+ }
3286
+ const [r, c] = reach(target, test2, depth - 1, seen);
3287
+ for (const m of c) cut.add(m);
3288
+ if (r === "yes") {
3289
+ result = "yes";
3290
+ break;
3291
+ }
3292
+ if (r === "unknown") unknown = true;
3293
+ }
3294
+ seen.delete(file.absolutePath);
3295
+ cut.delete(file.absolutePath);
3296
+ }
3297
+ if (result === "no" && unknown) result = "unknown";
3120
3298
  }
3121
- const set = [];
3122
- for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
3123
- const cs = comparators(token);
3124
- if (!cs) return null;
3125
- set.push(...cs);
3299
+ if (result === "yes" || cut.size === 0) {
3300
+ cache2.free.set(k, result);
3301
+ return [result, /* @__PURE__ */ new Set()];
3126
3302
  }
3127
- alts.push(set);
3303
+ const entries = cache2.cut.get(k) ?? [];
3304
+ entries.push({ cut: [...cut], result });
3305
+ cache2.cut.set(k, entries);
3306
+ return [result, cut];
3307
+ };
3308
+ return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
3309
+ }
3310
+
3311
+ // src/doctor/packages.ts
3312
+ var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
3313
+ var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
3314
+ var BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
3315
+ var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
3316
+ var TYPE_ONLY = /\b(?:import|export)\s+type\b[^;"'`]*?\bfrom\s*["'][^"']+["']/g;
3317
+ function sourceFiles(dir, rel = "") {
3318
+ const out = [];
3319
+ for (const entry of readdirSync(path14.join(dir, rel)).sort()) {
3320
+ if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
3321
+ const child = rel ? `${rel}/${entry}` : entry;
3322
+ const stat = lstatSync(path14.join(dir, child));
3323
+ if (stat.isSymbolicLink()) continue;
3324
+ if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
3325
+ else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
3128
3326
  }
3129
- return alts;
3327
+ return out;
3130
3328
  }
3131
- function satisfies(version, range) {
3132
- const v = parseVersion(version);
3133
- const alts = parseRange(range);
3134
- if (!v || !alts) return null;
3135
- return alts.some(
3136
- (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))
3137
- );
3329
+ function packageName2(specifier) {
3330
+ const parts = specifier.split("/");
3331
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3138
3332
  }
3139
-
3140
- // src/doctor/installs.ts
3141
- var GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
3142
- var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
3143
- var 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)$/;
3144
- var readManifest = (dir) => {
3333
+ function git(root, args) {
3334
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3335
+ return r.status === 0 ? r.stdout : null;
3336
+ }
3337
+ function matchPattern(pattern, spec) {
3338
+ const star = pattern.indexOf("*");
3339
+ if (star < 0) return pattern === spec ? "" : null;
3340
+ const head = pattern.slice(0, star);
3341
+ const tail = pattern.slice(star + 1);
3342
+ return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3343
+ }
3344
+ function tsconfigPaths(dir) {
3345
+ const file = path14.join(dir, "tsconfig.json");
3346
+ if (!existsSync(file)) return [];
3145
3347
  try {
3146
- return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
3348
+ const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
3349
+ const options = JSON.parse(text).compilerOptions ?? {};
3350
+ const base = path14.resolve(dir, options.baseUrl ?? ".");
3351
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path14.resolve(base, t)) }));
3147
3352
  } catch {
3353
+ return [];
3354
+ }
3355
+ }
3356
+ function checkImports2(ctx, pkg, json) {
3357
+ const aliases2 = tsconfigPaths(pkg.dir);
3358
+ const subpathImports = Object.keys(json.imports ?? {});
3359
+ const viaAlias = (spec) => {
3360
+ if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
3361
+ for (const { pattern, targets } of aliases2) {
3362
+ const hit = matchPattern(pattern, spec);
3363
+ if (hit === null) continue;
3364
+ return targets.some((t) => {
3365
+ const rel = path14.relative(pkg.dir, t.replace("*", hit));
3366
+ return !rel.startsWith("..") && !path14.isAbsolute(rel);
3367
+ });
3368
+ }
3148
3369
  return null;
3370
+ };
3371
+ const declared = /* @__PURE__ */ new Set([
3372
+ json.name,
3373
+ ...Object.keys(json.dependencies ?? {}),
3374
+ ...Object.keys(json.peerDependencies ?? {}),
3375
+ ...Object.keys(json.devDependencies ?? {}),
3376
+ ...Object.keys(json.optionalDependencies ?? {})
3377
+ ]);
3378
+ for (const file of sourceFiles(pkg.dir)) {
3379
+ const code = stripForImports(readFileSync(path14.join(pkg.dir, file), "utf8"));
3380
+ if (code === null) continue;
3381
+ const at = `${pkg.rel}/${file}`;
3382
+ const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
3383
+ let offset = 0;
3384
+ code.split("\n").forEach((text, i) => {
3385
+ const lineStart = offset;
3386
+ offset += text.length + 1;
3387
+ for (const m of text.matchAll(IMPORT)) {
3388
+ const spec = m[1];
3389
+ const line = i + 1;
3390
+ const at0 = lineStart + m.index;
3391
+ if (typeOnly.some(([a, b]) => at0 >= a && at0 < b)) continue;
3392
+ const alias = viaAlias(spec);
3393
+ if (alias === true) continue;
3394
+ if (alias === false) {
3395
+ ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} imports ${spec}, an alias that points outside the package` });
3396
+ continue;
3397
+ }
3398
+ if (spec.startsWith("#")) continue;
3399
+ if (spec.startsWith("@/") || spec.startsWith("~/")) {
3400
+ 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` });
3401
+ continue;
3402
+ }
3403
+ if (spec.startsWith(".")) {
3404
+ const target = path14.resolve(pkg.dir, path14.dirname(file), spec);
3405
+ const rel = path14.relative(pkg.dir, target);
3406
+ if (rel.startsWith("..") || path14.isAbsolute(rel)) {
3407
+ 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` });
3408
+ }
3409
+ continue;
3410
+ }
3411
+ if (BUILTINS.has(spec) || spec.startsWith("node:") || spec.startsWith("virtual:") || /^[a-z]+:/.test(spec)) continue;
3412
+ const name = packageName2(spec);
3413
+ if (!declared.has(name)) {
3414
+ 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` });
3415
+ }
3416
+ }
3417
+ });
3149
3418
  }
3150
- };
3151
- var real = (p) => {
3152
- try {
3153
- return realpathSync(p);
3154
- } catch {
3155
- return p;
3156
- }
3157
- };
3158
- var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
3159
- function nodeModulesOf(dir) {
3160
- const parent = path14.dirname(dir);
3161
- return path14.basename(parent).startsWith("@") ? path14.dirname(parent) : parent;
3162
3419
  }
3163
- function packagesIn(nodeModules) {
3164
- if (!existsSync(nodeModules)) return [];
3165
- const out = [];
3166
- for (const entry of readdirSync(nodeModules)) {
3167
- if (entry.startsWith(".")) continue;
3168
- const p = path14.join(nodeModules, entry);
3169
- if (entry.startsWith("@")) {
3170
- try {
3171
- for (const sub of readdirSync(p)) out.push(path14.join(p, sub));
3172
- } catch {
3420
+ function checkMigrations(ctx, pkg, json) {
3421
+ const declaredFiles = /* @__PURE__ */ new Set();
3422
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
3423
+ const migrations = raw.migrations ?? [];
3424
+ for (const m of migrations) {
3425
+ if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
3426
+ if (typeof m.file === "string" && typeof m.test !== "string") {
3427
+ 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` });
3428
+ } else if (typeof m.test === "string" && !existsSync(path14.join(pkg.dir, m.test))) {
3429
+ 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` });
3173
3430
  }
3174
- } else {
3175
- out.push(p);
3176
3431
  }
3177
3432
  }
3178
- return out;
3179
- }
3180
- function genesisInstalls(root) {
3181
- const copies = /* @__PURE__ */ new Map();
3182
- const realRoot = real(root);
3183
- const rel = (abs) => path14.relative(realRoot, abs).split(path14.sep).join("/") || ".";
3184
- const via = /* @__PURE__ */ new Map();
3185
- const record = (real2, manifest, by, range, root2) => {
3186
- let copy = copies.get(real2);
3187
- if (!copy) {
3188
- copy = { name: manifest.name, version: String(manifest.version ?? "unknown"), dir: rel(real2), absolutePath: real2, requiredBy: [], devOnly: false, runtime: false };
3189
- copies.set(real2, copy);
3190
- via.set(real2, /* @__PURE__ */ new Set());
3433
+ const dir = path14.join(pkg.dir, "migrations");
3434
+ if (!existsSync(dir)) return;
3435
+ const seen = /* @__PURE__ */ new Map();
3436
+ for (const name of readdirSync(dir).sort()) {
3437
+ const m = MIGRATION_FILE.exec(name);
3438
+ if (!m) continue;
3439
+ const other = seen.get(m[1]);
3440
+ 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` });
3441
+ else seen.set(m[1], name);
3442
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path14.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
3443
+ 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")})` });
3191
3444
  }
3192
- via.get(real2).add(root2);
3193
- if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
3445
+ }
3446
+ }
3447
+ function checkExports(ctx, pkg, json) {
3448
+ const targets = [];
3449
+ const walk = (v) => {
3450
+ if (typeof v === "string") targets.push(v);
3451
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk(x);
3194
3452
  };
3195
- const walk = (kind, roots) => {
3196
- const expanded = /* @__PURE__ */ new Set();
3197
- const queue = [];
3198
- const visit = (dir, by, range) => {
3199
- const manifest = readManifest(dir);
3200
- if (!manifest?.name) return;
3201
- if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
3202
- const realDir = real(dir);
3203
- if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
3204
- if (expanded.has(realDir)) return;
3205
- expanded.add(realDir);
3206
- queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
3207
- };
3208
- for (const r of roots) visit(r.dir, r.by, r.range);
3209
- while (queue.length) {
3210
- const { real: from, manifest, label } = queue.shift();
3211
- const deps = { ...manifest.optionalDependencies, ...manifest.dependencies };
3212
- for (const [name, range] of Object.entries(deps)) {
3213
- const dir = findPackageDir(from, name);
3214
- if (dir) visit(dir, label, range);
3215
- }
3216
- for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
3217
- if (name in deps) continue;
3218
- const dir = peerOf(from, name);
3219
- if (dir) visit(dir, label, range);
3220
- }
3453
+ walk(json.exports);
3454
+ for (const t of targets) {
3455
+ if (!t.startsWith("./") || t.includes("*") || /^\.\/(dist|build)\//.test(t)) continue;
3456
+ if (!existsSync(path14.join(pkg.dir, t))) {
3457
+ ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
3221
3458
  }
3222
- };
3223
- const peerOf = (from, name) => {
3224
- const dir = findPackageDir(from, name);
3225
- if (!dir) return null;
3226
- if (!ownInstall || name in declared) return dir;
3227
- const realDir = real(dir);
3228
- if (realDir.startsWith(realRoot + path14.sep)) return dir;
3229
- return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
3230
- };
3231
- const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
3232
- const dir = findPackageDir(root, name);
3233
- return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
3234
- });
3235
- const app = readManifest(root);
3236
- const ownInstall = LOCKFILES.some((f) => existsSync(path14.join(root, f)));
3237
- const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
3238
- const declaredDev = Object.entries(app?.devDependencies ?? {});
3239
- const runtimeDeps = {
3240
- ...Object.fromEntries(declaredDev.filter(([n]) => !NON_SHIPPING.test(n))),
3241
- ...app?.peerDependencies,
3242
- ...app?.optionalDependencies,
3243
- ...app?.dependencies
3244
- };
3245
- const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
3246
- walk("runtime", rootsOf(runtimeDeps, "the app"));
3247
- const top = path14.join(root, "node_modules");
3248
- walk(
3249
- "hoisted",
3250
- packagesIn(top).filter((dir) => {
3251
- const name = path14.relative(top, dir).split(path14.sep).join("/");
3252
- return !(name in runtimeDeps) && !(name in devDeps);
3253
- }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
3459
+ }
3460
+ }
3461
+ function checkBlocks(ctx, pkg, json) {
3462
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
3463
+ try {
3464
+ parseManifest(json.name, id, raw, json.version, { local: true });
3465
+ } catch (err) {
3466
+ if (!(err instanceof ManifestError)) throw err;
3467
+ for (const problem of err.problems) ctx.report({ rule: "package-block-invalid", file: `${pkg.rel}/package.json`, subject: id, message: problem });
3468
+ }
3469
+ }
3470
+ }
3471
+ function checkTaggedTests(ctx, pkg) {
3472
+ const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
3473
+ if (!tests.length) return;
3474
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path14.join(pkg.dir, f), "utf8")));
3475
+ 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>` });
3476
+ }
3477
+ function checkRegistered(ctx, pkg) {
3478
+ const file = path14.join(ctx.root, "features.json");
3479
+ if (!existsSync(file)) return;
3480
+ let doc;
3481
+ try {
3482
+ doc = JSON.parse(readFileSync(file, "utf8"));
3483
+ } catch {
3484
+ return;
3485
+ }
3486
+ const covered = (doc.features ?? []).some(
3487
+ (f) => (f.links?.code ?? []).some((c) => {
3488
+ const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
3489
+ return norm === pkg.rel || norm.startsWith(`${pkg.rel}/`) || pkg.rel.startsWith(`${norm}/`);
3490
+ })
3254
3491
  );
3255
- const devRoots = { ...devDeps };
3256
- for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
3257
- walk("dev", rootsOf(devRoots, "the app (dev)"));
3258
- for (const [key2, copy] of copies) {
3259
- const kinds = via.get(key2);
3260
- copy.runtime = kinds.has("runtime");
3261
- copy.devOnly = kinds.size === 1 && kinds.has("dev");
3492
+ if (!covered) {
3493
+ 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` });
3262
3494
  }
3263
- const byName = /* @__PURE__ */ new Map();
3264
- for (const copy of copies.values()) byName.set(copy.name, [...byName.get(copy.name) ?? [], copy]);
3265
- for (const list of byName.values()) list.sort((a, b) => a.dir.split("/").length - b.dir.split("/").length || a.dir.localeCompare(b.dir));
3266
- return byName;
3267
3495
  }
3268
- function checkDuplicatePackages(ctx) {
3269
- const describe = (c) => `${c.version} at ${c.dir} (${c.requiredBy.map((r) => `${r.by}${r.range ? ` wants ${r.range}` : ""}`).join("; ")})`;
3270
- for (const [name, copies] of genesisInstalls(ctx.root)) {
3271
- if (copies.length < 2) continue;
3272
- const shipping = copies.filter((c) => c.runtime);
3273
- if (!(shipping.length === 1 && copies.every((c) => c === shipping[0] || c.devOnly))) {
3274
- ctx.report({
3275
- rule: "duplicate-genesis-package",
3276
- level: "warn",
3277
- file: "package.json",
3278
- subject: name,
3279
- 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`
3280
- });
3281
- continue;
3496
+ function changesetNames(text) {
3497
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
3498
+ const names = /* @__PURE__ */ new Set();
3499
+ if (!m) return names;
3500
+ for (const line of m[1].split(/\r?\n/)) {
3501
+ const entry = /^\s*(?:"([^"]+)"|'([^']+)'|([^\s:'"]+))\s*:\s*(major|minor|patch)\s*$/.exec(line);
3502
+ if (entry) names.add(entry[1] ?? entry[2] ?? entry[3]);
3503
+ }
3504
+ return names;
3505
+ }
3506
+ function mergeBaseOf(root, base) {
3507
+ if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository" };
3508
+ if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) return { reason: `the git ref ${base} isn't available (fetch it)` };
3509
+ const sha = git(root, ["merge-base", "HEAD", base])?.trim();
3510
+ return sha ? { sha } : { reason: `HEAD has no merge base with ${base} (fetch with depth 0)` };
3511
+ }
3512
+ function checkChanges(ctx, pkg, json, base, mergeBase) {
3513
+ const diff = git(ctx.root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", pkg.rel]) ?? "";
3514
+ const untracked = (git(ctx.root, ["ls-files", "--others", "--exclude-standard", "--", pkg.rel]) ?? "").split("\n").filter(Boolean);
3515
+ const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
3516
+ (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
3517
+ );
3518
+ for (const row of diff.split("\n").filter(Boolean)) {
3519
+ const [status, a] = row.split(" ");
3520
+ if (a && /\/migrations\/\d{4}_[a-z0-9_]+\.sql$/.test(a) && /^[MDRT]/.test(status)) {
3521
+ 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` });
3282
3522
  }
3523
+ }
3524
+ if (!changed.length) return;
3525
+ const before = git(ctx.root, ["show", `${mergeBase}:./${pkg.rel}/package.json`]);
3526
+ let versionBefore;
3527
+ try {
3528
+ versionBefore = before ? JSON.parse(before).version : void 0;
3529
+ } catch {
3530
+ versionBefore = void 0;
3531
+ }
3532
+ const now = typeof json.version === "string" ? parseVersion(json.version) : null;
3533
+ const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
3534
+ const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
3535
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3536
+ 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) => path14.join(top, f)) : [];
3537
+ const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
3538
+ const named = naming.length > 0;
3539
+ if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
3540
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: path14.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
3541
+ }
3542
+ let jsonBefore = null;
3543
+ try {
3544
+ jsonBefore = before ? JSON.parse(before) : null;
3545
+ } catch {
3546
+ jsonBefore = null;
3547
+ }
3548
+ const raw = json;
3549
+ if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
3550
+ const registry = (git(ctx.root, ["diff", "--relative", "--name-only", mergeBase, "--", "features.ts", "src/features.ts"]) ?? "").trim();
3551
+ 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` });
3552
+ }
3553
+ if (!bumped && !named) {
3283
3554
  ctx.report({
3284
- rule: "duplicate-genesis-package",
3285
- level: "info",
3286
- file: "package.json",
3287
- subject: name,
3288
- 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`
3555
+ rule: "package-unversioned-change",
3556
+ level: "warn",
3557
+ file: `${pkg.rel}/package.json`,
3558
+ 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`
3289
3559
  });
3290
3560
  }
3291
3561
  }
3292
- function checkPeerRanges(ctx) {
3293
- const rel = (abs) => path14.relative(ctx.root, abs).split(path14.sep).join("/");
3294
- for (const copies of genesisInstalls(ctx.root).values()) {
3295
- for (const copy of copies) {
3296
- const dir = copy.absolutePath;
3297
- const peers = readManifest(dir)?.peerDependencies ?? {};
3298
- for (const [peer, range] of Object.entries(peers)) {
3299
- if (!GENESIS.test(peer)) continue;
3300
- const peerDir = findPackageDir(dir, peer);
3301
- const installed = peerDir && readManifest(peerDir)?.version;
3302
- if (!peerDir || !installed) continue;
3303
- if (satisfies(installed, range) !== false) continue;
3304
- ctx.report({
3305
- rule: "peer-range-mismatch",
3306
- // A dev tool's own tree (the CLI's) doesn't run in the app.
3307
- level: copy.devOnly ? "info" : "warn",
3308
- file: "package.json",
3309
- subject: `${copy.name}>${peer}`,
3310
- 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}`
3311
- });
3312
- }
3313
- }
3562
+ function checkPackagesPack(ctx) {
3563
+ let packages;
3564
+ try {
3565
+ packages = localPackages(ctx.root);
3566
+ } catch (err) {
3567
+ ctx.report({ rule: "package-block-invalid", file: "genesis.config.json", message: err.message });
3568
+ return;
3569
+ }
3570
+ if (!packages.length) return;
3571
+ const base = ctx.base ?? ctx.config.packages?.base;
3572
+ const merge = base ? mergeBaseOf(ctx.root, base) : { reason: "no base ref (pass --base <ref>, e.g. --base origin/main)" };
3573
+ if ("reason" in merge) {
3574
+ ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
3575
+ }
3576
+ for (const pkg of packages) {
3577
+ const json = JSON.parse(readFileSync(path14.join(pkg.dir, "package.json"), "utf8"));
3578
+ checkImports2(ctx, pkg, json);
3579
+ checkExports(ctx, pkg, json);
3580
+ checkBlocks(ctx, pkg, json);
3581
+ checkMigrations(ctx, pkg, json);
3582
+ checkTaggedTests(ctx, pkg);
3583
+ checkRegistered(ctx, pkg);
3584
+ if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
3314
3585
  }
3315
3586
  }
3316
- var TRAIL_DEPTH = 6;
3317
- var RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
3318
- var IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
3319
- var EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
3320
- var DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
3321
- function stripForImports(code) {
3587
+ var DEFAULT_MIGRATIONS = "supabase/migrations";
3588
+ var DEFAULT_BASE = "origin/main";
3589
+ var DEFAULT_EXPOSED = ["public"];
3590
+ function sqlStatements(text) {
3322
3591
  const out = [];
3323
- const blank = (ch) => ch === "\n" ? "\n" : " ";
3324
- const n = code.length;
3325
- const templates = [];
3326
- let depth = 0;
3327
- let i = 0;
3328
- let sure = true;
3329
- const isSpecifier = () => /(?:\bfrom|(?:^|[;{}\n])\s*import|\bimport\s*\(|\brequire\s*\()\s*$/.test(out.slice(-40).join(""));
3330
- const before = () => out.slice(-24).join("");
3331
- const KEYWORD = /(?:^|[^\w$.])(?:return|typeof|instanceof|case|do|else|in|of|new|delete|void|throw|yield|await|from|import|export|default|require)\s*$/;
3332
- const startsExpression = (b) => {
3333
- const t = b.replace(/\s+$/, "");
3334
- if (!t) return true;
3335
- if (KEYWORD.test(b)) return true;
3336
- return /[([{,;:=!&|?+\-*%<>~^}]$/.test(t);
3592
+ let buf = "";
3593
+ let bodies = [];
3594
+ let line = 1;
3595
+ let start = 0;
3596
+ const flush = () => {
3597
+ const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
3598
+ if (sql) out.push({ sql, line: start, bodies });
3599
+ buf = "";
3600
+ bodies = [];
3601
+ start = 0;
3337
3602
  };
3338
- const exprStart = () => startsExpression(before());
3339
- const taggedTemplate = () => {
3340
- const b = out.slice(-48).join("");
3341
- const m = /([A-Za-z_$][\w$.]*)$/.exec(b);
3342
- return m !== null && startsExpression(b.slice(0, b.length - m[1].length));
3603
+ const put = (s) => {
3604
+ if (!start && /\S/.test(s)) start = line;
3605
+ buf += s;
3343
3606
  };
3344
- const templateBody = () => {
3345
- while (i < n) {
3346
- const ch = code[i];
3347
- if (ch === "\\") {
3348
- out.push(" ", blank(code[i + 1] ?? ""));
3349
- i += 2;
3350
- } else if (ch === "`") {
3351
- out.push("`");
3352
- i++;
3353
- return;
3354
- } else if (ch === "$" && code[i + 1] === "{") {
3355
- out.push("${");
3356
- i += 2;
3357
- templates.push(depth);
3358
- depth++;
3359
- return;
3360
- } else {
3361
- out.push(blank(ch));
3362
- i++;
3363
- }
3364
- }
3365
- sure = false;
3366
- };
3367
- while (i < n && sure) {
3368
- const ch = code[i];
3369
- const next = code[i + 1];
3370
- if (ch === "/" && next === "/") {
3371
- while (i < n && code[i] !== "\n") {
3372
- out.push(" ");
3373
- i++;
3374
- }
3375
- } else if (ch === "/" && next === "*") {
3376
- out.push(" ");
3377
- i += 2;
3378
- while (i < n && !(code[i] === "*" && code[i + 1] === "/")) {
3379
- out.push(blank(code[i]));
3380
- i++;
3381
- }
3382
- if (i < n) {
3383
- out.push(" ");
3384
- i += 2;
3385
- }
3386
- } else if (ch === "/" && next !== ">" && code[i - 1] !== "<" && exprStart()) {
3387
- const afterBrace = /[}>]\s*$/.test(before());
3388
- const start = i;
3389
- const mark = out.length;
3390
- out.push("/");
3607
+ let i = 0;
3608
+ while (i < text.length) {
3609
+ const ch = text[i];
3610
+ const two = text.slice(i, i + 2);
3611
+ if (ch === "\n") {
3612
+ buf += " ";
3613
+ line++;
3391
3614
  i++;
3392
- let inClass = false;
3393
- for (; ; ) {
3394
- const c = code[i];
3395
- if (c === void 0 || c === "\n") {
3396
- if (afterBrace) {
3397
- out.length = mark;
3398
- out.push("/");
3399
- i = start + 1;
3400
- } else sure = false;
3401
- break;
3402
- }
3403
- if (c === "\\") {
3404
- out.push(" ", blank(code[i + 1] ?? ""));
3615
+ } else if (two === "--") {
3616
+ while (i < text.length && text[i] !== "\n") i++;
3617
+ } else if (two === "/*") {
3618
+ let depth = 0;
3619
+ while (i < text.length) {
3620
+ if (text.startsWith("/*", i)) {
3621
+ depth++;
3405
3622
  i += 2;
3406
- continue;
3407
- }
3408
- i++;
3409
- if (c === "[") inClass = true;
3410
- else if (c === "]") inClass = false;
3411
- else if (c === "/" && !inClass) {
3412
- if (afterBrace && /[<>]/.test(code.slice(start + 1, i - 1))) {
3413
- out.length = mark;
3414
- out.push("/");
3415
- i = start + 1;
3416
- break;
3417
- }
3418
- out.push("/");
3419
- break;
3420
- }
3421
- out.push(" ");
3422
- }
3423
- if (out.length > mark + 1 || i > start + 1) while (i < n && /[a-z]/.test(code[i])) out.push(code[i++]);
3424
- } else if ((ch === '"' || ch === "'") && exprStart()) {
3425
- const keep = isSpecifier();
3426
- out.push(ch);
3427
- i++;
3428
- while (i < n && code[i] !== ch && code[i] !== "\n") {
3429
- if (code[i] === "\\") {
3430
- out.push(keep ? code[i] : " ", keep ? code[i + 1] ?? "" : blank(code[i + 1] ?? ""));
3623
+ } else if (text.startsWith("*/", i)) {
3624
+ depth--;
3431
3625
  i += 2;
3626
+ if (depth === 0) break;
3432
3627
  } else {
3433
- out.push(keep ? code[i] : blank(code[i]));
3628
+ if (text[i] === "\n") line++;
3434
3629
  i++;
3435
3630
  }
3436
3631
  }
3437
- if (code[i] !== ch) sure = false;
3438
- else {
3439
- out.push(code[i]);
3440
- i++;
3632
+ buf += " ";
3633
+ } else if (ch === "'") {
3634
+ const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
3635
+ put("'");
3636
+ i++;
3637
+ while (i < text.length) {
3638
+ if (escapes && text[i] === "\\") i += 2;
3639
+ else if (text[i] === "'" && text[i + 1] === "'") i += 2;
3640
+ else if (text[i] === "'") break;
3641
+ else {
3642
+ if (text[i] === "\n") line++;
3643
+ i++;
3644
+ }
3441
3645
  }
3442
- } else if (ch === "`" && (exprStart() || taggedTemplate())) {
3443
- out.push("`");
3646
+ put("'");
3444
3647
  i++;
3445
- templateBody();
3446
- } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
3447
- templates.pop();
3448
- depth--;
3449
- out.push("}");
3648
+ } else if (ch === '"') {
3649
+ i++;
3650
+ while (i < text.length && text[i] !== '"') put(text[i++]);
3651
+ i++;
3652
+ } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
3653
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
3654
+ const end = text.indexOf(tag, i + tag.length);
3655
+ const stop = end === -1 ? text.length : end + tag.length;
3656
+ bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
3657
+ for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
3658
+ put(`${tag} ${tag}`);
3659
+ i = stop;
3660
+ } else if (ch === ";") {
3661
+ flush();
3450
3662
  i++;
3451
- templateBody();
3452
3663
  } else {
3453
- if (ch === "{") depth++;
3454
- else if (ch === "}") depth--;
3455
- out.push(ch);
3664
+ put(ch);
3456
3665
  i++;
3457
3666
  }
3458
3667
  }
3459
- return sure && templates.length === 0 ? out.join("") : null;
3460
- }
3461
- function bindings(clause) {
3462
- const out = [];
3463
- const named = /\{([^}]*)\}/.exec(clause);
3464
- for (const part of named?.[1].split(",") ?? []) {
3465
- const p = part.trim();
3466
- if (!p || p.startsWith("type ")) continue;
3467
- out.push(p.split(/\s+as\s+/).pop().trim());
3468
- }
3469
- const rest = clause.replace(/\{[^}]*\}/, "");
3470
- const ns = /\*\s*as\s+([\w$]+)/.exec(rest);
3471
- if (ns) out.push(ns[1]);
3472
- const def = /^\s*([\w$]+)/.exec(rest);
3473
- if (def && def[1] !== "as") out.push(def[1]);
3668
+ flush();
3474
3669
  return out;
3475
3670
  }
3476
- function readJsonc(file) {
3477
- try {
3478
- const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? "").replace(/,(\s*[}\]])/g, "$1");
3479
- return JSON.parse(text);
3480
- } catch {
3481
- return null;
3482
- }
3671
+ function qualify(name) {
3672
+ const n = name.trim().toLowerCase();
3673
+ return n.includes(".") ? n : `public.${n}`;
3483
3674
  }
3484
- function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3485
- if (seen.has(file) || seen.size > 10) return {};
3486
- seen.add(file);
3487
- const json = readJsonc(file);
3488
- if (!json) return {};
3489
- const dir = path14.dirname(file);
3490
- let merged = {};
3491
- const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
3492
- for (const ext of parents) {
3493
- if (typeof ext !== "string") continue;
3494
- let target = null;
3495
- if (ext.startsWith(".") || path14.isAbsolute(ext)) {
3496
- const abs = path14.resolve(dir, ext);
3497
- target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3498
- } else {
3499
- const parts = ext.split("/");
3500
- const nameLength = ext.startsWith("@") ? 2 : 1;
3501
- const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
3502
- if (pkgDir) {
3503
- const sub = parts.slice(nameLength).join("/");
3504
- const abs = path14.join(pkgDir, sub || "tsconfig.json");
3505
- target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3506
- }
3507
- }
3508
- if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
3509
- }
3510
- const opts = json.compilerOptions ?? {};
3511
- if (typeof opts.baseUrl === "string") merged.baseUrl = path14.resolve(dir, opts.baseUrl);
3512
- if (opts.paths && typeof opts.paths === "object") {
3513
- merged.paths = opts.paths;
3514
- merged.pathsDir = dir;
3675
+ var schemaOf = (name) => name.split(".")[0];
3676
+ function parenthesized(sql, open) {
3677
+ let depth = 0;
3678
+ for (let k = open; k < sql.length; k++) {
3679
+ if (sql[k] === "(") depth++;
3680
+ else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
3515
3681
  }
3516
- return merged;
3682
+ return { inner: sql.slice(open + 1), end: sql.length };
3517
3683
  }
3518
- function aliases(root) {
3519
- const table = [];
3520
- let baseUrl = null;
3521
- for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
3522
- const file = path14.join(root, name);
3523
- if (!existsSync(file)) continue;
3524
- const config = readTsconfig(root, file);
3525
- baseUrl ??= config.baseUrl ?? null;
3526
- const base = config.baseUrl ?? config.pathsDir ?? root;
3527
- for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
3528
- if (!Array.isArray(targets)) continue;
3529
- const exact = !pattern.endsWith("*");
3530
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path14.join(base, String(t).replace(/\*$/, ""))) });
3531
- }
3684
+ function stripParens(s) {
3685
+ let out = "";
3686
+ let depth = 0;
3687
+ for (const c of s) {
3688
+ if (c === "(") depth++;
3689
+ else if (c === ")") depth = Math.max(0, depth - 1);
3690
+ else if (depth === 0) out += c;
3532
3691
  }
3533
- const pkg = readJsonc(path14.join(root, "package.json"));
3534
- for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
3535
- if (typeof target !== "string") continue;
3536
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path14.join(root, target.replace(/\*.*$/, ""))] });
3692
+ return out;
3693
+ }
3694
+ function splitTop(s) {
3695
+ const parts = [];
3696
+ let depth = 0;
3697
+ let cur = "";
3698
+ for (const c of s) {
3699
+ if (c === "(") depth++;
3700
+ if (c === ")") depth--;
3701
+ if (c === "," && depth === 0) {
3702
+ parts.push(cur);
3703
+ cur = "";
3704
+ } else cur += c;
3537
3705
  }
3538
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
3539
- return { table, baseUrl };
3706
+ if (cur.trim()) parts.push(cur);
3707
+ return parts.map((p) => p.trim()).filter(Boolean);
3540
3708
  }
3541
- function resolveFile(base) {
3542
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path14.join(base, `index${e}`))];
3543
- if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
3544
- for (const p of tries) {
3545
- if (SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
3709
+ var TYPE_ALIASES = {
3710
+ int: "integer",
3711
+ int4: "integer",
3712
+ int8: "bigint",
3713
+ int2: "smallint",
3714
+ bool: "boolean",
3715
+ varchar: "character varying",
3716
+ timestamptz: "timestamp with time zone",
3717
+ float8: "double precision"
3718
+ };
3719
+ var MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
3720
+ function argTypes(args) {
3721
+ const types = [];
3722
+ for (const raw of splitTop(args)) {
3723
+ let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
3724
+ const mode = tokens[0];
3725
+ if (mode === "out") continue;
3726
+ if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
3727
+ const joined = tokens.join(" ");
3728
+ const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
3729
+ types.push(TYPE_ALIASES[type] ?? type);
3546
3730
  }
3547
- return null;
3731
+ return types;
3548
3732
  }
3549
- var trails = /* @__PURE__ */ new WeakMap();
3550
- function trailFor(ctx) {
3551
- let t = trails.get(ctx.files);
3552
- if (!t) trails.set(ctx.files, t = createTrail(ctx));
3553
- return t;
3733
+ function git2(root, args) {
3734
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3735
+ return r.status === 0 ? r.stdout : null;
3554
3736
  }
3555
- function createTrail(ctx) {
3556
- const { table, baseUrl } = aliases(ctx.root);
3557
- let declared = null;
3737
+ function gitView(root, dir, base) {
3738
+ if (git2(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
3739
+ if (git2(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
3740
+ return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
3741
+ }
3742
+ const mergeBase = git2(root, ["merge-base", "HEAD", base])?.trim();
3743
+ if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
3744
+ const diff = git2(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
3745
+ const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
3746
+ if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
3747
+ const sql = (p) => p !== void 0 && p.endsWith(".sql");
3748
+ const touched = new Set(untracked.split("\n").filter(sql));
3749
+ const edited = [];
3750
+ for (const row of diff.split("\n").filter(Boolean)) {
3751
+ const [status, a, b] = row.split(" ");
3752
+ if (status.startsWith("R")) {
3753
+ if (sql(b)) touched.add(b);
3754
+ if (sql(a)) edited.push({ file: a, status: "renamed" });
3755
+ continue;
3756
+ }
3757
+ if (!sql(a)) continue;
3758
+ if (status.startsWith("A")) touched.add(a);
3759
+ else if (status.startsWith("M") || status.startsWith("T")) {
3760
+ touched.add(a);
3761
+ edited.push({ file: a, status: "modified" });
3762
+ } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
3763
+ }
3764
+ return { touched, edited };
3765
+ }
3766
+ function checkSupabasePack(ctx) {
3767
+ const settings = ctx.config.supabase ?? {};
3768
+ const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
3769
+ const abs = path14.join(ctx.root, dir);
3770
+ if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
3771
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path14.join(abs, n), "utf8")) }));
3772
+ const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
3773
+ const base = settings.base ?? DEFAULT_BASE;
3774
+ const view = gitView(ctx.root, dir, base);
3775
+ if ("reason" in view) {
3776
+ if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
3777
+ } else {
3778
+ for (const e of view.edited) {
3779
+ ctx.report({
3780
+ rule: "migration-edited",
3781
+ file: e.file,
3782
+ subject: e.file,
3783
+ 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`
3784
+ });
3785
+ }
3786
+ }
3787
+ const since = settings.since;
3788
+ const afterSince = (file) => since === void 0 || path14.posix.basename(file) >= since;
3789
+ if ("reason" in view && since === void 0) {
3790
+ ctx.report({
3791
+ rule: "migration-grants",
3792
+ level: "warn",
3793
+ file: dir,
3794
+ 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`
3795
+ });
3796
+ } else {
3797
+ const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
3798
+ checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
3799
+ }
3800
+ checkRls(ctx, migrations, exposed);
3801
+ checkViewInvoker(ctx, migrations, exposed);
3802
+ checkDefinerSearchPath(ctx, migrations);
3803
+ checkTestingKit(ctx, migrations);
3804
+ }
3805
+ function checkTestingKit(ctx, migrations) {
3806
+ for (const { file, statements } of migrations) {
3807
+ const hit = statements.find(({ sql }) => /\bgenesis_testing\b/.test(sql));
3808
+ if (!hit) continue;
3809
+ ctx.report({
3810
+ rule: "migration-testing-kit",
3811
+ file,
3812
+ line: hit.line,
3813
+ subject: "genesis_testing",
3814
+ message: "a migration uses genesis_testing, the pgTAP kit for test databases only; move it to supabase/tests/database/000_genesis_testing.test.sql"
3815
+ });
3816
+ }
3817
+ }
3818
+ function granteesOf(s) {
3819
+ return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
3820
+ }
3821
+ function checkGrants(ctx, migrations, exposed) {
3822
+ const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
3823
+ const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
3824
+ const blanket = (roles) => {
3825
+ const o = open(roles);
3826
+ if (o.length) return { level: "error", who: o.join(" and ") };
3827
+ if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
3828
+ return null;
3829
+ };
3830
+ for (const { file, statements } of migrations) {
3831
+ for (const { sql, line } of statements) {
3832
+ const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
3833
+ if (all) {
3834
+ const hit = blanket(granteesOf(all[1]));
3835
+ if (hit) {
3836
+ 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}` });
3837
+ }
3838
+ continue;
3839
+ }
3840
+ const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
3841
+ if (defaults) {
3842
+ const hit = blanket(granteesOf(defaults[1]));
3843
+ if (hit) {
3844
+ 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}` });
3845
+ }
3846
+ continue;
3847
+ }
3848
+ const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
3849
+ if (fn) {
3850
+ const roles = open(granteesOf(fn[2]));
3851
+ if (!roles.length) continue;
3852
+ for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
3853
+ if (exposed.has(schemaOf(name))) continue;
3854
+ ctx.report({
3855
+ rule: "migration-grants",
3856
+ file,
3857
+ line,
3858
+ subject: name,
3859
+ 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)`
3860
+ });
3861
+ }
3862
+ continue;
3863
+ }
3864
+ const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
3865
+ if (schema) {
3866
+ const roles = open(granteesOf(schema[2]));
3867
+ if (!roles.length) continue;
3868
+ for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
3869
+ if (exposed.has(s)) continue;
3870
+ ctx.report({
3871
+ rule: "migration-grants",
3872
+ file,
3873
+ line,
3874
+ subject: `schema ${s}`,
3875
+ message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
3876
+ });
3877
+ }
3878
+ }
3879
+ }
3880
+ }
3881
+ }
3882
+ function checkRls(ctx, migrations, exposed) {
3883
+ const tables = /* @__PURE__ */ new Map();
3884
+ const name = String.raw`([\w$.]+)`;
3885
+ const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
3886
+ for (const { file, statements } of migrations) {
3887
+ for (const { sql, line, bodies } of statements) {
3888
+ if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
3889
+ const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
3890
+ if (create) {
3891
+ if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
3892
+ continue;
3893
+ }
3894
+ const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
3895
+ const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
3896
+ if (rename || move) {
3897
+ const from = qualify((rename ?? move)[1]);
3898
+ const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
3899
+ const state = tables.get(from);
3900
+ if (state) {
3901
+ tables.delete(from);
3902
+ tables.set(to, state);
3903
+ }
3904
+ continue;
3905
+ }
3906
+ const alter = new RegExp(target).exec(sql);
3907
+ if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
3908
+ const t = qualify(alter[1]);
3909
+ if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
3910
+ else {
3911
+ const state = tables.get(t);
3912
+ if (state) state.rls = true;
3913
+ }
3914
+ continue;
3915
+ }
3916
+ const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3917
+ if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
3918
+ }
3919
+ }
3920
+ for (const [t, at] of tables) {
3921
+ if (at.rls || !exposed.has(schemaOf(t))) continue;
3922
+ ctx.report({
3923
+ rule: "migration-rls",
3924
+ file: at.file,
3925
+ line: at.line,
3926
+ subject: t,
3927
+ 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`
3928
+ });
3929
+ }
3930
+ }
3931
+ function checkViewInvoker(ctx, migrations, exposed) {
3932
+ const views = /* @__PURE__ */ new Map();
3933
+ const name = String.raw`([\w$.]+)`;
3934
+ const invokerOn = /\bsecurity_invoker\s*(?:=\s*(?:true|on|yes|1|'true'|'on'))?\s*(?:,|\))/;
3935
+ for (const { file, statements } of migrations) {
3936
+ for (const { sql, line } of statements) {
3937
+ const create = new RegExp(String.raw`^create (?:or replace )?(?:temp |temporary )?(?:recursive )?view ${name}`).exec(sql);
3938
+ if (create) {
3939
+ if (/^create (?:or replace )?(?:temp|temporary) /.test(sql)) continue;
3940
+ const options = /^[^(]*?\bwith\s*(\([^)]*\))\s*as\b/.exec(sql)?.[1] ?? "";
3941
+ views.set(qualify(create[1]), { invoker: invokerOn.test(options), file, line });
3942
+ continue;
3943
+ }
3944
+ const alter = new RegExp(String.raw`^alter view (?:if exists )?${name} (set|reset) (\([^)]*\))`).exec(sql);
3945
+ if (alter && /\bsecurity_invoker\b/.test(alter[3])) {
3946
+ const state = views.get(qualify(alter[1]));
3947
+ if (state) state.invoker = alter[2] === "set" && invokerOn.test(alter[3]);
3948
+ continue;
3949
+ }
3950
+ const rename = new RegExp(String.raw`^alter view (?:if exists )?${name} rename to ([\w$]+)$`).exec(sql);
3951
+ if (rename) {
3952
+ const from = qualify(rename[1]);
3953
+ const state = views.get(from);
3954
+ if (state) {
3955
+ views.delete(from);
3956
+ views.set(`${schemaOf(from)}.${rename[2]}`, state);
3957
+ }
3958
+ continue;
3959
+ }
3960
+ const drop = /^drop view (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3961
+ if (drop) for (const n of drop[1].split(",")) views.delete(qualify(n));
3962
+ }
3963
+ }
3964
+ for (const [v, at] of views) {
3965
+ if (at.invoker || !exposed.has(schemaOf(v))) continue;
3966
+ ctx.report({
3967
+ rule: "migration-view-rls",
3968
+ file: at.file,
3969
+ line: at.line,
3970
+ subject: v,
3971
+ 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);"`
3972
+ });
3973
+ }
3974
+ }
3975
+ function checkDefinerSearchPath(ctx, migrations) {
3976
+ const fns = /* @__PURE__ */ new Map();
3977
+ const keysFor = (sql, nameEnd, fnName) => {
3978
+ const rest = sql.slice(nameEnd).trimStart();
3979
+ if (rest.startsWith("(")) {
3980
+ const { inner } = parenthesized(rest, 0);
3981
+ return [`${fnName}(${argTypes(inner).join(",")})`];
3982
+ }
3983
+ return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
3984
+ };
3985
+ for (const { file, statements } of migrations) {
3986
+ for (const { sql, line } of statements) {
3987
+ const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
3988
+ if (create) {
3989
+ const [key2] = keysFor(sql, create[0].length, qualify(create[1]));
3990
+ fns.set(key2, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
3991
+ continue;
3992
+ }
3993
+ const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
3994
+ if (alter) {
3995
+ const fnName = qualify(alter[1]);
3996
+ const keys = keysFor(sql, alter[0].length, fnName);
3997
+ const rename = / rename to ([\w$]+)$/.exec(sql);
3998
+ const move = / set schema ([\w$]+)$/.exec(sql);
3999
+ for (const key2 of keys) {
4000
+ const state = fns.get(key2);
4001
+ if (rename || move) {
4002
+ if (!state) continue;
4003
+ fns.delete(key2);
4004
+ const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
4005
+ fns.set(newName + key2.slice(fnName.length), state);
4006
+ continue;
4007
+ }
4008
+ const next = state ?? { definer: false, searchPath: false, file, line };
4009
+ if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
4010
+ if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
4011
+ if (/\bset search_path\b/.test(sql)) next.searchPath = true;
4012
+ if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
4013
+ fns.set(key2, next);
4014
+ }
4015
+ continue;
4016
+ }
4017
+ const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
4018
+ if (drop) {
4019
+ for (const part of splitTop(drop[1])) {
4020
+ const m = /^([\w$.]+)\s*/.exec(part);
4021
+ if (m) for (const key2 of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key2);
4022
+ }
4023
+ }
4024
+ }
4025
+ }
4026
+ for (const [key2, at] of fns) {
4027
+ if (!at.definer || at.searchPath) continue;
4028
+ ctx.report({
4029
+ rule: "migration-definer-search-path",
4030
+ file: at.file,
4031
+ line: at.line,
4032
+ subject: key2,
4033
+ 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`
4034
+ });
4035
+ }
4036
+ }
4037
+ var UMBRELLA_PACKAGE = "@marktiderman/genesis";
4038
+ function readReleaseManifest(root) {
4039
+ const dir = findPackageDir(root, UMBRELLA_PACKAGE);
4040
+ const file = dir && path14.join(dir, "dist", "versions.json");
4041
+ if (!file || !existsSync(file)) return null;
4042
+ return JSON.parse(readFileSync(file, "utf8"));
4043
+ }
4044
+ function checkVersionSkew(ctx) {
4045
+ const manifest = readReleaseManifest(ctx.root);
4046
+ if (!manifest) return;
4047
+ for (const [name, want] of Object.entries(manifest.packages)) {
4048
+ const dir = findPackageDir(ctx.root, name);
4049
+ if (!dir) continue;
4050
+ const have = JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8")).version;
4051
+ if (have === want) continue;
4052
+ ctx.report({
4053
+ rule: "version-skew",
4054
+ level: "warn",
4055
+ file: "package.json",
4056
+ subject: name,
4057
+ message: `${name} is ${have}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Install ${name}@${want}, or move every Genesis package to one release.`
4058
+ });
4059
+ }
4060
+ }
4061
+ var GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
4062
+ var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
4063
+ var 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)$/;
4064
+ var readManifest = (dir) => {
3558
4065
  try {
3559
- const pkg = JSON.parse(readFileSync(path14.join(ctx.root, "package.json"), "utf8"));
3560
- declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
4066
+ return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
3561
4067
  } catch {
3562
- declared = null;
4068
+ return null;
3563
4069
  }
3564
- const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
3565
- const read = (abs) => byPath.get(abs) ?? readSource(abs);
3566
- const importsCache = /* @__PURE__ */ new Map();
3567
- const importsOf = (file) => {
3568
- const hit = importsCache.get(file.absolutePath);
3569
- if (hit) return hit;
3570
- const files = [];
3571
- let lost = false;
3572
- const code = stripped(file);
3573
- if (code === null) {
3574
- const out2 = { files: [], lost: true };
3575
- importsCache.set(file.absolutePath, out2);
3576
- return out2;
4070
+ };
4071
+ var real = (p) => {
4072
+ try {
4073
+ return realpathSync(p);
4074
+ } catch {
4075
+ return p;
4076
+ }
4077
+ };
4078
+ var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
4079
+ function nodeModulesOf(dir) {
4080
+ const parent = path14.dirname(dir);
4081
+ return path14.basename(parent).startsWith("@") ? path14.dirname(parent) : parent;
4082
+ }
4083
+ function packagesIn(nodeModules) {
4084
+ if (!existsSync(nodeModules)) return [];
4085
+ const out = [];
4086
+ for (const entry of readdirSync(nodeModules)) {
4087
+ if (entry.startsWith(".")) continue;
4088
+ const p = path14.join(nodeModules, entry);
4089
+ if (entry.startsWith("@")) {
4090
+ try {
4091
+ for (const sub of readdirSync(p)) out.push(path14.join(p, sub));
4092
+ } catch {
4093
+ }
4094
+ } else {
4095
+ out.push(p);
3577
4096
  }
3578
- const used = new Set(renderedElements(code).map((e) => e.split(".")[0]));
3579
- for (const m of code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
3580
- for (const m of code.matchAll(/\bexport\s+default\s+([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
3581
- 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]);
3582
- const specs = [];
3583
- for (const m of code.matchAll(IMPORT_FROM)) if (!m[1] && bindings(m[2]).some((b) => used.has(b))) specs.push(m[3]);
3584
- for (const m of code.matchAll(EXPORT_FROM)) if (!m[1]) specs.push(m[2]);
3585
- for (const m of code.matchAll(DYNAMIC)) specs.push(m[1]);
3586
- for (const spec of specs) {
3587
- if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
3588
- let resolved = null;
3589
- if (spec.startsWith(".")) {
3590
- resolved = resolveFile(path14.resolve(path14.dirname(file.absolutePath), spec));
3591
- if (!resolved) lost = true;
3592
- } else {
3593
- const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
3594
- if (alias) {
3595
- for (const t of alias.targets) {
3596
- resolved = resolveFile(alias.exact ? t : path14.join(t, spec.slice(alias.prefix.length)));
3597
- if (resolved) break;
3598
- }
3599
- }
3600
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path14.join(baseUrl, spec));
3601
- if (!resolved) {
3602
- const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
3603
- if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
3604
- }
4097
+ }
4098
+ return out;
4099
+ }
4100
+ function genesisInstalls(root) {
4101
+ const copies = /* @__PURE__ */ new Map();
4102
+ const realRoot = real(root);
4103
+ const rel = (abs) => path14.relative(realRoot, abs).split(path14.sep).join("/") || ".";
4104
+ const via = /* @__PURE__ */ new Map();
4105
+ const record = (real2, manifest, by, range, root2) => {
4106
+ let copy = copies.get(real2);
4107
+ if (!copy) {
4108
+ copy = { name: manifest.name, version: String(manifest.version ?? "unknown"), dir: rel(real2), absolutePath: real2, requiredBy: [], devOnly: false, runtime: false };
4109
+ copies.set(real2, copy);
4110
+ via.set(real2, /* @__PURE__ */ new Set());
4111
+ }
4112
+ via.get(real2).add(root2);
4113
+ if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
4114
+ };
4115
+ const walk = (kind, roots) => {
4116
+ const expanded = /* @__PURE__ */ new Set();
4117
+ const queue = [];
4118
+ const visit = (dir, by, range) => {
4119
+ const manifest = readManifest(dir);
4120
+ if (!manifest?.name) return;
4121
+ if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
4122
+ const realDir = real(dir);
4123
+ if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
4124
+ if (expanded.has(realDir)) return;
4125
+ expanded.add(realDir);
4126
+ queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
4127
+ };
4128
+ for (const r of roots) visit(r.dir, r.by, r.range);
4129
+ while (queue.length) {
4130
+ const { real: from, manifest, label } = queue.shift();
4131
+ const deps = { ...manifest.optionalDependencies, ...manifest.dependencies };
4132
+ for (const [name, range] of Object.entries(deps)) {
4133
+ const dir = findPackageDir(from, name);
4134
+ if (dir) visit(dir, label, range);
4135
+ }
4136
+ for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
4137
+ if (name in deps) continue;
4138
+ const dir = peerOf(from, name);
4139
+ if (dir) visit(dir, label, range);
3605
4140
  }
3606
- if (resolved && !files.includes(resolved)) files.push(resolved);
3607
4141
  }
3608
- const out = { files, lost };
3609
- importsCache.set(file.absolutePath, out);
3610
- return out;
3611
4142
  };
3612
- const strippedCache = /* @__PURE__ */ new Map();
3613
- const stripped = (file) => {
3614
- if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
3615
- return strippedCache.get(file.absolutePath);
4143
+ const peerOf = (from, name) => {
4144
+ const dir = findPackageDir(from, name);
4145
+ if (!dir) return null;
4146
+ if (!ownInstall || name in declared) return dir;
4147
+ const realDir = real(dir);
4148
+ if (realDir.startsWith(realRoot + path14.sep)) return dir;
4149
+ return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
3616
4150
  };
3617
- const memo = /* @__PURE__ */ new WeakMap();
3618
- const reach = (file, test2, depth, seen) => {
3619
- let cache = memo.get(test2);
3620
- if (!cache) memo.set(test2, cache = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
3621
- const k = `${file.absolutePath}\0${depth}`;
3622
- const free = cache.free.get(k);
3623
- if (free) return [free, /* @__PURE__ */ new Set()];
3624
- const reusable = cache.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
3625
- if (reusable) return [reusable.result, new Set(reusable.cut)];
3626
- let result;
3627
- const cut = /* @__PURE__ */ new Set();
3628
- const code = stripped(file);
3629
- if (code === null) result = "unknown";
3630
- else if (test2(code)) result = "yes";
3631
- else {
3632
- const { files, lost } = importsOf(file);
3633
- let unknown = lost && depth > 0;
3634
- result = "no";
3635
- if (depth > 0) {
3636
- seen.add(file.absolutePath);
3637
- for (const abs of files) {
3638
- if (seen.has(abs)) {
3639
- cut.add(abs);
3640
- continue;
3641
- }
3642
- const target = read(abs);
3643
- if (!target) {
3644
- unknown = true;
3645
- continue;
3646
- }
3647
- const [r, c] = reach(target, test2, depth - 1, seen);
3648
- for (const m of c) cut.add(m);
3649
- if (r === "yes") {
3650
- result = "yes";
3651
- break;
3652
- }
3653
- if (r === "unknown") unknown = true;
3654
- }
3655
- seen.delete(file.absolutePath);
3656
- cut.delete(file.absolutePath);
3657
- }
3658
- if (result === "no" && unknown) result = "unknown";
4151
+ const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
4152
+ const dir = findPackageDir(root, name);
4153
+ return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
4154
+ });
4155
+ const app = readManifest(root);
4156
+ const ownInstall = LOCKFILES.some((f) => existsSync(path14.join(root, f)));
4157
+ const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
4158
+ const declaredDev = Object.entries(app?.devDependencies ?? {});
4159
+ const runtimeDeps = {
4160
+ ...Object.fromEntries(declaredDev.filter(([n]) => !NON_SHIPPING.test(n))),
4161
+ ...app?.peerDependencies,
4162
+ ...app?.optionalDependencies,
4163
+ ...app?.dependencies
4164
+ };
4165
+ const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
4166
+ walk("runtime", rootsOf(runtimeDeps, "the app"));
4167
+ const top = path14.join(root, "node_modules");
4168
+ walk(
4169
+ "hoisted",
4170
+ packagesIn(top).filter((dir) => {
4171
+ const name = path14.relative(top, dir).split(path14.sep).join("/");
4172
+ return !(name in runtimeDeps) && !(name in devDeps);
4173
+ }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
4174
+ );
4175
+ const devRoots = { ...devDeps };
4176
+ for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
4177
+ walk("dev", rootsOf(devRoots, "the app (dev)"));
4178
+ for (const [key2, copy] of copies) {
4179
+ const kinds = via.get(key2);
4180
+ copy.runtime = kinds.has("runtime");
4181
+ copy.devOnly = kinds.size === 1 && kinds.has("dev");
4182
+ }
4183
+ const byName = /* @__PURE__ */ new Map();
4184
+ for (const copy of copies.values()) byName.set(copy.name, [...byName.get(copy.name) ?? [], copy]);
4185
+ for (const list of byName.values()) list.sort((a, b) => a.dir.split("/").length - b.dir.split("/").length || a.dir.localeCompare(b.dir));
4186
+ return byName;
4187
+ }
4188
+ function checkDuplicatePackages(ctx) {
4189
+ const describe = (c) => `${c.version} at ${c.dir} (${c.requiredBy.map((r) => `${r.by}${r.range ? ` wants ${r.range}` : ""}`).join("; ")})`;
4190
+ for (const [name, copies] of genesisInstalls(ctx.root)) {
4191
+ if (copies.length < 2) continue;
4192
+ const shipping = copies.filter((c) => c.runtime);
4193
+ if (!(shipping.length === 1 && copies.every((c) => c === shipping[0] || c.devOnly))) {
4194
+ ctx.report({
4195
+ rule: "duplicate-genesis-package",
4196
+ level: "warn",
4197
+ file: "package.json",
4198
+ subject: name,
4199
+ 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`
4200
+ });
4201
+ continue;
3659
4202
  }
3660
- if (result === "yes" || cut.size === 0) {
3661
- cache.free.set(k, result);
3662
- return [result, /* @__PURE__ */ new Set()];
4203
+ ctx.report({
4204
+ rule: "duplicate-genesis-package",
4205
+ level: "info",
4206
+ file: "package.json",
4207
+ subject: name,
4208
+ 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`
4209
+ });
4210
+ }
4211
+ }
4212
+ function checkPeerRanges(ctx) {
4213
+ const rel = (abs) => path14.relative(ctx.root, abs).split(path14.sep).join("/");
4214
+ for (const copies of genesisInstalls(ctx.root).values()) {
4215
+ for (const copy of copies) {
4216
+ const dir = copy.absolutePath;
4217
+ const peers = readManifest(dir)?.peerDependencies ?? {};
4218
+ for (const [peer, range] of Object.entries(peers)) {
4219
+ if (!GENESIS.test(peer)) continue;
4220
+ const peerDir = findPackageDir(dir, peer);
4221
+ const installed = peerDir && readManifest(peerDir)?.version;
4222
+ if (!peerDir || !installed) continue;
4223
+ if (satisfies(installed, range) !== false) continue;
4224
+ ctx.report({
4225
+ rule: "peer-range-mismatch",
4226
+ // A dev tool's own tree (the CLI's) doesn't run in the app.
4227
+ level: copy.devOnly ? "info" : "warn",
4228
+ file: "package.json",
4229
+ subject: `${copy.name}>${peer}`,
4230
+ 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}`
4231
+ });
4232
+ }
3663
4233
  }
3664
- const entries = cache.cut.get(k) ?? [];
3665
- entries.push({ cut: [...cut], result });
3666
- cache.cut.set(k, entries);
3667
- return [result, cut];
3668
- };
3669
- return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
4234
+ }
3670
4235
  }
3671
-
3672
- // src/doctor/routes.ts
3673
4236
  var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
3674
4237
  var STEMS = {
3675
4238
  tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
@@ -3782,7 +4345,7 @@ var SUB_NAV_DOCS = "https://github.com/marktiderman/genesis/blob/main/packages/u
3782
4345
  var CONTAINER = /(?:Card|CardContent|Dialog|DialogContent|Sheet|SheetContent|Drawer|DrawerContent|Popover|PopoverContent|Modal|Accordion|AccordionContent|AccordionItem|Collapsible|CollapsibleContent|Tooltip|Menu|MenuContent|Panel|Table|TabsContent)$/;
3783
4346
  var SWITCHER = /<(TabsList|SubNavTabs)(?=[\s>/])/g;
3784
4347
  var SHELL = /<AppShell(?=[\s>/])/;
3785
- var GENESIS_PACKAGE = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
4348
+ var GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
3786
4349
  var PAGE_LAYOUT = /^(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)$/;
3787
4350
  var PACKAGE_SCREEN = /^(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)$/;
3788
4351
  var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
@@ -3838,7 +4401,7 @@ function checkLocalGenesisCopies(ctx) {
3838
4401
  const routes = routesDir(ctx);
3839
4402
  for (const file of ctx.files) {
3840
4403
  if (!JSX_EXTS2.has(file.ext)) continue;
3841
- const imported = new Set(namedImportsFrom(file.code, GENESIS_PACKAGE));
4404
+ const imported = new Set(namedImportsFrom(file.code, GENESIS_PACKAGE2));
3842
4405
  const inRoutes = routes !== null && file.path.startsWith(`${routes}/`);
3843
4406
  const routeComponents = new Set([...file.code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Z][\w$]*)\b/g)].map((r) => r[1]));
3844
4407
  const decls = [...file.code.matchAll(decl)];
@@ -3897,13 +4460,13 @@ function checkPageLayouts(ctx) {
3897
4460
  const inShell = insideShell(ctx, routes);
3898
4461
  const rendersLayout = (code) => {
3899
4462
  const names = new Set(layouts);
3900
- for (const n of namedImportsFrom(code, GENESIS_PACKAGE)) if (PACKAGE_SCREEN.test(n)) names.add(n);
4463
+ for (const n of namedImportsFrom(code, GENESIS_PACKAGE2)) if (PACKAGE_SCREEN.test(n)) names.add(n);
3901
4464
  return rendersRe(names)?.test(code) ?? false;
3902
4465
  };
3903
- const cache = /* @__PURE__ */ new Map();
4466
+ const cache2 = /* @__PURE__ */ new Map();
3904
4467
  const provides = (r) => {
3905
- if (!cache.has(r)) cache.set(r, routeReach(ctx, r, rendersLayout));
3906
- return cache.get(r);
4468
+ if (!cache2.has(r)) cache2.set(r, routeReach(ctx, r, rendersLayout));
4469
+ return cache2.get(r);
3907
4470
  };
3908
4471
  const list = [...layouts].sort();
3909
4472
  const named = list.length > 4 ? `${list.slice(0, 4).join(", ")}, \u2026` : list.join(", ");
@@ -3952,7 +4515,7 @@ async function runDoctor(options = {}) {
3952
4515
  if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
3953
4516
  }
3954
4517
  const raw = [];
3955
- const ctx = { root, files, genesis, config, report: (f) => raw.push(f) };
4518
+ const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
3956
4519
  for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
3957
4520
  try {
3958
4521
  await plugin.check(ctx);
@@ -3984,7 +4547,8 @@ async function runDoctor(options = {}) {
3984
4547
  function builtinChecks(config) {
3985
4548
  const packs = {
3986
4549
  native: { name: "native", check: checkNativePack },
3987
- supabase: { name: "supabase", check: checkSupabasePack }
4550
+ supabase: { name: "supabase", check: checkSupabasePack },
4551
+ packages: { name: "packages", check: checkPackagesPack }
3988
4552
  };
3989
4553
  return [
3990
4554
  { name: "layout", check: checkProjectLayout },