@marktiderman/genesis-cli 1.5.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/cli.js CHANGED
@@ -380,6 +380,13 @@ var init_build = __esm({
380
380
  BUILD_GUARD_ENV = "GENESIS_DOCTOR_BUILDING";
381
381
  }
382
382
  });
383
+ function appPath(v, where, fail) {
384
+ if (typeof v !== "string" || !v.trim()) return fail(`${where} must be a non-empty path`);
385
+ if (path3.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where} must be relative to the app, not absolute ("${v}")`);
386
+ const norm = path3.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
387
+ if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where} must be a folder inside the app ("${v}")`);
388
+ return norm;
389
+ }
383
390
  function loadConfig(root, configPath) {
384
391
  if (configPath) {
385
392
  const file = path3.resolve(root, configPath);
@@ -501,6 +508,27 @@ function validateConfig(raw, source = "config") {
501
508
  }
502
509
  });
503
510
  }
511
+ if (c.packs !== void 0) {
512
+ if (!isStringList(c.packs)) fail(`"packs" must be a list, e.g. ["native", "supabase"]`);
513
+ for (const p of c.packs) if (!PACKS.has(p)) fail(`packs: unknown pack "${p}" (known: ${[...PACKS].join(", ")})`);
514
+ if (new Set(c.packs).size !== c.packs.length) fail(`packs: lists a pack twice`);
515
+ }
516
+ for (const [pack, keys] of Object.entries(PACK_KEYS)) {
517
+ const block = c[pack];
518
+ if (block === void 0) continue;
519
+ if (!isObject(block)) fail(`"${pack}" must be an object`);
520
+ if (!(c.packs ?? []).includes(pack)) fail(`"${pack}" settings are set but the ${pack} pack is not in "packs"`);
521
+ for (const [k, v] of Object.entries(block)) {
522
+ const want = keys[k];
523
+ if (!want) fail(`${pack}: unknown setting "${k}"`);
524
+ if (want === "string" && typeof v !== "string") fail(`${pack}.${k} must be a string`);
525
+ if (want === "list" && !isStringList(v)) fail(`${pack}.${k} must be a list of strings`);
526
+ if (want === "string" && !v.trim()) fail(`${pack}.${k} must not be empty`);
527
+ if (want === "path") block[k] = appPath(v, `${pack}.${k}`, fail);
528
+ }
529
+ }
530
+ const supa = c.supabase;
531
+ if (Array.isArray(supa?.exposedSchemas)) supa.exposedSchemas = supa.exposedSchemas.map((s) => s.toLowerCase());
504
532
  if (c.plugins !== void 0) {
505
533
  const ok = Array.isArray(c.plugins) && c.plugins.every((p) => typeof p === "string" || Array.isArray(p) && p.length === 2 && typeof p[0] === "string");
506
534
  if (!ok) fail(`"plugins" must be a list of module paths or [path, options] pairs`);
@@ -520,7 +548,7 @@ function isObject(v) {
520
548
  function isStringList(v) {
521
549
  return Array.isArray(v) && v.every((x) => typeof x === "string");
522
550
  }
523
- var GenesisConfigError, DoctorConfigError, STRING_LISTS, STRINGS, KNOWN, LEVELS, PATTERN_KEYS, LINK_KEYS, HOST;
551
+ var GenesisConfigError, DoctorConfigError, STRING_LISTS, STRINGS, KNOWN, LEVELS, PATTERN_KEYS, PACKS, PACK_KEYS, LINK_KEYS, HOST;
524
552
  var init_config = __esm({
525
553
  "src/doctor/config.ts"() {
526
554
  GenesisConfigError = class extends Error {
@@ -541,11 +569,19 @@ var init_config = __esm({
541
569
  "allow",
542
570
  "patterns",
543
571
  "plugins",
572
+ "packs",
573
+ "native",
574
+ "supabase",
544
575
  "$schema",
545
576
  "$comment"
546
577
  ]);
547
578
  LEVELS = /* @__PURE__ */ new Set(["error", "warn", "off"]);
548
579
  PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
580
+ PACKS = /* @__PURE__ */ new Set(["native", "supabase"]);
581
+ PACK_KEYS = {
582
+ native: { routerRoot: "path" },
583
+ supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" }
584
+ };
549
585
  LINK_KEYS = /* @__PURE__ */ new Set(["hosts", "paths", "webcredentials"]);
550
586
  HOST = /^(?=.{1,253}$)(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
551
587
  }
@@ -576,7 +612,7 @@ function globToRegExp(glob) {
576
612
  }
577
613
  function globMatcher(globs) {
578
614
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
579
- return (path12) => res.some((re) => re.test(path12));
615
+ return (path15) => res.some((re) => re.test(path15));
580
616
  }
581
617
  var init_glob = __esm({
582
618
  "src/doctor/glob.ts"() {
@@ -592,10 +628,39 @@ function findPackageDir(from, name) {
592
628
  dir = parent;
593
629
  }
594
630
  }
631
+ function uiPackageFor(config) {
632
+ return config.uiPackage ?? (config.packs?.includes("native") ? NATIVE_UI_PACKAGE : DEFAULT_UI_PACKAGE);
633
+ }
595
634
  function loadGenesis(root, config) {
596
- const uiPackage = config.uiPackage ?? DEFAULT_UI_PACKAGE;
635
+ const uiPackage = uiPackageFor(config);
636
+ const pkg = readPackageExports(root, uiPackage);
637
+ if (!pkg) throw new DoctorConfigError(`${uiPackage} is not installed here. Install it, or set doctor.uiPackage.`);
638
+ const { dir: uiDir, exports: exportNames, values, components } = pkg;
639
+ const tokens = /* @__PURE__ */ new Set();
640
+ const themeFiles = resolveThemeFiles(root, config, uiDir);
641
+ for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
642
+ const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
643
+ const rawTags = /* @__PURE__ */ new Map();
644
+ for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
645
+ for (const [tag, comp] of Object.entries(TAG_ALIASES)) if (values.has(comp)) rawTags.set(tag, comp);
646
+ for (const [tag, comp] of Object.entries(config.rawTags ?? {})) {
647
+ if (comp === false) rawTags.delete(tag);
648
+ else rawTags.set(tag, comp);
649
+ }
650
+ return {
651
+ uiPackage,
652
+ uiVersion: pkg.version,
653
+ exports: exportNames,
654
+ values,
655
+ components,
656
+ tokens,
657
+ rawTags,
658
+ palette: loadPalette(root)
659
+ };
660
+ }
661
+ function readPackageExports(root, uiPackage) {
597
662
  const uiDir = findPackageDir(root, uiPackage);
598
- if (!uiDir) throw new DoctorConfigError(`${uiPackage} is not installed here. Install it, or set doctor.uiPackage.`);
663
+ if (!uiDir) return null;
599
664
  const uiPkg = JSON.parse(readFileSync(path3.join(uiDir, "package.json"), "utf8"));
600
665
  const typeEntries = /* @__PURE__ */ new Set();
601
666
  const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
@@ -636,27 +701,7 @@ function loadGenesis(root, config) {
636
701
  const isTypeOnly = (n) => typeDecls.has(n) && !valueDecls.has(n);
637
702
  const values = new Set([...exportNames].filter((n) => !isTypeOnly(n)));
638
703
  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();
639
- const tokens = /* @__PURE__ */ new Set();
640
- const themeFiles = resolveThemeFiles(root, config, uiDir);
641
- for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
642
- const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
643
- const rawTags = /* @__PURE__ */ new Map();
644
- for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
645
- for (const [tag, comp] of Object.entries(TAG_ALIASES)) if (values.has(comp)) rawTags.set(tag, comp);
646
- for (const [tag, comp] of Object.entries(config.rawTags ?? {})) {
647
- if (comp === false) rawTags.delete(tag);
648
- else rawTags.set(tag, comp);
649
- }
650
- return {
651
- uiPackage,
652
- uiVersion: String(uiPkg.version ?? "unknown"),
653
- exports: exportNames,
654
- values,
655
- components,
656
- tokens,
657
- rawTags,
658
- palette: loadPalette(root)
659
- };
704
+ return { dir: uiDir, version: String(uiPkg.version ?? "unknown"), exports: exportNames, values, components };
660
705
  }
661
706
  function parseExportNames(dts) {
662
707
  const names = [];
@@ -746,11 +791,12 @@ function loadPalette(root) {
746
791
  }
747
792
  return [...names].sort();
748
793
  }
749
- var DEFAULT_UI_PACKAGE, DESIGN_SYSTEM_PACKAGE, TAGS, TAG_ALIASES, NON_COMPONENT_SUFFIX, TAILWIND_PALETTE;
794
+ var DEFAULT_UI_PACKAGE, NATIVE_UI_PACKAGE, DESIGN_SYSTEM_PACKAGE, TAGS, TAG_ALIASES, NON_COMPONENT_SUFFIX, TAILWIND_PALETTE;
750
795
  var init_genesis = __esm({
751
796
  "src/doctor/genesis.ts"() {
752
797
  init_config();
753
798
  DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
799
+ NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
754
800
  DESIGN_SYSTEM_PACKAGE = "@marktiderman/genesis-design-system";
755
801
  TAGS = ["button", "input", "textarea", "select", "label", "table", "dialog", "progress", "details", "summary"];
756
802
  TAG_ALIASES = { hr: "Separator" };
@@ -976,7 +1022,7 @@ function scanFiles(root, config) {
976
1022
  }
977
1023
  }
978
1024
  };
979
- for (const src of config.src ?? DEFAULT_SRC) {
1025
+ for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
980
1026
  const abs = path3.resolve(root, src);
981
1027
  if (!existsSync(abs)) continue;
982
1028
  if (statSync(abs).isDirectory()) walk(abs);
@@ -989,12 +1035,13 @@ function lineAt(text, index) {
989
1035
  for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
990
1036
  return line;
991
1037
  }
992
- var DEFAULT_SRC, DEFAULT_EXTENSIONS, DEFAULT_IGNORE, SKIP_DIRS, MAX_FILE_BYTES, toPosix;
1038
+ var DEFAULT_SRC, DEFAULT_NATIVE_SRC, DEFAULT_EXTENSIONS, DEFAULT_IGNORE, SKIP_DIRS, MAX_FILE_BYTES, toPosix;
993
1039
  var init_scan = __esm({
994
1040
  "src/doctor/scan.ts"() {
995
1041
  init_color_literals();
996
1042
  init_glob();
997
1043
  DEFAULT_SRC = ["src"];
1044
+ DEFAULT_NATIVE_SRC = ["app", "src", "components"];
998
1045
  DEFAULT_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".css"];
999
1046
  DEFAULT_IGNORE = [
1000
1047
  "**/*.d.ts",
@@ -1220,7 +1267,10 @@ function checkColors(ctx) {
1220
1267
  `(?<![\\w-])(?:${COLOR_UTILITIES})-(?:${ctx.genesis.palette.join("|")})(?:-\\d{2,3})?(?:\\/\\d{1,3})?(?![\\w-])`,
1221
1268
  "g"
1222
1269
  );
1270
+ const native = ctx.config.packs?.includes("native") ?? false;
1271
+ const themeRoles = ctx.genesis.values.has("useThemeRoles") ? "a theme role (useThemeRoles())" : "a theme role";
1223
1272
  for (const file of ctx.files) {
1273
+ const nativeCode = native && SCRIPT_EXTS.has(file.ext);
1224
1274
  file.code.split("\n").forEach((text, i) => {
1225
1275
  const line = i + 1;
1226
1276
  for (const m of text.matchAll(palette)) {
@@ -1234,6 +1284,16 @@ function checkColors(ctx) {
1234
1284
  for (const hit of [...findHexLiterals(text), ...findColorFunctions(text)]) {
1235
1285
  const at = hit.column - 1;
1236
1286
  if (arbitrary.some(([a, b]) => at >= a && at < b)) continue;
1287
+ if (nativeCode) {
1288
+ ctx.report({
1289
+ rule: "native-literal-color",
1290
+ file: file.path,
1291
+ line,
1292
+ subject: hit.literal,
1293
+ message: `hardcodes the color ${hit.literal}; use ${themeRoles}, a token className (bg-primary, text-muted-foreground) or PlatformColor(...)`
1294
+ });
1295
+ continue;
1296
+ }
1237
1297
  ctx.report({ rule: "raw-color", file: file.path, line, subject: hit.literal, message: `hardcodes the color ${hit.literal}; color values come from Genesis tokens` });
1238
1298
  }
1239
1299
  });
@@ -1306,7 +1366,18 @@ var init_rules = __esm({
1306
1366
  "raw-color",
1307
1367
  "undefined-token",
1308
1368
  "shadowed-export",
1309
- "version-skew"
1369
+ "version-skew",
1370
+ // native pack
1371
+ "native-raw-primitive",
1372
+ "native-literal-color",
1373
+ "native-custom-header",
1374
+ "native-screen-layout",
1375
+ "store-readiness",
1376
+ // supabase pack
1377
+ "migration-grants",
1378
+ "migration-rls",
1379
+ "migration-definer-search-path",
1380
+ "migration-edited"
1310
1381
  ];
1311
1382
  DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
1312
1383
  STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -1317,6 +1388,777 @@ var init_rules = __esm({
1317
1388
  ARBITRARY_COLOR_RE = /(?<![\w-])[a-z][a-z-]*-\[(?:#|(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb|color)\()[^\]]*\]/g;
1318
1389
  }
1319
1390
  });
1391
+
1392
+ // ../../scripts/lib/native-primitives.mjs
1393
+ function wrappedPrimitivesIn(namedImports) {
1394
+ 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));
1395
+ }
1396
+ var NATIVE_WRAPPED_PRIMITIVES;
1397
+ var init_native_primitives = __esm({
1398
+ "../../scripts/lib/native-primitives.mjs"() {
1399
+ NATIVE_WRAPPED_PRIMITIVES = Object.freeze({
1400
+ Modal: Object.freeze(["NativeDialog", "NativeSheet", "NativeDrawer"]),
1401
+ ActivityIndicator: Object.freeze(["NativeSkeleton", "NativeProgress"])
1402
+ });
1403
+ }
1404
+ });
1405
+ function privacyApisFor(dependencies2) {
1406
+ return Object.keys(PRIVACY_APIS).filter((pkg) => pkg in dependencies2).flatMap((pkg) => PRIVACY_APIS[pkg]);
1407
+ }
1408
+ var PRIVACY_APIS;
1409
+ var init_expo = __esm({
1410
+ "src/expo.ts"() {
1411
+ init_config();
1412
+ init_config();
1413
+ PRIVACY_APIS = {
1414
+ "@react-native-async-storage/async-storage": [
1415
+ { NSPrivacyAccessedAPIType: "NSPrivacyAccessedAPICategoryFileTimestamp", NSPrivacyAccessedAPITypeReasons: ["C617.1"] }
1416
+ ]
1417
+ };
1418
+ }
1419
+ });
1420
+ function nativePackage(ctx) {
1421
+ const pkg = readPackageExports(ctx.root, NATIVE_UI_PACKAGE);
1422
+ if (!pkg) throw new DoctorConfigError(`the native pack needs ${NATIVE_UI_PACKAGE}; install it, or remove "native" from doctor.packs`);
1423
+ return pkg;
1424
+ }
1425
+ function nativeLayouts(pkg) {
1426
+ return pkg.components.filter((n) => LAYOUT_NAME.test(n));
1427
+ }
1428
+ function checkNativePack(ctx) {
1429
+ const pkg = nativePackage(ctx);
1430
+ checkRawPrimitives(ctx, pkg);
1431
+ checkCustomHeaders(ctx, pkg);
1432
+ checkScreenLayouts(ctx, pkg);
1433
+ checkStoreReadiness(ctx);
1434
+ }
1435
+ function checkRawPrimitives(ctx, pkg) {
1436
+ const wrapped = Object.keys(NATIVE_WRAPPED_PRIMITIVES);
1437
+ const named = [
1438
+ // import { Modal } / import RN, { Modal }; `import type { … }` doesn't match.
1439
+ new RegExp(String.raw`\bimport\s+(?:[\w$]+\s*,\s*)?\{([^}]*)\}\s*from\s*${RN}`, "g"),
1440
+ new RegExp(String.raw`\bexport\s+\{([^}]*)\}\s*from\s*${RN}`, "g"),
1441
+ new RegExp(String.raw`\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*${RN}\s*\)`, "g")
1442
+ ];
1443
+ const namespaces = [
1444
+ new RegExp(String.raw`\bimport\s+\*\s+as\s+([\w$]+)\s+from\s*${RN}`, "g"),
1445
+ new RegExp(String.raw`\b(?:const|let|var)\s+([\w$]+)\s*=\s*require\(\s*${RN}\s*\)`, "g")
1446
+ ];
1447
+ const member = new RegExp(String.raw`\brequire\(\s*${RN}\s*\)\.(${wrapped.join("|")})\b`, "g");
1448
+ for (const file of ctx.files) {
1449
+ if (!SCRIPT_EXTS2.has(file.ext)) continue;
1450
+ const code = file.code;
1451
+ const report = (name, at) => {
1452
+ const use = NATIVE_WRAPPED_PRIMITIVES[name].filter((c) => pkg.values.has(c));
1453
+ ctx.report({
1454
+ rule: "native-raw-primitive",
1455
+ file: file.path,
1456
+ line: lineAt(code, at),
1457
+ subject: name,
1458
+ message: `uses ${name} from react-native, which Genesis wraps; use ${use.length ? use.join(" or ") : "the Genesis wrapper"} from ${NATIVE_UI_PACKAGE}`
1459
+ });
1460
+ };
1461
+ for (const re of named) {
1462
+ for (const m of code.matchAll(re)) {
1463
+ for (const name of wrappedPrimitivesIn(m[1].replace(/:/g, " as "))) report(name, m.index + m[0].indexOf(name));
1464
+ }
1465
+ }
1466
+ for (const re of namespaces) {
1467
+ for (const m of code.matchAll(re)) {
1468
+ for (const use of code.matchAll(new RegExp(String.raw`\b${m[1].replace(/\$/g, "\\$")}\.(${wrapped.join("|")})\b`, "g"))) report(use[1], use.index);
1469
+ }
1470
+ }
1471
+ for (const m of code.matchAll(member)) report(m[1], m.index);
1472
+ }
1473
+ }
1474
+ function customElement(code, re, pkg) {
1475
+ for (const m of code.matchAll(re)) {
1476
+ const name = m[1];
1477
+ if (!pkg.values.has(name.split(".")[0]) && !PART_HEADER.test(name)) return { name, index: m.index };
1478
+ }
1479
+ return null;
1480
+ }
1481
+ function ownHeader(code, pkg) {
1482
+ const el = customElement(code, /<([A-Z][\w$]*Header)\b/g, pkg);
1483
+ if (el) return el;
1484
+ const style = /\bstyle=\{\s*styles\.header\s*\}/.exec(code);
1485
+ return style ? { name: "styles.header", index: style.index } : null;
1486
+ }
1487
+ function checkCustomHeaders(ctx, pkg) {
1488
+ const layouts = nativeLayouts(pkg);
1489
+ if (layouts.length === 0) return;
1490
+ const headerWay = pkg.values.has("ScreenContainer") ? `ScreenContainer's header props${pkg.values.has("composeHeaderOptions") ? " (composeHeaderOptions)" : ""}` : `a Genesis layout's header (${layouts.join(", ")})`;
1491
+ const rootDir = routerRoot(ctx);
1492
+ const reported = /* @__PURE__ */ new Set();
1493
+ const hidingLayouts = /* @__PURE__ */ new Map();
1494
+ for (const file of ctx.files) {
1495
+ if (!JSX_EXTS2.has(file.ext)) continue;
1496
+ const code = file.code;
1497
+ const hidden = HIDES_HEADER.exec(code);
1498
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path3.posix.dirname(file.path), file.path);
1499
+ const own = hidden ? ownHeader(code, pkg) : null;
1500
+ if (hidden && own) {
1501
+ reported.add(file.path);
1502
+ ctx.report({
1503
+ rule: "native-custom-header",
1504
+ level: "warn",
1505
+ file: file.path,
1506
+ line: lineAt(code, hidden.index),
1507
+ subject: own.name,
1508
+ message: `hides the navigator header and draws its own (${own.name}); use ${headerWay} so the title, back button and large-title behavior stay native`
1509
+ });
1510
+ }
1511
+ const tabBarProp = /<Tabs\b/.test(code) ? /\btabBar\s*=\s*\{/.exec(code) : null;
1512
+ const tabBar = tabBarProp ? { name: "tabBar prop", index: tabBarProp.index } : customElement(code, /<([A-Z][\w$]*TabBar)\b/g, pkg);
1513
+ if (tabBar) {
1514
+ ctx.report({
1515
+ rule: "native-custom-header",
1516
+ level: "warn",
1517
+ file: file.path,
1518
+ line: lineAt(code, tabBar.index),
1519
+ subject: tabBar.name,
1520
+ message: `builds a tab bar by hand (${tabBar.name}); use the router's native <Tabs> bar, themed through Genesis screenOptions`
1521
+ });
1522
+ }
1523
+ }
1524
+ for (const file of ctx.files) {
1525
+ if (!JSX_EXTS2.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
1526
+ const layout = hidingLayouts.get(path3.posix.dirname(file.path));
1527
+ const own = layout ? ownHeader(file.code, pkg) : null;
1528
+ if (!layout || !own) continue;
1529
+ ctx.report({
1530
+ rule: "native-custom-header",
1531
+ level: "warn",
1532
+ file: file.path,
1533
+ line: lineAt(file.code, own.index),
1534
+ subject: own.name,
1535
+ 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`
1536
+ });
1537
+ }
1538
+ }
1539
+ function routerRoot(ctx) {
1540
+ if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
1541
+ return existsSync(path3.join(ctx.root, "src", "app")) ? "src/app" : "app";
1542
+ }
1543
+ function checkScreenLayouts(ctx, pkg) {
1544
+ const layouts = nativeLayouts(pkg);
1545
+ if (layouts.length === 0) return;
1546
+ const rootDir = routerRoot(ctx);
1547
+ if (!existsSync(path3.join(ctx.root, rootDir))) {
1548
+ ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
1549
+ return;
1550
+ }
1551
+ const routes = ctx.files.filter((f) => f.path.startsWith(`${rootDir}/`));
1552
+ if (routes.length === 0) {
1553
+ ctx.report({
1554
+ rule: "native-screen-layout",
1555
+ level: "warn",
1556
+ file: rootDir,
1557
+ message: `no scanned file is under the router root ${rootDir}, so no screen was checked; add it to doctor.src`
1558
+ });
1559
+ return;
1560
+ }
1561
+ const renders = new RegExp(`<(?:${layouts.join("|")}|Redirect)\\b`);
1562
+ const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
1563
+ for (const file of routes) {
1564
+ if (!JSX_EXTS2.has(file.ext) || NON_SCREEN_ROUTE.test(file.path)) continue;
1565
+ if (!/\bexport\s+default\b/.test(file.code) || !/<[A-Za-z]/.test(file.code)) continue;
1566
+ if (renders.test(file.code)) continue;
1567
+ const viaImport = localImports(ctx.root, file).some((abs) => {
1568
+ const target = byPath.get(abs) ?? readSource(abs);
1569
+ return target !== null && renders.test(target.code);
1570
+ });
1571
+ if (viaImport) continue;
1572
+ ctx.report({
1573
+ rule: "native-screen-layout",
1574
+ level: "warn",
1575
+ file: file.path,
1576
+ 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`
1577
+ });
1578
+ }
1579
+ }
1580
+ function localImports(root, file) {
1581
+ const out = [];
1582
+ for (const m of file.code.matchAll(/\bfrom\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g)) {
1583
+ const spec = m[1];
1584
+ const bases = spec.startsWith(".") ? [path3.resolve(path3.dirname(file.absolutePath), spec)] : [path3.join(root, spec.slice(2)), path3.join(root, "src", spec.slice(2))];
1585
+ for (const base of bases) {
1586
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path3.join(base, `index${e}`))].find(
1587
+ (p) => SCRIPT_EXTS2.has(path3.extname(p)) && existsSync(p)
1588
+ );
1589
+ if (hit) {
1590
+ out.push(hit);
1591
+ break;
1592
+ }
1593
+ }
1594
+ }
1595
+ return out;
1596
+ }
1597
+ function readSource(abs) {
1598
+ try {
1599
+ return { code: readFileSync(abs, "utf8") };
1600
+ } catch {
1601
+ return null;
1602
+ }
1603
+ }
1604
+ function readExpoConfigs(root) {
1605
+ const out = [];
1606
+ for (const name of EXPO_CONFIGS) {
1607
+ const abs = path3.join(root, name);
1608
+ if (!existsSync(abs)) continue;
1609
+ const text = readFileSync(abs, "utf8");
1610
+ let json = null;
1611
+ if (name.endsWith(".json")) {
1612
+ try {
1613
+ const raw = JSON.parse(text);
1614
+ json = raw.expo ?? raw;
1615
+ } catch (err) {
1616
+ throw new DoctorConfigError(`${name} is not valid JSON: ${err.message}`);
1617
+ }
1618
+ }
1619
+ out.push({ file: name, json, text });
1620
+ }
1621
+ return out;
1622
+ }
1623
+ function get(obj, keys) {
1624
+ let cur = obj;
1625
+ for (const k of keys) {
1626
+ if (!cur || typeof cur !== "object") return void 0;
1627
+ cur = cur[k];
1628
+ }
1629
+ return cur;
1630
+ }
1631
+ function pluginOptions(json, module) {
1632
+ const plugins = json?.plugins;
1633
+ if (!Array.isArray(plugins)) return null;
1634
+ for (const p of plugins) {
1635
+ if (p === module) return {};
1636
+ if (Array.isArray(p) && p[0] === module) return p[1] && typeof p[1] === "object" ? p[1] : {};
1637
+ }
1638
+ return null;
1639
+ }
1640
+ function dependencies(root) {
1641
+ const file = path3.join(root, "package.json");
1642
+ if (!existsSync(file)) return /* @__PURE__ */ new Set();
1643
+ const pkg = JSON.parse(readFileSync(file, "utf8"));
1644
+ return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
1645
+ }
1646
+ function runtimeDependencies(root) {
1647
+ const file = path3.join(root, "package.json");
1648
+ if (!existsSync(file)) return {};
1649
+ return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
1650
+ }
1651
+ function checkStoreReadiness(ctx) {
1652
+ const configs = readExpoConfigs(ctx.root);
1653
+ if (configs.length === 0) {
1654
+ 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" });
1655
+ return;
1656
+ }
1657
+ const file = configs[0].file;
1658
+ const deps = dependencies(ctx.root);
1659
+ const has2 = (keys, word) => configs.some((c) => c.json ? get(c.json, keys) !== void 0 : new RegExp(`\\b${word}\\b`).test(c.text));
1660
+ const genesisPluginDoes = (option) => configs.some((c) => {
1661
+ if (c.json) {
1662
+ const options = pluginOptions(c.json, GENESIS_PLUGIN) ?? pluginOptions(c.json, `${GENESIS_PLUGIN}/expo`);
1663
+ return options !== null && options[option] !== false;
1664
+ }
1665
+ const listed = c.text.replace(GENESIS_PLUGIN_IMPORT, "");
1666
+ return GENESIS_PLUGIN_TEXT.test(listed) && !new RegExp(`\\b${option}\\s*:\\s*false\\b`).test(c.text);
1667
+ });
1668
+ const exportCompliance = has2(["ios", "config", "usesNonExemptEncryption"], "usesNonExemptEncryption") || has2(["ios", "infoPlist", "ITSAppUsesNonExemptEncryption"], "ITSAppUsesNonExemptEncryption") || genesisPluginDoes("exportCompliance");
1669
+ if (!exportCompliance) {
1670
+ ctx.report({
1671
+ rule: "store-readiness",
1672
+ level: "warn",
1673
+ file,
1674
+ subject: "usesNonExemptEncryption",
1675
+ 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"
1676
+ });
1677
+ }
1678
+ const social = SOCIAL_SIGN_IN.filter((d) => deps.has(d));
1679
+ let apple = APPLE_SIGN_IN.some((d) => deps.has(d));
1680
+ for (const f of ctx.files) {
1681
+ for (const m of f.code.matchAll(SUPABASE_SIGN_IN)) {
1682
+ if (m[1] === "apple") apple = true;
1683
+ else if (!social.includes(`Supabase ${m[1]} sign-in`)) social.push(`Supabase ${m[1]} sign-in`);
1684
+ }
1685
+ }
1686
+ if (social.length > 0 && !apple) {
1687
+ const weak = WEAK_SOCIAL_SIGN_IN.filter((d) => deps.has(d));
1688
+ ctx.report({
1689
+ rule: "store-readiness",
1690
+ level: "warn",
1691
+ file: "package.json",
1692
+ subject: "sign-in-with-apple",
1693
+ 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.`
1694
+ });
1695
+ }
1696
+ const generic = /* @__PURE__ */ new Map();
1697
+ for (const p of PERMISSIONS) {
1698
+ if (!deps.has(p.module)) continue;
1699
+ const set = configs.some((c) => {
1700
+ if (!c.json) return new RegExp(`\\b(?:${p.key}|${p.option})\\b`).test(c.text);
1701
+ const plist = get(c.json, ["ios", "infoPlist", p.key]);
1702
+ const option = pluginOptions(c.json, p.module)?.[p.option];
1703
+ return typeof plist === "string" && plist.trim() !== "" || typeof option === "string" && option.trim() !== "" || option === false;
1704
+ });
1705
+ if (!set) generic.set(p.key, [...generic.get(p.key) ?? [], `${p.module}${p.maybe ? `, if the app ${p.maybe}` : ""}`]);
1706
+ }
1707
+ for (const [key, modules] of generic) {
1708
+ const opt = PERMISSIONS.find((p) => p.key === key).option;
1709
+ ctx.report({
1710
+ rule: "store-readiness",
1711
+ level: "warn",
1712
+ file,
1713
+ subject: key,
1714
+ 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`
1715
+ });
1716
+ }
1717
+ const pluginManifest = genesisPluginDoes("privacyManifest") && privacyApisFor(runtimeDependencies(ctx.root)).length > 0;
1718
+ if (!has2(["ios", "privacyManifests"], "privacyManifests") && !pluginManifest) {
1719
+ ctx.report({
1720
+ rule: "store-readiness",
1721
+ level: "warn",
1722
+ file,
1723
+ subject: "privacyManifests",
1724
+ message: "has no ios.privacyManifests; declare the required-reason APIs the app uses (NSPrivacyAccessedAPITypes) so uploads aren't rejected for a missing privacy manifest"
1725
+ });
1726
+ }
1727
+ }
1728
+ var SCRIPT_EXTS2, JSX_EXTS2, RESOLVE_EXTS, LAYOUT_NAME, NON_SCREEN_ROUTE, PART_HEADER, HIDES_HEADER, RN, PERMISSIONS, SOCIAL_SIGN_IN, WEAK_SOCIAL_SIGN_IN, APPLE_SIGN_IN, EXPO_CONFIGS, SUPABASE_SIGN_IN, GENESIS_PLUGIN, GENESIS_PLUGIN_TEXT, GENESIS_PLUGIN_IMPORT;
1729
+ var init_native = __esm({
1730
+ "src/doctor/native.ts"() {
1731
+ init_native_primitives();
1732
+ init_expo();
1733
+ init_config();
1734
+ init_genesis();
1735
+ init_scan();
1736
+ SCRIPT_EXTS2 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
1737
+ JSX_EXTS2 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
1738
+ RESOLVE_EXTS = [".tsx", ".ts", ".jsx", ".js"];
1739
+ LAYOUT_NAME = /(?:Page|Screen|ScreenContainer)$/;
1740
+ NON_SCREEN_ROUTE = /(?:^|\/)(?:_layout|\+html|\+native-intent|\+middleware)\.[jt]sx?$|\+api\.[jt]sx?$/;
1741
+ PART_HEADER = /(?:Section|List|Card|Dialog|Table|Group|Column|Row|Cell|Accordion|Sheet|Drawer|Modal|Popover|Menu|Panel|Form)Header$/;
1742
+ HIDES_HEADER = /\bheaderShown\s*(?::|=\s*\{)\s*false\b/;
1743
+ RN = String.raw`["']react-native["']`;
1744
+ PERMISSIONS = [
1745
+ { module: "expo-camera", key: "NSCameraUsageDescription", option: "cameraPermission" },
1746
+ { module: "expo-image-picker", key: "NSPhotoLibraryUsageDescription", option: "photosPermission" },
1747
+ { module: "expo-image-picker", key: "NSCameraUsageDescription", option: "cameraPermission", maybe: "takes photos with the camera" },
1748
+ { module: "expo-media-library", key: "NSPhotoLibraryUsageDescription", option: "photosPermission" },
1749
+ { module: "expo-location", key: "NSLocationWhenInUseUsageDescription", option: "locationWhenInUsePermission" },
1750
+ { module: "expo-av", key: "NSMicrophoneUsageDescription", option: "microphonePermission", maybe: "records audio" },
1751
+ { module: "expo-audio", key: "NSMicrophoneUsageDescription", option: "microphonePermission", maybe: "records audio" },
1752
+ { module: "expo-contacts", key: "NSContactsUsageDescription", option: "contactsPermission" },
1753
+ { module: "expo-local-authentication", key: "NSFaceIDUsageDescription", option: "faceIDPermission" }
1754
+ ];
1755
+ SOCIAL_SIGN_IN = ["@react-native-google-signin/google-signin", "react-native-fbsdk-next"];
1756
+ WEAK_SOCIAL_SIGN_IN = ["expo-auth-session"];
1757
+ APPLE_SIGN_IN = ["expo-apple-authentication", "@invertase/react-native-apple-authentication"];
1758
+ EXPO_CONFIGS = ["app.json", "app.config.json", "app.config.ts", "app.config.js", "app.config.mjs", "app.config.cjs"];
1759
+ SUPABASE_SIGN_IN = /\bsignInWith(?:OAuth|IdToken)\s*\(\s*\{\s*provider\s*:\s*["']([\w-]+)["']/g;
1760
+ GENESIS_PLUGIN = "@marktiderman/genesis-cli";
1761
+ GENESIS_PLUGIN_TEXT = /["']@marktiderman\/genesis-cli(?:\/expo)?["']|\bwithGenesis\s*\(/;
1762
+ GENESIS_PLUGIN_IMPORT = /\bfrom\s*["']@marktiderman\/genesis-cli[^"']*["']|\b(?:require|import)\s*\(\s*["']@marktiderman\/genesis-cli[^"']*["']\s*\)/g;
1763
+ }
1764
+ });
1765
+ function sqlStatements(text) {
1766
+ const out = [];
1767
+ let buf = "";
1768
+ let bodies = [];
1769
+ let line = 1;
1770
+ let start = 0;
1771
+ const flush = () => {
1772
+ const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
1773
+ if (sql) out.push({ sql, line: start, bodies });
1774
+ buf = "";
1775
+ bodies = [];
1776
+ start = 0;
1777
+ };
1778
+ const put = (s) => {
1779
+ if (!start && /\S/.test(s)) start = line;
1780
+ buf += s;
1781
+ };
1782
+ let i = 0;
1783
+ while (i < text.length) {
1784
+ const ch = text[i];
1785
+ const two = text.slice(i, i + 2);
1786
+ if (ch === "\n") {
1787
+ buf += " ";
1788
+ line++;
1789
+ i++;
1790
+ } else if (two === "--") {
1791
+ while (i < text.length && text[i] !== "\n") i++;
1792
+ } else if (two === "/*") {
1793
+ let depth = 0;
1794
+ while (i < text.length) {
1795
+ if (text.startsWith("/*", i)) {
1796
+ depth++;
1797
+ i += 2;
1798
+ } else if (text.startsWith("*/", i)) {
1799
+ depth--;
1800
+ i += 2;
1801
+ if (depth === 0) break;
1802
+ } else {
1803
+ if (text[i] === "\n") line++;
1804
+ i++;
1805
+ }
1806
+ }
1807
+ buf += " ";
1808
+ } else if (ch === "'") {
1809
+ const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
1810
+ put("'");
1811
+ i++;
1812
+ while (i < text.length) {
1813
+ if (escapes && text[i] === "\\") i += 2;
1814
+ else if (text[i] === "'" && text[i + 1] === "'") i += 2;
1815
+ else if (text[i] === "'") break;
1816
+ else {
1817
+ if (text[i] === "\n") line++;
1818
+ i++;
1819
+ }
1820
+ }
1821
+ put("'");
1822
+ i++;
1823
+ } else if (ch === '"') {
1824
+ i++;
1825
+ while (i < text.length && text[i] !== '"') put(text[i++]);
1826
+ i++;
1827
+ } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
1828
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
1829
+ const end = text.indexOf(tag, i + tag.length);
1830
+ const stop = end === -1 ? text.length : end + tag.length;
1831
+ bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
1832
+ for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
1833
+ put(`${tag} ${tag}`);
1834
+ i = stop;
1835
+ } else if (ch === ";") {
1836
+ flush();
1837
+ i++;
1838
+ } else {
1839
+ put(ch);
1840
+ i++;
1841
+ }
1842
+ }
1843
+ flush();
1844
+ return out;
1845
+ }
1846
+ function qualify(name) {
1847
+ const n = name.trim().toLowerCase();
1848
+ return n.includes(".") ? n : `public.${n}`;
1849
+ }
1850
+ function parenthesized(sql, open) {
1851
+ let depth = 0;
1852
+ for (let k = open; k < sql.length; k++) {
1853
+ if (sql[k] === "(") depth++;
1854
+ else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
1855
+ }
1856
+ return { inner: sql.slice(open + 1), end: sql.length };
1857
+ }
1858
+ function stripParens(s) {
1859
+ let out = "";
1860
+ let depth = 0;
1861
+ for (const c of s) {
1862
+ if (c === "(") depth++;
1863
+ else if (c === ")") depth = Math.max(0, depth - 1);
1864
+ else if (depth === 0) out += c;
1865
+ }
1866
+ return out;
1867
+ }
1868
+ function splitTop(s) {
1869
+ const parts = [];
1870
+ let depth = 0;
1871
+ let cur = "";
1872
+ for (const c of s) {
1873
+ if (c === "(") depth++;
1874
+ if (c === ")") depth--;
1875
+ if (c === "," && depth === 0) {
1876
+ parts.push(cur);
1877
+ cur = "";
1878
+ } else cur += c;
1879
+ }
1880
+ if (cur.trim()) parts.push(cur);
1881
+ return parts.map((p) => p.trim()).filter(Boolean);
1882
+ }
1883
+ function argTypes(args) {
1884
+ const types = [];
1885
+ for (const raw of splitTop(args)) {
1886
+ let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
1887
+ const mode = tokens[0];
1888
+ if (mode === "out") continue;
1889
+ if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
1890
+ const joined = tokens.join(" ");
1891
+ const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
1892
+ types.push(TYPE_ALIASES[type] ?? type);
1893
+ }
1894
+ return types;
1895
+ }
1896
+ function git(root, args) {
1897
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
1898
+ return r.status === 0 ? r.stdout : null;
1899
+ }
1900
+ function gitView(root, dir, base) {
1901
+ if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
1902
+ if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
1903
+ return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
1904
+ }
1905
+ const mergeBase = git(root, ["merge-base", "HEAD", base])?.trim();
1906
+ if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
1907
+ const diff = git(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
1908
+ const untracked = git(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
1909
+ if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
1910
+ const sql = (p) => p !== void 0 && p.endsWith(".sql");
1911
+ const touched = new Set(untracked.split("\n").filter(sql));
1912
+ const edited = [];
1913
+ for (const row of diff.split("\n").filter(Boolean)) {
1914
+ const [status, a, b] = row.split(" ");
1915
+ if (status.startsWith("R")) {
1916
+ if (sql(b)) touched.add(b);
1917
+ if (sql(a)) edited.push({ file: a, status: "renamed" });
1918
+ continue;
1919
+ }
1920
+ if (!sql(a)) continue;
1921
+ if (status.startsWith("A")) touched.add(a);
1922
+ else if (status.startsWith("M") || status.startsWith("T")) {
1923
+ touched.add(a);
1924
+ edited.push({ file: a, status: "modified" });
1925
+ } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
1926
+ }
1927
+ return { touched, edited };
1928
+ }
1929
+ function checkSupabasePack(ctx) {
1930
+ const settings2 = ctx.config.supabase ?? {};
1931
+ const dir = settings2.migrations ?? DEFAULT_MIGRATIONS;
1932
+ const abs = path3.join(ctx.root, dir);
1933
+ if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
1934
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path3.join(abs, n), "utf8")) }));
1935
+ const exposed = new Set((settings2.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
1936
+ const base = settings2.base ?? DEFAULT_BASE;
1937
+ const view = gitView(ctx.root, dir, base);
1938
+ if ("reason" in view) {
1939
+ if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
1940
+ } else {
1941
+ for (const e of view.edited) {
1942
+ ctx.report({
1943
+ rule: "migration-edited",
1944
+ file: e.file,
1945
+ subject: e.file,
1946
+ 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`
1947
+ });
1948
+ }
1949
+ }
1950
+ const since = settings2.since;
1951
+ const afterSince = (file) => since === void 0 || path3.posix.basename(file) >= since;
1952
+ if ("reason" in view && since === void 0) {
1953
+ ctx.report({
1954
+ rule: "migration-grants",
1955
+ level: "warn",
1956
+ file: dir,
1957
+ 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`
1958
+ });
1959
+ } else {
1960
+ const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
1961
+ checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
1962
+ }
1963
+ checkRls(ctx, migrations, exposed);
1964
+ checkDefinerSearchPath(ctx, migrations);
1965
+ }
1966
+ function granteesOf(s) {
1967
+ return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
1968
+ }
1969
+ function checkGrants(ctx, migrations, exposed) {
1970
+ const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
1971
+ const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
1972
+ const blanket = (roles) => {
1973
+ const o = open(roles);
1974
+ if (o.length) return { level: "error", who: o.join(" and ") };
1975
+ if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
1976
+ return null;
1977
+ };
1978
+ for (const { file, statements } of migrations) {
1979
+ for (const { sql, line } of statements) {
1980
+ const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
1981
+ if (all) {
1982
+ const hit = blanket(granteesOf(all[1]));
1983
+ if (hit) {
1984
+ 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}` });
1985
+ }
1986
+ continue;
1987
+ }
1988
+ const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
1989
+ if (defaults) {
1990
+ const hit = blanket(granteesOf(defaults[1]));
1991
+ if (hit) {
1992
+ 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}` });
1993
+ }
1994
+ continue;
1995
+ }
1996
+ const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
1997
+ if (fn) {
1998
+ const roles = open(granteesOf(fn[2]));
1999
+ if (!roles.length) continue;
2000
+ for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
2001
+ if (exposed.has(schemaOf(name))) continue;
2002
+ ctx.report({
2003
+ rule: "migration-grants",
2004
+ file,
2005
+ line,
2006
+ subject: name,
2007
+ 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)`
2008
+ });
2009
+ }
2010
+ continue;
2011
+ }
2012
+ const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
2013
+ if (schema) {
2014
+ const roles = open(granteesOf(schema[2]));
2015
+ if (!roles.length) continue;
2016
+ for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
2017
+ if (exposed.has(s)) continue;
2018
+ ctx.report({
2019
+ rule: "migration-grants",
2020
+ file,
2021
+ line,
2022
+ subject: `schema ${s}`,
2023
+ message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
2024
+ });
2025
+ }
2026
+ }
2027
+ }
2028
+ }
2029
+ }
2030
+ function checkRls(ctx, migrations, exposed) {
2031
+ const tables = /* @__PURE__ */ new Map();
2032
+ const name = String.raw`([\w$.]+)`;
2033
+ const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
2034
+ for (const { file, statements } of migrations) {
2035
+ for (const { sql, line, bodies } of statements) {
2036
+ if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
2037
+ const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
2038
+ if (create) {
2039
+ if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
2040
+ continue;
2041
+ }
2042
+ const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
2043
+ const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
2044
+ if (rename || move) {
2045
+ const from = qualify((rename ?? move)[1]);
2046
+ const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
2047
+ const state = tables.get(from);
2048
+ if (state) {
2049
+ tables.delete(from);
2050
+ tables.set(to, state);
2051
+ }
2052
+ continue;
2053
+ }
2054
+ const alter = new RegExp(target).exec(sql);
2055
+ if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
2056
+ const t = qualify(alter[1]);
2057
+ if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
2058
+ else {
2059
+ const state = tables.get(t);
2060
+ if (state) state.rls = true;
2061
+ }
2062
+ continue;
2063
+ }
2064
+ const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
2065
+ if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
2066
+ }
2067
+ }
2068
+ for (const [t, at] of tables) {
2069
+ if (at.rls || !exposed.has(schemaOf(t))) continue;
2070
+ ctx.report({
2071
+ rule: "migration-rls",
2072
+ file: at.file,
2073
+ line: at.line,
2074
+ subject: t,
2075
+ 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`
2076
+ });
2077
+ }
2078
+ }
2079
+ function checkDefinerSearchPath(ctx, migrations) {
2080
+ const fns = /* @__PURE__ */ new Map();
2081
+ const keysFor = (sql, nameEnd, fnName) => {
2082
+ const rest = sql.slice(nameEnd).trimStart();
2083
+ if (rest.startsWith("(")) {
2084
+ const { inner } = parenthesized(rest, 0);
2085
+ return [`${fnName}(${argTypes(inner).join(",")})`];
2086
+ }
2087
+ return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
2088
+ };
2089
+ for (const { file, statements } of migrations) {
2090
+ for (const { sql, line } of statements) {
2091
+ const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
2092
+ if (create) {
2093
+ const [key] = keysFor(sql, create[0].length, qualify(create[1]));
2094
+ fns.set(key, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
2095
+ continue;
2096
+ }
2097
+ const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
2098
+ if (alter) {
2099
+ const fnName = qualify(alter[1]);
2100
+ const keys = keysFor(sql, alter[0].length, fnName);
2101
+ const rename = / rename to ([\w$]+)$/.exec(sql);
2102
+ const move = / set schema ([\w$]+)$/.exec(sql);
2103
+ for (const key of keys) {
2104
+ const state = fns.get(key);
2105
+ if (rename || move) {
2106
+ if (!state) continue;
2107
+ fns.delete(key);
2108
+ const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
2109
+ fns.set(newName + key.slice(fnName.length), state);
2110
+ continue;
2111
+ }
2112
+ const next = state ?? { definer: false, searchPath: false, file, line };
2113
+ if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
2114
+ if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
2115
+ if (/\bset search_path\b/.test(sql)) next.searchPath = true;
2116
+ if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
2117
+ fns.set(key, next);
2118
+ }
2119
+ continue;
2120
+ }
2121
+ const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
2122
+ if (drop) {
2123
+ for (const part of splitTop(drop[1])) {
2124
+ const m = /^([\w$.]+)\s*/.exec(part);
2125
+ if (m) for (const key of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key);
2126
+ }
2127
+ }
2128
+ }
2129
+ }
2130
+ for (const [key, at] of fns) {
2131
+ if (!at.definer || at.searchPath) continue;
2132
+ ctx.report({
2133
+ rule: "migration-definer-search-path",
2134
+ file: at.file,
2135
+ line: at.line,
2136
+ subject: key,
2137
+ 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`
2138
+ });
2139
+ }
2140
+ }
2141
+ var DEFAULT_MIGRATIONS, DEFAULT_BASE, DEFAULT_EXPOSED, schemaOf, TYPE_ALIASES, MULTIWORD_TYPE;
2142
+ var init_supabase = __esm({
2143
+ "src/doctor/supabase.ts"() {
2144
+ init_config();
2145
+ DEFAULT_MIGRATIONS = "supabase/migrations";
2146
+ DEFAULT_BASE = "origin/main";
2147
+ DEFAULT_EXPOSED = ["public"];
2148
+ schemaOf = (name) => name.split(".")[0];
2149
+ TYPE_ALIASES = {
2150
+ int: "integer",
2151
+ int4: "integer",
2152
+ int8: "bigint",
2153
+ int2: "smallint",
2154
+ bool: "boolean",
2155
+ varchar: "character varying",
2156
+ timestamptz: "timestamp with time zone",
2157
+ float8: "double precision"
2158
+ };
2159
+ MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
2160
+ }
2161
+ });
1320
2162
  function readReleaseManifest(root) {
1321
2163
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
1322
2164
  const file = dir && path3.join(dir, "dist", "versions.json");
@@ -1361,11 +2203,14 @@ __export(doctor_exports, {
1361
2203
  globToRegExp: () => globToRegExp,
1362
2204
  loadConfig: () => loadConfig,
1363
2205
  loadGenesis: () => loadGenesis,
2206
+ nativeLayouts: () => nativeLayouts,
1364
2207
  parseExportNames: () => parseExportNames,
1365
2208
  parseRulesMarkdown: () => parseRulesMarkdown,
1366
2209
  readGenesisConfig: () => readGenesisConfig,
2210
+ readPackageExports: () => readPackageExports,
1367
2211
  readReleaseManifest: () => readReleaseManifest,
1368
2212
  runDoctor: () => runDoctor,
2213
+ sqlStatements: () => sqlStatements,
1369
2214
  toJson: () => toJson,
1370
2215
  validateConfig: () => validateConfig,
1371
2216
  validateLinks: () => validateLinks
@@ -1391,7 +2236,9 @@ async function runDoctor(options = {}) {
1391
2236
  { name: "colors", check: checkColors },
1392
2237
  { name: "tokens", check: checkTokens },
1393
2238
  { name: "shadowed-exports", check: checkShadowedExports },
1394
- { name: "version-skew", check: checkVersionSkew }
2239
+ { name: "version-skew", check: checkVersionSkew },
2240
+ ...config.packs?.includes("native") ? [{ name: "native", check: checkNativePack }] : [],
2241
+ ...config.packs?.includes("supabase") ? [{ name: "supabase", check: checkSupabasePack }] : []
1395
2242
  ];
1396
2243
  for (const plugin of [...builtins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
1397
2244
  try {
@@ -1496,7 +2343,9 @@ var init_doctor = __esm({
1496
2343
  init_patterns();
1497
2344
  init_plugins();
1498
2345
  init_rules();
2346
+ init_native();
1499
2347
  init_scan();
2348
+ init_supabase();
1500
2349
  init_versions();
1501
2350
  init_config();
1502
2351
  init_genesis();
@@ -1504,6 +2353,8 @@ var init_doctor = __esm({
1504
2353
  init_plugins();
1505
2354
  init_rules();
1506
2355
  init_glob();
2356
+ init_native();
2357
+ init_supabase();
1507
2358
  init_versions();
1508
2359
  }
1509
2360
  });
@@ -2026,7 +2877,7 @@ var NOOP_LOGGER = {
2026
2877
  function validateConsumerName(name) {
2027
2878
  if (!VALID_NAME_PATTERN.test(name)) {
2028
2879
  throw new Error(
2029
- `Invalid consumer name "${name}". Must be lowercase letters/digits/hyphens, 2-31 chars, starting with a letter (e.g., "acme", "gamify-mobile").`
2880
+ `Invalid consumer name "${name}". Must be lowercase letters/digits/hyphens, 2-31 chars, starting with a letter (e.g., "acme", "arcade-mobile").`
2030
2881
  );
2031
2882
  }
2032
2883
  }
@@ -2109,9 +2960,9 @@ async function runScaffold(opts, fs2) {
2109
2960
  function joinPath(...parts) {
2110
2961
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
2111
2962
  }
2112
- function dirname(path12) {
2113
- const idx = path12.lastIndexOf("/");
2114
- return idx === -1 ? "." : path12.slice(0, idx);
2963
+ function dirname(path15) {
2964
+ const idx = path15.lastIndexOf("/");
2965
+ return idx === -1 ? "." : path15.slice(0, idx);
2115
2966
  }
2116
2967
  function brandPackageJson(consumer, genesisVersion) {
2117
2968
  return JSON.stringify(
@@ -2152,7 +3003,7 @@ function brandSchema(consumer) {
2152
3003
  * Genesis primitives consume tokens from this file via the design-system
2153
3004
  * provider. Edit colors/spacing/typography here to retheme every screen
2154
3005
  * at once. Domain-specific tokens (e.g., "mood" for Acme, "rarity" for
2155
- * Gamify) go under \`extensions\` \u2014 Genesis primitives don't read these,
3006
+ * a game app) go under \`extensions\` \u2014 Genesis primitives don't read these,
2156
3007
  * but consumer composites do via \`useGenesisExtension(key)\`.
2157
3008
  *
2158
3009
  * Schema is intentionally narrow at the top level. Add categories under
@@ -2486,22 +3337,22 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
2486
3337
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
2487
3338
  const root = path3.resolve(opts.dir);
2488
3339
  const packageJson = JSON.parse(await fs.readFile(path3.join(root, "package.json"), "utf-8").catch(() => "{}"));
2489
- const existsSync9 = (await import('fs')).existsSync;
3340
+ const existsSync12 = (await import('fs')).existsSync;
2490
3341
  const readSync = (await import('fs')).readFileSync;
2491
- const readdirSync3 = (await import('fs')).readdirSync;
3342
+ const readdirSync4 = (await import('fs')).readdirSync;
2492
3343
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
2493
3344
  throw new Error("--host must be next, tanstack-start or supabase-function.");
2494
3345
  }
2495
3346
  const plan = planStudioInit2(
2496
3347
  {
2497
3348
  packageJson,
2498
- exists: (p) => existsSync9(path3.join(root, p)),
2499
- read: (p) => existsSync9(path3.join(root, p)) ? readSync(path3.join(root, p), "utf-8") : null,
3349
+ exists: (p) => existsSync12(path3.join(root, p)),
3350
+ read: (p) => existsSync12(path3.join(root, p)) ? readSync(path3.join(root, p), "utf-8") : null,
2500
3351
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
2501
3352
  listDeep: (p) => {
2502
3353
  const out = [];
2503
3354
  const walk = (rel) => {
2504
- for (const entry of readdirSync3(path3.join(root, rel), { withFileTypes: true })) {
3355
+ for (const entry of readdirSync4(path3.join(root, rel), { withFileTypes: true })) {
2505
3356
  const child = `${rel}/${entry.name}`;
2506
3357
  if (entry.isDirectory()) walk(child);
2507
3358
  else out.push(child);
@@ -2515,7 +3366,7 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
2515
3366
  },
2516
3367
  list: (p) => {
2517
3368
  try {
2518
- return readdirSync3(path3.join(root, p));
3369
+ return readdirSync4(path3.join(root, p));
2519
3370
  } catch {
2520
3371
  return [];
2521
3372
  }
@@ -2536,14 +3387,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
2536
3387
  console.log(`+ ${file.path} (appended)`);
2537
3388
  continue;
2538
3389
  }
2539
- if (existsSync9(target) && !opts.force) {
3390
+ if (existsSync12(target) && !opts.force) {
2540
3391
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
2541
3392
  continue;
2542
3393
  }
2543
3394
  await fs.writeFile(target, file.content, "utf-8");
2544
3395
  console.log(`+ ${file.path}`);
2545
3396
  }
2546
- const pm = existsSync9(path3.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync9(path3.join(root, "yarn.lock")) ? "yarn add" : existsSync9(path3.join(root, "bun.lock")) || existsSync9(path3.join(root, "bun.lockb")) ? "bun add" : "npm install";
3397
+ const pm = existsSync12(path3.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync12(path3.join(root, "yarn.lock")) ? "yarn add" : existsSync12(path3.join(root, "bun.lock")) || existsSync12(path3.join(root, "bun.lockb")) ? "bun add" : "npm install";
2547
3398
  console.log("");
2548
3399
  console.log(`\u2714 The Data Studio is set up for ${{ next: "Next.js", "tanstack-start": "TanStack Start", "supabase-function": "a Supabase Edge Function" }[plan.host]}. To finish:`);
2549
3400
  console.log(` 1. ${pm} ${plan.install.join(" ")}`);