@marktiderman/genesis-supabase 0.4.0 → 0.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/README.md CHANGED
@@ -589,6 +589,143 @@ A delete that cascades into `tenant_features` (from your tenant table, or a pers
589
589
  goes with them) isn't recorded, so it never refuses the tenant's or the person's deletion; saving
590
590
  the same switch and reason again changes nothing, not even who and when.
591
591
 
592
+ ## The feature registry in the database (the feature-mirror block)
593
+
594
+ Migration `0008_genesis_feature_registry.sql` (needs 0004) gives the feature gate its rows. Why it works this
595
+ way: [ADR 0001](../../docs/adr/0001-one-feature-gate.md).
596
+
597
+ - **The mirror.** `features` and `feature_flags` copy `features.json`, written only by `sync_feature_registry`
598
+ with the service key. Run it from **production deployments only**, when one starts serving, with
599
+ `Date.now()` as the version (not the build time), so an instant rollback syncs as the newest. The same
600
+ registry again changes nothing; an empty registry, or one dropping more than a fifth of the features, is
601
+ refused unless `allowShrink`. Nothing is deleted: a removed feature or flag is marked `in_registry = false`,
602
+ and a flag's tenant values stay.
603
+ - **Paid access.** `feature_entitlements` (tenant, feature, source, `active`, optional `ends_at`). Your billing
604
+ webhook writes it with the service key.
605
+ - **Flag values.** `tenant_flag_values` overrides a flag's default for one tenant (service key).
606
+ - **The gate in SQL.** `feature_on(tenant, feature)` is true for a shipped feature that, when paid, has an
607
+ active entitlement; a signed-in caller outside the tenant gets false. It runs once per row, so in policies
608
+ over many rows use the once-per-statement pair instead:
609
+ `using ((select feature_shipped('exports')) and team_id = any (array(select feature_entitled_tenants('exports'))))`
610
+ (drop the second half for a free feature). Switches and flags are not checked here: server code enforces them.
611
+ - **Reading features.** Signed-in people (not anonymous sign-ins) read shipped, customer-facing features, and
612
+ only `id, name, status, visibility, access_plan, platforms, in_registry`; the full record stays server side.
613
+ - **The snapshot's input.** `feature_gate_state(tenant)` returns the tenant's switches off, entitlements and
614
+ flag values, to its members (with their own JWT, so browsers and extensions can call it) and the service role.
615
+
616
+ ```ts
617
+ import { featureGateState, syncFeatureRegistry } from "@marktiderman/genesis-supabase";
618
+ import { gateSnapshot } from "@marktiderman/genesis-features/gate";
619
+ import registry from "../features.json";
620
+
621
+ // When a production deployment starts serving (never from a preview):
622
+ if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: Date.now() });
623
+
624
+ const state = await featureGateState(supabase, teamId); // per session
625
+ const snapshot = gateSnapshot({ features, flags }, { platform: "web", ...state }, { version: BUILD_TIME });
626
+ ```
627
+
628
+ ## Background jobs (the jobs block)
629
+
630
+ `migrations/0007_genesis_jobs.sql` is one queue for background work and one way to schedule it, so
631
+ an app writes neither its own outbox table nor its own cron wiring. `@marktiderman/genesis-supabase/jobs`
632
+ is the server half. It is server only, since it takes the service-role client and the job secret.
633
+
634
+ **Queue.** Enqueue from server code (`enqueueJob`) or from SQL (`genesis_job_enqueue`, for example
635
+ in a trigger). Then run the handlers on a schedule:
636
+
637
+ ```ts
638
+ import { enqueueJob, runJobs, PermanentJobError } from "@marktiderman/genesis-supabase/jobs";
639
+
640
+ await enqueueJob(admin, "email.digest", { personId }, { idempotencyKey: `${personId}:${day}` });
641
+
642
+ const report = await runJobs(admin, {
643
+ handlers: {
644
+ "email.digest": async ({ payload, redelivery }) => {
645
+ if (redelivery && (await alreadySent(payload.personId))) return;
646
+ const res = await send(payload.personId);
647
+ if (res.status === 429) return { retryAfterSeconds: Number(res.headers.get("retry-after") ?? 60) };
648
+ if (res.status >= 400 && res.status < 500) throw new PermanentJobError(`refused: ${res.status}`);
649
+ },
650
+ },
651
+ });
652
+ ```
653
+
654
+ - **Claims.** `runJobs` claims due jobs of the kinds it handles (`SKIP LOCKED`), each leased for
655
+ `leaseSeconds`. A lease that runs out brings the job back as a `redelivery`. A job that keeps
656
+ dying fails as `lease_expired`.
657
+ - **Outcomes.** A handler that returns nothing is done. One that throws is retried with jittered
658
+ backoff (30 s, doubling, at most an hour) until `maxAttempts`, which defaults to 8.
659
+ `PermanentJobError` or `{ failed }` stops it at once.
660
+ - **Idempotency.** An idempotency key makes a repeated enqueue return the job already queued. It
661
+ only dedupes while that job is pending or running: once it is done, failed or cancelled, the key
662
+ is free again.
663
+ - **Clean-up.** Finished jobs are deleted after 14 days. That is scheduled only if pg_cron was
664
+ installed when the migration ran. If you enable pg_cron later, schedule
665
+ `select private.genesis_jobs_purge()` yourself.
666
+ - **Logs.** Nothing about a payload is logged, so payloads should hold ids and never secrets.
667
+
668
+ - **Settle failures.** If recording an outcome fails, the job is counted as `unsettled` and comes
669
+ back when its lease runs out. The run carries on, and only a failed claim throws.
670
+
671
+ **One job route.** `createJobsHandler` runs the job the route names, but only if the request passes
672
+ one of two constant-time checks:
673
+
674
+ - **Signed for that job.** `Authorization: GenesisJob t=<unix seconds>,sig=<hex HMAC-SHA256 of
675
+ "<t>.<job>">` is good for five minutes. This is what schedules send, and `signJobRequest` builds
676
+ it from your own code.
677
+ - **The plain secret.** `Authorization: Bearer <secret>` (any case) is for a platform cron or a
678
+ person running a job by hand.
679
+
680
+ `previousSecret` is accepted too while you rotate the secret, so remove it once every caller has the
681
+ new one.
682
+
683
+ A signed call is signed for the job name only, so the route trusts nothing else in it. The job gets
684
+ an empty `body`, and the response is `{ job, ok: true }` with no result, because pg_net keeps responses
685
+ in `net._http_response`. A bearer call gets its body, and the job's result comes back as `result`.
686
+
687
+ ```ts
688
+ const handle = createJobsHandler({
689
+ secret: process.env.GENESIS_JOBS_SECRET,
690
+ previousSecret: process.env.GENESIS_JOBS_SECRET_PREVIOUS,
691
+ jobs: {
692
+ queue: () => runJobs(admin, { handlers }),
693
+ "purge-uploads": () => purgeUploads(admin),
694
+ },
695
+ });
696
+ // /api/jobs/$job, GET and POST
697
+ export const POST = ({ request, params }) => handle(request, params.job);
698
+ ```
699
+
700
+ It answers 401 for a wrong or missing secret, and 500 when no secret is set. An unknown job gets
701
+ 404, and a failure gets 500 with no detail (the error goes to `log`).
702
+
703
+ **Schedules.** pg_cron calls the route through pg_net, which needs pgcrypto too (Supabase has it
704
+ in `extensions`). The URL and the secret are read from Vault each time, so they never sit in
705
+ `cron.job`. The request carries a five-minute signature for that one job, never the secret itself.
706
+ That matters because pg_net keeps each request's headers in `net.http_request_queue` until it sends
707
+ them, and on some images other roles can read that table.
708
+
709
+ ```sql
710
+ create extension if not exists pg_cron;
711
+ create extension if not exists pg_net;
712
+ select vault.create_secret('https://app.example.com/api/jobs', 'genesis_jobs_url');
713
+ select vault.create_secret('<the same secret as GENESIS_JOBS_SECRET>', 'genesis_jobs_secret');
714
+ select genesis_schedule_job('jobs-queue', '* * * * *', 'queue'); -- POST …/api/jobs/queue
715
+ select genesis_schedule_job('purge-uploads', '15 3 * * *', 'purge-uploads');
716
+ ```
717
+
718
+ The Vault secrets belong to each environment, so create them by hand in each project and never in
719
+ a migration.
720
+
721
+ - A schedule is the cron job `genesis-job:<name>`. Calling `genesis_schedule_job` with an existing
722
+ name replaces it.
723
+ - `genesis_unschedule_job(name)` removes one, and never touches a cron job it didn't make. A platform cron (Vercel, Cloudflare) can call the same
724
+ route instead: it sends GET with the bearer.
725
+
726
+ **Access.** The queue table has RLS on, no policies, and no grants to `anon` or `authenticated`.
727
+ Every function is granted by name to `service_role` only.
728
+
592
729
  ## Testing your schema's data contract (genesis_testing)
593
730
 
594
731
  `sql/testing/genesis_testing.sql` is a pgTAP kit that checks your own tables and functions keep the
@@ -637,7 +774,7 @@ ids are shared with `@marktiderman/genesis-core/testing`.
637
774
 
638
775
  ## Blocks
639
776
 
640
- `accountBlock` and `tenantFeaturesBlock` are `defineBlock` declarations
777
+ `accountBlock`, `tenantFeaturesBlock` and `jobsBlock` are `defineBlock` declarations
641
778
  (`@marktiderman/genesis-features/blocks`) of what this package's blocks need: their migrations
642
779
  (with their tests) and, for the account, what it means for the stores' privacy forms. The
643
780
  functions above don't change; the declarations are for `resolveBlocks` and the shell.
package/dist/blocks.d.ts CHANGED
@@ -15,5 +15,20 @@ declare const accountBlock: _marktiderman_genesis_features_blocks.BlockDef<"acco
15
15
  * @stability Beta
16
16
  */
17
17
  declare const tenantFeaturesBlock: _marktiderman_genesis_features_blocks.BlockDef<"tenant-features", never>;
18
+ /**
19
+ * The feature registry block: the registry mirrored into the app's database
20
+ * on deploy, entitlements, per-tenant and platform flag values and SQL `feature_on()`,
21
+ * for the feature gate. Needs the tenant features block.
22
+ *
23
+ * @stability Beta
24
+ */
25
+ declare const featureMirrorBlock: _marktiderman_genesis_features_blocks.BlockDef<"feature-mirror", never>;
26
+ /**
27
+ * The jobs block: a background-job queue and named schedules that call the
28
+ * app's job route. Server only; the route is `createJobsHandler` from `/jobs`.
29
+ *
30
+ * @stability Beta
31
+ */
32
+ declare const jobsBlock: _marktiderman_genesis_features_blocks.BlockDef<"jobs", never>;
18
33
 
19
- export { accountBlock, tenantFeaturesBlock };
34
+ export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock };
package/dist/blocks.js CHANGED
@@ -1,3 +1,3 @@
1
- export { accountBlock, tenantFeaturesBlock } from './chunk-T2HGFC4C.js';
1
+ export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-ONBOLMXH.js';
2
2
  //# sourceMappingURL=blocks.js.map
3
3
  //# sourceMappingURL=blocks.js.map
@@ -0,0 +1,96 @@
1
+ import { defineBlock } from '@marktiderman/genesis-features/blocks';
2
+
3
+ // src/blocks.ts
4
+ var PACKAGE = "@marktiderman/genesis-supabase";
5
+ var accountBlock = defineBlock({
6
+ id: "account",
7
+ platforms: ["web", "native"],
8
+ contributes: {
9
+ migrations: [
10
+ {
11
+ package: PACKAGE,
12
+ file: "migrations/0001_genesis_account_deletion.sql",
13
+ test: "migrations/tests/0001_genesis_account_deletion.test.sql"
14
+ },
15
+ // With Sign in with Apple, with the genesis-apple-revoke function beside it.
16
+ {
17
+ package: PACKAGE,
18
+ file: "migrations/0003_genesis_apple_token_revocation.sql",
19
+ test: "migrations/tests/0003_genesis_apple_token_revocation.test.sql"
20
+ }
21
+ ],
22
+ privacy: {
23
+ collects: [
24
+ {
25
+ type: "email address",
26
+ purposes: ["app functionality"],
27
+ linked: true,
28
+ tracking: false
29
+ },
30
+ {
31
+ type: "user id",
32
+ purposes: ["app functionality"],
33
+ linked: true,
34
+ tracking: false
35
+ },
36
+ {
37
+ type: "name",
38
+ purposes: ["app functionality"],
39
+ linked: true,
40
+ tracking: false
41
+ }
42
+ ],
43
+ notes: [
44
+ "People delete their account from inside the app; their login and the rows that cascade from it go with it.",
45
+ "With Sign in with Apple, the person's Apple tokens are revoked when the account is deleted."
46
+ ]
47
+ }
48
+ }
49
+ });
50
+ var tenantFeaturesBlock = defineBlock({
51
+ id: "tenant-features",
52
+ contributes: {
53
+ migrations: [
54
+ {
55
+ package: PACKAGE,
56
+ file: "migrations/0004_genesis_tenant_features.sql",
57
+ test: "migrations/tests/0004_genesis_tenant_features.test.sql"
58
+ }
59
+ ],
60
+ privacy: {
61
+ notes: [
62
+ "Keeps who changed a tenant's switches; a deleted person's changes stay, without the person."
63
+ ]
64
+ }
65
+ }
66
+ });
67
+ var featureMirrorBlock = defineBlock({
68
+ id: "feature-mirror",
69
+ requires: ["tenant-features"],
70
+ contributes: {
71
+ migrations: [
72
+ {
73
+ package: PACKAGE,
74
+ file: "migrations/0008_genesis_feature_registry.sql",
75
+ test: "migrations/tests/0008_genesis_feature_registry.test.sql"
76
+ }
77
+ ],
78
+ privacy: {
79
+ notes: [
80
+ "Stores which tenants hold which paid features and flag values; no personal data."
81
+ ]
82
+ }
83
+ }
84
+ });
85
+ var jobsBlock = defineBlock({
86
+ id: "jobs",
87
+ platforms: ["web"],
88
+ contributes: {
89
+ migrations: [{ package: PACKAGE, file: "migrations/0007_genesis_jobs.sql", test: "migrations/tests/0007_genesis_jobs.test.sql" }],
90
+ privacy: { notes: ["Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days."] }
91
+ }
92
+ });
93
+
94
+ export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock };
95
+ //# sourceMappingURL=ch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A,MACV;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,6CAAA;AAAA,QACN,IAAA,EAAM;AAAA;AACR,KACF;AAAA,IACA,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC;AASM,IAAM,qBAAqB,WAAA,CAAY;AAAA,EAC5C,EAAA,EAAI,gBAAA;AAAA,EACJ,QAAA,EAAU,CAAC,iBAAiB,CAAA;AAAA,EAC5B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,8CAAA;AAAA,QACN,IAAA,EAAM;AAAA;AACR,KACF;AAAA,IACA,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC;AAQM,IAAM,YAAY,WAAA,CAAY;AAAA,EACnC,EAAA,EAAI,MAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAK,CAAA;AAAA,EACjB,WAAA,EAAa;AAAA,IACX,UAAA,EAAY,CAAC,EAAE,OAAA,EAAS,SAAS,IAAA,EAAM,kCAAA,EAAoC,IAAA,EAAM,6CAAA,EAA+C,CAAA;AAAA,IAChI,OAAA,EAAS,EAAE,KAAA,EAAO,CAAC,2FAA2F,CAAA;AAAE;AAEpH,CAAC","file":"chunk-ONBOLMXH.js","sourcesContent":["/**\n * The blocks this package carries the server half of, as `defineBlock`\n * declarations: what each needs in the database, and what it means for the\n * stores' privacy forms. The functions themselves (`deleteMyAccount`,\n * `tenantFeatures`, …) don't change.\n */\nimport { defineBlock } from \"@marktiderman/genesis-features/blocks\";\n\nconst PACKAGE = \"@marktiderman/genesis-supabase\";\n\n/**\n * The account block: sign-in, profile and in-app account deletion. Its\n * screens are the app's (or genesis-ui-native's `AuthScreen`); this names its\n * migrations and its data.\n *\n * @stability Beta\n */\nexport const accountBlock = defineBlock({\n id: \"account\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0001_genesis_account_deletion.sql\",\n test: \"migrations/tests/0001_genesis_account_deletion.test.sql\",\n },\n // With Sign in with Apple, with the genesis-apple-revoke function beside it.\n {\n package: PACKAGE,\n file: \"migrations/0003_genesis_apple_token_revocation.sql\",\n test: \"migrations/tests/0003_genesis_apple_token_revocation.test.sql\",\n },\n ],\n privacy: {\n collects: [\n {\n type: \"email address\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"user id\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n {\n type: \"name\",\n purposes: [\"app functionality\"],\n linked: true,\n tracking: false,\n },\n ],\n notes: [\n \"People delete their account from inside the app; their login and the rows that cascade from it go with it.\",\n \"With Sign in with Apple, the person's Apple tokens are revoked when the account is deleted.\",\n ],\n },\n },\n});\n\n/**\n * The tenant features block: per-tenant on/off switches for shipped\n * features, set by the tenant's admins with a reason.\n *\n * @stability Beta\n */\nexport const tenantFeaturesBlock = defineBlock({\n id: \"tenant-features\",\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0004_genesis_tenant_features.sql\",\n test: \"migrations/tests/0004_genesis_tenant_features.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Keeps who changed a tenant's switches; a deleted person's changes stay, without the person.\",\n ],\n },\n },\n});\n\n/**\n * The feature registry block: the registry mirrored into the app's database\n * on deploy, entitlements, per-tenant and platform flag values and SQL `feature_on()`,\n * for the feature gate. Needs the tenant features block.\n *\n * @stability Beta\n */\nexport const featureMirrorBlock = defineBlock({\n id: \"feature-mirror\",\n requires: [\"tenant-features\"],\n contributes: {\n migrations: [\n {\n package: PACKAGE,\n file: \"migrations/0008_genesis_feature_registry.sql\",\n test: \"migrations/tests/0008_genesis_feature_registry.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Stores which tenants hold which paid features and flag values; no personal data.\",\n ],\n },\n },\n});\n\n/**\n * The jobs block: a background-job queue and named schedules that call the\n * app's job route. Server only; the route is `createJobsHandler` from `/jobs`.\n *\n * @stability Beta\n */\nexport const jobsBlock = defineBlock({\n id: \"jobs\",\n platforms: [\"web\"],\n contributes: {\n migrations: [{ package: PACKAGE, file: \"migrations/0007_genesis_jobs.sql\", test: \"migrations/tests/0007_genesis_jobs.test.sql\" }],\n privacy: { notes: [\"Job payloads hold ids, never content or secrets; finished jobs are deleted after 14 days.\"] },\n },\n});\n"]}
@@ -185,6 +185,81 @@ declare function tenantFeatureHistory(client: TenantFeaturesClient, tenantId: st
185
185
  maxRows?: number;
186
186
  }): Promise<TenantFeatureChange[]>;
187
187
 
188
+ /**
189
+ * The feature registry in the database: the client half of
190
+ * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code
191
+ * registry on deploy; anyone building the gate's snapshot reads a tenant's
192
+ * runtime state in one call.
193
+ */
194
+
195
+ /** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */
196
+ interface FeatureRegistryClient {
197
+ rpc: (fn: any, ...rest: any[]) => PromiseLike<{
198
+ data: unknown;
199
+ error: PostgrestErrorLike | null;
200
+ }>;
201
+ }
202
+ /** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */
203
+ type FlagStateValue = boolean | string | number | {
204
+ readonly [key: string]: unknown;
205
+ };
206
+ /**
207
+ * A tenant's runtime state for the gate, shaped to spread into a
208
+ * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.
209
+ *
210
+ * @stability Beta
211
+ */
212
+ interface FeatureGateState {
213
+ /** Feature ids the tenant switched off. */
214
+ off: string[];
215
+ /** Feature ids the tenant holds an active entitlement for. */
216
+ entitlements: string[];
217
+ /** Flag values for the tenant (platform values applied), by flag name. */
218
+ flags: Record<string, FlagStateValue>;
219
+ }
220
+ /**
221
+ * A tenant's switches, entitlements and flag values: `feature_gate_state`.
222
+ * Works with a signed-in person's client (for tenants they belong to) or the
223
+ * service key. Throws a `SupabaseQueryError` (`42501`) for anyone else, so a
224
+ * refusal is never mistaken for "nothing set".
225
+ *
226
+ * @stability Beta
227
+ */
228
+ declare function featureGateState(client: FeatureRegistryClient, tenantId: string): Promise<FeatureGateState>;
229
+ /** `features.json` as `genesis features build` writes it. @stability Beta */
230
+ interface FeatureRegistryDocument {
231
+ features: readonly ({
232
+ id: string;
233
+ } & Record<string, unknown>)[];
234
+ flags?: Readonly<Record<string, Record<string, unknown>>>;
235
+ }
236
+ /** @stability Beta */
237
+ interface SyncFeatureRegistryOptions {
238
+ /**
239
+ * When this deployment started serving, in milliseconds (`Date.now()` at server start), not its
240
+ * build time: an instant rollback to an older build then syncs as the newest. Older versions
241
+ * than the last sync are refused.
242
+ */
243
+ version: number;
244
+ /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */
245
+ allowShrink?: boolean;
246
+ }
247
+ /**
248
+ * Copy the registry into the database: `sync_feature_registry`. Call it with
249
+ * the service key when a production deployment starts serving, never from a
250
+ * preview. Returns false when the database already has this registry or a
251
+ * newer one; throws (`22023`) for an empty registry or one that drops most
252
+ * features, unless `allowShrink`.
253
+ *
254
+ * ```ts
255
+ * import registry from "../features.json";
256
+ * if (process.env.VERCEL_ENV === "production") await syncFeatureRegistry(admin, registry, { version: Date.now() });
257
+ * ```
258
+ *
259
+ * @stability Beta
260
+ */
261
+ declare function syncFeatureRegistry(client: FeatureRegistryClient, document: FeatureRegistryDocument, options: SyncFeatureRegistryOptions): Promise<boolean>;
262
+
188
263
  /**
189
264
  * Supabase for Genesis apps. Platform-neutral: web, React Native and the
190
265
  * server import it. Native-only helpers (Keychain storage, foreground
@@ -314,4 +389,4 @@ interface DeleteMyAccountOptions {
314
389
  */
315
390
  declare function deleteMyAccount(client: DeleteAccountClient, options?: DeleteMyAccountOptions): Promise<void>;
316
391
 
317
- export { APPLE_REVOKE_FUNCTION as A, type DeleteAccountClient as D, type ExpoCryptoLike as E, type FunctionsClient as F, type GenesisSupabaseOptions as G, type PostgrestErrorLike as P, type SessionStorage as S, type TenantFeatureChange as T, type WebCryptoSource as W, assertPkceCrypto as a, isDigestOnlyPolyfill as b, type DeleteMyAccountOptions as c, type SetTenantFeatureInput as d, type StoreAppleTokenOptions as e, type StoreAppleTokenResult as f, SupabaseQueryError as g, hasPkceCrypto as h, installWebCrypto as i, type TenantFeatureSetting as j, type TenantFeatures as k, type TenantFeaturesClient as l, createGenesisSupabase as m, deleteMyAccount as n, must as o, storeAppleToken as p, tenantFeatureSettings as q, requestAppleRevocation as r, setTenantFeature as s, tenantFeatureHistory as t, tenantFeatures as u };
392
+ export { APPLE_REVOKE_FUNCTION as A, tenantFeatureSettings as B, tenantFeatures as C, type DeleteAccountClient as D, type ExpoCryptoLike as E, type FeatureGateState as F, type GenesisSupabaseOptions as G, type PostgrestErrorLike as P, type SessionStorage as S, type TenantFeatureChange as T, type WebCryptoSource as W, assertPkceCrypto as a, isDigestOnlyPolyfill as b, type DeleteMyAccountOptions as c, type FeatureRegistryClient as d, type FeatureRegistryDocument as e, type FlagStateValue as f, type FunctionsClient as g, hasPkceCrypto as h, installWebCrypto as i, type SetTenantFeatureInput as j, type StoreAppleTokenOptions as k, type StoreAppleTokenResult as l, SupabaseQueryError as m, type SyncFeatureRegistryOptions as n, type TenantFeatureSetting as o, type TenantFeatures as p, type TenantFeaturesClient as q, createGenesisSupabase as r, deleteMyAccount as s, featureGateState as t, must as u, requestAppleRevocation as v, setTenantFeature as w, storeAppleToken as x, syncFeatureRegistry as y, tenantFeatureHistory as z };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import '@supabase/supabase-js';
2
- export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, S as SessionStorage, d as SetTenantFeatureInput, e as StoreAppleTokenOptions, f as StoreAppleTokenResult, g as SupabaseQueryError, T as TenantFeatureChange, j as TenantFeatureSetting, k as TenantFeatures, l as TenantFeaturesClient, m as createGenesisSupabase, n as deleteMyAccount, o as must, r as requestAppleRevocation, s as setTenantFeature, p as storeAppleToken, t as tenantFeatureHistory, q as tenantFeatureSettings, u as tenantFeatures } from './index-BSGz3RGk.js';
3
- export { accountBlock, tenantFeaturesBlock } from './blocks.js';
2
+ export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, d as FeatureRegistryClient, e as FeatureRegistryDocument, f as FlagStateValue, g as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, S as SessionStorage, j as SetTenantFeatureInput, k as StoreAppleTokenOptions, l as StoreAppleTokenResult, m as SupabaseQueryError, n as SyncFeatureRegistryOptions, T as TenantFeatureChange, o as TenantFeatureSetting, p as TenantFeatures, q as TenantFeaturesClient, r as createGenesisSupabase, s as deleteMyAccount, t as featureGateState, u as must, v as requestAppleRevocation, w as setTenantFeature, x as storeAppleToken, y as syncFeatureRegistry, z as tenantFeatureHistory, B as tenantFeatureSettings, C as tenantFeatures } from './index-Ds0tO9WP.js';
3
+ export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './blocks.js';
4
4
  import '@marktiderman/genesis-features/blocks';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { installWebCrypto, assertPkceCrypto, isDigestOnlyPolyfill, claimsViaServer } from './chunk-FAA2FTF4.js';
2
- export { accountBlock, tenantFeaturesBlock } from './chunk-T2HGFC4C.js';
2
+ export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-ONBOLMXH.js';
3
3
  import { createClient, AuthInvalidJwtError } from '@supabase/supabase-js';
4
4
 
5
5
  // src/apple-tokens.ts
@@ -48,6 +48,65 @@ async function tenantFeatureHistory(client, tenantId, options = {}) {
48
48
  return must(await client.rpc("tenant_feature_history", args)) ?? [];
49
49
  }
50
50
 
51
+ // src/feature-registry.ts
52
+ var strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
53
+ async function featureGateState(client, tenantId) {
54
+ const data = must(await client.rpc("feature_gate_state", { tenant: tenantId }));
55
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new TypeError("feature_gate_state returned no state");
56
+ const { off, entitled, flags } = data;
57
+ if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== "object" || Array.isArray(flags)) {
58
+ throw new TypeError("feature_gate_state returned an unexpected shape");
59
+ }
60
+ const values = {};
61
+ for (const [key, value] of Object.entries(flags)) {
62
+ if (typeof value === "boolean" || typeof value === "string" || typeof value === "number") values[key] = value;
63
+ else if (value && typeof value === "object" && !Array.isArray(value)) values[key] = value;
64
+ }
65
+ return { off: strings(off), entitlements: strings(entitled), flags: values };
66
+ }
67
+ function canonical(value) {
68
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
69
+ if (value && typeof value === "object") {
70
+ const entries = Object.entries(value).filter(
71
+ ([, v]) => v !== void 0
72
+ );
73
+ return `{${entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
74
+ }
75
+ return JSON.stringify(value) ?? "null";
76
+ }
77
+ async function sha256(text) {
78
+ const digest = await globalThis.crypto.subtle.digest(
79
+ "SHA-256",
80
+ new TextEncoder().encode(text)
81
+ );
82
+ return Array.from(
83
+ new Uint8Array(digest),
84
+ (b) => b.toString(16).padStart(2, "0")
85
+ ).join("");
86
+ }
87
+ async function syncFeatureRegistry(client, document, options) {
88
+ if (!Number.isSafeInteger(options.version) || options.version < 0) {
89
+ throw new TypeError(
90
+ "syncFeatureRegistry: version must be a non-negative integer"
91
+ );
92
+ }
93
+ const features = [...document.features];
94
+ const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({
95
+ key,
96
+ ...flag
97
+ }));
98
+ const hash = await sha256(canonical({ features, flags }));
99
+ return must(
100
+ await client.rpc("sync_feature_registry", {
101
+ version: options.version,
102
+ hash,
103
+ features,
104
+ flags,
105
+ allow_shrink: options.allowShrink ?? false
106
+ })
107
+ ) === true;
108
+ }
109
+
51
110
  // src/index.ts
52
111
  function createGenesisSupabase({
53
112
  url,
@@ -100,6 +159,6 @@ async function deleteMyAccount(client, options = {}) {
100
159
  await client.auth.signOut({ scope: "local" });
101
160
  }
102
161
 
103
- export { APPLE_REVOKE_FUNCTION, SupabaseQueryError, createGenesisSupabase, deleteMyAccount, must, requestAppleRevocation, setTenantFeature, storeAppleToken, tenantFeatureHistory, tenantFeatureSettings, tenantFeatures };
162
+ export { APPLE_REVOKE_FUNCTION, SupabaseQueryError, createGenesisSupabase, deleteMyAccount, featureGateState, must, requestAppleRevocation, setTenantFeature, storeAppleToken, syncFeatureRegistry, tenantFeatureHistory, tenantFeatureSettings, tenantFeatures };
104
163
  //# sourceMappingURL=index.js.map
105
164
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/index.ts"],"names":[],"mappings":";;;;;AASO,IAAM,qBAAA,GAAwB;AAGrC,IAAM,gBAAA,GAAmB,GAAA;AAEzB,IAAM,iBAAA,GAAoB,GAAA;AAiC1B,eAAsB,gBAAgB,MAAA,EAAyB,EAAE,mBAAmB,QAAA,EAAU,YAAA,GAAe,uBAAsB,EAA2D;AAC5L,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,UAAU,MAAA,CAAO,YAAA,EAAc,EAAE,IAAA,EAAM,EAAE,MAAA,EAAQ,SAAS,IAAA,EAAM,iBAAA,EAAmB,GAAI,QAAA,GAAW,EAAE,QAAA,EAAS,GAAI,EAAC,EAAG,EAAG,OAAA,EAAS,gBAAA,EAAkB,CAAA;AAClL,IAAA,IAAI,OAAO,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,MA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EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,EAAG,OAAO,MAAA,KAAW,QAAA,GAAW,SAAS,qBAAqB,CAAA;AAEzJ,EAAA,MAAM,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAE,KAAA,EAAO,SAAS,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\n * The app's side of Sign in with Apple token revocation: hand the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport { accountBlock, tenantFeaturesBlock } from \"./blocks\";\n"]}
1
+ {"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/feature-registry.ts","../src/index.ts"],"names":[],"mappings":";;;;;AASO,IAAM,qBAAA,GAAwB;AAGrC,IAAM,gBAAA,GAAmB,GAAA;AAEzB,IAAM,iBAAA,GAAoB,GAAA;AAiC1B,eAAsB,gBAAgB,MAAA,EAAyB,EAAE,mBAAmB,QAAA,EAAU,YAAA,GAAe,uBAAsB,EAA2D;AAC5L,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,MAAA,C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AM,SAAS,OAAA,CAAQ,iBAAA;AAEvB,EAAA,IAAI,MAAA,IAAU,MAAA,CAAO,SAAA,EAAW,MAAM,uBAAuB,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,EAAG,OAAO,MAAA,KAAW,QAAA,GAAW,SAAS,qBAAqB,CAAA;AAEzJ,EAAA,MAAM,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAE,KAAA,EAAO,SAAS,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\n * The app's side of Sign in with Apple token revocation: hand the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * The feature registry in the database: the client half of\n * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code\n * registry on deploy; anyone building the gate's snapshot reads a tenant's\n * runtime state in one call.\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FeatureRegistryClient {\n // Loose on purpose, as in tenant-features: an app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (\n fn: any,\n ...rest: any[]\n ) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult =\n { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */\nexport type FlagStateValue = boolean | string | number | { readonly [key: string]: unknown };\n\n/**\n * A tenant's runtime state for the gate, shaped to spread into a\n * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.\n *\n * @stability Beta\n */\nexport interface FeatureGateState {\n /** Feature ids the tenant switched off. */\n off: string[];\n /** Feature ids the tenant holds an active entitlement for. */\n entitlements: string[];\n /** Flag values for the tenant (platform values applied), by flag name. */\n flags: Record<string, FlagStateValue>;\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : [];\n\n/**\n * A tenant's switches, entitlements and flag values: `feature_gate_state`.\n * Works with a signed-in person's client (for tenants they belong to) or the\n * service key. Throws a `SupabaseQueryError` (`42501`) for anyone else, so a\n * refusal is never mistaken for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(client: FeatureRegistryClient, tenantId: string): Promise<FeatureGateState> {\n const data = must((await client.rpc(\"feature_gate_state\", { tenant: tenantId })) as RpcResult);\n // Anything but the expected shape is an error, never \"nothing set\": an empty answer would turn\n // switched-off features back on.\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new TypeError(\"feature_gate_state returned no state\");\n const { off, entitled, flags } = data as Record<string, unknown>;\n if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== \"object\" || Array.isArray(flags)) {\n throw new TypeError(\"feature_gate_state returned an unexpected shape\");\n }\n const values: Record<string, FlagStateValue> = {};\n for (const [key, value] of Object.entries(flags as Record<string, unknown>)) {\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"number\") values[key] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) values[key] = value as { [key: string]: unknown };\n }\n return { off: strings(off), entitlements: strings(entitled), flags: values };\n}\n\n/** `features.json` as `genesis features build` writes it. @stability Beta */\nexport interface FeatureRegistryDocument {\n features: readonly ({ id: string } & Record<string, unknown>)[];\n flags?: Readonly<Record<string, Record<string, unknown>>>;\n}\n\n/** @stability Beta */\nexport interface SyncFeatureRegistryOptions {\n /**\n * When this deployment started serving, in milliseconds (`Date.now()` at server start), not its\n * build time: an instant rollback to an older build then syncs as the newest. Older versions\n * than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: Date.now() });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from \"./blocks\";\n"]}