@marktiderman/genesis-cli 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ var NOOP_LOGGER = {
18
18
  function validateConsumerName(name) {
19
19
  if (!VALID_NAME_PATTERN.test(name)) {
20
20
  throw new Error(
21
- `Invalid consumer name "${name}". Must be lowercase letters/digits/hyphens, 2-31 chars, starting with a letter (e.g., "acme", "gamify-mobile").`
21
+ `Invalid consumer name "${name}". Must be lowercase letters/digits/hyphens, 2-31 chars, starting with a letter (e.g., "acme", "arcade-mobile").`
22
22
  );
23
23
  }
24
24
  }
@@ -101,9 +101,9 @@ async function runScaffold(opts, fs) {
101
101
  function joinPath(...parts) {
102
102
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
103
103
  }
104
- function dirname(path10) {
105
- const idx = path10.lastIndexOf("/");
106
- return idx === -1 ? "." : path10.slice(0, idx);
104
+ function dirname(path13) {
105
+ const idx = path13.lastIndexOf("/");
106
+ return idx === -1 ? "." : path13.slice(0, idx);
107
107
  }
108
108
  function brandPackageJson(consumer, genesisVersion) {
109
109
  return JSON.stringify(
@@ -144,7 +144,7 @@ function brandSchema(consumer) {
144
144
  * Genesis primitives consume tokens from this file via the design-system
145
145
  * provider. Edit colors/spacing/typography here to retheme every screen
146
146
  * at once. Domain-specific tokens (e.g., "mood" for Acme, "rarity" for
147
- * Gamify) go under \`extensions\` \u2014 Genesis primitives don't read these,
147
+ * a game app) go under \`extensions\` \u2014 Genesis primitives don't read these,
148
148
  * but consumer composites do via \`useGenesisExtension(key)\`.
149
149
  *
150
150
  * Schema is intentionally narrow at the top level. Add categories under
@@ -1012,11 +1012,26 @@ var KNOWN = /* @__PURE__ */ new Set([
1012
1012
  "allow",
1013
1013
  "patterns",
1014
1014
  "plugins",
1015
+ "packs",
1016
+ "native",
1017
+ "supabase",
1015
1018
  "$schema",
1016
1019
  "$comment"
1017
1020
  ]);
1018
1021
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "off"]);
1019
1022
  var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
1023
+ var PACKS = /* @__PURE__ */ new Set(["native", "supabase"]);
1024
+ var PACK_KEYS = {
1025
+ native: { routerRoot: "path" },
1026
+ supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" }
1027
+ };
1028
+ function appPath(v, where, fail) {
1029
+ if (typeof v !== "string" || !v.trim()) return fail(`${where} must be a non-empty path`);
1030
+ if (path3.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where} must be relative to the app, not absolute ("${v}")`);
1031
+ const norm = path3.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
1032
+ if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where} must be a folder inside the app ("${v}")`);
1033
+ return norm;
1034
+ }
1020
1035
  function loadConfig(root, configPath) {
1021
1036
  if (configPath) {
1022
1037
  const file = path3.resolve(root, configPath);
@@ -1140,6 +1155,27 @@ function validateConfig(raw, source = "config") {
1140
1155
  }
1141
1156
  });
1142
1157
  }
1158
+ if (c.packs !== void 0) {
1159
+ if (!isStringList(c.packs)) fail(`"packs" must be a list, e.g. ["native", "supabase"]`);
1160
+ for (const p of c.packs) if (!PACKS.has(p)) fail(`packs: unknown pack "${p}" (known: ${[...PACKS].join(", ")})`);
1161
+ if (new Set(c.packs).size !== c.packs.length) fail(`packs: lists a pack twice`);
1162
+ }
1163
+ for (const [pack, keys] of Object.entries(PACK_KEYS)) {
1164
+ const block = c[pack];
1165
+ if (block === void 0) continue;
1166
+ if (!isObject(block)) fail(`"${pack}" must be an object`);
1167
+ if (!(c.packs ?? []).includes(pack)) fail(`"${pack}" settings are set but the ${pack} pack is not in "packs"`);
1168
+ for (const [k, v] of Object.entries(block)) {
1169
+ const want = keys[k];
1170
+ if (!want) fail(`${pack}: unknown setting "${k}"`);
1171
+ if (want === "string" && typeof v !== "string") fail(`${pack}.${k} must be a string`);
1172
+ if (want === "list" && !isStringList(v)) fail(`${pack}.${k} must be a list of strings`);
1173
+ if (want === "string" && !v.trim()) fail(`${pack}.${k} must not be empty`);
1174
+ if (want === "path") block[k] = appPath(v, `${pack}.${k}`, fail);
1175
+ }
1176
+ }
1177
+ const supa = c.supabase;
1178
+ if (Array.isArray(supa?.exposedSchemas)) supa.exposedSchemas = supa.exposedSchemas.map((s) => s.toLowerCase());
1143
1179
  if (c.plugins !== void 0) {
1144
1180
  const ok = Array.isArray(c.plugins) && c.plugins.every((p) => typeof p === "string" || Array.isArray(p) && p.length === 2 && typeof p[0] === "string");
1145
1181
  if (!ok) fail(`"plugins" must be a list of module paths or [path, options] pairs`);
@@ -1185,9 +1221,10 @@ function globToRegExp(glob) {
1185
1221
  }
1186
1222
  function globMatcher(globs) {
1187
1223
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1188
- return (path10) => res.some((re) => re.test(path10));
1224
+ return (path13) => res.some((re) => re.test(path13));
1189
1225
  }
1190
1226
  var DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
1227
+ var NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
1191
1228
  var DESIGN_SYSTEM_PACKAGE = "@marktiderman/genesis-design-system";
1192
1229
  var TAGS = ["button", "input", "textarea", "select", "label", "table", "dialog", "progress", "details", "summary"];
1193
1230
  var TAG_ALIASES = { hr: "Separator" };
@@ -1232,10 +1269,39 @@ function findPackageDir(from, name) {
1232
1269
  dir = parent;
1233
1270
  }
1234
1271
  }
1272
+ function uiPackageFor(config) {
1273
+ return config.uiPackage ?? (config.packs?.includes("native") ? NATIVE_UI_PACKAGE : DEFAULT_UI_PACKAGE);
1274
+ }
1235
1275
  function loadGenesis(root, config) {
1236
- const uiPackage = config.uiPackage ?? DEFAULT_UI_PACKAGE;
1276
+ const uiPackage = uiPackageFor(config);
1277
+ const pkg = readPackageExports(root, uiPackage);
1278
+ if (!pkg) throw new DoctorConfigError(`${uiPackage} is not installed here. Install it, or set doctor.uiPackage.`);
1279
+ const { dir: uiDir, exports: exportNames, values, components } = pkg;
1280
+ const tokens = /* @__PURE__ */ new Set();
1281
+ const themeFiles = resolveThemeFiles(root, config, uiDir);
1282
+ for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
1283
+ const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
1284
+ const rawTags = /* @__PURE__ */ new Map();
1285
+ for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
1286
+ for (const [tag, comp] of Object.entries(TAG_ALIASES)) if (values.has(comp)) rawTags.set(tag, comp);
1287
+ for (const [tag, comp] of Object.entries(config.rawTags ?? {})) {
1288
+ if (comp === false) rawTags.delete(tag);
1289
+ else rawTags.set(tag, comp);
1290
+ }
1291
+ return {
1292
+ uiPackage,
1293
+ uiVersion: pkg.version,
1294
+ exports: exportNames,
1295
+ values,
1296
+ components,
1297
+ tokens,
1298
+ rawTags,
1299
+ palette: loadPalette(root)
1300
+ };
1301
+ }
1302
+ function readPackageExports(root, uiPackage) {
1237
1303
  const uiDir = findPackageDir(root, uiPackage);
1238
- if (!uiDir) throw new DoctorConfigError(`${uiPackage} is not installed here. Install it, or set doctor.uiPackage.`);
1304
+ if (!uiDir) return null;
1239
1305
  const uiPkg = JSON.parse(readFileSync(path3.join(uiDir, "package.json"), "utf8"));
1240
1306
  const typeEntries = /* @__PURE__ */ new Set();
1241
1307
  const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
@@ -1276,27 +1342,7 @@ function loadGenesis(root, config) {
1276
1342
  const isTypeOnly = (n) => typeDecls.has(n) && !valueDecls.has(n);
1277
1343
  const values = new Set([...exportNames].filter((n) => !isTypeOnly(n)));
1278
1344
  const components = [...values].filter((n) => /^[A-Z][A-Za-z0-9]*$/.test(n) && !(n.length > 2 && n === n.toUpperCase()) && !NON_COMPONENT_SUFFIX.test(n)).sort();
1279
- const tokens = /* @__PURE__ */ new Set();
1280
- const themeFiles = resolveThemeFiles(root, config, uiDir);
1281
- for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
1282
- const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
1283
- const rawTags = /* @__PURE__ */ new Map();
1284
- for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
1285
- for (const [tag, comp] of Object.entries(TAG_ALIASES)) if (values.has(comp)) rawTags.set(tag, comp);
1286
- for (const [tag, comp] of Object.entries(config.rawTags ?? {})) {
1287
- if (comp === false) rawTags.delete(tag);
1288
- else rawTags.set(tag, comp);
1289
- }
1290
- return {
1291
- uiPackage,
1292
- uiVersion: String(uiPkg.version ?? "unknown"),
1293
- exports: exportNames,
1294
- values,
1295
- components,
1296
- tokens,
1297
- rawTags,
1298
- palette: loadPalette(root)
1299
- };
1345
+ return { dir: uiDir, version: String(uiPkg.version ?? "unknown"), exports: exportNames, values, components };
1300
1346
  }
1301
1347
  function parseExportNames(dts) {
1302
1348
  const names = [];
@@ -1549,6 +1595,7 @@ function findColorFunctions(line) {
1549
1595
 
1550
1596
  // src/doctor/scan.ts
1551
1597
  var DEFAULT_SRC = ["src"];
1598
+ var DEFAULT_NATIVE_SRC = ["app", "src", "components"];
1552
1599
  var DEFAULT_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".css"];
1553
1600
  var DEFAULT_IGNORE = [
1554
1601
  "**/*.d.ts",
@@ -1586,7 +1633,7 @@ function scanFiles(root, config) {
1586
1633
  }
1587
1634
  }
1588
1635
  };
1589
- for (const src of config.src ?? DEFAULT_SRC) {
1636
+ for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
1590
1637
  const abs = path3.resolve(root, src);
1591
1638
  if (!existsSync(abs)) continue;
1592
1639
  if (statSync(abs).isDirectory()) walk(abs);
@@ -1742,7 +1789,18 @@ var BUILTIN_RULES = [
1742
1789
  "raw-color",
1743
1790
  "undefined-token",
1744
1791
  "shadowed-export",
1745
- "version-skew"
1792
+ "version-skew",
1793
+ // native pack
1794
+ "native-raw-primitive",
1795
+ "native-literal-color",
1796
+ "native-custom-header",
1797
+ "native-screen-layout",
1798
+ "store-readiness",
1799
+ // supabase pack
1800
+ "migration-grants",
1801
+ "migration-rls",
1802
+ "migration-definer-search-path",
1803
+ "migration-edited"
1746
1804
  ];
1747
1805
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
1748
1806
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -1818,7 +1876,10 @@ function checkColors(ctx) {
1818
1876
  `(?<![\\w-])(?:${COLOR_UTILITIES})-(?:${ctx.genesis.palette.join("|")})(?:-\\d{2,3})?(?:\\/\\d{1,3})?(?![\\w-])`,
1819
1877
  "g"
1820
1878
  );
1879
+ const native = ctx.config.packs?.includes("native") ?? false;
1880
+ const themeRoles = ctx.genesis.values.has("useThemeRoles") ? "a theme role (useThemeRoles())" : "a theme role";
1821
1881
  for (const file of ctx.files) {
1882
+ const nativeCode = native && SCRIPT_EXTS.has(file.ext);
1822
1883
  file.code.split("\n").forEach((text, i) => {
1823
1884
  const line = i + 1;
1824
1885
  for (const m of text.matchAll(palette)) {
@@ -1832,6 +1893,16 @@ function checkColors(ctx) {
1832
1893
  for (const hit of [...findHexLiterals(text), ...findColorFunctions(text)]) {
1833
1894
  const at = hit.column - 1;
1834
1895
  if (arbitrary.some(([a, b]) => at >= a && at < b)) continue;
1896
+ if (nativeCode) {
1897
+ ctx.report({
1898
+ rule: "native-literal-color",
1899
+ file: file.path,
1900
+ line,
1901
+ subject: hit.literal,
1902
+ message: `hardcodes the color ${hit.literal}; use ${themeRoles}, a token className (bg-primary, text-muted-foreground) or PlatformColor(...)`
1903
+ });
1904
+ continue;
1905
+ }
1835
1906
  ctx.report({ rule: "raw-color", file: file.path, line, subject: hit.literal, message: `hardcodes the color ${hit.literal}; color values come from Genesis tokens` });
1836
1907
  }
1837
1908
  });
@@ -1888,6 +1959,751 @@ function unusedComponents(ctx) {
1888
1959
  }
1889
1960
  return ctx.genesis.components.filter((c) => !used.has(c));
1890
1961
  }
1962
+
1963
+ // ../../scripts/lib/native-primitives.mjs
1964
+ var NATIVE_WRAPPED_PRIMITIVES = Object.freeze({
1965
+ Modal: Object.freeze(["NativeDialog", "NativeSheet", "NativeDrawer"]),
1966
+ ActivityIndicator: Object.freeze(["NativeSkeleton", "NativeProgress"])
1967
+ });
1968
+ function wrappedPrimitivesIn(namedImports) {
1969
+ return namedImports.split(",").map((n) => n.trim()).filter((n) => n && !/^type\s/.test(n)).map((n) => n.split(/\s+as\s+/)[0].trim()).filter((n) => n && Object.hasOwn(NATIVE_WRAPPED_PRIMITIVES, n));
1970
+ }
1971
+ var PRIVACY_APIS = {
1972
+ "@react-native-async-storage/async-storage": [
1973
+ { NSPrivacyAccessedAPIType: "NSPrivacyAccessedAPICategoryFileTimestamp", NSPrivacyAccessedAPITypeReasons: ["C617.1"] }
1974
+ ]
1975
+ };
1976
+ function privacyApisFor(dependencies2) {
1977
+ return Object.keys(PRIVACY_APIS).filter((pkg) => pkg in dependencies2).flatMap((pkg) => PRIVACY_APIS[pkg]);
1978
+ }
1979
+
1980
+ // src/doctor/native.ts
1981
+ var SCRIPT_EXTS2 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
1982
+ var JSX_EXTS2 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
1983
+ var RESOLVE_EXTS = [".tsx", ".ts", ".jsx", ".js"];
1984
+ var LAYOUT_NAME = /(?:Page|Screen|ScreenContainer)$/;
1985
+ var NON_SCREEN_ROUTE = /(?:^|\/)(?:_layout|\+html|\+native-intent|\+middleware)\.[jt]sx?$|\+api\.[jt]sx?$/;
1986
+ var PART_HEADER = /(?:Section|List|Card|Dialog|Table|Group|Column|Row|Cell|Accordion|Sheet|Drawer|Modal|Popover|Menu|Panel|Form)Header$/;
1987
+ var HIDES_HEADER = /\bheaderShown\s*(?::|=\s*\{)\s*false\b/;
1988
+ function nativePackage(ctx) {
1989
+ const pkg = readPackageExports(ctx.root, NATIVE_UI_PACKAGE);
1990
+ if (!pkg) throw new DoctorConfigError(`the native pack needs ${NATIVE_UI_PACKAGE}; install it, or remove "native" from doctor.packs`);
1991
+ return pkg;
1992
+ }
1993
+ function nativeLayouts(pkg) {
1994
+ return pkg.components.filter((n) => LAYOUT_NAME.test(n));
1995
+ }
1996
+ function checkNativePack(ctx) {
1997
+ const pkg = nativePackage(ctx);
1998
+ checkRawPrimitives(ctx, pkg);
1999
+ checkCustomHeaders(ctx, pkg);
2000
+ checkScreenLayouts(ctx, pkg);
2001
+ checkStoreReadiness(ctx);
2002
+ }
2003
+ var RN = String.raw`["']react-native["']`;
2004
+ function checkRawPrimitives(ctx, pkg) {
2005
+ const wrapped = Object.keys(NATIVE_WRAPPED_PRIMITIVES);
2006
+ const named = [
2007
+ // import { Modal } / import RN, { Modal }; `import type { … }` doesn't match.
2008
+ new RegExp(String.raw`\bimport\s+(?:[\w$]+\s*,\s*)?\{([^}]*)\}\s*from\s*${RN}`, "g"),
2009
+ new RegExp(String.raw`\bexport\s+\{([^}]*)\}\s*from\s*${RN}`, "g"),
2010
+ new RegExp(String.raw`\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*${RN}\s*\)`, "g")
2011
+ ];
2012
+ const namespaces = [
2013
+ new RegExp(String.raw`\bimport\s+\*\s+as\s+([\w$]+)\s+from\s*${RN}`, "g"),
2014
+ new RegExp(String.raw`\b(?:const|let|var)\s+([\w$]+)\s*=\s*require\(\s*${RN}\s*\)`, "g")
2015
+ ];
2016
+ const member = new RegExp(String.raw`\brequire\(\s*${RN}\s*\)\.(${wrapped.join("|")})\b`, "g");
2017
+ for (const file of ctx.files) {
2018
+ if (!SCRIPT_EXTS2.has(file.ext)) continue;
2019
+ const code = file.code;
2020
+ const report = (name, at) => {
2021
+ const use = NATIVE_WRAPPED_PRIMITIVES[name].filter((c) => pkg.values.has(c));
2022
+ ctx.report({
2023
+ rule: "native-raw-primitive",
2024
+ file: file.path,
2025
+ line: lineAt(code, at),
2026
+ subject: name,
2027
+ message: `uses ${name} from react-native, which Genesis wraps; use ${use.length ? use.join(" or ") : "the Genesis wrapper"} from ${NATIVE_UI_PACKAGE}`
2028
+ });
2029
+ };
2030
+ for (const re of named) {
2031
+ for (const m of code.matchAll(re)) {
2032
+ for (const name of wrappedPrimitivesIn(m[1].replace(/:/g, " as "))) report(name, m.index + m[0].indexOf(name));
2033
+ }
2034
+ }
2035
+ for (const re of namespaces) {
2036
+ for (const m of code.matchAll(re)) {
2037
+ for (const use of code.matchAll(new RegExp(String.raw`\b${m[1].replace(/\$/g, "\\$")}\.(${wrapped.join("|")})\b`, "g"))) report(use[1], use.index);
2038
+ }
2039
+ }
2040
+ for (const m of code.matchAll(member)) report(m[1], m.index);
2041
+ }
2042
+ }
2043
+ function customElement(code, re, pkg) {
2044
+ for (const m of code.matchAll(re)) {
2045
+ const name = m[1];
2046
+ if (!pkg.values.has(name.split(".")[0]) && !PART_HEADER.test(name)) return { name, index: m.index };
2047
+ }
2048
+ return null;
2049
+ }
2050
+ function ownHeader(code, pkg) {
2051
+ const el = customElement(code, /<([A-Z][\w$]*Header)\b/g, pkg);
2052
+ if (el) return el;
2053
+ const style = /\bstyle=\{\s*styles\.header\s*\}/.exec(code);
2054
+ return style ? { name: "styles.header", index: style.index } : null;
2055
+ }
2056
+ function checkCustomHeaders(ctx, pkg) {
2057
+ const layouts = nativeLayouts(pkg);
2058
+ if (layouts.length === 0) return;
2059
+ const headerWay = pkg.values.has("ScreenContainer") ? `ScreenContainer's header props${pkg.values.has("composeHeaderOptions") ? " (composeHeaderOptions)" : ""}` : `a Genesis layout's header (${layouts.join(", ")})`;
2060
+ const rootDir = routerRoot(ctx);
2061
+ const reported = /* @__PURE__ */ new Set();
2062
+ const hidingLayouts = /* @__PURE__ */ new Map();
2063
+ for (const file of ctx.files) {
2064
+ if (!JSX_EXTS2.has(file.ext)) continue;
2065
+ const code = file.code;
2066
+ const hidden = HIDES_HEADER.exec(code);
2067
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path3.posix.dirname(file.path), file.path);
2068
+ const own = hidden ? ownHeader(code, pkg) : null;
2069
+ if (hidden && own) {
2070
+ reported.add(file.path);
2071
+ ctx.report({
2072
+ rule: "native-custom-header",
2073
+ level: "warn",
2074
+ file: file.path,
2075
+ line: lineAt(code, hidden.index),
2076
+ subject: own.name,
2077
+ message: `hides the navigator header and draws its own (${own.name}); use ${headerWay} so the title, back button and large-title behavior stay native`
2078
+ });
2079
+ }
2080
+ const tabBarProp = /<Tabs\b/.test(code) ? /\btabBar\s*=\s*\{/.exec(code) : null;
2081
+ const tabBar = tabBarProp ? { name: "tabBar prop", index: tabBarProp.index } : customElement(code, /<([A-Z][\w$]*TabBar)\b/g, pkg);
2082
+ if (tabBar) {
2083
+ ctx.report({
2084
+ rule: "native-custom-header",
2085
+ level: "warn",
2086
+ file: file.path,
2087
+ line: lineAt(code, tabBar.index),
2088
+ subject: tabBar.name,
2089
+ message: `builds a tab bar by hand (${tabBar.name}); use the router's native <Tabs> bar, themed through Genesis screenOptions`
2090
+ });
2091
+ }
2092
+ }
2093
+ for (const file of ctx.files) {
2094
+ if (!JSX_EXTS2.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
2095
+ const layout = hidingLayouts.get(path3.posix.dirname(file.path));
2096
+ const own = layout ? ownHeader(file.code, pkg) : null;
2097
+ if (!layout || !own) continue;
2098
+ ctx.report({
2099
+ rule: "native-custom-header",
2100
+ level: "warn",
2101
+ file: file.path,
2102
+ line: lineAt(file.code, own.index),
2103
+ subject: own.name,
2104
+ message: `draws its own header (${own.name}) while ${layout} hides the navigator's; use ${headerWay} so the title, back button and large-title behavior stay native`
2105
+ });
2106
+ }
2107
+ }
2108
+ function routerRoot(ctx) {
2109
+ if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
2110
+ return existsSync(path3.join(ctx.root, "src", "app")) ? "src/app" : "app";
2111
+ }
2112
+ function checkScreenLayouts(ctx, pkg) {
2113
+ const layouts = nativeLayouts(pkg);
2114
+ if (layouts.length === 0) return;
2115
+ const rootDir = routerRoot(ctx);
2116
+ if (!existsSync(path3.join(ctx.root, rootDir))) {
2117
+ ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
2118
+ return;
2119
+ }
2120
+ const routes = ctx.files.filter((f) => f.path.startsWith(`${rootDir}/`));
2121
+ if (routes.length === 0) {
2122
+ ctx.report({
2123
+ rule: "native-screen-layout",
2124
+ level: "warn",
2125
+ file: rootDir,
2126
+ message: `no scanned file is under the router root ${rootDir}, so no screen was checked; add it to doctor.src`
2127
+ });
2128
+ return;
2129
+ }
2130
+ const renders = new RegExp(`<(?:${layouts.join("|")}|Redirect)\\b`);
2131
+ const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
2132
+ for (const file of routes) {
2133
+ if (!JSX_EXTS2.has(file.ext) || NON_SCREEN_ROUTE.test(file.path)) continue;
2134
+ if (!/\bexport\s+default\b/.test(file.code) || !/<[A-Za-z]/.test(file.code)) continue;
2135
+ if (renders.test(file.code)) continue;
2136
+ const viaImport = localImports(ctx.root, file).some((abs) => {
2137
+ const target = byPath.get(abs) ?? readSource(abs);
2138
+ return target !== null && renders.test(target.code);
2139
+ });
2140
+ if (viaImport) continue;
2141
+ ctx.report({
2142
+ rule: "native-screen-layout",
2143
+ level: "warn",
2144
+ file: file.path,
2145
+ message: `doesn't render a Genesis screen layout (${layouts.join(", ")}); wrap the screen in one so the header, safe area and scrolling match every other screen`
2146
+ });
2147
+ }
2148
+ }
2149
+ function localImports(root, file) {
2150
+ const out = [];
2151
+ for (const m of file.code.matchAll(/\bfrom\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g)) {
2152
+ const spec = m[1];
2153
+ const bases = spec.startsWith(".") ? [path3.resolve(path3.dirname(file.absolutePath), spec)] : [path3.join(root, spec.slice(2)), path3.join(root, "src", spec.slice(2))];
2154
+ for (const base of bases) {
2155
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path3.join(base, `index${e}`))].find(
2156
+ (p) => SCRIPT_EXTS2.has(path3.extname(p)) && existsSync(p)
2157
+ );
2158
+ if (hit) {
2159
+ out.push(hit);
2160
+ break;
2161
+ }
2162
+ }
2163
+ }
2164
+ return out;
2165
+ }
2166
+ function readSource(abs) {
2167
+ try {
2168
+ return { code: readFileSync(abs, "utf8") };
2169
+ } catch {
2170
+ return null;
2171
+ }
2172
+ }
2173
+ var PERMISSIONS = [
2174
+ { module: "expo-camera", key: "NSCameraUsageDescription", option: "cameraPermission" },
2175
+ { module: "expo-image-picker", key: "NSPhotoLibraryUsageDescription", option: "photosPermission" },
2176
+ { module: "expo-image-picker", key: "NSCameraUsageDescription", option: "cameraPermission", maybe: "takes photos with the camera" },
2177
+ { module: "expo-media-library", key: "NSPhotoLibraryUsageDescription", option: "photosPermission" },
2178
+ { module: "expo-location", key: "NSLocationWhenInUseUsageDescription", option: "locationWhenInUsePermission" },
2179
+ { module: "expo-av", key: "NSMicrophoneUsageDescription", option: "microphonePermission", maybe: "records audio" },
2180
+ { module: "expo-audio", key: "NSMicrophoneUsageDescription", option: "microphonePermission", maybe: "records audio" },
2181
+ { module: "expo-contacts", key: "NSContactsUsageDescription", option: "contactsPermission" },
2182
+ { module: "expo-local-authentication", key: "NSFaceIDUsageDescription", option: "faceIDPermission" }
2183
+ ];
2184
+ var SOCIAL_SIGN_IN = ["@react-native-google-signin/google-signin", "react-native-fbsdk-next"];
2185
+ var WEAK_SOCIAL_SIGN_IN = ["expo-auth-session"];
2186
+ var APPLE_SIGN_IN = ["expo-apple-authentication", "@invertase/react-native-apple-authentication"];
2187
+ var EXPO_CONFIGS = ["app.json", "app.config.json", "app.config.ts", "app.config.js", "app.config.mjs", "app.config.cjs"];
2188
+ var SUPABASE_SIGN_IN = /\bsignInWith(?:OAuth|IdToken)\s*\(\s*\{\s*provider\s*:\s*["']([\w-]+)["']/g;
2189
+ var GENESIS_PLUGIN = "@marktiderman/genesis-cli";
2190
+ var GENESIS_PLUGIN_TEXT = /["']@marktiderman\/genesis-cli(?:\/expo)?["']|\bwithGenesis\s*\(/;
2191
+ var GENESIS_PLUGIN_IMPORT = /\bfrom\s*["']@marktiderman\/genesis-cli[^"']*["']|\b(?:require|import)\s*\(\s*["']@marktiderman\/genesis-cli[^"']*["']\s*\)/g;
2192
+ function readExpoConfigs(root) {
2193
+ const out = [];
2194
+ for (const name of EXPO_CONFIGS) {
2195
+ const abs = path3.join(root, name);
2196
+ if (!existsSync(abs)) continue;
2197
+ const text = readFileSync(abs, "utf8");
2198
+ let json = null;
2199
+ if (name.endsWith(".json")) {
2200
+ try {
2201
+ const raw = JSON.parse(text);
2202
+ json = raw.expo ?? raw;
2203
+ } catch (err) {
2204
+ throw new DoctorConfigError(`${name} is not valid JSON: ${err.message}`);
2205
+ }
2206
+ }
2207
+ out.push({ file: name, json, text });
2208
+ }
2209
+ return out;
2210
+ }
2211
+ function get(obj, keys) {
2212
+ let cur = obj;
2213
+ for (const k of keys) {
2214
+ if (!cur || typeof cur !== "object") return void 0;
2215
+ cur = cur[k];
2216
+ }
2217
+ return cur;
2218
+ }
2219
+ function pluginOptions(json, module) {
2220
+ const plugins = json?.plugins;
2221
+ if (!Array.isArray(plugins)) return null;
2222
+ for (const p of plugins) {
2223
+ if (p === module) return {};
2224
+ if (Array.isArray(p) && p[0] === module) return p[1] && typeof p[1] === "object" ? p[1] : {};
2225
+ }
2226
+ return null;
2227
+ }
2228
+ function dependencies(root) {
2229
+ const file = path3.join(root, "package.json");
2230
+ if (!existsSync(file)) return /* @__PURE__ */ new Set();
2231
+ const pkg = JSON.parse(readFileSync(file, "utf8"));
2232
+ return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
2233
+ }
2234
+ function runtimeDependencies(root) {
2235
+ const file = path3.join(root, "package.json");
2236
+ if (!existsSync(file)) return {};
2237
+ return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
2238
+ }
2239
+ function checkStoreReadiness(ctx) {
2240
+ const configs = readExpoConfigs(ctx.root);
2241
+ if (configs.length === 0) {
2242
+ ctx.report({ rule: "store-readiness", level: "warn", file: "app.json", message: "no app.json or app.config.* found; the store checks read the Expo config" });
2243
+ return;
2244
+ }
2245
+ const file = configs[0].file;
2246
+ const deps = dependencies(ctx.root);
2247
+ const has2 = (keys, word) => configs.some((c) => c.json ? get(c.json, keys) !== void 0 : new RegExp(`\\b${word}\\b`).test(c.text));
2248
+ const genesisPluginDoes = (option) => configs.some((c) => {
2249
+ if (c.json) {
2250
+ const options = pluginOptions(c.json, GENESIS_PLUGIN) ?? pluginOptions(c.json, `${GENESIS_PLUGIN}/expo`);
2251
+ return options !== null && options[option] !== false;
2252
+ }
2253
+ const listed = c.text.replace(GENESIS_PLUGIN_IMPORT, "");
2254
+ return GENESIS_PLUGIN_TEXT.test(listed) && !new RegExp(`\\b${option}\\s*:\\s*false\\b`).test(c.text);
2255
+ });
2256
+ const exportCompliance = has2(["ios", "config", "usesNonExemptEncryption"], "usesNonExemptEncryption") || has2(["ios", "infoPlist", "ITSAppUsesNonExemptEncryption"], "ITSAppUsesNonExemptEncryption") || genesisPluginDoes("exportCompliance");
2257
+ if (!exportCompliance) {
2258
+ ctx.report({
2259
+ rule: "store-readiness",
2260
+ level: "warn",
2261
+ file,
2262
+ subject: "usesNonExemptEncryption",
2263
+ message: "sets neither ios.config.usesNonExemptEncryption nor ios.infoPlist.ITSAppUsesNonExemptEncryption; set it (false for HTTPS-only apps) so App Store Connect doesn't hold every build for the export-compliance question"
2264
+ });
2265
+ }
2266
+ const social = SOCIAL_SIGN_IN.filter((d) => deps.has(d));
2267
+ let apple = APPLE_SIGN_IN.some((d) => deps.has(d));
2268
+ for (const f of ctx.files) {
2269
+ for (const m of f.code.matchAll(SUPABASE_SIGN_IN)) {
2270
+ if (m[1] === "apple") apple = true;
2271
+ else if (!social.includes(`Supabase ${m[1]} sign-in`)) social.push(`Supabase ${m[1]} sign-in`);
2272
+ }
2273
+ }
2274
+ if (social.length > 0 && !apple) {
2275
+ const weak = WEAK_SOCIAL_SIGN_IN.filter((d) => deps.has(d));
2276
+ ctx.report({
2277
+ rule: "store-readiness",
2278
+ level: "warn",
2279
+ file: "package.json",
2280
+ subject: "sign-in-with-apple",
2281
+ message: `offers third-party sign-in (${[...social, ...weak].join(", ")}) and no Sign in with Apple. App Store guideline 4.8 asks for an equivalent login that limits data collection to name and email, lets people keep their email private and doesn't track them; Sign in with Apple (expo-apple-authentication, or Supabase's apple provider) is the usual one. If another option qualifies, allow this with the reason.`
2282
+ });
2283
+ }
2284
+ const generic = /* @__PURE__ */ new Map();
2285
+ for (const p of PERMISSIONS) {
2286
+ if (!deps.has(p.module)) continue;
2287
+ const set = configs.some((c) => {
2288
+ if (!c.json) return new RegExp(`\\b(?:${p.key}|${p.option})\\b`).test(c.text);
2289
+ const plist = get(c.json, ["ios", "infoPlist", p.key]);
2290
+ const option = pluginOptions(c.json, p.module)?.[p.option];
2291
+ return typeof plist === "string" && plist.trim() !== "" || typeof option === "string" && option.trim() !== "" || option === false;
2292
+ });
2293
+ if (!set) generic.set(p.key, [...generic.get(p.key) ?? [], `${p.module}${p.maybe ? `, if the app ${p.maybe}` : ""}`]);
2294
+ }
2295
+ for (const [key, modules] of generic) {
2296
+ const opt = PERMISSIONS.find((p) => p.key === key).option;
2297
+ ctx.report({
2298
+ rule: "store-readiness",
2299
+ level: "warn",
2300
+ file,
2301
+ subject: key,
2302
+ message: `leaves ${key} to Expo's generic default string (${modules.join("; ")}), and App Review rejects generic purpose strings; set the plugin's ${opt} (or ios.infoPlist.${key}) to a sentence saying why the app needs it, or ${opt}: false if it doesn't`
2303
+ });
2304
+ }
2305
+ const pluginManifest = genesisPluginDoes("privacyManifest") && privacyApisFor(runtimeDependencies(ctx.root)).length > 0;
2306
+ if (!has2(["ios", "privacyManifests"], "privacyManifests") && !pluginManifest) {
2307
+ ctx.report({
2308
+ rule: "store-readiness",
2309
+ level: "warn",
2310
+ file,
2311
+ subject: "privacyManifests",
2312
+ message: "has no ios.privacyManifests; declare the required-reason APIs the app uses (NSPrivacyAccessedAPITypes) so uploads aren't rejected for a missing privacy manifest"
2313
+ });
2314
+ }
2315
+ }
2316
+ var DEFAULT_MIGRATIONS = "supabase/migrations";
2317
+ var DEFAULT_BASE = "origin/main";
2318
+ var DEFAULT_EXPOSED = ["public"];
2319
+ function sqlStatements(text) {
2320
+ const out = [];
2321
+ let buf = "";
2322
+ let bodies = [];
2323
+ let line = 1;
2324
+ let start = 0;
2325
+ const flush = () => {
2326
+ const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
2327
+ if (sql) out.push({ sql, line: start, bodies });
2328
+ buf = "";
2329
+ bodies = [];
2330
+ start = 0;
2331
+ };
2332
+ const put = (s) => {
2333
+ if (!start && /\S/.test(s)) start = line;
2334
+ buf += s;
2335
+ };
2336
+ let i = 0;
2337
+ while (i < text.length) {
2338
+ const ch = text[i];
2339
+ const two = text.slice(i, i + 2);
2340
+ if (ch === "\n") {
2341
+ buf += " ";
2342
+ line++;
2343
+ i++;
2344
+ } else if (two === "--") {
2345
+ while (i < text.length && text[i] !== "\n") i++;
2346
+ } else if (two === "/*") {
2347
+ let depth = 0;
2348
+ while (i < text.length) {
2349
+ if (text.startsWith("/*", i)) {
2350
+ depth++;
2351
+ i += 2;
2352
+ } else if (text.startsWith("*/", i)) {
2353
+ depth--;
2354
+ i += 2;
2355
+ if (depth === 0) break;
2356
+ } else {
2357
+ if (text[i] === "\n") line++;
2358
+ i++;
2359
+ }
2360
+ }
2361
+ buf += " ";
2362
+ } else if (ch === "'") {
2363
+ const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
2364
+ put("'");
2365
+ i++;
2366
+ while (i < text.length) {
2367
+ if (escapes && text[i] === "\\") i += 2;
2368
+ else if (text[i] === "'" && text[i + 1] === "'") i += 2;
2369
+ else if (text[i] === "'") break;
2370
+ else {
2371
+ if (text[i] === "\n") line++;
2372
+ i++;
2373
+ }
2374
+ }
2375
+ put("'");
2376
+ i++;
2377
+ } else if (ch === '"') {
2378
+ i++;
2379
+ while (i < text.length && text[i] !== '"') put(text[i++]);
2380
+ i++;
2381
+ } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
2382
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
2383
+ const end = text.indexOf(tag, i + tag.length);
2384
+ const stop = end === -1 ? text.length : end + tag.length;
2385
+ bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
2386
+ for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
2387
+ put(`${tag} ${tag}`);
2388
+ i = stop;
2389
+ } else if (ch === ";") {
2390
+ flush();
2391
+ i++;
2392
+ } else {
2393
+ put(ch);
2394
+ i++;
2395
+ }
2396
+ }
2397
+ flush();
2398
+ return out;
2399
+ }
2400
+ function qualify(name) {
2401
+ const n = name.trim().toLowerCase();
2402
+ return n.includes(".") ? n : `public.${n}`;
2403
+ }
2404
+ var schemaOf = (name) => name.split(".")[0];
2405
+ function parenthesized(sql, open) {
2406
+ let depth = 0;
2407
+ for (let k = open; k < sql.length; k++) {
2408
+ if (sql[k] === "(") depth++;
2409
+ else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
2410
+ }
2411
+ return { inner: sql.slice(open + 1), end: sql.length };
2412
+ }
2413
+ function stripParens(s) {
2414
+ let out = "";
2415
+ let depth = 0;
2416
+ for (const c of s) {
2417
+ if (c === "(") depth++;
2418
+ else if (c === ")") depth = Math.max(0, depth - 1);
2419
+ else if (depth === 0) out += c;
2420
+ }
2421
+ return out;
2422
+ }
2423
+ function splitTop(s) {
2424
+ const parts = [];
2425
+ let depth = 0;
2426
+ let cur = "";
2427
+ for (const c of s) {
2428
+ if (c === "(") depth++;
2429
+ if (c === ")") depth--;
2430
+ if (c === "," && depth === 0) {
2431
+ parts.push(cur);
2432
+ cur = "";
2433
+ } else cur += c;
2434
+ }
2435
+ if (cur.trim()) parts.push(cur);
2436
+ return parts.map((p) => p.trim()).filter(Boolean);
2437
+ }
2438
+ var TYPE_ALIASES = {
2439
+ int: "integer",
2440
+ int4: "integer",
2441
+ int8: "bigint",
2442
+ int2: "smallint",
2443
+ bool: "boolean",
2444
+ varchar: "character varying",
2445
+ timestamptz: "timestamp with time zone",
2446
+ float8: "double precision"
2447
+ };
2448
+ var MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
2449
+ function argTypes(args) {
2450
+ const types = [];
2451
+ for (const raw of splitTop(args)) {
2452
+ let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
2453
+ const mode = tokens[0];
2454
+ if (mode === "out") continue;
2455
+ if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
2456
+ const joined = tokens.join(" ");
2457
+ const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
2458
+ types.push(TYPE_ALIASES[type] ?? type);
2459
+ }
2460
+ return types;
2461
+ }
2462
+ function git(root, args) {
2463
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
2464
+ return r.status === 0 ? r.stdout : null;
2465
+ }
2466
+ function gitView(root, dir, base) {
2467
+ if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
2468
+ if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
2469
+ return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
2470
+ }
2471
+ const mergeBase = git(root, ["merge-base", "HEAD", base])?.trim();
2472
+ if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
2473
+ const diff = git(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
2474
+ const untracked = git(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
2475
+ if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
2476
+ const sql = (p) => p !== void 0 && p.endsWith(".sql");
2477
+ const touched = new Set(untracked.split("\n").filter(sql));
2478
+ const edited = [];
2479
+ for (const row of diff.split("\n").filter(Boolean)) {
2480
+ const [status, a, b] = row.split(" ");
2481
+ if (status.startsWith("R")) {
2482
+ if (sql(b)) touched.add(b);
2483
+ if (sql(a)) edited.push({ file: a, status: "renamed" });
2484
+ continue;
2485
+ }
2486
+ if (!sql(a)) continue;
2487
+ if (status.startsWith("A")) touched.add(a);
2488
+ else if (status.startsWith("M") || status.startsWith("T")) {
2489
+ touched.add(a);
2490
+ edited.push({ file: a, status: "modified" });
2491
+ } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
2492
+ }
2493
+ return { touched, edited };
2494
+ }
2495
+ function checkSupabasePack(ctx) {
2496
+ const settings = ctx.config.supabase ?? {};
2497
+ const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
2498
+ const abs = path3.join(ctx.root, dir);
2499
+ if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
2500
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path3.join(abs, n), "utf8")) }));
2501
+ const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
2502
+ const base = settings.base ?? DEFAULT_BASE;
2503
+ const view = gitView(ctx.root, dir, base);
2504
+ if ("reason" in view) {
2505
+ if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
2506
+ } else {
2507
+ for (const e of view.edited) {
2508
+ ctx.report({
2509
+ rule: "migration-edited",
2510
+ file: e.file,
2511
+ subject: e.file,
2512
+ 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`
2513
+ });
2514
+ }
2515
+ }
2516
+ const since = settings.since;
2517
+ const afterSince = (file) => since === void 0 || path3.posix.basename(file) >= since;
2518
+ if ("reason" in view && since === void 0) {
2519
+ ctx.report({
2520
+ rule: "migration-grants",
2521
+ level: "warn",
2522
+ file: dir,
2523
+ 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`
2524
+ });
2525
+ } else {
2526
+ const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
2527
+ checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
2528
+ }
2529
+ checkRls(ctx, migrations, exposed);
2530
+ checkDefinerSearchPath(ctx, migrations);
2531
+ }
2532
+ function granteesOf(s) {
2533
+ return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
2534
+ }
2535
+ function checkGrants(ctx, migrations, exposed) {
2536
+ const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
2537
+ const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
2538
+ const blanket = (roles) => {
2539
+ const o = open(roles);
2540
+ if (o.length) return { level: "error", who: o.join(" and ") };
2541
+ if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
2542
+ return null;
2543
+ };
2544
+ for (const { file, statements } of migrations) {
2545
+ for (const { sql, line } of statements) {
2546
+ const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
2547
+ if (all) {
2548
+ const hit = blanket(granteesOf(all[1]));
2549
+ if (hit) {
2550
+ 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}` });
2551
+ }
2552
+ continue;
2553
+ }
2554
+ const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
2555
+ if (defaults) {
2556
+ const hit = blanket(granteesOf(defaults[1]));
2557
+ if (hit) {
2558
+ 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}` });
2559
+ }
2560
+ continue;
2561
+ }
2562
+ const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
2563
+ if (fn) {
2564
+ const roles = open(granteesOf(fn[2]));
2565
+ if (!roles.length) continue;
2566
+ for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
2567
+ if (exposed.has(schemaOf(name))) continue;
2568
+ ctx.report({
2569
+ rule: "migration-grants",
2570
+ file,
2571
+ line,
2572
+ subject: name,
2573
+ 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)`
2574
+ });
2575
+ }
2576
+ continue;
2577
+ }
2578
+ const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
2579
+ if (schema) {
2580
+ const roles = open(granteesOf(schema[2]));
2581
+ if (!roles.length) continue;
2582
+ for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
2583
+ if (exposed.has(s)) continue;
2584
+ ctx.report({
2585
+ rule: "migration-grants",
2586
+ file,
2587
+ line,
2588
+ subject: `schema ${s}`,
2589
+ message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
2590
+ });
2591
+ }
2592
+ }
2593
+ }
2594
+ }
2595
+ }
2596
+ function checkRls(ctx, migrations, exposed) {
2597
+ const tables = /* @__PURE__ */ new Map();
2598
+ const name = String.raw`([\w$.]+)`;
2599
+ const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
2600
+ for (const { file, statements } of migrations) {
2601
+ for (const { sql, line, bodies } of statements) {
2602
+ if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
2603
+ const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
2604
+ if (create) {
2605
+ if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
2606
+ continue;
2607
+ }
2608
+ const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
2609
+ const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
2610
+ if (rename || move) {
2611
+ const from = qualify((rename ?? move)[1]);
2612
+ const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
2613
+ const state = tables.get(from);
2614
+ if (state) {
2615
+ tables.delete(from);
2616
+ tables.set(to, state);
2617
+ }
2618
+ continue;
2619
+ }
2620
+ const alter = new RegExp(target).exec(sql);
2621
+ if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
2622
+ const t = qualify(alter[1]);
2623
+ if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
2624
+ else {
2625
+ const state = tables.get(t);
2626
+ if (state) state.rls = true;
2627
+ }
2628
+ continue;
2629
+ }
2630
+ const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
2631
+ if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
2632
+ }
2633
+ }
2634
+ for (const [t, at] of tables) {
2635
+ if (at.rls || !exposed.has(schemaOf(t))) continue;
2636
+ ctx.report({
2637
+ rule: "migration-rls",
2638
+ file: at.file,
2639
+ line: at.line,
2640
+ subject: t,
2641
+ 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`
2642
+ });
2643
+ }
2644
+ }
2645
+ function checkDefinerSearchPath(ctx, migrations) {
2646
+ const fns = /* @__PURE__ */ new Map();
2647
+ const keysFor = (sql, nameEnd, fnName) => {
2648
+ const rest = sql.slice(nameEnd).trimStart();
2649
+ if (rest.startsWith("(")) {
2650
+ const { inner } = parenthesized(rest, 0);
2651
+ return [`${fnName}(${argTypes(inner).join(",")})`];
2652
+ }
2653
+ return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
2654
+ };
2655
+ for (const { file, statements } of migrations) {
2656
+ for (const { sql, line } of statements) {
2657
+ const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
2658
+ if (create) {
2659
+ const [key] = keysFor(sql, create[0].length, qualify(create[1]));
2660
+ fns.set(key, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
2661
+ continue;
2662
+ }
2663
+ const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
2664
+ if (alter) {
2665
+ const fnName = qualify(alter[1]);
2666
+ const keys = keysFor(sql, alter[0].length, fnName);
2667
+ const rename = / rename to ([\w$]+)$/.exec(sql);
2668
+ const move = / set schema ([\w$]+)$/.exec(sql);
2669
+ for (const key of keys) {
2670
+ const state = fns.get(key);
2671
+ if (rename || move) {
2672
+ if (!state) continue;
2673
+ fns.delete(key);
2674
+ const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
2675
+ fns.set(newName + key.slice(fnName.length), state);
2676
+ continue;
2677
+ }
2678
+ const next = state ?? { definer: false, searchPath: false, file, line };
2679
+ if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
2680
+ if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
2681
+ if (/\bset search_path\b/.test(sql)) next.searchPath = true;
2682
+ if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
2683
+ fns.set(key, next);
2684
+ }
2685
+ continue;
2686
+ }
2687
+ const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
2688
+ if (drop) {
2689
+ for (const part of splitTop(drop[1])) {
2690
+ const m = /^([\w$.]+)\s*/.exec(part);
2691
+ if (m) for (const key of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key);
2692
+ }
2693
+ }
2694
+ }
2695
+ }
2696
+ for (const [key, at] of fns) {
2697
+ if (!at.definer || at.searchPath) continue;
2698
+ ctx.report({
2699
+ rule: "migration-definer-search-path",
2700
+ file: at.file,
2701
+ line: at.line,
2702
+ subject: key,
2703
+ message: `${key} 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`
2704
+ });
2705
+ }
2706
+ }
1891
2707
  var UMBRELLA_PACKAGE = "@marktiderman/genesis";
1892
2708
  function readReleaseManifest(root) {
1893
2709
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
@@ -1935,7 +2751,9 @@ async function runDoctor(options = {}) {
1935
2751
  { name: "colors", check: checkColors },
1936
2752
  { name: "tokens", check: checkTokens },
1937
2753
  { name: "shadowed-exports", check: checkShadowedExports },
1938
- { name: "version-skew", check: checkVersionSkew }
2754
+ { name: "version-skew", check: checkVersionSkew },
2755
+ ...config.packs?.includes("native") ? [{ name: "native", check: checkNativePack }] : [],
2756
+ ...config.packs?.includes("supabase") ? [{ name: "supabase", check: checkSupabasePack }] : []
1939
2757
  ];
1940
2758
  for (const plugin of [...builtins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
1941
2759
  try {