@marktiderman/genesis-cli 1.11.3 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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(
@@ -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,276 @@ 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))) {
1799
+ throw new LocalPackagesError(`${path14.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
1800
+ }
1801
+ let pkg;
1802
+ try {
1803
+ pkg = JSON.parse(readFileSync(manifest, "utf8"));
1804
+ } catch {
1805
+ continue;
1806
+ }
1807
+ if (typeof pkg.name !== "string" || !pkg.name) continue;
1808
+ const rel = path14.relative(appRoot, dir).split(path14.sep).join("/");
1809
+ const other = byName.get(pkg.name);
1810
+ if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
1811
+ byName.set(pkg.name, rel);
1812
+ out.push({ name: pkg.name, dir, rel, ...typeof pkg.version === "string" ? { version: pkg.version } : {} });
1813
+ }
1814
+ cache.set(key2, out);
1815
+ return out;
1816
+ }
1543
1817
 
1544
1818
  // ../../scripts/lib/color-literals.mjs
1545
1819
  var LINE_COMMENT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".jsx", ".js", ".mjs", ".cjs", ".scss", ".less"]);
@@ -1747,6 +2021,13 @@ function scanFiles(root, config) {
1747
2021
  if (statSync(abs).isDirectory()) walk(abs);
1748
2022
  else visit(abs);
1749
2023
  }
2024
+ let local = [];
2025
+ try {
2026
+ local = localPackages(root);
2027
+ } catch {
2028
+ local = [];
2029
+ }
2030
+ for (const pkg of local) walk(pkg.dir);
1750
2031
  return files;
1751
2032
  }
1752
2033
  function lineAt(text, index) {
@@ -1919,7 +2200,18 @@ var BUILTIN_RULES = [
1919
2200
  "migration-definer-search-path",
1920
2201
  "migration-edited",
1921
2202
  "migration-testing-kit",
1922
- "migration-view-rls"
2203
+ "migration-view-rls",
2204
+ // packages pack
2205
+ "package-app-import",
2206
+ "package-undeclared-dependency",
2207
+ "package-migration-test",
2208
+ "package-migration-number",
2209
+ "package-migration-edited",
2210
+ "package-unregistered",
2211
+ "package-unversioned-change",
2212
+ "package-export-missing",
2213
+ "package-block-invalid",
2214
+ "package-untagged-tests"
1923
2215
  ];
1924
2216
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
1925
2217
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -2542,1134 +2834,1416 @@ function checkStoreReadiness(ctx) {
2542
2834
  });
2543
2835
  }
2544
2836
  }
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;
2837
+
2838
+ // src/doctor/semver.ts
2839
+ var VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
2840
+ function parseVersion(v) {
2841
+ const m = VERSION.exec(v.trim());
2842
+ return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
2628
2843
  }
2629
- function qualify(name) {
2630
- const n = name.trim().toLowerCase();
2631
- return n.includes(".") ? n : `public.${n}`;
2844
+ function compareVersions(a, b) {
2845
+ for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
2846
+ if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
2847
+ for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
2848
+ const x = a.pre[i];
2849
+ const y = b.pre[i];
2850
+ if (x === void 0) return -1;
2851
+ if (y === void 0) return 1;
2852
+ if (x === y) continue;
2853
+ const nx = /^\d+$/.test(x);
2854
+ const ny = /^\d+$/.test(y);
2855
+ if (nx && ny) return +x < +y ? -1 : 1;
2856
+ if (nx !== ny) return nx ? -1 : 1;
2857
+ return x < y ? -1 : 1;
2858
+ }
2859
+ return 0;
2632
2860
  }
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 };
2861
+ function partial(s) {
2862
+ const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
2863
+ if (!m) return null;
2864
+ const nums = [];
2865
+ let wild = false;
2866
+ for (const part of [m[1], m[2], m[3]]) {
2867
+ if (wild || part === void 0 || /^[xX*]$/.test(part)) {
2868
+ wild = true;
2869
+ nums.push(null);
2870
+ } else nums.push(+part);
2639
2871
  }
2640
- return { inner: sql.slice(open + 1), end: sql.length };
2872
+ return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
2641
2873
  }
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;
2874
+ var ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
2875
+ function comparators(token) {
2876
+ const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
2877
+ if (!m) return null;
2878
+ const op = m[1] ?? "";
2879
+ const p = partial(m[2]);
2880
+ if (!p) return null;
2881
+ const [major, mi, pa] = p.nums;
2882
+ if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
2883
+ const M = major;
2884
+ const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
2885
+ 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"]);
2886
+ const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
2887
+ const out = switchOp();
2888
+ if (p.pre.length) {
2889
+ for (const c of out) if (c.v === lo) c.pre = true;
2649
2890
  }
2650
2891
  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;
2892
+ function switchOp() {
2893
+ switch (op) {
2894
+ case "^": {
2895
+ const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
2896
+ return [
2897
+ { op: ">=", v: lo },
2898
+ { op: "<", v: bound }
2899
+ ];
2900
+ }
2901
+ case "~":
2902
+ case "~>":
2903
+ return [
2904
+ { op: ">=", v: lo },
2905
+ { op: "<", v: mi === null ? next("major") : next("minor") }
2906
+ ];
2907
+ case ">":
2908
+ return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
2909
+ case ">=":
2910
+ return [{ op: ">=", v: lo }];
2911
+ case "<":
2912
+ return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
2913
+ case "<=":
2914
+ return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
2915
+ default:
2916
+ return upper ? [
2917
+ { op: ">=", v: lo },
2918
+ { op: "<", v: upper }
2919
+ ] : [{ op: "=", v: lo }];
2920
+ }
2663
2921
  }
2664
- if (cur.trim()) parts.push(cur);
2665
- return parts.map((p) => p.trim()).filter(Boolean);
2666
- }
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
2922
  }
2691
- function git(root, args) {
2692
- const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
2693
- return r.status === 0 ? r.stdout : null;
2923
+ function test(c, v) {
2924
+ const d = compareVersions(v, c.v);
2925
+ return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
2694
2926
  }
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" });
2927
+ function parseRange(range) {
2928
+ const alts = [];
2929
+ for (const raw of range.trim().split("||")) {
2930
+ const alt = raw.trim();
2931
+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
2932
+ if (hyphen) {
2933
+ const from = comparators(`>=${hyphen[1]}`);
2934
+ const to = comparators(`<=${hyphen[2]}`);
2935
+ if (!from || !to) return null;
2936
+ alts.push([...from, ...to]);
2713
2937
  continue;
2714
2938
  }
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
- });
2939
+ const set = [];
2940
+ for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
2941
+ const cs = comparators(token);
2942
+ if (!cs) return null;
2943
+ set.push(...cs);
2743
2944
  }
2945
+ alts.push(set);
2744
2946
  }
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
- }
2947
+ return alts;
2775
2948
  }
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);
2949
+ function satisfies(version, range) {
2950
+ const v = parseVersion(version);
2951
+ const alts = parseRange(range);
2952
+ if (!v || !alts) return null;
2953
+ return alts.some(
2954
+ (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))
2955
+ );
2778
2956
  }
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;
2957
+ var TRAIL_DEPTH = 6;
2958
+ var RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
2959
+ var IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
2960
+ var EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
2961
+ var DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
2962
+ function stripForImports(code) {
2963
+ const out = [];
2964
+ const blank = (ch) => ch === "\n" ? "\n" : " ";
2965
+ const n = code.length;
2966
+ const templates = [];
2967
+ let depth = 0;
2968
+ let i = 0;
2969
+ let sure = true;
2970
+ const isSpecifier = () => /(?:\bfrom|(?:^|[;{}\n])\s*import|\bimport\s*\(|\brequire\s*\()\s*$/.test(out.slice(-40).join(""));
2971
+ const before = () => out.slice(-24).join("");
2972
+ const KEYWORD = /(?:^|[^\w$.])(?:return|typeof|instanceof|case|do|else|in|of|new|delete|void|throw|yield|await|from|import|export|default|require)\s*$/;
2973
+ const startsExpression = (b) => {
2974
+ const t = b.replace(/\s+$/, "");
2975
+ if (!t) return true;
2976
+ if (KEYWORD.test(b)) return true;
2977
+ return /[([{,;:=!&|?+\-*%<>~^}]$/.test(t);
2787
2978
  };
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;
2979
+ const exprStart = () => startsExpression(before());
2980
+ const taggedTemplate = () => {
2981
+ const b = out.slice(-48).join("");
2982
+ const m = /([A-Za-z_$][\w$.]*)$/.exec(b);
2983
+ return m !== null && startsExpression(b.slice(0, b.length - m[1].length));
2984
+ };
2985
+ const templateBody = () => {
2986
+ while (i < n) {
2987
+ const ch = code[i];
2988
+ if (ch === "\\") {
2989
+ out.push(" ", blank(code[i + 1] ?? ""));
2990
+ i += 2;
2991
+ } else if (ch === "`") {
2992
+ out.push("`");
2993
+ i++;
2994
+ return;
2995
+ } else if (ch === "$" && code[i + 1] === "{") {
2996
+ out.push("${");
2997
+ i += 2;
2998
+ templates.push(depth);
2999
+ depth++;
3000
+ return;
3001
+ } else {
3002
+ out.push(blank(ch));
3003
+ i++;
2797
3004
  }
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;
3005
+ }
3006
+ sure = false;
3007
+ };
3008
+ while (i < n && sure) {
3009
+ const ch = code[i];
3010
+ const next = code[i + 1];
3011
+ if (ch === "/" && next === "/") {
3012
+ while (i < n && code[i] !== "\n") {
3013
+ out.push(" ");
3014
+ i++;
2805
3015
  }
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;
3016
+ } else if (ch === "/" && next === "*") {
3017
+ out.push(" ");
3018
+ i += 2;
3019
+ while (i < n && !(code[i] === "*" && code[i + 1] === "/")) {
3020
+ out.push(blank(code[i]));
3021
+ i++;
2821
3022
  }
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
- }
3023
+ if (i < n) {
3024
+ out.push(" ");
3025
+ i += 2;
2836
3026
  }
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);
3027
+ } else if (ch === "/" && next !== ">" && code[i - 1] !== "<" && exprStart()) {
3028
+ const afterBrace = /[}>]\s*$/.test(before());
3029
+ const start = i;
3030
+ const mark = out.length;
3031
+ out.push("/");
3032
+ i++;
3033
+ let inClass = false;
3034
+ for (; ; ) {
3035
+ const c = code[i];
3036
+ if (c === void 0 || c === "\n") {
3037
+ if (afterBrace) {
3038
+ out.length = mark;
3039
+ out.push("/");
3040
+ i = start + 1;
3041
+ } else sure = false;
3042
+ break;
2861
3043
  }
2862
- continue;
3044
+ if (c === "\\") {
3045
+ out.push(" ", blank(code[i + 1] ?? ""));
3046
+ i += 2;
3047
+ continue;
3048
+ }
3049
+ i++;
3050
+ if (c === "[") inClass = true;
3051
+ else if (c === "]") inClass = false;
3052
+ else if (c === "/" && !inClass) {
3053
+ if (afterBrace && /[<>]/.test(code.slice(start + 1, i - 1))) {
3054
+ out.length = mark;
3055
+ out.push("/");
3056
+ i = start + 1;
3057
+ break;
3058
+ }
3059
+ out.push("/");
3060
+ break;
3061
+ }
3062
+ out.push(" ");
2863
3063
  }
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;
3064
+ if (out.length > mark + 1 || i > start + 1) while (i < n && /[a-z]/.test(code[i])) out.push(code[i++]);
3065
+ } else if ((ch === '"' || ch === "'") && exprStart()) {
3066
+ const keep = isSpecifier();
3067
+ out.push(ch);
3068
+ i++;
3069
+ while (i < n && code[i] !== ch && code[i] !== "\n") {
3070
+ if (code[i] === "\\") {
3071
+ out.push(keep ? code[i] : " ", keep ? code[i + 1] ?? "" : blank(code[i + 1] ?? ""));
3072
+ i += 2;
3073
+ } else {
3074
+ out.push(keep ? code[i] : blank(code[i]));
3075
+ i++;
2871
3076
  }
2872
- continue;
2873
3077
  }
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));
3078
+ if (code[i] !== ch) sure = false;
3079
+ else {
3080
+ out.push(code[i]);
3081
+ i++;
3082
+ }
3083
+ } else if (ch === "`" && (exprStart() || taggedTemplate())) {
3084
+ out.push("`");
3085
+ i++;
3086
+ templateBody();
3087
+ } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
3088
+ templates.pop();
3089
+ depth--;
3090
+ out.push("}");
3091
+ i++;
3092
+ templateBody();
3093
+ } else {
3094
+ if (ch === "{") depth++;
3095
+ else if (ch === "}") depth--;
3096
+ out.push(ch);
3097
+ i++;
2876
3098
  }
2877
3099
  }
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
- }
3100
+ return sure && templates.length === 0 ? out.join("") : null;
2888
3101
  }
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
- }
3102
+ function bindings(clause) {
3103
+ const out = [];
3104
+ const named = /\{([^}]*)\}/.exec(clause);
3105
+ for (const part of named?.[1].split(",") ?? []) {
3106
+ const p = part.trim();
3107
+ if (!p || p.startsWith("type ")) continue;
3108
+ out.push(p.split(/\s+as\s+/).pop().trim());
2921
3109
  }
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
- });
3110
+ const rest = clause.replace(/\{[^}]*\}/, "");
3111
+ const ns = /\*\s*as\s+([\w$]+)/.exec(rest);
3112
+ if (ns) out.push(ns[1]);
3113
+ const def = /^\s*([\w$]+)/.exec(rest);
3114
+ if (def && def[1] !== "as") out.push(def[1]);
3115
+ return out;
3116
+ }
3117
+ function readJsonc(file) {
3118
+ try {
3119
+ const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? "").replace(/,(\s*[}\]])/g, "$1");
3120
+ return JSON.parse(text);
3121
+ } catch {
3122
+ return null;
2931
3123
  }
2932
3124
  }
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
- }
3125
+ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3126
+ if (seen.has(file) || seen.size > 10) return {};
3127
+ seen.add(file);
3128
+ const json = readJsonc(file);
3129
+ if (!json) return {};
3130
+ const dir = path14.dirname(file);
3131
+ let merged = {};
3132
+ const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
3133
+ for (const ext of parents) {
3134
+ if (typeof ext !== "string") continue;
3135
+ let target = null;
3136
+ if (ext.startsWith(".") || path14.isAbsolute(ext)) {
3137
+ const abs = path14.resolve(dir, ext);
3138
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3139
+ } else {
3140
+ const parts = ext.split("/");
3141
+ const nameLength = ext.startsWith("@") ? 2 : 1;
3142
+ const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
3143
+ if (pkgDir) {
3144
+ const sub = parts.slice(nameLength).join("/");
3145
+ const abs = path14.join(pkgDir, sub || "tsconfig.json");
3146
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2981
3147
  }
2982
3148
  }
3149
+ if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
2983
3150
  }
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
- });
3151
+ const opts = json.compilerOptions ?? {};
3152
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path14.resolve(dir, opts.baseUrl);
3153
+ if (opts.paths && typeof opts.paths === "object") {
3154
+ merged.paths = opts.paths;
3155
+ merged.pathsDir = dir;
2993
3156
  }
3157
+ return merged;
2994
3158
  }
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"));
3159
+ function aliases(root) {
3160
+ const table = [];
3161
+ let baseUrl = null;
3162
+ for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
3163
+ const file = path14.join(root, name);
3164
+ if (!existsSync(file)) continue;
3165
+ const config = readTsconfig(root, file);
3166
+ baseUrl ??= config.baseUrl ?? null;
3167
+ const base = config.baseUrl ?? config.pathsDir ?? root;
3168
+ for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
3169
+ if (!Array.isArray(targets)) continue;
3170
+ const exact = !pattern.endsWith("*");
3171
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path14.join(base, String(t).replace(/\*$/, ""))) });
3172
+ }
3173
+ }
3174
+ const pkg = readJsonc(path14.join(root, "package.json"));
3175
+ for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
3176
+ if (typeof target !== "string") continue;
3177
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path14.join(root, target.replace(/\*.*$/, ""))] });
3178
+ }
3179
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
3180
+ return { table, baseUrl };
3001
3181
  }
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
- });
3182
+ function resolveFile(base) {
3183
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path14.join(base, `index${e}`))];
3184
+ if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
3185
+ for (const p of tries) {
3186
+ if (SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
3187
+ }
3188
+ return null;
3189
+ }
3190
+ var trails = /* @__PURE__ */ new WeakMap();
3191
+ function trailFor(ctx) {
3192
+ let t = trails.get(ctx.files);
3193
+ if (!t) trails.set(ctx.files, t = createTrail(ctx));
3194
+ return t;
3195
+ }
3196
+ function createTrail(ctx) {
3197
+ const { table, baseUrl } = aliases(ctx.root);
3198
+ let declared = null;
3199
+ try {
3200
+ const pkg = JSON.parse(readFileSync(path14.join(ctx.root, "package.json"), "utf8"));
3201
+ declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
3202
+ } catch {
3203
+ declared = null;
3017
3204
  }
3205
+ const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
3206
+ const read = (abs) => byPath.get(abs) ?? readSource(abs);
3207
+ const importsCache = /* @__PURE__ */ new Map();
3208
+ const importsOf = (file) => {
3209
+ const hit = importsCache.get(file.absolutePath);
3210
+ if (hit) return hit;
3211
+ const files = [];
3212
+ let lost = false;
3213
+ const code = stripped(file);
3214
+ if (code === null) {
3215
+ const out2 = { files: [], lost: true };
3216
+ importsCache.set(file.absolutePath, out2);
3217
+ return out2;
3218
+ }
3219
+ const used = new Set(renderedElements(code).map((e) => e.split(".")[0]));
3220
+ for (const m of code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
3221
+ for (const m of code.matchAll(/\bexport\s+default\s+([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
3222
+ 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]);
3223
+ const specs = [];
3224
+ for (const m of code.matchAll(IMPORT_FROM)) if (!m[1] && bindings(m[2]).some((b) => used.has(b))) specs.push(m[3]);
3225
+ for (const m of code.matchAll(EXPORT_FROM)) if (!m[1]) specs.push(m[2]);
3226
+ for (const m of code.matchAll(DYNAMIC)) specs.push(m[1]);
3227
+ for (const spec of specs) {
3228
+ if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
3229
+ let resolved = null;
3230
+ if (spec.startsWith(".")) {
3231
+ resolved = resolveFile(path14.resolve(path14.dirname(file.absolutePath), spec));
3232
+ if (!resolved) lost = true;
3233
+ } else {
3234
+ const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
3235
+ if (alias) {
3236
+ for (const t of alias.targets) {
3237
+ resolved = resolveFile(alias.exact ? t : path14.join(t, spec.slice(alias.prefix.length)));
3238
+ if (resolved) break;
3239
+ }
3240
+ }
3241
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path14.join(baseUrl, spec));
3242
+ if (!resolved) {
3243
+ const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
3244
+ if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
3245
+ }
3246
+ }
3247
+ if (resolved && !files.includes(resolved)) files.push(resolved);
3248
+ }
3249
+ const out = { files, lost };
3250
+ importsCache.set(file.absolutePath, out);
3251
+ return out;
3252
+ };
3253
+ const strippedCache = /* @__PURE__ */ new Map();
3254
+ const stripped = (file) => {
3255
+ if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
3256
+ return strippedCache.get(file.absolutePath);
3257
+ };
3258
+ const memo = /* @__PURE__ */ new WeakMap();
3259
+ const reach = (file, test2, depth, seen) => {
3260
+ let cache2 = memo.get(test2);
3261
+ if (!cache2) memo.set(test2, cache2 = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
3262
+ const k = `${file.absolutePath}\0${depth}`;
3263
+ const free = cache2.free.get(k);
3264
+ if (free) return [free, /* @__PURE__ */ new Set()];
3265
+ const reusable = cache2.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
3266
+ if (reusable) return [reusable.result, new Set(reusable.cut)];
3267
+ let result;
3268
+ const cut = /* @__PURE__ */ new Set();
3269
+ const code = stripped(file);
3270
+ if (code === null) result = "unknown";
3271
+ else if (test2(code)) result = "yes";
3272
+ else {
3273
+ const { files, lost } = importsOf(file);
3274
+ let unknown = lost && depth > 0;
3275
+ result = "no";
3276
+ if (depth > 0) {
3277
+ seen.add(file.absolutePath);
3278
+ for (const abs of files) {
3279
+ if (seen.has(abs)) {
3280
+ cut.add(abs);
3281
+ continue;
3282
+ }
3283
+ const target = read(abs);
3284
+ if (!target) {
3285
+ unknown = true;
3286
+ continue;
3287
+ }
3288
+ const [r, c] = reach(target, test2, depth - 1, seen);
3289
+ for (const m of c) cut.add(m);
3290
+ if (r === "yes") {
3291
+ result = "yes";
3292
+ break;
3293
+ }
3294
+ if (r === "unknown") unknown = true;
3295
+ }
3296
+ seen.delete(file.absolutePath);
3297
+ cut.delete(file.absolutePath);
3298
+ }
3299
+ if (result === "no" && unknown) result = "unknown";
3300
+ }
3301
+ if (result === "yes" || cut.size === 0) {
3302
+ cache2.free.set(k, result);
3303
+ return [result, /* @__PURE__ */ new Set()];
3304
+ }
3305
+ const entries = cache2.cut.get(k) ?? [];
3306
+ entries.push({ cut: [...cut], result });
3307
+ cache2.cut.set(k, entries);
3308
+ return [result, cut];
3309
+ };
3310
+ return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
3018
3311
  }
3019
3312
 
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;
3313
+ // src/doctor/packages.ts
3314
+ var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
3315
+ var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
3316
+ var BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
3317
+ var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
3318
+ var TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
3319
+ function sourceFiles(dir, rel = "") {
3320
+ const out = [];
3321
+ for (const entry of readdirSync(path14.join(dir, rel)).sort()) {
3322
+ if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
3323
+ const child = rel ? `${rel}/${entry}` : entry;
3324
+ const stat = lstatSync(path14.join(dir, child));
3325
+ if (stat.isSymbolicLink()) continue;
3326
+ if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
3327
+ else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
3328
+ }
3329
+ return out;
3025
3330
  }
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;
3331
+ function packageName2(specifier) {
3332
+ const parts = specifier.split("/");
3333
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3334
+ }
3335
+ function git(root, args) {
3336
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3337
+ return r.status === 0 ? r.stdout : null;
3338
+ }
3339
+ function matchPattern(pattern, spec) {
3340
+ const star = pattern.indexOf("*");
3341
+ if (star < 0) return pattern === spec ? "" : null;
3342
+ const head = pattern.slice(0, star);
3343
+ const tail = pattern.slice(star + 1);
3344
+ return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3345
+ }
3346
+ function tsconfigPaths(dir) {
3347
+ const file = path14.join(dir, "tsconfig.json");
3348
+ if (!existsSync(file)) return [];
3349
+ try {
3350
+ const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
3351
+ const options = JSON.parse(text).compilerOptions ?? {};
3352
+ const base = path14.resolve(dir, options.baseUrl ?? ".");
3353
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path14.resolve(base, t)) }));
3354
+ } catch {
3355
+ return [];
3356
+ }
3357
+ }
3358
+ function checkImports2(ctx, pkg, json) {
3359
+ const aliases2 = tsconfigPaths(pkg.dir);
3360
+ const subpathImports = Object.keys(json.imports ?? {});
3361
+ const viaAlias = (spec) => {
3362
+ if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
3363
+ for (const { pattern, targets } of aliases2) {
3364
+ const hit = matchPattern(pattern, spec);
3365
+ if (hit === null) continue;
3366
+ return targets.some((t) => {
3367
+ const rel = path14.relative(pkg.dir, t.replace("*", hit));
3368
+ return !rel.startsWith("..") && !path14.isAbsolute(rel);
3369
+ });
3370
+ }
3371
+ return null;
3372
+ };
3373
+ const declared = /* @__PURE__ */ new Set([
3374
+ json.name,
3375
+ ...Object.keys(json.dependencies ?? {}),
3376
+ ...Object.keys(json.peerDependencies ?? {}),
3377
+ ...Object.keys(json.devDependencies ?? {}),
3378
+ ...Object.keys(json.optionalDependencies ?? {})
3379
+ ]);
3380
+ for (const file of sourceFiles(pkg.dir)) {
3381
+ const code = stripForImports(readFileSync(path14.join(pkg.dir, file), "utf8"));
3382
+ if (code === null) continue;
3383
+ const at = `${pkg.rel}/${file}`;
3384
+ const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
3385
+ let offset = 0;
3386
+ code.split("\n").forEach((text, i) => {
3387
+ const lineStart = offset;
3388
+ offset += text.length + 1;
3389
+ for (const m of text.matchAll(IMPORT)) {
3390
+ const spec = m[1];
3391
+ const line = i + 1;
3392
+ const at0 = lineStart + m.index;
3393
+ if (typeOnly.some(([a, b]) => at0 >= a && at0 < b)) continue;
3394
+ const alias = viaAlias(spec);
3395
+ if (alias === true) continue;
3396
+ if (alias === false) {
3397
+ ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} imports ${spec}, an alias that points outside the package` });
3398
+ continue;
3399
+ }
3400
+ if (spec.startsWith("#")) continue;
3401
+ if (spec.startsWith("@/") || spec.startsWith("~/")) {
3402
+ 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` });
3403
+ continue;
3404
+ }
3405
+ if (spec.startsWith(".")) {
3406
+ const target = path14.resolve(pkg.dir, path14.dirname(file), spec);
3407
+ const rel = path14.relative(pkg.dir, target);
3408
+ if (rel.startsWith("..") || path14.isAbsolute(rel)) {
3409
+ 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` });
3410
+ }
3411
+ continue;
3412
+ }
3413
+ if (BUILTINS.has(spec) || spec.startsWith("node:") || spec.startsWith("virtual:") || /^[a-z]+:/.test(spec)) continue;
3414
+ const name = packageName2(spec);
3415
+ if (!declared.has(name)) {
3416
+ 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` });
3417
+ }
3418
+ }
3419
+ });
3040
3420
  }
3041
- return 0;
3042
3421
  }
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);
3422
+ function checkMigrations(ctx, pkg, json) {
3423
+ const declaredFiles = /* @__PURE__ */ new Set();
3424
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
3425
+ const migrations = raw.migrations ?? [];
3426
+ for (const m of migrations) {
3427
+ if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
3428
+ if (typeof m.file === "string" && typeof m.test !== "string") {
3429
+ 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` });
3430
+ } else if (typeof m.test === "string" && !existsSync(path14.join(pkg.dir, m.test))) {
3431
+ 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` });
3432
+ }
3433
+ }
3434
+ }
3435
+ const dir = path14.join(pkg.dir, "migrations");
3436
+ if (!existsSync(dir)) return;
3437
+ const seen = /* @__PURE__ */ new Map();
3438
+ for (const name of readdirSync(dir).sort()) {
3439
+ const m = MIGRATION_FILE.exec(name);
3440
+ if (!m) continue;
3441
+ const other = seen.get(m[1]);
3442
+ 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` });
3443
+ else seen.set(m[1], name);
3444
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path14.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
3445
+ 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")})` });
3446
+ }
3053
3447
  }
3054
- return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
3055
3448
  }
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;
3449
+ function checkExports(ctx, pkg, json) {
3450
+ const targets = [];
3451
+ const walk = (v) => {
3452
+ if (typeof v === "string") targets.push(v);
3453
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk(x);
3454
+ };
3455
+ walk(json.exports);
3456
+ for (const t of targets) {
3457
+ if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
3458
+ if (!existsSync(path14.join(pkg.dir, t))) {
3459
+ ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
3460
+ }
3072
3461
  }
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
- ];
3462
+ }
3463
+ function checkBlocks(ctx, pkg, json) {
3464
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
3465
+ try {
3466
+ parseManifest(json.name, id, raw, json.version, { local: true });
3467
+ } catch (err) {
3468
+ if (!(err instanceof ManifestError)) throw err;
3469
+ for (const problem of err.problems) ctx.report({ rule: "package-block-invalid", file: `${pkg.rel}/package.json`, subject: id, message: problem });
3470
+ }
3471
+ }
3472
+ }
3473
+ function checkTaggedTests(ctx, pkg) {
3474
+ const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
3475
+ if (!tests.length) return;
3476
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path14.join(pkg.dir, f), "utf8")));
3477
+ 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>` });
3478
+ }
3479
+ function checkRegistered(ctx, pkg) {
3480
+ const file = path14.join(ctx.root, "features.json");
3481
+ if (!existsSync(file)) return;
3482
+ let doc;
3483
+ try {
3484
+ doc = JSON.parse(readFileSync(file, "utf8"));
3485
+ } catch {
3486
+ return;
3487
+ }
3488
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3489
+ const forms = /* @__PURE__ */ new Set([pkg.rel]);
3490
+ if (top) forms.add(path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/"));
3491
+ const covered = (doc.features ?? []).some(
3492
+ (f) => (f.links?.code ?? []).some((c) => {
3493
+ const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
3494
+ return [...forms].some((rel) => norm === rel || norm.startsWith(`${rel}/`) || rel.startsWith(`${norm}/`));
3495
+ })
3496
+ );
3497
+ if (!covered) {
3498
+ 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` });
3499
+ }
3500
+ }
3501
+ function changesetNames(text) {
3502
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
3503
+ const names = /* @__PURE__ */ new Set();
3504
+ if (!m) return names;
3505
+ for (const line of m[1].split(/\r?\n/)) {
3506
+ const entry = /^\s*(?:"([^"]+)"|'([^']+)'|([^\s:'"]+))\s*:\s*(major|minor|patch)\s*$/.exec(line);
3507
+ if (entry) names.add(entry[1] ?? entry[2] ?? entry[3]);
3508
+ }
3509
+ return names;
3510
+ }
3511
+ function mergeBaseOf(root, base) {
3512
+ if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository" };
3513
+ if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) return { reason: `the git ref ${base} isn't available (fetch it)` };
3514
+ const sha = git(root, ["merge-base", "HEAD", base])?.trim();
3515
+ return sha ? { sha } : { reason: `HEAD has no merge base with ${base} (fetch with depth 0)` };
3516
+ }
3517
+ function checkChanges(ctx, pkg, json, base, mergeBase) {
3518
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3519
+ if (!top) return;
3520
+ const appRelative = (fromTop) => path14.relative(realpathSync(ctx.root), path14.join(top, fromTop)).split(path14.sep).join("/");
3521
+ const inRepo = path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/");
3522
+ const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell, i) => i === 0 ? cell : appRelative(cell)).join(" ")).join("\n");
3523
+ const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
3524
+ const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
3525
+ (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
3526
+ );
3527
+ for (const row of diff.split("\n").filter(Boolean)) {
3528
+ const [status, a] = row.split(" ");
3529
+ if (a && /\/migrations\/\d{4}_[a-z0-9_]+\.sql$/.test(a) && /^[MDRT]/.test(status)) {
3530
+ 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` });
3531
+ }
3532
+ }
3533
+ if (!changed.length) return;
3534
+ const before = git(ctx.root, ["show", `${mergeBase}:./${pkg.rel}/package.json`]);
3535
+ let versionBefore;
3536
+ try {
3537
+ versionBefore = before ? JSON.parse(before).version : void 0;
3538
+ } catch {
3539
+ versionBefore = void 0;
3540
+ }
3541
+ const now = typeof json.version === "string" ? parseVersion(json.version) : null;
3542
+ const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
3543
+ const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
3544
+ 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)) : [];
3545
+ const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
3546
+ const named = naming.length > 0;
3547
+ if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
3548
+ 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` });
3549
+ }
3550
+ let jsonBefore = null;
3551
+ try {
3552
+ jsonBefore = before ? JSON.parse(before) : null;
3553
+ } catch {
3554
+ jsonBefore = null;
3555
+ }
3556
+ const raw = json;
3557
+ if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
3558
+ const registry = (git(ctx.root, ["diff", "--relative", "--name-only", mergeBase, "--", "features.ts", "src/features.ts"]) ?? "").trim();
3559
+ 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` });
3560
+ }
3561
+ if (bumped && !named && before !== null) {
3562
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: `${pkg.rel}/package.json`, message: `${pkg.name}'s version went up without a changeset; add one with a "Features:" line so the change is recorded` });
3563
+ }
3564
+ if (!bumped && !named) {
3565
+ ctx.report({
3566
+ rule: "package-unversioned-change",
3567
+ level: "warn",
3568
+ file: `${pkg.rel}/package.json`,
3569
+ 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`
3570
+ });
3571
+ }
3572
+ }
3573
+ function checkPackagesPack(ctx) {
3574
+ let packages;
3575
+ try {
3576
+ packages = localPackages(ctx.root);
3577
+ } catch (err) {
3578
+ ctx.report({ rule: "package-block-invalid", file: "genesis.config.json", message: err.message });
3579
+ return;
3580
+ }
3581
+ if (!packages.length) return;
3582
+ const base = ctx.base ?? ctx.config.packages?.base;
3583
+ const merge = base ? mergeBaseOf(ctx.root, base) : { reason: "no base ref (pass --base <ref>, e.g. --base origin/main)" };
3584
+ if ("reason" in merge) {
3585
+ ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
3586
+ }
3587
+ for (const pkg of packages) {
3588
+ const json = JSON.parse(readFileSync(path14.join(pkg.dir, "package.json"), "utf8"));
3589
+ checkImports2(ctx, pkg, json);
3590
+ checkExports(ctx, pkg, json);
3591
+ checkBlocks(ctx, pkg, json);
3592
+ checkMigrations(ctx, pkg, json);
3593
+ checkTaggedTests(ctx, pkg);
3594
+ checkRegistered(ctx, pkg);
3595
+ if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
3596
+ }
3597
+ }
3598
+ var DEFAULT_MIGRATIONS = "supabase/migrations";
3599
+ var DEFAULT_BASE = "origin/main";
3600
+ var DEFAULT_EXPOSED = ["public"];
3601
+ function sqlStatements(text) {
3602
+ const out = [];
3603
+ let buf = "";
3604
+ let bodies = [];
3605
+ let line = 1;
3606
+ let start = 0;
3607
+ const flush = () => {
3608
+ const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
3609
+ if (sql) out.push({ sql, line: start, bodies });
3610
+ buf = "";
3611
+ bodies = [];
3612
+ start = 0;
3613
+ };
3614
+ const put = (s) => {
3615
+ if (!start && /\S/.test(s)) start = line;
3616
+ buf += s;
3617
+ };
3618
+ let i = 0;
3619
+ while (i < text.length) {
3620
+ const ch = text[i];
3621
+ const two = text.slice(i, i + 2);
3622
+ if (ch === "\n") {
3623
+ buf += " ";
3624
+ line++;
3625
+ i++;
3626
+ } else if (two === "--") {
3627
+ while (i < text.length && text[i] !== "\n") i++;
3628
+ } else if (two === "/*") {
3629
+ let depth = 0;
3630
+ while (i < text.length) {
3631
+ if (text.startsWith("/*", i)) {
3632
+ depth++;
3633
+ i += 2;
3634
+ } else if (text.startsWith("*/", i)) {
3635
+ depth--;
3636
+ i += 2;
3637
+ if (depth === 0) break;
3638
+ } else {
3639
+ if (text[i] === "\n") line++;
3640
+ i++;
3641
+ }
3082
3642
  }
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 }];
3643
+ buf += " ";
3644
+ } else if (ch === "'") {
3645
+ const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
3646
+ put("'");
3647
+ i++;
3648
+ while (i < text.length) {
3649
+ if (escapes && text[i] === "\\") i += 2;
3650
+ else if (text[i] === "'" && text[i + 1] === "'") i += 2;
3651
+ else if (text[i] === "'") break;
3652
+ else {
3653
+ if (text[i] === "\n") line++;
3654
+ i++;
3655
+ }
3656
+ }
3657
+ put("'");
3658
+ i++;
3659
+ } else if (ch === '"') {
3660
+ i++;
3661
+ while (i < text.length && text[i] !== '"') put(text[i++]);
3662
+ i++;
3663
+ } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
3664
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
3665
+ const end = text.indexOf(tag, i + tag.length);
3666
+ const stop = end === -1 ? text.length : end + tag.length;
3667
+ bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
3668
+ for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
3669
+ put(`${tag} ${tag}`);
3670
+ i = stop;
3671
+ } else if (ch === ";") {
3672
+ flush();
3673
+ i++;
3674
+ } else {
3675
+ put(ch);
3676
+ i++;
3102
3677
  }
3103
3678
  }
3679
+ flush();
3680
+ return out;
3104
3681
  }
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;
3682
+ function qualify(name) {
3683
+ const n = name.trim().toLowerCase();
3684
+ return n.includes(".") ? n : `public.${n}`;
3108
3685
  }
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;
3120
- }
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);
3126
- }
3127
- alts.push(set);
3686
+ var schemaOf = (name) => name.split(".")[0];
3687
+ function parenthesized(sql, open) {
3688
+ let depth = 0;
3689
+ for (let k = open; k < sql.length; k++) {
3690
+ if (sql[k] === "(") depth++;
3691
+ else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
3128
3692
  }
3129
- return alts;
3693
+ return { inner: sql.slice(open + 1), end: sql.length };
3130
3694
  }
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
- );
3695
+ function stripParens(s) {
3696
+ let out = "";
3697
+ let depth = 0;
3698
+ for (const c of s) {
3699
+ if (c === "(") depth++;
3700
+ else if (c === ")") depth = Math.max(0, depth - 1);
3701
+ else if (depth === 0) out += c;
3702
+ }
3703
+ return out;
3138
3704
  }
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) => {
3145
- try {
3146
- return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
3147
- } catch {
3148
- return null;
3705
+ function splitTop(s) {
3706
+ const parts = [];
3707
+ let depth = 0;
3708
+ let cur = "";
3709
+ for (const c of s) {
3710
+ if (c === "(") depth++;
3711
+ if (c === ")") depth--;
3712
+ if (c === "," && depth === 0) {
3713
+ parts.push(cur);
3714
+ cur = "";
3715
+ } else cur += c;
3149
3716
  }
3717
+ if (cur.trim()) parts.push(cur);
3718
+ return parts.map((p) => p.trim()).filter(Boolean);
3719
+ }
3720
+ var TYPE_ALIASES = {
3721
+ int: "integer",
3722
+ int4: "integer",
3723
+ int8: "bigint",
3724
+ int2: "smallint",
3725
+ bool: "boolean",
3726
+ varchar: "character varying",
3727
+ timestamptz: "timestamp with time zone",
3728
+ float8: "double precision"
3150
3729
  };
3151
- var real = (p) => {
3152
- try {
3153
- return realpathSync(p);
3154
- } catch {
3155
- return p;
3730
+ var MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
3731
+ function argTypes(args) {
3732
+ const types = [];
3733
+ for (const raw of splitTop(args)) {
3734
+ let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
3735
+ const mode = tokens[0];
3736
+ if (mode === "out") continue;
3737
+ if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
3738
+ const joined = tokens.join(" ");
3739
+ const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
3740
+ types.push(TYPE_ALIASES[type] ?? type);
3156
3741
  }
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;
3742
+ return types;
3162
3743
  }
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 {
3173
- }
3174
- } else {
3175
- out.push(p);
3176
- }
3177
- }
3178
- return out;
3744
+ function git2(root, args) {
3745
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3746
+ return r.status === 0 ? r.stdout : null;
3179
3747
  }
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());
3191
- }
3192
- via.get(real2).add(root2);
3193
- if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
3194
- };
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
- }
3748
+ function gitView(root, dir, base) {
3749
+ if (git2(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
3750
+ if (git2(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
3751
+ return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
3752
+ }
3753
+ const mergeBase = git2(root, ["merge-base", "HEAD", base])?.trim();
3754
+ if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
3755
+ const diff = git2(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
3756
+ const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
3757
+ if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
3758
+ const sql = (p) => p !== void 0 && p.endsWith(".sql");
3759
+ const touched = new Set(untracked.split("\n").filter(sql));
3760
+ const edited = [];
3761
+ for (const row of diff.split("\n").filter(Boolean)) {
3762
+ const [status, a, b] = row.split(" ");
3763
+ if (status.startsWith("R")) {
3764
+ if (sql(b)) touched.add(b);
3765
+ if (sql(a)) edited.push({ file: a, status: "renamed" });
3766
+ continue;
3221
3767
  }
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" }))
3254
- );
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");
3768
+ if (!sql(a)) continue;
3769
+ if (status.startsWith("A")) touched.add(a);
3770
+ else if (status.startsWith("M") || status.startsWith("T")) {
3771
+ touched.add(a);
3772
+ edited.push({ file: a, status: "modified" });
3773
+ } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
3262
3774
  }
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;
3775
+ return { touched, edited };
3267
3776
  }
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))) {
3777
+ function checkSupabasePack(ctx) {
3778
+ const settings = ctx.config.supabase ?? {};
3779
+ const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
3780
+ const abs = path14.join(ctx.root, dir);
3781
+ if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
3782
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path14.join(abs, n), "utf8")) }));
3783
+ const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
3784
+ const base = settings.base ?? DEFAULT_BASE;
3785
+ const view = gitView(ctx.root, dir, base);
3786
+ if ("reason" in view) {
3787
+ if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
3788
+ } else {
3789
+ for (const e of view.edited) {
3274
3790
  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`
3791
+ rule: "migration-edited",
3792
+ file: e.file,
3793
+ subject: e.file,
3794
+ 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`
3280
3795
  });
3281
- continue;
3282
3796
  }
3797
+ }
3798
+ const since = settings.since;
3799
+ const afterSince = (file) => since === void 0 || path14.posix.basename(file) >= since;
3800
+ if ("reason" in view && since === void 0) {
3283
3801
  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`
3802
+ rule: "migration-grants",
3803
+ level: "warn",
3804
+ file: dir,
3805
+ 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`
3289
3806
  });
3807
+ } else {
3808
+ const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
3809
+ checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
3290
3810
  }
3811
+ checkRls(ctx, migrations, exposed);
3812
+ checkViewInvoker(ctx, migrations, exposed);
3813
+ checkDefinerSearchPath(ctx, migrations);
3814
+ checkTestingKit(ctx, migrations);
3291
3815
  }
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
- }
3816
+ function checkTestingKit(ctx, migrations) {
3817
+ for (const { file, statements } of migrations) {
3818
+ const hit = statements.find(({ sql }) => /\bgenesis_testing\b/.test(sql));
3819
+ if (!hit) continue;
3820
+ ctx.report({
3821
+ rule: "migration-testing-kit",
3822
+ file,
3823
+ line: hit.line,
3824
+ subject: "genesis_testing",
3825
+ message: "a migration uses genesis_testing, the pgTAP kit for test databases only; move it to supabase/tests/database/000_genesis_testing.test.sql"
3826
+ });
3314
3827
  }
3315
3828
  }
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) {
3322
- 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);
3337
- };
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));
3343
- };
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;
3829
+ function granteesOf(s) {
3830
+ return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
3831
+ }
3832
+ function checkGrants(ctx, migrations, exposed) {
3833
+ const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
3834
+ const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
3835
+ const blanket = (roles) => {
3836
+ const o = open(roles);
3837
+ if (o.length) return { level: "error", who: o.join(" and ") };
3838
+ if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
3839
+ return null;
3366
3840
  };
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;
3841
+ for (const { file, statements } of migrations) {
3842
+ for (const { sql, line } of statements) {
3843
+ const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
3844
+ if (all) {
3845
+ const hit = blanket(granteesOf(all[1]));
3846
+ if (hit) {
3847
+ 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}` });
3848
+ }
3849
+ continue;
3385
3850
  }
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("/");
3391
- 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;
3851
+ const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
3852
+ if (defaults) {
3853
+ const hit = blanket(granteesOf(defaults[1]));
3854
+ if (hit) {
3855
+ 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}` });
3402
3856
  }
3403
- if (c === "\\") {
3404
- out.push(" ", blank(code[i + 1] ?? ""));
3405
- i += 2;
3406
- continue;
3857
+ continue;
3858
+ }
3859
+ const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
3860
+ if (fn) {
3861
+ const roles = open(granteesOf(fn[2]));
3862
+ if (!roles.length) continue;
3863
+ for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
3864
+ if (exposed.has(schemaOf(name))) continue;
3865
+ ctx.report({
3866
+ rule: "migration-grants",
3867
+ file,
3868
+ line,
3869
+ subject: name,
3870
+ 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)`
3871
+ });
3407
3872
  }
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;
3873
+ continue;
3874
+ }
3875
+ const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
3876
+ if (schema) {
3877
+ const roles = open(granteesOf(schema[2]));
3878
+ if (!roles.length) continue;
3879
+ for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
3880
+ if (exposed.has(s)) continue;
3881
+ ctx.report({
3882
+ rule: "migration-grants",
3883
+ file,
3884
+ line,
3885
+ subject: `schema ${s}`,
3886
+ message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
3887
+ });
3420
3888
  }
3421
- out.push(" ");
3422
3889
  }
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] ?? ""));
3431
- i += 2;
3432
- } else {
3433
- out.push(keep ? code[i] : blank(code[i]));
3434
- i++;
3890
+ }
3891
+ }
3892
+ }
3893
+ function checkRls(ctx, migrations, exposed) {
3894
+ const tables = /* @__PURE__ */ new Map();
3895
+ const name = String.raw`([\w$.]+)`;
3896
+ const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
3897
+ for (const { file, statements } of migrations) {
3898
+ for (const { sql, line, bodies } of statements) {
3899
+ if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
3900
+ const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
3901
+ if (create) {
3902
+ if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
3903
+ continue;
3904
+ }
3905
+ const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
3906
+ const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
3907
+ if (rename || move) {
3908
+ const from = qualify((rename ?? move)[1]);
3909
+ const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
3910
+ const state = tables.get(from);
3911
+ if (state) {
3912
+ tables.delete(from);
3913
+ tables.set(to, state);
3435
3914
  }
3915
+ continue;
3436
3916
  }
3437
- if (code[i] !== ch) sure = false;
3438
- else {
3439
- out.push(code[i]);
3440
- i++;
3917
+ const alter = new RegExp(target).exec(sql);
3918
+ if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
3919
+ const t = qualify(alter[1]);
3920
+ if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
3921
+ else {
3922
+ const state = tables.get(t);
3923
+ if (state) state.rls = true;
3924
+ }
3925
+ continue;
3441
3926
  }
3442
- } else if (ch === "`" && (exprStart() || taggedTemplate())) {
3443
- out.push("`");
3444
- i++;
3445
- templateBody();
3446
- } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
3447
- templates.pop();
3448
- depth--;
3449
- out.push("}");
3450
- i++;
3451
- templateBody();
3452
- } else {
3453
- if (ch === "{") depth++;
3454
- else if (ch === "}") depth--;
3455
- out.push(ch);
3456
- i++;
3927
+ const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3928
+ if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
3457
3929
  }
3458
3930
  }
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]);
3474
- return out;
3475
- }
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;
3931
+ for (const [t, at] of tables) {
3932
+ if (at.rls || !exposed.has(schemaOf(t))) continue;
3933
+ ctx.report({
3934
+ rule: "migration-rls",
3935
+ file: at.file,
3936
+ line: at.line,
3937
+ subject: t,
3938
+ 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`
3939
+ });
3482
3940
  }
3483
3941
  }
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;
3942
+ function checkViewInvoker(ctx, migrations, exposed) {
3943
+ const views = /* @__PURE__ */ new Map();
3944
+ const name = String.raw`([\w$.]+)`;
3945
+ const invokerOn = /\bsecurity_invoker\s*(?:=\s*(?:true|on|yes|1|'true'|'on'))?\s*(?:,|\))/;
3946
+ for (const { file, statements } of migrations) {
3947
+ for (const { sql, line } of statements) {
3948
+ const create = new RegExp(String.raw`^create (?:or replace )?(?:temp |temporary )?(?:recursive )?view ${name}`).exec(sql);
3949
+ if (create) {
3950
+ if (/^create (?:or replace )?(?:temp|temporary) /.test(sql)) continue;
3951
+ const options = /^[^(]*?\bwith\s*(\([^)]*\))\s*as\b/.exec(sql)?.[1] ?? "";
3952
+ views.set(qualify(create[1]), { invoker: invokerOn.test(options), file, line });
3953
+ continue;
3954
+ }
3955
+ const alter = new RegExp(String.raw`^alter view (?:if exists )?${name} (set|reset) (\([^)]*\))`).exec(sql);
3956
+ if (alter && /\bsecurity_invoker\b/.test(alter[3])) {
3957
+ const state = views.get(qualify(alter[1]));
3958
+ if (state) state.invoker = alter[2] === "set" && invokerOn.test(alter[3]);
3959
+ continue;
3960
+ }
3961
+ const rename = new RegExp(String.raw`^alter view (?:if exists )?${name} rename to ([\w$]+)$`).exec(sql);
3962
+ if (rename) {
3963
+ const from = qualify(rename[1]);
3964
+ const state = views.get(from);
3965
+ if (state) {
3966
+ views.delete(from);
3967
+ views.set(`${schemaOf(from)}.${rename[2]}`, state);
3968
+ }
3969
+ continue;
3506
3970
  }
3971
+ const drop = /^drop view (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3972
+ if (drop) for (const n of drop[1].split(",")) views.delete(qualify(n));
3507
3973
  }
3508
- if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
3509
3974
  }
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;
3975
+ for (const [v, at] of views) {
3976
+ if (at.invoker || !exposed.has(schemaOf(v))) continue;
3977
+ ctx.report({
3978
+ rule: "migration-view-rls",
3979
+ file: at.file,
3980
+ line: at.line,
3981
+ subject: v,
3982
+ 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);"`
3983
+ });
3515
3984
  }
3516
- return merged;
3517
3985
  }
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(/\*$/, ""))) });
3986
+ function checkDefinerSearchPath(ctx, migrations) {
3987
+ const fns = /* @__PURE__ */ new Map();
3988
+ const keysFor = (sql, nameEnd, fnName) => {
3989
+ const rest = sql.slice(nameEnd).trimStart();
3990
+ if (rest.startsWith("(")) {
3991
+ const { inner } = parenthesized(rest, 0);
3992
+ return [`${fnName}(${argTypes(inner).join(",")})`];
3993
+ }
3994
+ return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
3995
+ };
3996
+ for (const { file, statements } of migrations) {
3997
+ for (const { sql, line } of statements) {
3998
+ const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
3999
+ if (create) {
4000
+ const [key2] = keysFor(sql, create[0].length, qualify(create[1]));
4001
+ fns.set(key2, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
4002
+ continue;
4003
+ }
4004
+ const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
4005
+ if (alter) {
4006
+ const fnName = qualify(alter[1]);
4007
+ const keys = keysFor(sql, alter[0].length, fnName);
4008
+ const rename = / rename to ([\w$]+)$/.exec(sql);
4009
+ const move = / set schema ([\w$]+)$/.exec(sql);
4010
+ for (const key2 of keys) {
4011
+ const state = fns.get(key2);
4012
+ if (rename || move) {
4013
+ if (!state) continue;
4014
+ fns.delete(key2);
4015
+ const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
4016
+ fns.set(newName + key2.slice(fnName.length), state);
4017
+ continue;
4018
+ }
4019
+ const next = state ?? { definer: false, searchPath: false, file, line };
4020
+ if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
4021
+ if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
4022
+ if (/\bset search_path\b/.test(sql)) next.searchPath = true;
4023
+ if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
4024
+ fns.set(key2, next);
4025
+ }
4026
+ continue;
4027
+ }
4028
+ const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
4029
+ if (drop) {
4030
+ for (const part of splitTop(drop[1])) {
4031
+ const m = /^([\w$.]+)\s*/.exec(part);
4032
+ if (m) for (const key2 of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key2);
4033
+ }
4034
+ }
3531
4035
  }
3532
4036
  }
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(/\*.*$/, ""))] });
4037
+ for (const [key2, at] of fns) {
4038
+ if (!at.definer || at.searchPath) continue;
4039
+ ctx.report({
4040
+ rule: "migration-definer-search-path",
4041
+ file: at.file,
4042
+ line: at.line,
4043
+ subject: key2,
4044
+ 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`
4045
+ });
3537
4046
  }
3538
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
3539
- return { table, baseUrl };
3540
4047
  }
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;
3546
- }
3547
- return null;
4048
+ var UMBRELLA_PACKAGE = "@marktiderman/genesis";
4049
+ function readReleaseManifest(root) {
4050
+ const dir = findPackageDir(root, UMBRELLA_PACKAGE);
4051
+ const file = dir && path14.join(dir, "dist", "versions.json");
4052
+ if (!file || !existsSync(file)) return null;
4053
+ return JSON.parse(readFileSync(file, "utf8"));
3548
4054
  }
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;
4055
+ function checkVersionSkew(ctx) {
4056
+ const manifest = readReleaseManifest(ctx.root);
4057
+ if (!manifest) return;
4058
+ for (const [name, want] of Object.entries(manifest.packages)) {
4059
+ const dir = findPackageDir(ctx.root, name);
4060
+ if (!dir) continue;
4061
+ const have = JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8")).version;
4062
+ if (have === want) continue;
4063
+ ctx.report({
4064
+ rule: "version-skew",
4065
+ level: "warn",
4066
+ file: "package.json",
4067
+ subject: name,
4068
+ message: `${name} is ${have}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Install ${name}@${want}, or move every Genesis package to one release.`
4069
+ });
4070
+ }
3554
4071
  }
3555
- function createTrail(ctx) {
3556
- const { table, baseUrl } = aliases(ctx.root);
3557
- let declared = null;
4072
+ var GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
4073
+ var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
4074
+ 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)$/;
4075
+ var readManifest = (dir) => {
3558
4076
  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] ?? {})));
4077
+ return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
3561
4078
  } catch {
3562
- declared = null;
4079
+ return null;
3563
4080
  }
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;
4081
+ };
4082
+ var real = (p) => {
4083
+ try {
4084
+ return realpathSync(p);
4085
+ } catch {
4086
+ return p;
4087
+ }
4088
+ };
4089
+ var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
4090
+ function nodeModulesOf(dir) {
4091
+ const parent = path14.dirname(dir);
4092
+ return path14.basename(parent).startsWith("@") ? path14.dirname(parent) : parent;
4093
+ }
4094
+ function packagesIn(nodeModules) {
4095
+ if (!existsSync(nodeModules)) return [];
4096
+ const out = [];
4097
+ for (const entry of readdirSync(nodeModules)) {
4098
+ if (entry.startsWith(".")) continue;
4099
+ const p = path14.join(nodeModules, entry);
4100
+ if (entry.startsWith("@")) {
4101
+ try {
4102
+ for (const sub of readdirSync(p)) out.push(path14.join(p, sub));
4103
+ } catch {
4104
+ }
4105
+ } else {
4106
+ out.push(p);
3577
4107
  }
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
- }
4108
+ }
4109
+ return out;
4110
+ }
4111
+ function genesisInstalls(root) {
4112
+ const copies = /* @__PURE__ */ new Map();
4113
+ const realRoot = real(root);
4114
+ const rel = (abs) => path14.relative(realRoot, abs).split(path14.sep).join("/") || ".";
4115
+ const via = /* @__PURE__ */ new Map();
4116
+ const record = (real2, manifest, by, range, root2) => {
4117
+ let copy = copies.get(real2);
4118
+ if (!copy) {
4119
+ copy = { name: manifest.name, version: String(manifest.version ?? "unknown"), dir: rel(real2), absolutePath: real2, requiredBy: [], devOnly: false, runtime: false };
4120
+ copies.set(real2, copy);
4121
+ via.set(real2, /* @__PURE__ */ new Set());
4122
+ }
4123
+ via.get(real2).add(root2);
4124
+ if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
4125
+ };
4126
+ const walk = (kind, roots) => {
4127
+ const expanded = /* @__PURE__ */ new Set();
4128
+ const queue = [];
4129
+ const visit = (dir, by, range) => {
4130
+ const manifest = readManifest(dir);
4131
+ if (!manifest?.name) return;
4132
+ if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
4133
+ const realDir = real(dir);
4134
+ if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
4135
+ if (expanded.has(realDir)) return;
4136
+ expanded.add(realDir);
4137
+ queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
4138
+ };
4139
+ for (const r of roots) visit(r.dir, r.by, r.range);
4140
+ while (queue.length) {
4141
+ const { real: from, manifest, label } = queue.shift();
4142
+ const deps = { ...manifest.optionalDependencies, ...manifest.dependencies };
4143
+ for (const [name, range] of Object.entries(deps)) {
4144
+ const dir = findPackageDir(from, name);
4145
+ if (dir) visit(dir, label, range);
4146
+ }
4147
+ for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
4148
+ if (name in deps) continue;
4149
+ const dir = peerOf(from, name);
4150
+ if (dir) visit(dir, label, range);
3605
4151
  }
3606
- if (resolved && !files.includes(resolved)) files.push(resolved);
3607
4152
  }
3608
- const out = { files, lost };
3609
- importsCache.set(file.absolutePath, out);
3610
- return out;
3611
4153
  };
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);
4154
+ const peerOf = (from, name) => {
4155
+ const dir = findPackageDir(from, name);
4156
+ if (!dir) return null;
4157
+ if (!ownInstall || name in declared) return dir;
4158
+ const realDir = real(dir);
4159
+ if (realDir.startsWith(realRoot + path14.sep)) return dir;
4160
+ return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
3616
4161
  };
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";
4162
+ const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
4163
+ const dir = findPackageDir(root, name);
4164
+ return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
4165
+ });
4166
+ const app = readManifest(root);
4167
+ const ownInstall = LOCKFILES.some((f) => existsSync(path14.join(root, f)));
4168
+ const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
4169
+ const declaredDev = Object.entries(app?.devDependencies ?? {});
4170
+ const runtimeDeps = {
4171
+ ...Object.fromEntries(declaredDev.filter(([n]) => !NON_SHIPPING.test(n))),
4172
+ ...app?.peerDependencies,
4173
+ ...app?.optionalDependencies,
4174
+ ...app?.dependencies
4175
+ };
4176
+ const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
4177
+ walk("runtime", rootsOf(runtimeDeps, "the app"));
4178
+ const top = path14.join(root, "node_modules");
4179
+ walk(
4180
+ "hoisted",
4181
+ packagesIn(top).filter((dir) => {
4182
+ const name = path14.relative(top, dir).split(path14.sep).join("/");
4183
+ return !(name in runtimeDeps) && !(name in devDeps);
4184
+ }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
4185
+ );
4186
+ const devRoots = { ...devDeps };
4187
+ for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
4188
+ walk("dev", rootsOf(devRoots, "the app (dev)"));
4189
+ for (const [key2, copy] of copies) {
4190
+ const kinds = via.get(key2);
4191
+ copy.runtime = kinds.has("runtime");
4192
+ copy.devOnly = kinds.size === 1 && kinds.has("dev");
4193
+ }
4194
+ const byName = /* @__PURE__ */ new Map();
4195
+ for (const copy of copies.values()) byName.set(copy.name, [...byName.get(copy.name) ?? [], copy]);
4196
+ for (const list of byName.values()) list.sort((a, b) => a.dir.split("/").length - b.dir.split("/").length || a.dir.localeCompare(b.dir));
4197
+ return byName;
4198
+ }
4199
+ function checkDuplicatePackages(ctx) {
4200
+ const describe = (c) => `${c.version} at ${c.dir} (${c.requiredBy.map((r) => `${r.by}${r.range ? ` wants ${r.range}` : ""}`).join("; ")})`;
4201
+ for (const [name, copies] of genesisInstalls(ctx.root)) {
4202
+ if (copies.length < 2) continue;
4203
+ const shipping = copies.filter((c) => c.runtime);
4204
+ if (!(shipping.length === 1 && copies.every((c) => c === shipping[0] || c.devOnly))) {
4205
+ ctx.report({
4206
+ rule: "duplicate-genesis-package",
4207
+ level: "warn",
4208
+ file: "package.json",
4209
+ subject: name,
4210
+ 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`
4211
+ });
4212
+ continue;
3659
4213
  }
3660
- if (result === "yes" || cut.size === 0) {
3661
- cache.free.set(k, result);
3662
- return [result, /* @__PURE__ */ new Set()];
4214
+ ctx.report({
4215
+ rule: "duplicate-genesis-package",
4216
+ level: "info",
4217
+ file: "package.json",
4218
+ subject: name,
4219
+ 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`
4220
+ });
4221
+ }
4222
+ }
4223
+ function checkPeerRanges(ctx) {
4224
+ const rel = (abs) => path14.relative(ctx.root, abs).split(path14.sep).join("/");
4225
+ for (const copies of genesisInstalls(ctx.root).values()) {
4226
+ for (const copy of copies) {
4227
+ const dir = copy.absolutePath;
4228
+ const peers = readManifest(dir)?.peerDependencies ?? {};
4229
+ for (const [peer, range] of Object.entries(peers)) {
4230
+ if (!GENESIS.test(peer)) continue;
4231
+ const peerDir = findPackageDir(dir, peer);
4232
+ const installed = peerDir && readManifest(peerDir)?.version;
4233
+ if (!peerDir || !installed) continue;
4234
+ if (satisfies(installed, range) !== false) continue;
4235
+ ctx.report({
4236
+ rule: "peer-range-mismatch",
4237
+ // A dev tool's own tree (the CLI's) doesn't run in the app.
4238
+ level: copy.devOnly ? "info" : "warn",
4239
+ file: "package.json",
4240
+ subject: `${copy.name}>${peer}`,
4241
+ 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}`
4242
+ });
4243
+ }
3663
4244
  }
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] };
4245
+ }
3670
4246
  }
3671
-
3672
- // src/doctor/routes.ts
3673
4247
  var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
3674
4248
  var STEMS = {
3675
4249
  tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
@@ -3782,7 +4356,7 @@ var SUB_NAV_DOCS = "https://github.com/marktiderman/genesis/blob/main/packages/u
3782
4356
  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
4357
  var SWITCHER = /<(TabsList|SubNavTabs)(?=[\s>/])/g;
3784
4358
  var SHELL = /<AppShell(?=[\s>/])/;
3785
- var GENESIS_PACKAGE = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
4359
+ var GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
3786
4360
  var PAGE_LAYOUT = /^(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)$/;
3787
4361
  var PACKAGE_SCREEN = /^(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)$/;
3788
4362
  var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
@@ -3838,7 +4412,7 @@ function checkLocalGenesisCopies(ctx) {
3838
4412
  const routes = routesDir(ctx);
3839
4413
  for (const file of ctx.files) {
3840
4414
  if (!JSX_EXTS2.has(file.ext)) continue;
3841
- const imported = new Set(namedImportsFrom(file.code, GENESIS_PACKAGE));
4415
+ const imported = new Set(namedImportsFrom(file.code, GENESIS_PACKAGE2));
3842
4416
  const inRoutes = routes !== null && file.path.startsWith(`${routes}/`);
3843
4417
  const routeComponents = new Set([...file.code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Z][\w$]*)\b/g)].map((r) => r[1]));
3844
4418
  const decls = [...file.code.matchAll(decl)];
@@ -3897,13 +4471,13 @@ function checkPageLayouts(ctx) {
3897
4471
  const inShell = insideShell(ctx, routes);
3898
4472
  const rendersLayout = (code) => {
3899
4473
  const names = new Set(layouts);
3900
- for (const n of namedImportsFrom(code, GENESIS_PACKAGE)) if (PACKAGE_SCREEN.test(n)) names.add(n);
4474
+ for (const n of namedImportsFrom(code, GENESIS_PACKAGE2)) if (PACKAGE_SCREEN.test(n)) names.add(n);
3901
4475
  return rendersRe(names)?.test(code) ?? false;
3902
4476
  };
3903
- const cache = /* @__PURE__ */ new Map();
4477
+ const cache2 = /* @__PURE__ */ new Map();
3904
4478
  const provides = (r) => {
3905
- if (!cache.has(r)) cache.set(r, routeReach(ctx, r, rendersLayout));
3906
- return cache.get(r);
4479
+ if (!cache2.has(r)) cache2.set(r, routeReach(ctx, r, rendersLayout));
4480
+ return cache2.get(r);
3907
4481
  };
3908
4482
  const list = [...layouts].sort();
3909
4483
  const named = list.length > 4 ? `${list.slice(0, 4).join(", ")}, \u2026` : list.join(", ");
@@ -3952,7 +4526,7 @@ async function runDoctor(options = {}) {
3952
4526
  if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
3953
4527
  }
3954
4528
  const raw = [];
3955
- const ctx = { root, files, genesis, config, report: (f) => raw.push(f) };
4529
+ const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
3956
4530
  for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
3957
4531
  try {
3958
4532
  await plugin.check(ctx);
@@ -3984,7 +4558,8 @@ async function runDoctor(options = {}) {
3984
4558
  function builtinChecks(config) {
3985
4559
  const packs = {
3986
4560
  native: { name: "native", check: checkNativePack },
3987
- supabase: { name: "supabase", check: checkSupabasePack }
4561
+ supabase: { name: "supabase", check: checkSupabasePack },
4562
+ packages: { name: "packages", check: checkPackagesPack }
3988
4563
  };
3989
4564
  return [
3990
4565
  { name: "layout", check: checkProjectLayout },