@marktiderman/genesis-cli 1.18.0 → 1.19.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.
@@ -0,0 +1,219 @@
1
+ -- @feat:support-feedback
2
+ -- pgTAP test for 0003_genesis_support_findings.sql (after 0006_genesis_support.sql). Copy into
3
+ -- your app's `supabase/tests/database/` and run `supabase test db`. It writes only its own
4
+ -- users, reports and replies and rolls everything back. If your app already has the staff hook
5
+ -- (`private.genesis_support_staff`), the handler hook (`private.genesis_support_report_handler`)
6
+ -- or the verify prompt hook (`private.genesis_support_verify_prompt_enabled`), they are replaced
7
+ -- inside this transaction only, as is the reply trigger function (to stand for a later rule).
8
+ --
9
+ -- People: a1 reports, b2 is someone else, c3 is staff, d4 handles a1's first report (the app's
10
+ -- hook says so), nobody else's.
11
+ begin;
12
+ create extension if not exists pgtap with schema extensions;
13
+ select plan(32);
14
+
15
+ insert into auth.users (id, aud, role, email, instance_id)
16
+ select ('00000000-0000-4000-8000-0000000003' || n)::uuid, 'authenticated', 'authenticated',
17
+ 'genesis-support-findings-' || n || '@example.test', '00000000-0000-0000-0000-000000000000'
18
+ from unnest(array['a1', 'b2', 'c3', 'd4']) n;
19
+
20
+ create function pg_temp.person(n text) returns uuid language sql immutable as $$ select ('00000000-0000-4000-8000-0000000003' || n)::uuid $$;
21
+ create function pg_temp.sign_in(n text) returns void language plpgsql as $$
22
+ begin
23
+ perform set_config('request.jwt.claims', json_build_object('sub', pg_temp.person(n), 'role', 'authenticated')::text, true);
24
+ perform set_config('request.jwt.claim.sub', pg_temp.person(n)::text, true);
25
+ end $$;
26
+ create table pg_temp.ids (name text primary key, id uuid);
27
+ create function pg_temp.remember(name text, q text) returns void language plpgsql as $$
28
+ declare v uuid;
29
+ begin
30
+ execute q into v;
31
+ insert into pg_temp.ids values (name, v);
32
+ end $$;
33
+ create function pg_temp.id(n text) returns uuid language sql stable as $$ select id from pg_temp.ids where name = n $$;
34
+ grant select, insert on pg_temp.ids to anon, authenticated;
35
+ grant execute on function pg_temp.person(text), pg_temp.sign_in(text), pg_temp.remember(text, text), pg_temp.id(text)
36
+ to anon, authenticated, service_role;
37
+
38
+ drop function if exists private.genesis_support_staff(uuid);
39
+ create function private.genesis_support_staff(person uuid) returns boolean
40
+ language sql stable set search_path = '' as $$
41
+ select person = '00000000-0000-4000-8000-0000000003c3'::uuid
42
+ $$;
43
+ revoke execute on function private.genesis_support_staff(uuid) from public, anon, authenticated;
44
+
45
+ -- The schema --------------------------------------------------------------------------
46
+ select has_column('public', 'support_reports', 'severity', 'a report has a severity');
47
+ select ok(
48
+ has_column_privilege('authenticated', 'public.support_reports', 'severity', 'insert')
49
+ and not has_column_privilege('authenticated', 'public.support_reports', 'severity', 'update'),
50
+ 'the person sends a severity with the report, and can''t change it after'
51
+ );
52
+ select ok(
53
+ not has_function_privilege('authenticated', 'private.genesis_support_handler(uuid, uuid)', 'execute')
54
+ and not has_function_privilege('anon', 'public.support_handles(uuid)', 'execute')
55
+ and not has_function_privilege('anon', 'public.support_verify_report(uuid, boolean, text)', 'execute')
56
+ and has_function_privilege('authenticated', 'public.support_verify_report(uuid, boolean, text)', 'execute'),
57
+ 'the handler check is the database''s, and anon calls nothing'
58
+ );
59
+ select ok(
60
+ not has_column_privilege('authenticated', 'public.support_replies', 'prompt', 'insert'),
61
+ 'nobody writes a reply as the system''s'
62
+ );
63
+
64
+ -- Severity ----------------------------------------------------------------------------
65
+ select pg_temp.sign_in('a1');
66
+ set local role authenticated;
67
+ select pg_temp.remember('r1', $$ insert into public.support_reports (type, title, message, severity) values ('bug', 'Export broke', 'It broke', 'high') returning id $$);
68
+ select pg_temp.remember('r2', $$ insert into public.support_reports (type, title, message) values ('bug', 'Second', 'Another') returning id $$);
69
+ select throws_ok($$ insert into public.support_reports (type, message, severity) values ('bug', 'x', 'dire') $$,
70
+ '23514', null, 'a severity outside the list is refused');
71
+ reset role;
72
+ select is((select severity from public.support_reports where id = pg_temp.id('r1')), 'high', 'the severity is kept');
73
+
74
+ -- Without the app's handler hook, only the person and staff handle a report ----------------
75
+ select pg_temp.sign_in('d4');
76
+ set local role authenticated;
77
+ select ok(not public.support_handles(pg_temp.id('r1')), 'without the hook, someone else doesn''t handle it');
78
+ select is((select count(*)::int from public.support_reports where id = pg_temp.id('r1')), 0, 'or read it');
79
+ reset role;
80
+ select pg_temp.sign_in('c3');
81
+ set local role authenticated;
82
+ select ok(public.support_handles(pg_temp.id('r1')), 'staff handle every report');
83
+ reset role;
84
+
85
+ -- The app names a handler ---------------------------------------------------------------
86
+ drop function if exists private.genesis_support_report_handler(uuid, uuid);
87
+ create function private.genesis_support_report_handler(report uuid, person uuid) returns boolean
88
+ language sql stable set search_path = '' as $$
89
+ select person = '00000000-0000-4000-8000-0000000003d4'::uuid
90
+ and report = (select id from pg_temp.ids where name = 'r1')
91
+ $$;
92
+ revoke execute on function private.genesis_support_report_handler(uuid, uuid) from public, anon, authenticated;
93
+
94
+ select pg_temp.sign_in('d4');
95
+ set local role authenticated;
96
+ select ok(public.support_handles(pg_temp.id('r1')), 'the hook''s handler handles the report it names');
97
+ select ok(not public.support_handles(pg_temp.id('r2')), 'and not another');
98
+ select is((select count(*)::int from public.support_reports where user_id = pg_temp.person('a1')), 1, 'and reads only that one');
99
+ insert into public.support_replies (report_id, body) values (pg_temp.id('r1'), 'Looking at it');
100
+ select is((select from_staff from public.support_replies where report_id = pg_temp.id('r1') and body = 'Looking at it'), true,
101
+ 'a handler replies as support');
102
+ select throws_ok($$ insert into public.support_replies (report_id, body) values (pg_temp.id('r2'), 'Not mine') $$,
103
+ '42501', null, 'but not on a report they don''t handle');
104
+ select lives_ok($$ select public.support_set_report_status(pg_temp.id('r1'), 'in_progress') $$, 'a handler sets the status');
105
+ select throws_ok($$ select public.support_set_report_status(pg_temp.id('r2'), 'in_progress') $$,
106
+ '42501', null, 'not on a report they don''t handle');
107
+ reset role;
108
+
109
+ select pg_temp.sign_in('b2');
110
+ set local role authenticated;
111
+ select ok(not public.support_handles(pg_temp.id('r1')), 'someone else doesn''t handle it');
112
+ reset role;
113
+
114
+ -- The verify loop -----------------------------------------------------------------------
115
+ drop function if exists private.genesis_support_verify_prompt_enabled();
116
+
117
+ select pg_temp.sign_in('d4');
118
+ set local role authenticated;
119
+ select public.support_set_report_status(pg_temp.id('r1'), 'addressed');
120
+ reset role;
121
+ select isnt((select resolved_at from public.support_reports where id = pg_temp.id('r1')), null, 'marked addressed, it is stamped');
122
+ select is((select count(*)::int from public.support_replies where report_id = pg_temp.id('r1') and prompt is not null), 0,
123
+ 'without the app''s hook, nobody is asked to check the fix');
124
+
125
+ -- The app turns the prompt on.
126
+ create function private.genesis_support_verify_prompt_enabled() returns boolean
127
+ language sql stable set search_path = '' as $$ select true $$;
128
+ revoke execute on function private.genesis_support_verify_prompt_enabled() from public, anon, authenticated;
129
+
130
+ select pg_temp.sign_in('d4');
131
+ set local role authenticated;
132
+ select public.support_set_report_status(pg_temp.id('r1'), 'in_progress');
133
+ reset role;
134
+ select is((select resolved_at from public.support_reports where id = pg_temp.id('r1')), null, 'back in progress, no longer resolved');
135
+ select pg_temp.sign_in('d4');
136
+ set local role authenticated;
137
+ select public.support_set_report_status(pg_temp.id('r1'), 'addressed');
138
+ reset role;
139
+ select is((select count(*)::int from public.support_replies where report_id = pg_temp.id('r1') and from_staff and prompt = 'verify'), 1,
140
+ 'with the hook on, its person is asked to check the fix, as the system');
141
+
142
+ -- Flipped back and forth within the hour: asked once.
143
+ select pg_temp.sign_in('d4');
144
+ set local role authenticated;
145
+ select public.support_set_report_status(pg_temp.id('r1'), 'in_progress');
146
+ select public.support_set_report_status(pg_temp.id('r1'), 'addressed');
147
+ reset role;
148
+ select is((select count(*)::int from public.support_replies where report_id = pg_temp.id('r1') and prompt = 'verify'), 1,
149
+ 'a status flipped back and forth asks once an hour');
150
+
151
+ select pg_temp.sign_in('b2');
152
+ set local role authenticated;
153
+ select throws_ok($$ select public.support_verify_report(pg_temp.id('r1'), true) $$, '42501', null, 'only its person verifies it');
154
+ reset role;
155
+
156
+ select pg_temp.sign_in('a1');
157
+ set local role authenticated;
158
+ select public.support_verify_report(pg_temp.id('r1'), false, 'Still broken');
159
+ reset role;
160
+ select is((select status from public.support_reports where id = pg_temp.id('r1')), 'in_progress', 'not fixed: it is reopened');
161
+ select ok((select reopened_at is not null and resolved_at is null from public.support_reports where id = pg_temp.id('r1')),
162
+ 'stamped reopened, and no longer resolved');
163
+ select is((select count(*)::int from public.support_replies where report_id = pg_temp.id('r1') and not from_staff and body = 'Still broken'), 1,
164
+ 'with what is still wrong in the thread');
165
+
166
+ select pg_temp.sign_in('a1');
167
+ set local role authenticated;
168
+ select throws_ok($$ select public.support_verify_report(pg_temp.id('r1'), true) $$, '22023', null, 'a report not marked fixed can''t be confirmed');
169
+ reset role;
170
+
171
+ select pg_temp.sign_in('c3');
172
+ set local role authenticated;
173
+ select public.support_set_report_status(pg_temp.id('r1'), 'addressed');
174
+ reset role;
175
+ select pg_temp.sign_in('a1');
176
+ set local role authenticated;
177
+ select public.support_verify_report(pg_temp.id('r1'), true);
178
+ reset role;
179
+ select ok((select status = 'addressed' and verified_at is not null from public.support_reports where id = pg_temp.id('r1')),
180
+ 'fixed: it stays addressed, confirmed');
181
+
182
+ -- Won't fix is resolved too.
183
+ select pg_temp.sign_in('c3');
184
+ set local role authenticated;
185
+ select public.support_set_report_status(pg_temp.id('r2'), 'wont_fix');
186
+ reset role;
187
+ select isnt((select resolved_at from public.support_reports where id = pg_temp.id('r2')), null, 'marked won''t fix, it is stamped');
188
+
189
+ -- A reply rule installed later that refuses the prompt (support-email's 0002 applied after this
190
+ -- file lets only staff reply on someone else's report) never blocks the status change.
191
+ select pg_temp.sign_in('c3');
192
+ set local role authenticated;
193
+ select public.support_set_report_status(pg_temp.id('r1'), 'in_progress');
194
+ reset role;
195
+ delete from public.support_replies where report_id = pg_temp.id('r1') and prompt = 'verify';
196
+ create or replace function private.genesis_support_new_reply() returns trigger
197
+ language plpgsql security definer set search_path = '' as $$
198
+ declare owner uuid;
199
+ begin
200
+ select r.user_id into owner from public.support_reports r where r.id = new.report_id;
201
+ if auth.uid() is null or owner is null or (owner <> auth.uid() and not public.support_is_staff()) then
202
+ raise exception 'support: not your report' using errcode = '42501';
203
+ end if;
204
+ new.author_id := auth.uid();
205
+ new.from_staff := public.support_is_staff() and owner <> auth.uid();
206
+ new.created_at := clock_timestamp();
207
+ return new;
208
+ end $$;
209
+ select pg_temp.sign_in('d4');
210
+ set local role authenticated;
211
+ select lives_ok($$ select public.support_set_report_status(pg_temp.id('r1'), 'addressed') $$,
212
+ 'a handler still marks it addressed when a later reply rule refuses the prompt');
213
+ reset role;
214
+ select is((select status from public.support_reports where id = pg_temp.id('r1')), 'addressed', 'the status change is kept');
215
+ select is((select count(*)::int from public.support_replies where report_id = pg_temp.id('r1') and prompt = 'verify'), 0,
216
+ 'without the prompt');
217
+
218
+ select * from finish();
219
+ rollback;
@@ -16,6 +16,7 @@ jobs:
16
16
  uses: marktiderman/genesis/.github/workflows/genesis-upgrade.yml@GENESIS_SHA # @marktiderman/genesis@X.Y.Z
17
17
  with:
18
18
  package-manager: pnpm # or bun, npm
19
+ # base-branch: staging # the branch the pull request targets; default: the default branch
19
20
  # So CI runs on the pull request (the default token can't start workflows):
20
21
  # secrets:
21
22
  # token: ${{ secrets.GENESIS_UPGRADE_TOKEN }}
package/dist/vite.js CHANGED
@@ -455,14 +455,14 @@ function inherit(own, source) {
455
455
  }
456
456
  function resolveViews(relations) {
457
457
  const done = /* @__PURE__ */ new Set();
458
- const resolve16 = (relation, depth) => {
458
+ const resolve17 = (relation, depth) => {
459
459
  if (done.has(relation.oid) || !relation.origins || depth > MAX_VIEW_DEPTH) return;
460
460
  done.add(relation.oid);
461
461
  const sources = new Set([...relation.origins.values()].map((o) => o.relation));
462
462
  if (sources.size !== 1) return;
463
463
  const source = relations.get([...sources][0]);
464
464
  if (!source) return;
465
- resolve16(source, depth + 1);
465
+ resolve17(source, depth + 1);
466
466
  const viewAttnumOf = /* @__PURE__ */ new Map();
467
467
  for (const [attnum, origin] of relation.origins) {
468
468
  const own = relation.columns.get(attnum);
@@ -485,7 +485,7 @@ function resolveViews(relations) {
485
485
  };
486
486
  if (Object.keys(inherited).length) relation.table.settings = { ...inherited, ...relation.table.settings };
487
487
  };
488
- for (const relation of relations.values()) resolve16(relation, 0);
488
+ for (const relation of relations.values()) resolve17(relation, 0);
489
489
  }
490
490
  async function introspectPostgres(sql, schemas, options = {}) {
491
491
  const relations = /* @__PURE__ */ new Map();
@@ -899,8 +899,26 @@ function readGenesisConfig(root) {
899
899
  const out = { raw };
900
900
  if (raw.links !== void 0) out.links = validateLinks(raw.links, file);
901
901
  if (raw.privacy !== void 0) out.privacy = validatePrivacy(raw.privacy, file);
902
+ if (raw.supabase !== void 0) {
903
+ const supabase = validateSupabase(raw.supabase, file);
904
+ if (supabase !== true) out.supabase = supabase;
905
+ }
902
906
  return out;
903
907
  }
908
+ function validateSupabase(raw, source = "config") {
909
+ const fail = (msg) => {
910
+ throw new GenesisConfigError(`${source}: ${msg}`);
911
+ };
912
+ if (typeof raw === "boolean") return raw ? true : false;
913
+ if (!isObject(raw)) return fail(`"supabase" must be false or { "app": "<the folder of the app that holds supabase/>" }`);
914
+ for (const key2 of Object.keys(raw)) if (key2 !== "app" && key2 !== "$comment") fail(`supabase: unknown setting "${key2}" (known: app)`);
915
+ const app = raw.app;
916
+ if (typeof app !== "string" || !app.trim()) return fail(`supabase.app must be the folder of the app that holds supabase/, relative to this one (e.g. "../app")`);
917
+ if (path20.isAbsolute(app) || /^[A-Za-z]:[\\/]/.test(app) || app.includes("\\")) fail(`supabase.app must be relative to this app, with forward slashes ("${app}")`);
918
+ const norm = path20.posix.normalize(app).replace(/\/+$/, "");
919
+ if (norm === "." || norm === "") fail(`supabase.app names this app itself; leave "supabase" out instead`);
920
+ return { app: norm };
921
+ }
904
922
  var PRIVACY_KEYS = /* @__PURE__ */ new Set(["blocks", "collects", "tracking"]);
905
923
  var DATA_USE_KEYS = /* @__PURE__ */ new Set(["type", "purposes", "linked", "tracking"]);
906
924
  function validatePrivacy(raw, source = "config") {
@@ -1125,7 +1143,7 @@ function globToRegExp(glob) {
1125
1143
  }
1126
1144
  function globMatcher(globs) {
1127
1145
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1128
- return (path37) => res.some((re) => re.test(path37));
1146
+ return (path40) => res.some((re) => re.test(path40));
1129
1147
  }
1130
1148
  var DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
1131
1149
  var NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
@@ -1511,6 +1529,26 @@ function parseManifest(home, id, raw, version, options = {}) {
1511
1529
  const file = pathOf(m["file"], `${where2}.file`);
1512
1530
  if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where2}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
1513
1531
  const out = { package: pkgOf(m["package"], where2), file };
1532
+ if (m["provides"] !== void 0) {
1533
+ if (!Array.isArray(m["provides"])) problems.push(`${where2}.provides: must be a list of { package, file }`);
1534
+ else {
1535
+ out.provides = m["provides"].map((p, j) => {
1536
+ const at2 = `${where2}.provides[${j}]`;
1537
+ if (!isObject2(p)) {
1538
+ problems.push(`${at2}: must be an object`);
1539
+ return { package: home, file: "" };
1540
+ }
1541
+ const provided = { package: pkgOf(p["package"], at2), file: pathOf(p["file"], `${at2}.file`) };
1542
+ if (p["functions"] !== void 0) {
1543
+ if (!Array.isArray(p["functions"])) problems.push(`${at2}.functions: must be a list of function folders`);
1544
+ else provided.functions = p["functions"].map((f, k) => pathOf(f, `${at2}.functions[${k}]`));
1545
+ }
1546
+ if (provided.file && !MIGRATION_FILE.test(provided.file.split("/").pop())) problems.push(`${at2}.file: "${provided.file}" must be named NNNN_name.sql`);
1547
+ if (provided.package === out.package && provided.file === file) problems.push(`${at2}: a migration can't provide itself`);
1548
+ return provided;
1549
+ });
1550
+ }
1551
+ }
1514
1552
  if (m["test"] !== void 0) {
1515
1553
  out.test = pathOf(m["test"], `${where2}.test`);
1516
1554
  if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where2}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
@@ -1654,10 +1692,6 @@ function appPath2(root, rel) {
1654
1692
  if (there(target) && lstatSync(target).isSymbolicLink()) throw new Error(`${rel} is a symlink; left alone`);
1655
1693
  return target;
1656
1694
  }
1657
- function readApp(root, rel) {
1658
- const file = appPath2(root, rel);
1659
- return existsSync(file) ? readFileSync(file, "utf8") : null;
1660
- }
1661
1695
 
1662
1696
  // src/blocks/local.ts
1663
1697
  var LOCAL_PACKAGES_KEY = "localPackages";
@@ -2474,7 +2508,9 @@ var BUILTIN_RULES = [
2474
2508
  // supabase pack: contracts (contracts.ts)
2475
2509
  "contracts-stale",
2476
2510
  // genesis.lock.json against the files (lock-files.ts)
2477
- "lock-files"
2511
+ "lock-files",
2512
+ // an app whose database files live in another app (database.ts)
2513
+ "database-elsewhere"
2478
2514
  ];
2479
2515
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
2480
2516
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -2697,7 +2733,7 @@ function privacyApisFor(dependencies2) {
2697
2733
  var EAS_PLACEHOLDERS = {
2698
2734
  REPLACE_WITH_APP_STORE_CONNECT_APP_ID: "the app's Apple ID from App Store Connect (create the app there, then App Information \u2192 General Information \u2192 Apple ID, a number)",
2699
2735
  REPLACE_WITH_APPLE_TEAM_ID: "your Apple Developer Team ID (developer.apple.com \u2192 Account \u2192 Membership details, 10 characters)",
2700
- REPLACE_WITH_PATH_TO_GOOGLE_SERVICE_ACCOUNT_JSON: "the path to your Google Play service account key, a JSON file kept out of git (Play Console \u2192 Setup \u2192 API access); or delete submit.production.android until you ship to Google Play",
2736
+ REPLACE_WITH_PATH_TO_GOOGLE_SERVICE_ACCOUNT_JSON: "the Google Play service account key uploaded to EAS, not a local path (deploy-production.yml submits on EAS, where a local file isn't there): create a Google Cloud service account and its JSON key, invite it in Play Console \u2192 Users and permissions, upload the key with `eas credentials` (Android \u2192 Google Service Account), then remove only this serviceAccountKeyPath line (https://docs.expo.dev/submit/android/). Until you ship to Google Play, remove the submit_android job from deploy-production.yml instead, and keep submit.production.android as it is (the internal track, as a draft)",
2701
2737
  REPLACE_WITH_APP_FOLDER: "the app's code folder (src, or apps/<name> in a monorepo)"
2702
2738
  };
2703
2739
  function placeholderKey(line, placeholder) {
@@ -3606,11 +3642,21 @@ async function blocksOfInstalled(dir, warnings = [], options = {}) {
3606
3642
  const out = [];
3607
3643
  for (const id of [...ids].sort()) {
3608
3644
  const fromJson = raw[id] ?? {};
3609
- const manifest = tryParse(() => parseManifest(pkg.name, id, { ...fromJson, ...declared[id] }, pkg.version, options), warnings);
3645
+ const merged = { ...fromJson, ...declared[id] };
3646
+ if (declared[id]?.["migrations"] && Array.isArray(fromJson["migrations"])) merged["migrations"] = withProvides(declared[id]["migrations"], fromJson["migrations"]);
3647
+ const manifest = tryParse(() => parseManifest(pkg.name, id, merged, pkg.version, options), warnings);
3610
3648
  if (manifest) out.push(manifest);
3611
3649
  }
3612
3650
  return out;
3613
3651
  }
3652
+ function withProvides(declared, json) {
3653
+ if (!Array.isArray(declared)) return declared;
3654
+ const fileOf = (m) => m && typeof m === "object" ? m["file"] : void 0;
3655
+ return declared.map((m) => {
3656
+ const same = json.find((j) => fileOf(j) === fileOf(m));
3657
+ return same?.["provides"] !== void 0 && m && typeof m === "object" && !("provides" in m) ? { ...m, provides: same["provides"] } : m;
3658
+ });
3659
+ }
3614
3660
  async function allBlocks(root, warnings = []) {
3615
3661
  const out = [];
3616
3662
  for (const local of localPackages(root)) {
@@ -4469,6 +4515,45 @@ function checkPackagesPack(ctx) {
4469
4515
  if (base && "sha" in merge && !overlay) checkChanges(ctx, pkg, json, base, merge.sha);
4470
4516
  }
4471
4517
  }
4518
+ var LOCK_FILE = "genesis.lock.json";
4519
+ function emptyLock() {
4520
+ return { version: 1, blocks: {}, files: {} };
4521
+ }
4522
+ function readLock(root) {
4523
+ const file = path20.join(root, LOCK_FILE);
4524
+ if (!existsSync(file)) return emptyLock();
4525
+ const raw = JSON.parse(readFileSync(file, "utf8"));
4526
+ if (raw.version !== 1) throw new Error(`${LOCK_FILE} has version ${String(raw.version)}; this CLI reads version 1.`);
4527
+ return {
4528
+ version: 1,
4529
+ ...raw.substitutions ? { substitutions: raw.substitutions } : {},
4530
+ blocks: raw.blocks ?? {},
4531
+ files: raw.files ?? {},
4532
+ ...raw.migrations ? { migrations: raw.migrations } : {}
4533
+ };
4534
+ }
4535
+ function parseSource(source) {
4536
+ const at = source.indexOf(":");
4537
+ if (at < 1) throw new Error(`${LOCK_FILE}: "${source}" is not <package>:<path>`);
4538
+ return { package: source.slice(0, at), path: source.slice(at + 1) };
4539
+ }
4540
+
4541
+ // src/blocks/database.ts
4542
+ function databaseElsewhere(root) {
4543
+ const setting = readGenesisConfig(root)?.supabase;
4544
+ if (setting === void 0) return null;
4545
+ if (setting === false) return { app: null, dir: null, hasSupabase: false };
4546
+ const resolved = path20.resolve(root, setting.app);
4547
+ const real2 = (p) => existsSync(p) ? realpathSync(p) : p;
4548
+ const dir = real2(resolved);
4549
+ if (dir === real2(path20.resolve(root))) throw new GenesisConfigError(`${path20.join(root, "genesis.config.json")}: supabase.app "${setting.app}" is this app itself; leave "supabase" out instead`);
4550
+ return { app: setting.app, dir, hasSupabase: existsSync(path20.join(dir, "supabase")) };
4551
+ }
4552
+ function isSupabasePath(rel) {
4553
+ return rel === "supabase" || rel.startsWith("supabase/");
4554
+ }
4555
+
4556
+ // src/doctor/supabase.ts
4472
4557
  var DEFAULT_MIGRATIONS = "supabase/migrations";
4473
4558
  var DEFAULT_BASE = "origin/main";
4474
4559
  var DEFAULT_EXPOSED = ["public"];
@@ -4649,6 +4734,7 @@ function gitView(root, dir, base) {
4649
4734
  return { touched: touched2, edited };
4650
4735
  }
4651
4736
  function checkSupabasePack(ctx) {
4737
+ if (databaseElsewhere(ctx.root)) return;
4652
4738
  const settings = ctx.config.supabase ?? {};
4653
4739
  const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
4654
4740
  const abs = path20.join(ctx.root, dir);
@@ -6068,28 +6154,6 @@ function checkAgentGuide(ctx) {
6068
6154
  ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
6069
6155
  }
6070
6156
  }
6071
- var LOCK_FILE = "genesis.lock.json";
6072
- function emptyLock() {
6073
- return { version: 1, blocks: {}, files: {} };
6074
- }
6075
- function readLock(root) {
6076
- const file = path20.join(root, LOCK_FILE);
6077
- if (!existsSync(file)) return emptyLock();
6078
- const raw = JSON.parse(readFileSync(file, "utf8"));
6079
- if (raw.version !== 1) throw new Error(`${LOCK_FILE} has version ${String(raw.version)}; this CLI reads version 1.`);
6080
- return {
6081
- version: 1,
6082
- ...raw.substitutions ? { substitutions: raw.substitutions } : {},
6083
- blocks: raw.blocks ?? {},
6084
- files: raw.files ?? {},
6085
- ...raw.migrations ? { migrations: raw.migrations } : {}
6086
- };
6087
- }
6088
- function parseSource(source) {
6089
- const at = source.indexOf(":");
6090
- if (at < 1) throw new Error(`${LOCK_FILE}: "${source}" is not <package>:<path>`);
6091
- return { package: source.slice(0, at), path: source.slice(at + 1) };
6092
- }
6093
6157
  var CLI = "@marktiderman/genesis-cli";
6094
6158
  function ownedKeyProblem(key2, source, localNames = /* @__PURE__ */ new Set()) {
6095
6159
  let parsed;
@@ -6132,8 +6196,25 @@ function featuresBody(text) {
6132
6196
  const m = /\bfeatures:\s*\{/.exec(text);
6133
6197
  if (!m) return null;
6134
6198
  const start = m.index + m[0].length;
6135
- const end = text.indexOf("}", start);
6136
- return end < 0 ? null : { start, body: text.slice(start, end) };
6199
+ let depth = 1;
6200
+ for (let i = start; i < text.length; i++) {
6201
+ const c = text[i];
6202
+ if (c === "/" && text[i + 1] === "/") {
6203
+ const nl = text.indexOf("\n", i);
6204
+ if (nl < 0) return null;
6205
+ i = nl;
6206
+ } else if (c === "/" && text[i + 1] === "*") {
6207
+ const close = text.indexOf("*/", i + 2);
6208
+ if (close < 0) return null;
6209
+ i = close + 1;
6210
+ } else if (c === '"' || c === "'" || c === "`") {
6211
+ let j = i + 1;
6212
+ while (j < text.length && text[j] !== c) j += text[j] === "\\" ? 2 : 1;
6213
+ i = j;
6214
+ } else if (c === "{") depth++;
6215
+ else if (c === "}" && --depth === 0) return { start, body: text.slice(start, i) };
6216
+ }
6217
+ return null;
6137
6218
  }
6138
6219
  function parseStarterFeatures(text) {
6139
6220
  const found = featuresBody(text);
@@ -6155,6 +6236,7 @@ function parseStarterBlocks(json, source = GENESIS_CONFIG) {
6155
6236
  const starter = raw?.starter;
6156
6237
  if (starter === void 0) return null;
6157
6238
  const blocks = starter?.blocks;
6239
+ if (blocks === void 0 && typeof starter === "object" && starter !== null && !Array.isArray(starter)) return null;
6158
6240
  if (typeof blocks !== "object" || blocks === null || Array.isArray(blocks)) throw new Error(`${source}: starter.blocks must map each feature switch to a list of block ids`);
6159
6241
  const out = {};
6160
6242
  for (const [name, ids] of Object.entries(blocks)) {
@@ -6253,15 +6335,44 @@ async function checkLockFiles(ctx) {
6253
6335
  });
6254
6336
  }
6255
6337
  const local = localPackageNames(ctx.root);
6338
+ let home = null;
6339
+ try {
6340
+ home = databaseElsewhere(ctx.root);
6341
+ } catch {
6342
+ }
6343
+ const elsewhere = home ? Object.keys(lock.files).filter(isSupabasePath) : [];
6344
+ if (home && elsewhere.length) {
6345
+ ctx.report({
6346
+ rule: "lock-files",
6347
+ level: "info",
6348
+ file: LOCK_FILE,
6349
+ subject: "supabase/",
6350
+ message: `lists ${elsewhere.length} file${elsewhere.length === 1 ? "" : "s"} under supabase/, but this app's database files live ${home.app ? `in ${home.app}` : "nowhere"} (genesis.config.json supabase): genesis upgrade leaves them alone, so delete those entries`
6351
+ });
6352
+ }
6256
6353
  for (const [rel, entry] of Object.entries(lock.files)) {
6354
+ if (home && isSupabasePath(rel)) continue;
6257
6355
  if (ownedKeyProblem(rel, entry.source, local)) continue;
6258
6356
  if (offManifests.length && blockOfSource(entry.source, offManifests)) continue;
6259
- let text;
6357
+ let file;
6260
6358
  try {
6261
- text = readApp(ctx.root, rel);
6359
+ file = appPath2(ctx.root, rel);
6262
6360
  } catch {
6263
6361
  continue;
6264
6362
  }
6363
+ let text;
6364
+ try {
6365
+ text = existsSync(file) ? readFileSync(file, "utf8") : null;
6366
+ } catch (err) {
6367
+ ctx.report({
6368
+ rule: "lock-files",
6369
+ level: "warn",
6370
+ file: rel,
6371
+ subject: rel,
6372
+ message: `is in ${LOCK_FILE} (from ${entry.source}) but can't be read (${err instanceof Error ? err.message : String(err)}), so genesis upgrade can't refresh it. Make it a file again, or remove its entry from ${LOCK_FILE}`
6373
+ });
6374
+ continue;
6375
+ }
6265
6376
  if (text === null) {
6266
6377
  if (entry.deleted) continue;
6267
6378
  ctx.report({
@@ -6286,6 +6397,28 @@ async function checkLockFiles(ctx) {
6286
6397
  });
6287
6398
  }
6288
6399
  }
6400
+ function checkDatabaseHome(ctx) {
6401
+ const home = databaseElsewhere(ctx.root);
6402
+ if (!home) return;
6403
+ if (home.app && !home.hasSupabase) {
6404
+ ctx.report({
6405
+ rule: "database-elsewhere",
6406
+ level: "warn",
6407
+ file: "genesis.config.json",
6408
+ subject: home.app,
6409
+ message: `supabase.app is ${home.app}, which has no supabase folder; name the app that holds this app's database (its migrations, tests and Edge Functions)`
6410
+ });
6411
+ }
6412
+ if (existsSync(path20.join(ctx.root, "supabase"))) {
6413
+ ctx.report({
6414
+ rule: "database-elsewhere",
6415
+ level: "warn",
6416
+ file: "supabase",
6417
+ subject: "supabase/",
6418
+ message: `is here, but genesis.config.json says this app's database files live ${home.app ? `in ${home.app}/supabase` : "nowhere"}: genesis add, migrate and upgrade never plan it, so it is a second, unused copy. Delete it`
6419
+ });
6420
+ }
6421
+ }
6289
6422
  var RATCHETED_BY_DEFAULT = ["deprecated-import"];
6290
6423
  async function runDoctor(options = {}) {
6291
6424
  const root = path20.resolve(options.root ?? process.cwd());
@@ -6388,6 +6521,7 @@ function builtinChecks(config, options = {}) {
6388
6521
  { name: "agent-guide", check: checkAgentGuide },
6389
6522
  { name: "overlays", check: (ctx) => checkOverlays(ctx) },
6390
6523
  { name: "lock-files", check: checkLockFiles },
6524
+ { name: "database-elsewhere", check: checkDatabaseHome },
6391
6525
  ...(config.packs ?? []).map((p) => packs[p]),
6392
6526
  ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
6393
6527
  ];