@marktiderman/genesis-supabase 0.10.1 → 0.11.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
@@ -857,6 +857,34 @@ The page must send `Referrer-Policy: no-referrer`, `Cache-Control: no-store` and
857
857
  - **No email, no handoff.** Supabase's link sign-in is by email. A phone-only account gets a
858
858
  409 `no_email` with a `fallbackUrl` (the page, signed out), and `openOnWeb` opens that instead.
859
859
 
860
+ ## Product events (the events block)
861
+
862
+ The app's own product events, in its own Postgres (ADR 0010): who used which feature, in which
863
+ tenant, when, with the flags that were on. `genesis add events` copies
864
+ `migrations/0018_genesis_events.sql` and its pgTAP test.
865
+
866
+ ```ts
867
+ import { createEventTracker } from "@marktiderman/genesis-supabase/events";
868
+
869
+ const events = createEventTracker({ client: supabase, platform: "web", appVersion, flags: () => currentFlags() });
870
+ events.track("task.completed", { feature: "tasks", tenantId, properties: { count: 3 } });
871
+ ```
872
+
873
+ - A signed-in person's events go through `genesis_track_events` (at most 100 per call). One that
874
+ names a tenant the person has no record in is dropped, and the person record is filled in from
875
+ the tenant, through the `private.genesis_viewer_people` hook (0016).
876
+ - Server code tracks with a service-role client and `server: true` (`genesis_track_server_events`).
877
+ - On native, `createEventsSink(tracker, { feature, tenantId })` is an observability sink beside Sentry.
878
+ - Properties are flat labels and counts (no nested objects): never typed content or personal data.
879
+ Events carry identifiers only (the login and person ids); deleting a login clears its user_id.
880
+ - A login keeps at most 2,000 events an hour (GS429 past it). Call `tracker.reset()` on sign-out so
881
+ queued events never go out as the next person's.
882
+ - Only the service role reads the table. `genesis_feature_usage(tenant, since)` gives events and
883
+ people per feature for the product hub; `genesis_prune_events(older_than, max_rows)` (default 400 days, 50,000 rows a call) is
884
+ for a schedule; call it until it returns 0.
885
+ - A vendor (PostHog, Amplitude) is a later sink fed from these events; Genesis flags stay the
886
+ source of truth.
887
+
860
888
  ## Testing your schema's data contract (genesis_testing)
861
889
 
862
890
  `sql/testing/genesis_testing.sql` is a pgTAP kit that checks your own tables and functions keep the
package/dist/blocks.d.ts CHANGED
@@ -38,5 +38,13 @@ declare const jobsBlock: _marktiderman_genesis_features_blocks.BlockDef<"jobs",
38
38
  * @stability Beta
39
39
  */
40
40
  declare const webHandoffBlock: _marktiderman_genesis_features_blocks.BlockDef<"web-handoff", never>;
41
+ /**
42
+ * The product events block: the app's own events table and its tracking functions (ADR 0010).
43
+ * The client is `createEventTracker` from `/events`; on native, `createEventsSink` plugs it into the
44
+ * observability sinks.
45
+ *
46
+ * @stability Beta
47
+ */
48
+ declare const eventsBlock: _marktiderman_genesis_features_blocks.BlockDef<"events", never>;
41
49
 
42
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock };
50
+ export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock };
package/dist/blocks.js CHANGED
@@ -1,3 +1,3 @@
1
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock } from './chunk-FWQGZT4S.js';
1
+ export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock } from './chunk-34OBTZJQ.js';
2
2
  //# sourceMappingURL=blocks.js.map
3
3
  //# sourceMappingURL=blocks.js.map
@@ -115,7 +115,19 @@ var webHandoffBlock = defineBlock({
115
115
  }
116
116
  }
117
117
  });
118
+ var eventsBlock = defineBlock({
119
+ id: "events",
120
+ platforms: ["web", "native"],
121
+ contributes: {
122
+ migrations: [{ package: PACKAGE, file: "migrations/0018_genesis_events.sql", test: "migrations/tests/0018_genesis_events.test.sql" }],
123
+ privacy: {
124
+ notes: [
125
+ "Stores product events: the login, the person record and tenant, the feature, an event name, small properties (labels and counts, never typed content or personal data), the flags that were on, the platform and the time. Only the service role reads them; delete old ones with genesis_prune_events (default 400 days)."
126
+ ]
127
+ }
128
+ }
129
+ });
118
130
 
119
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock };
120
- //# sourceMappingURL=chunk-FWQGZT4S.js.map
121
- //# sourceMappingURL=chunk-FWQGZT4S.js.map
131
+ export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, webHandoffBlock };
132
+ //# sourceMappingURL=chunk-34OBTZJQ.js.map
133
+ //# sourceMappingURL=chunk-34OBTZJQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/blocks.ts"],"names":[],"mappings":";;;AAQA,IAAM,OAAA,GAAU,gCAAA;AAST,IAAM,eAAe,WAAA,CAAY;AAAA,EACtC,EAAA,EAAI,SAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,8CAAA;AAAA,QACN,IAAA,EAAM;AAAA,OACR;AAAA;AAAA,MAEA;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,oDAAA;AAAA,QACN,IAAA,EAAM;AAAA;AACR,KACF;AAAA,IACA,OAAA,EAAS;AAAA,MACP,QAAA,EAAU;AAAA,QACR;AAAA,UACE,IAAA,EAAM,eAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA,SACZ;AAAA,QACA;AAAA,UACE,IAAA,EAAM,SAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA,SACZ;AAAA,QACA;AAAA,UACE,IAAA,EAAM,MAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA;AACZ,OACF;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AAoC,IAAA,EAAM,6CAAA,EAA+C,CAAA;AAAA,IAChI,OAAA,EAAS,EAAE,KAAA,EAAO,CAAC,2FAA2F,CAAA;AAAE;AAEpH,CAAC;AASM,IAAM,kBAAkB,WAAA,CAAY;AAAA,EACzC,EAAA,EAAI,aAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV,EAAE,OAAA,EAAS,OAAA,EAAS,IAAA,EAAM,yCAAA,EAA2C,MAAM,oDAAA;AAAqD,KAClI;AAAA,IACA,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC;AAUM,IAAM,cAAc,WAAA,CAAY;AAAA,EACrC,EAAA,EAAI,QAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY,CAAC,EAAE,OAAA,EAAS,SAAS,IAAA,EAAM,oCAAA,EAAsC,IAAA,EAAM,+CAAA,EAAiD,CAAA;AAAA,IACpI,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC","file":"chunk-34OBTZJQ.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 package: PACKAGE,\n file: \"migrations/0014_genesis_feature_registry_hardening.sql\",\n test: \"migrations/tests/0014_genesis_feature_registry_hardening.test.sql\",\n },\n { package: PACKAGE, file: \"migrations/0016_genesis_viewer_people.sql\", test: \"migrations/tests/0016_genesis_viewer_people.test.sql\" },\n {\n package: PACKAGE,\n file: \"migrations/0017_genesis_person_entitlements.sql\",\n test: \"migrations/tests/0017_genesis_person_entitlements.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Stores which tenants and which people (the app's person ids) hold which paid features, and flag values.\",\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\n/**\n * The web handoff block: continue on the web, already signed in. The routes are\n * `createWebHandoff` from `/web-handoff/server`, the page uses `/web-handoff`, and the native\n * app calls `openOnWeb` from genesis-native.\n *\n * @stability Beta\n */\nexport const webHandoffBlock = defineBlock({\n id: \"web-handoff\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n { package: PACKAGE, file: \"migrations/0015_genesis_web_handoff.sql\", test: \"migrations/tests/0015_genesis_web_handoff.test.sql\" },\n ],\n privacy: {\n notes: [\n \"Logs each handoff (who, which page, when) for 30 days; keeps a SHA-256 digest of each link's token, never the token or a sign-in token.\",\n ],\n },\n },\n});\n\n\n/**\n * The product events block: the app's own events table and its tracking functions (ADR 0010).\n * The client is `createEventTracker` from `/events`; on native, `createEventsSink` plugs it into the\n * observability sinks.\n *\n * @stability Beta\n */\nexport const eventsBlock = defineBlock({\n id: \"events\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [{ package: PACKAGE, file: \"migrations/0018_genesis_events.sql\", test: \"migrations/tests/0018_genesis_events.test.sql\" }],\n privacy: {\n notes: [\n \"Stores product events: the login, the person record and tenant, the feature, an event name, small properties (labels and counts, never typed content or personal data), the flags that were on, the platform and the time. Only the service role reads them; delete old ones with genesis_prune_events (default 400 days).\",\n ],\n },\n },\n});\n"]}
@@ -0,0 +1,108 @@
1
+ /**
2
+ * `@marktiderman/genesis-supabase/events`: the client half of `migrations/0018_genesis_events.sql`,
3
+ * the app's own product events (ADR 0010).
4
+ *
5
+ * - `createEventTracker`: queues events and sends them in batches through
6
+ * `genesis_track_events` (a signed-in person's client) or `genesis_track_server_events`
7
+ * (`server: true`, a service-role client). A send that fails for a while (offline, a 5xx) is
8
+ * retried with backoff; one that can't succeed (signed out, a bad batch, the migration not
9
+ * applied) drops what it sent. Call `reset()` on sign-out. Tracking never throws into the app.
10
+ * - `createEventsSink`: the tracker as a genesis-native observability sink, so `observability.event(…)`
11
+ * reaches the table beside Sentry and EAS Observe.
12
+ *
13
+ * ```ts
14
+ * const events = createEventTracker({ client: supabase, platform: "web", appVersion });
15
+ * events.track("task.completed", { feature: "tasks", tenantId, properties: { count: 3 } });
16
+ * ```
17
+ *
18
+ * Properties are flat labels and counts: no content someone typed, no personal data. The timer is
19
+ * unref'd, so a short script calls `close()` to send what is left.
20
+ *
21
+ * @packageDocumentation
22
+ */
23
+ /** The part of a Supabase client the tracker uses. */
24
+ interface EventsClient {
25
+ rpc: (fn: any, ...rest: any[]) => PromiseLike<{
26
+ data: unknown;
27
+ error: {
28
+ message: string;
29
+ code?: string;
30
+ } | null;
31
+ }>;
32
+ }
33
+ /** A property or flag value: labels and counts only. */
34
+ type EventValue = string | number | boolean | null;
35
+ /** What `track` takes besides the name. */
36
+ interface TrackOptions {
37
+ /** The FeatureId it belongs to, so usage joins the feature. */
38
+ feature?: string;
39
+ /** The tenant it happened in; the server keeps it only when the person has a record there. */
40
+ tenantId?: string | null;
41
+ properties?: Readonly<Record<string, EventValue>>;
42
+ /** Server events only: who, as given. */
43
+ userId?: string;
44
+ personId?: string;
45
+ }
46
+ interface EventTrackerOptions {
47
+ client: EventsClient;
48
+ /** `web` (default), `native`, or `server` with `server: true`. */
49
+ platform?: "web" | "native" | "server";
50
+ appVersion?: string;
51
+ /** Groups a visit's events; default a random id per tracker. */
52
+ sessionId?: string;
53
+ /** The flags that are on now, added to every event (`{ "new-list": true }`). */
54
+ flags?: () => Readonly<Record<string, EventValue>>;
55
+ /** Send through the service-role function (server code only). */
56
+ server?: boolean;
57
+ /** Send when this many are queued. Default 20 (the server takes at most 100 at once). */
58
+ batchSize?: number;
59
+ /** Send at least this often, in ms, while events wait. Default 5000; 0 turns the timer off. */
60
+ flushIntervalMs?: number;
61
+ /** The most events kept while sending fails; older ones are dropped first. Default 500. */
62
+ maxQueue?: number;
63
+ /** Told when a send fails (the events stay queued). */
64
+ onError?: (error: {
65
+ message: string;
66
+ code?: string;
67
+ }) => void;
68
+ /** For tests. */
69
+ now?: () => Date;
70
+ }
71
+ interface EventTracker {
72
+ /** Queue one event. Never throws. */
73
+ track(name: string, options?: TrackOptions): void;
74
+ /** Send what is queued; resolves with how many the server kept (0 when the send failed). */
75
+ flush(): Promise<number>;
76
+ /** How many events are waiting. */
77
+ readonly pending: number;
78
+ /** Drop what is queued, unsent: call it when the login changes, so one person's events never go out as another's. */
79
+ reset(): void;
80
+ /** Stop the timer and send what is left; later events are ignored. */
81
+ close(): Promise<number>;
82
+ }
83
+ /**
84
+ * A batching tracker for the app's own events.
85
+ *
86
+ * @stability Beta
87
+ */
88
+ declare function createEventTracker(options: EventTrackerOptions): EventTracker;
89
+ /** What `createEventsSink` needs to place an event: its feature and tenant. */
90
+ interface EventsSinkOptions {
91
+ /** The FeatureId an event name belongs to (`"task.completed"` → `"tasks"`). */
92
+ feature?: (name: string) => string | undefined;
93
+ /** The tenant the app is in now. */
94
+ tenantId?: () => string | null | undefined;
95
+ }
96
+ /**
97
+ * The tracker as a genesis-native observability sink (structurally: an object with `name`,
98
+ * `event` and `flush`), so typed events reach the app's own table.
99
+ *
100
+ * @stability Beta
101
+ */
102
+ declare function createEventsSink(tracker: EventTracker, options?: EventsSinkOptions): {
103
+ name: string;
104
+ event(name: string, props: Readonly<Record<string, string | number | boolean>>): void;
105
+ flush(timeoutMs: number): Promise<boolean>;
106
+ };
107
+
108
+ export { type EventTracker, type EventTrackerOptions, type EventValue, type EventsClient, type EventsSinkOptions, type TrackOptions, createEventTracker, createEventsSink };
package/dist/events.js ADDED
@@ -0,0 +1,143 @@
1
+ // src/events.ts
2
+ var NAME = /^[a-z][a-z0-9]*([._:-][a-z0-9]+)*$/;
3
+ function randomId() {
4
+ const c = globalThis.crypto;
5
+ if (c?.randomUUID) return c.randomUUID();
6
+ if (c?.getRandomValues) return Array.from(c.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("");
7
+ return "none";
8
+ }
9
+ function createEventTracker(options) {
10
+ const batchSize = Math.min(Math.max(options.batchSize ?? 20, 1), 100);
11
+ const maxQueue = options.maxQueue ?? 500;
12
+ const platform = options.platform ?? (options.server ? "server" : "web");
13
+ const sessionId = options.sessionId ?? randomId();
14
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
15
+ const fn = options.server ? "genesis_track_server_events" : "genesis_track_events";
16
+ let queue = [];
17
+ let sending = null;
18
+ let timer = null;
19
+ let closed = false;
20
+ let failures = 0;
21
+ let retryAt = 0;
22
+ const startTimer = () => {
23
+ const ms = options.flushIntervalMs ?? 5e3;
24
+ if (ms > 0 && !timer) {
25
+ timer = setInterval(() => void flush(), ms);
26
+ timer.unref?.();
27
+ }
28
+ };
29
+ const permanent = (code) => code === "22023" || code === "413" || code === "PGRST202" || code === "42883";
30
+ const drop = (sent) => {
31
+ const gone = new Set(sent);
32
+ queue = queue.filter((e) => !gone.has(e));
33
+ };
34
+ const sendOnce = async () => {
35
+ const batch = queue.slice(0, 100);
36
+ let error = null;
37
+ let data = null;
38
+ try {
39
+ ({ data, error } = await options.client.rpc(fn, { events: batch }));
40
+ } catch (thrown) {
41
+ error = { message: thrown instanceof Error ? thrown.message : String(thrown) };
42
+ }
43
+ if (!error) {
44
+ drop(batch);
45
+ failures = 0;
46
+ return { settled: true, kept: typeof data === "number" ? data : 0 };
47
+ }
48
+ try {
49
+ options.onError?.(error);
50
+ } catch {
51
+ }
52
+ if (error.code === "42501") {
53
+ drop(batch);
54
+ return { settled: true, kept: 0 };
55
+ }
56
+ if (permanent(error.code)) {
57
+ drop(batch);
58
+ return { settled: true, kept: 0 };
59
+ }
60
+ failures++;
61
+ retryAt = Date.now() + Math.min(3e5, 1e3 * 2 ** Math.min(failures, 9));
62
+ return { settled: false, kept: 0 };
63
+ };
64
+ async function flush() {
65
+ if (sending) return sending;
66
+ if (Date.now() < retryAt) return 0;
67
+ sending = (async () => {
68
+ let kept = 0;
69
+ while (queue.length) {
70
+ const result = await sendOnce();
71
+ kept += result.kept;
72
+ if (!result.settled) break;
73
+ }
74
+ return kept;
75
+ })().finally(() => {
76
+ sending = null;
77
+ });
78
+ return sending;
79
+ }
80
+ return {
81
+ track(name, opts = {}) {
82
+ try {
83
+ if (closed || !NAME.test(name)) return;
84
+ const flags = options.flags?.();
85
+ queue.push({
86
+ name,
87
+ ...opts.feature ? { feature: opts.feature } : {},
88
+ ...opts.tenantId ? { tenantId: opts.tenantId } : {},
89
+ ...opts.properties ? { properties: opts.properties } : {},
90
+ ...flags && Object.keys(flags).length ? { flags } : {},
91
+ occurredAt: now().toISOString(),
92
+ platform,
93
+ ...options.appVersion ? { appVersion: options.appVersion } : {},
94
+ sessionId,
95
+ ...options.server && opts.userId ? { userId: opts.userId } : {},
96
+ ...options.server && opts.personId ? { personId: opts.personId } : {}
97
+ });
98
+ if (queue.length > maxQueue) queue = queue.slice(queue.length - maxQueue);
99
+ startTimer();
100
+ if (queue.length >= batchSize) void flush();
101
+ } catch {
102
+ }
103
+ },
104
+ flush,
105
+ get pending() {
106
+ return queue.length;
107
+ },
108
+ reset() {
109
+ queue = [];
110
+ failures = 0;
111
+ retryAt = 0;
112
+ },
113
+ async close() {
114
+ closed = true;
115
+ if (timer) clearInterval(timer);
116
+ timer = null;
117
+ if (sending) await sending;
118
+ retryAt = 0;
119
+ return flush();
120
+ }
121
+ };
122
+ }
123
+ function createEventsSink(tracker, options = {}) {
124
+ return {
125
+ name: "genesis-events",
126
+ event(name, props) {
127
+ const feature = options.feature?.(name);
128
+ const tenantId = options.tenantId?.();
129
+ tracker.track(name, { properties: props, ...feature ? { feature } : {}, ...tenantId ? { tenantId } : {} });
130
+ },
131
+ flush(timeoutMs) {
132
+ let timer;
133
+ const timeout = new Promise((resolve) => {
134
+ timer = setTimeout(() => resolve(false), timeoutMs);
135
+ });
136
+ return Promise.race([tracker.flush().then(() => tracker.pending === 0), timeout]).finally(() => clearTimeout(timer));
137
+ }
138
+ };
139
+ }
140
+
141
+ export { createEventTracker, createEventsSink };
142
+ //# sourceMappingURL=events.js.map
143
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/events.ts"],"names":[],"mappings":";AAiFA,IAAM,IAAA,GAAO,oCAAA;AAiBb,SAAS,QAAA,GAAmB;AAC1B,EAAA,MAAM,IAAI,UAAA,CAAW,MAAA;AACrB,EAAA,IAAI,CAAA,EAAG,UAAA,EAAY,OAAO,CAAA,CAAE,UAAA,EAAW;AACvC,EAAA,IAAI,CAAA,EAAG,eAAA,EAAiB,OAAO,KAAA,CAAM,IAAA,CAAK,EAAE,eAAA,CAAgB,IAAI,UAAA,CAAW,EAAE,CAAC,CAAA,EAAG,CAAC,CAAA,KAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAC,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA;AAEhI,EAAA,OAAO,MAAA;AACT;AAOO,SAAS,mBAAmB,OAAA,EAA4C;AAC7E,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,GAAA,CAAI,QAAQ,SAAA,IAAa,EAAA,EAAI,CAAC,CAAA,EAAG,GAAG,CAAA;AACpE,EAAA,MAAM,QAAA,GAAW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A;AACnB,MAAA,OAAA,GAAU,CAAA;AACV,MAAA,OAAO,KAAA,EAAM;AAAA,IACf;AAAA,GACF;AACF;AAgBO,SAAS,gBAAA,CAAiB,OAAA,EAAuB,OAAA,GAA6B,EAAC,EAAG;AACvF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,KAAA,CAAM,MAAc,KAAA,EAA4D;AAC9E,MAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,GAAU,IAAI,CAAA;AACtC,MAAA,MAAM,QAAA,GAAW,QAAQ,QAAA,IAAW;AACpC,MAAA,OAAA,CAAQ,MAAM,IAAA,EAAM,EAAE,YAAY,KAAA,EAAO,GAAI,UAAU,EAAE,OAAA,KAAY,EAAC,EAAI,GAAI,QAAA,GAAW,EAAE,UAAS,GAAI,IAAK,CAAA;AAAA,IAC/G,CAAA;AAAA,IACA,MAAM,SAAA,EAAqC;AACzC,MAAA,IAAI,KAAA;AACJ,MAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAiB,CAAC,OAAA,KAAY;AAChD,QAAA,KAAA,GAAQ,UAAA,CAAW,MAAM,OAAA,CAAQ,KAAK,GAAG,SAAS,CAAA;AAAA,MACpD,CAAC,CAAA;AAED,MAAA,OAAO,QAAQ,IAAA,CAAK,CAAC,QAAQ,KAAA,EAAM,CAAE,KAAK,MAAM,OAAA,CAAQ,YAAY,CAAC,CAAA,EAAG,OAAO,CAAC,CAAA,CAAE,QAAQ,MAAM,YAAA,CAAa,KAAK,CAAC,CAAA;AAAA,IACrH;AAAA,GACF;AACF","file":"events.js","sourcesContent":["/**\n * `@marktiderman/genesis-supabase/events`: the client half of `migrations/0018_genesis_events.sql`,\n * the app's own product events (ADR 0010).\n *\n * - `createEventTracker`: queues events and sends them in batches through\n * `genesis_track_events` (a signed-in person's client) or `genesis_track_server_events`\n * (`server: true`, a service-role client). A send that fails for a while (offline, a 5xx) is\n * retried with backoff; one that can't succeed (signed out, a bad batch, the migration not\n * applied) drops what it sent. Call `reset()` on sign-out. Tracking never throws into the app.\n * - `createEventsSink`: the tracker as a genesis-native observability sink, so `observability.event(…)`\n * reaches the table beside Sentry and EAS Observe.\n *\n * ```ts\n * const events = createEventTracker({ client: supabase, platform: \"web\", appVersion });\n * events.track(\"task.completed\", { feature: \"tasks\", tenantId, properties: { count: 3 } });\n * ```\n *\n * Properties are flat labels and counts: no content someone typed, no personal data. The timer is\n * unref'd, so a short script calls `close()` to send what is left.\n *\n * @packageDocumentation\n */\n\n/** The part of a Supabase client the tracker uses. */\nexport interface EventsClient {\n // Loose on purpose: an app's generated Database types may not list these functions yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: { message: string; code?: string } | null }>;\n}\n\n/** A property or flag value: labels and counts only. */\nexport type EventValue = string | number | boolean | null;\n\n/** What `track` takes besides the name. */\nexport interface TrackOptions {\n /** The FeatureId it belongs to, so usage joins the feature. */\n feature?: string;\n /** The tenant it happened in; the server keeps it only when the person has a record there. */\n tenantId?: string | null;\n properties?: Readonly<Record<string, EventValue>>;\n /** Server events only: who, as given. */\n userId?: string;\n personId?: string;\n}\n\nexport interface EventTrackerOptions {\n client: EventsClient;\n /** `web` (default), `native`, or `server` with `server: true`. */\n platform?: \"web\" | \"native\" | \"server\";\n appVersion?: string;\n /** Groups a visit's events; default a random id per tracker. */\n sessionId?: string;\n /** The flags that are on now, added to every event (`{ \"new-list\": true }`). */\n flags?: () => Readonly<Record<string, EventValue>>;\n /** Send through the service-role function (server code only). */\n server?: boolean;\n /** Send when this many are queued. Default 20 (the server takes at most 100 at once). */\n batchSize?: number;\n /** Send at least this often, in ms, while events wait. Default 5000; 0 turns the timer off. */\n flushIntervalMs?: number;\n /** The most events kept while sending fails; older ones are dropped first. Default 500. */\n maxQueue?: number;\n /** Told when a send fails (the events stay queued). */\n onError?: (error: { message: string; code?: string }) => void;\n /** For tests. */\n now?: () => Date;\n}\n\nexport interface EventTracker {\n /** Queue one event. Never throws. */\n track(name: string, options?: TrackOptions): void;\n /** Send what is queued; resolves with how many the server kept (0 when the send failed). */\n flush(): Promise<number>;\n /** How many events are waiting. */\n readonly pending: number;\n /** Drop what is queued, unsent: call it when the login changes, so one person's events never go out as another's. */\n reset(): void;\n /** Stop the timer and send what is left; later events are ignored. */\n close(): Promise<number>;\n}\n\nconst NAME = /^[a-z][a-z0-9]*([._:-][a-z0-9]+)*$/;\n\ninterface Queued {\n name: string;\n feature?: string;\n tenantId?: string;\n properties?: Readonly<Record<string, EventValue>>;\n flags?: Readonly<Record<string, EventValue>>;\n occurredAt: string;\n platform: string;\n appVersion?: string;\n sessionId: string;\n userId?: string;\n personId?: string;\n}\n\n/** A random session id from Web Crypto (Node 20+, browsers, React Native with a crypto polyfill). */\nfunction randomId(): string {\n const c = globalThis.crypto;\n if (c?.randomUUID) return c.randomUUID();\n if (c?.getRandomValues) return Array.from(c.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n // No Web Crypto: no session id rather than a guessable one; events still group by login.\n return \"none\";\n}\n\n/**\n * A batching tracker for the app's own events.\n *\n * @stability Beta\n */\nexport function createEventTracker(options: EventTrackerOptions): EventTracker {\n const batchSize = Math.min(Math.max(options.batchSize ?? 20, 1), 100);\n const maxQueue = options.maxQueue ?? 500;\n const platform = options.platform ?? (options.server ? \"server\" : \"web\");\n const sessionId = options.sessionId ?? randomId();\n const now = options.now ?? (() => new Date());\n const fn = options.server ? \"genesis_track_server_events\" : \"genesis_track_events\";\n let queue: Queued[] = [];\n let sending: Promise<number> | null = null;\n let timer: ReturnType<typeof setInterval> | null = null;\n let closed = false;\n let failures = 0;\n let retryAt = 0;\n\n const startTimer = () => {\n const ms = options.flushIntervalMs ?? 5000;\n if (ms > 0 && !timer) {\n timer = setInterval(() => void flush(), ms);\n (timer as { unref?: () => void }).unref?.();\n }\n };\n\n // Errors a retry can't fix: not signed in (42501: drop everything, it would go out as whoever\n // signs in next), a refused batch (22023, 413), the functions not installed (PGRST202, 42883).\n const permanent = (code?: string) => code === \"22023\" || code === \"413\" || code === \"PGRST202\" || code === \"42883\";\n const drop = (sent: readonly Queued[]) => {\n const gone = new Set(sent);\n queue = queue.filter((e) => !gone.has(e));\n };\n\n /** One batch: true when it is settled (sent or dropped), false to retry later. */\n const sendOnce = async (): Promise<{ settled: boolean; kept: number }> => {\n const batch = queue.slice(0, 100);\n let error: { message: string; code?: string } | null = null;\n let data: unknown = null;\n try {\n ({ data, error } = await options.client.rpc(fn, { events: batch }));\n } catch (thrown) {\n error = { message: thrown instanceof Error ? thrown.message : String(thrown) };\n }\n if (!error) {\n drop(batch);\n failures = 0;\n return { settled: true, kept: typeof data === \"number\" ? data : 0 };\n }\n try {\n options.onError?.(error);\n } catch {\n // A throwing callback doesn't break the tracker.\n }\n if (error.code === \"42501\") {\n // Signed out: this batch can't be sent as anyone; call reset() on sign-out for the rest.\n drop(batch);\n return { settled: true, kept: 0 };\n }\n if (permanent(error.code)) {\n drop(batch);\n return { settled: true, kept: 0 };\n }\n failures++;\n retryAt = Date.now() + Math.min(300_000, 1000 * 2 ** Math.min(failures, 9));\n return { settled: false, kept: 0 };\n };\n\n async function flush(): Promise<number> {\n if (sending) return sending;\n if (Date.now() < retryAt) return 0;\n sending = (async () => {\n let kept = 0;\n while (queue.length) {\n const result = await sendOnce();\n kept += result.kept;\n if (!result.settled) break; // retry after the backoff\n }\n return kept;\n })().finally(() => {\n sending = null;\n });\n return sending;\n }\n\n return {\n track(name, opts = {}) {\n try {\n if (closed || !NAME.test(name)) return;\n const flags = options.flags?.();\n queue.push({\n name,\n ...(opts.feature ? { feature: opts.feature } : {}),\n ...(opts.tenantId ? { tenantId: opts.tenantId } : {}),\n ...(opts.properties ? { properties: opts.properties } : {}),\n ...(flags && Object.keys(flags).length ? { flags } : {}),\n occurredAt: now().toISOString(),\n platform,\n ...(options.appVersion ? { appVersion: options.appVersion } : {}),\n sessionId,\n ...(options.server && opts.userId ? { userId: opts.userId } : {}),\n ...(options.server && opts.personId ? { personId: opts.personId } : {}),\n });\n if (queue.length > maxQueue) queue = queue.slice(queue.length - maxQueue); // oldest first\n\n startTimer();\n if (queue.length >= batchSize) void flush();\n } catch {\n // Tracking never breaks the app.\n }\n },\n flush,\n get pending() {\n return queue.length;\n },\n reset() {\n queue = [];\n failures = 0;\n retryAt = 0;\n },\n async close() {\n closed = true;\n if (timer) clearInterval(timer);\n timer = null;\n if (sending) await sending;\n retryAt = 0;\n return flush();\n },\n };\n}\n\n/** What `createEventsSink` needs to place an event: its feature and tenant. */\nexport interface EventsSinkOptions {\n /** The FeatureId an event name belongs to (`\"task.completed\"` → `\"tasks\"`). */\n feature?: (name: string) => string | undefined;\n /** The tenant the app is in now. */\n tenantId?: () => string | null | undefined;\n}\n\n/**\n * The tracker as a genesis-native observability sink (structurally: an object with `name`,\n * `event` and `flush`), so typed events reach the app's own table.\n *\n * @stability Beta\n */\nexport function createEventsSink(tracker: EventTracker, options: EventsSinkOptions = {}) {\n return {\n name: \"genesis-events\",\n event(name: string, props: Readonly<Record<string, string | number | boolean>>) {\n const feature = options.feature?.(name);\n const tenantId = options.tenantId?.();\n tracker.track(name, { properties: props, ...(feature ? { feature } : {}), ...(tenantId ? { tenantId } : {}) });\n },\n flush(timeoutMs: number): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs);\n });\n // Finished means nothing is left queued (a dropped batch counts as finished).\n return Promise.race([tracker.flush().then(() => tracker.pending === 0), timeout]).finally(() => clearTimeout(timer));\n },\n };\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import '@supabase/supabase-js';
2
2
  export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient, c as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, d as FeatureGateStateOptions, e as FeatureRegistryClient, f as FeatureRegistryDocument, g as FlagStateValue, j as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, S as SessionStorage, k as SetTenantFeatureInput, l as StoreAppleTokenOptions, m as StoreAppleTokenResult, n as SupabaseQueryError, o as SyncFeatureRegistryOptions, T as TenantFeatureChange, p as TenantFeatureSetting, q as TenantFeatures, r as TenantFeaturesClient, s as createGenesisSupabase, t as deleteMyAccount, u as featureGateState, v as must, w as requestAppleRevocation, x as setTenantFeature, y as storeAppleToken, z as syncFeatureRegistry, B as tenantFeatureHistory, C as tenantFeatureSettings, H as tenantFeatures } from './index-CaYX9z8D.js';
3
- export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './blocks.js';
3
+ export { accountBlock, eventsBlock, 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, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-FWQGZT4S.js';
2
+ export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-34OBTZJQ.js';
3
3
  import { createClient, AuthInvalidJwtError } from '@supabase/supabase-js';
4
4
 
5
5
  // src/apple-tokens.ts
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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,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CAAO,IAAA;AAChB;AAwCA,eAAsB,eAAA,CAAgB,MAAA,EAA6B,OAAA,GAAkC,EAAC,EAAkB;AACtH,EAAA,IAAA,CAAM,MAAM,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAgF,CAAA;AAC1H,EAAA,MAAM,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 with an active entitlement: the tenant's, plus the person's own (0017). */\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/** @stability Beta */\nexport interface FeatureGateStateOptions {\n /**\n * With the service key only: add this person's own entitlements (the app's person id, not a\n * login), for a snapshot built on the server. A signed-in person's client gets their own\n * without it, and is refused (`42501`) with it.\n */\n personId?: 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; their own\n * person entitlements are included) or the service key. Throws a\n * `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken\n * for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(\n client: FeatureRegistryClient,\n tenantId: string,\n options: FeatureGateStateOptions = {},\n): Promise<FeatureGateState> {\n const args = options.personId === undefined ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };\n const data = must((await client.rpc(\"feature_gate_state\", args)) 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 * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions 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: BUILD_TIME });\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 FeatureGateStateOptions,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, featureMirrorBlock, jobsBlock, 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,EA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CAAmB,OAAO,KAAK,CAAA;AAC3D,EAAA,OAAO,MAAA,CAAO,IAAA;AAChB;AAwCA,eAAsB,eAAA,CAAgB,MAAA,EAA6B,OAAA,GAAkC,EAAC,EAAkB;AACtH,EAAA,IAAA,CAAM,MAAM,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAgF,CAAA;AAC1H,EAAA,MAAM,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 with an active entitlement: the tenant's, plus the person's own (0017). */\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/** @stability Beta */\nexport interface FeatureGateStateOptions {\n /**\n * With the service key only: add this person's own entitlements (the app's person id, not a\n * login), for a snapshot built on the server. A signed-in person's client gets their own\n * without it, and is refused (`42501`) with it.\n */\n personId?: 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; their own\n * person entitlements are included) or the service key. Throws a\n * `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken\n * for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(\n client: FeatureRegistryClient,\n tenantId: string,\n options: FeatureGateStateOptions = {},\n): Promise<FeatureGateState> {\n const args = options.personId === undefined ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };\n const data = must((await client.rpc(\"feature_gate_state\", args)) 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 * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions 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: BUILD_TIME });\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 FeatureGateStateOptions,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from \"./blocks\";\n"]}
@@ -0,0 +1,260 @@
1
+ -- Genesis events: the app's own product events (ADR 0010).
2
+ --
3
+ -- public.genesis_events
4
+ -- One row per product event: when it happened, who (the login and, in a tenant, their person
5
+ -- record), where (the tenant), what (a short name and the feature id it belongs to), small
6
+ -- flat properties, the flags that were on, the platform and the app version. Properties are
7
+ -- labels and counts: no content someone typed, and identifiers only (the login and person
8
+ -- ids). Row security is on with no policies: only the service role reads it, and only the
9
+ -- functions below write it. Deleting a login (0001) clears its user_id.
10
+ --
11
+ -- public.genesis_track_events(events jsonb) returns integer
12
+ -- For a signed-in person. Takes a JSON array of at most 100 events and returns how many it
13
+ -- kept. An event naming a tenant the person has no record in (private.genesis_viewer_person_ids,
14
+ -- 0016) is dropped, as is one with a bad name or oversized properties; the person record is
15
+ -- filled in from the tenant. A client clock more than five minutes ahead or seven days behind
16
+ -- is replaced by now(). A person keeps at most 2,000 events an hour (SQLSTATE GS429 past it)
17
+ -- and a call is at most 512 KB; a client can't claim the `server` platform.
18
+ --
19
+ -- public.genesis_track_server_events(events jsonb) returns integer
20
+ -- For server code (service role only): the same shape, plus user_id and person_id, trusted as
21
+ -- given.
22
+ --
23
+ -- public.genesis_feature_usage(tenant uuid, since timestamptz) returns table
24
+ -- Per feature in a tenant since a time: events, distinct people, the last one. Service role
25
+ -- only; the product hub reads usage through it.
26
+ --
27
+ -- public.genesis_prune_events(older_than interval default '400 days', max_rows integer default 50000) returns bigint
28
+ -- Deletes up to max_rows older events and returns how many (call again until 0). Service role
29
+ -- only; run it from a schedule.
30
+ --
31
+ -- Needs 0016 (its private.genesis_viewer_person_ids, which reads the app's people hook).
32
+ --
33
+ -- Use: copy this file into your app's `supabase/migrations/` under a new timestamped name
34
+ -- (`genesis add events` does it). Never edit it once applied; change it with a new migration.
35
+ --
36
+ -- Verify: tests/0018_genesis_events.test.sql.
37
+
38
+ create table public.genesis_events (
39
+ id bigint generated always as identity primary key,
40
+ occurred_at timestamptz not null,
41
+ received_at timestamptz not null default now(),
42
+ -- The login, when there was one; null for an event server code raised for nobody in particular.
43
+ user_id uuid references auth.users (id) on delete set null,
44
+ tenant_id uuid,
45
+ person_id uuid,
46
+ name text not null
47
+ constraint genesis_events_name_format check (name ~ '^[a-z][a-z0-9]*([._:-][a-z0-9]+)*$' and char_length(name) <= 100),
48
+ -- The FeatureId it belongs to. No foreign key: an app's registry mirror may lag a deploy.
49
+ feature_id text
50
+ constraint genesis_events_feature_format check (feature_id is null or (feature_id ~ '^[a-z][a-z0-9]*([-_.][a-z0-9]+)*$' and char_length(feature_id) <= 100)),
51
+ -- Flat: { "count": 3, "view": "grid" }, no nested objects or lists.
52
+ properties jsonb not null default '{}'
53
+ constraint genesis_events_properties_object check (jsonb_typeof(properties) = 'object' and octet_length(properties::text) <= 4096
54
+ and not jsonb_path_exists(properties, '$.* ? (@.type() == "object" || @.type() == "array")')),
55
+ -- The flags that were on, { "flag-id": value }, so a reader can split by them.
56
+ flags jsonb not null default '{}'
57
+ constraint genesis_events_flags_object check (jsonb_typeof(flags) = 'object' and octet_length(flags::text) <= 2048),
58
+ platform text not null default 'web'
59
+ constraint genesis_events_platform check (platform in ('web', 'native', 'server')),
60
+ app_version text constraint genesis_events_app_version_length check (char_length(app_version) <= 40),
61
+ session_id text constraint genesis_events_session_length check (char_length(session_id) <= 64)
62
+ );
63
+
64
+ comment on table public.genesis_events is
65
+ 'Product events: who, where, which feature, when, small flat properties and the flags that were on. No content; identifiers only. Written through genesis_track_events and genesis_track_server_events; read by the service role. Genesis events.';
66
+
67
+ create index genesis_events_tenant_time on public.genesis_events (tenant_id, occurred_at desc);
68
+ create index genesis_events_feature_time on public.genesis_events (feature_id, occurred_at desc) where feature_id is not null;
69
+ create index genesis_events_name_time on public.genesis_events (name, occurred_at desc);
70
+ -- Append-only by time: a BRIN index keeps pruning old events cheap at any size.
71
+ create index genesis_events_occurred_brin on public.genesis_events using brin (occurred_at);
72
+ create index genesis_events_user_received on public.genesis_events (user_id, received_at desc) where user_id is not null;
73
+
74
+ alter table public.genesis_events enable row level security;
75
+ revoke all on table public.genesis_events from public, anon, authenticated;
76
+
77
+ -- One event from a JSON object, checked, or null when it can't be kept. Shared by both writers.
78
+ create or replace function private.genesis_event_row(e jsonb, trusted boolean)
79
+ returns public.genesis_events
80
+ language plpgsql
81
+ stable
82
+ set search_path = ''
83
+ as $$
84
+ declare
85
+ r public.genesis_events;
86
+ at timestamptz;
87
+ begin
88
+ if jsonb_typeof(e) is distinct from 'object' then
89
+ return null;
90
+ end if;
91
+ r.name := e ->> 'name';
92
+ r.feature_id := nullif(e ->> 'feature', '');
93
+ r.properties := coalesce(e -> 'properties', '{}');
94
+ r.flags := coalesce(e -> 'flags', '{}');
95
+ r.platform := coalesce(nullif(e ->> 'platform', ''), case when trusted then 'server' else 'web' end);
96
+ r.app_version := nullif(e ->> 'appVersion', '');
97
+ r.session_id := nullif(e ->> 'sessionId', '');
98
+ if r.name is null or r.name !~ '^[a-z][a-z0-9]*([._:-][a-z0-9]+)*$' or char_length(r.name) > 100
99
+ or (r.feature_id is not null and (r.feature_id !~ '^[a-z][a-z0-9]*([-_.][a-z0-9]+)*$' or char_length(r.feature_id) > 100))
100
+ or jsonb_typeof(r.properties) <> 'object' or octet_length(r.properties::text) > 4096
101
+ or jsonb_path_exists(r.properties, '$.* ? (@.type() == "object" || @.type() == "array")')
102
+ or jsonb_typeof(r.flags) <> 'object' or octet_length(r.flags::text) > 2048
103
+ or r.platform not in ('web', 'native', 'server') or (r.platform = 'server' and not trusted)
104
+ or char_length(r.app_version) > 40 or char_length(r.session_id) > 64 then
105
+ return null;
106
+ end if;
107
+ begin
108
+ at := (e ->> 'occurredAt')::timestamptz;
109
+ exception when others then
110
+ at := null;
111
+ end;
112
+ r.occurred_at := case when at is null or at > now() + interval '5 minutes' or at < now() - interval '7 days' then now() else at end;
113
+ r.received_at := now();
114
+ begin
115
+ r.tenant_id := nullif(e ->> 'tenantId', '')::uuid;
116
+ if trusted then
117
+ r.user_id := nullif(e ->> 'userId', '')::uuid;
118
+ r.person_id := nullif(e ->> 'personId', '')::uuid;
119
+ end if;
120
+ exception when others then
121
+ return null;
122
+ end;
123
+ return r;
124
+ end;
125
+ $$;
126
+
127
+ revoke execute on function private.genesis_event_row(jsonb, boolean) from public, anon, authenticated;
128
+
129
+ create or replace function public.genesis_track_events(events jsonb)
130
+ returns integer
131
+ language plpgsql
132
+ volatile
133
+ security definer
134
+ set search_path = ''
135
+ as $$
136
+ declare
137
+ e jsonb;
138
+ r public.genesis_events;
139
+ kept integer := 0;
140
+ viewer uuid := auth.uid();
141
+ begin
142
+ if viewer is null then
143
+ raise exception 'genesis_track_events: sign in first' using errcode = '42501';
144
+ end if;
145
+ -- One login's calls take turns, so two at once can't both pass the hourly limit.
146
+ perform pg_advisory_xact_lock(hashtextextended('genesis_events:' || viewer::text, 0));
147
+ if jsonb_typeof(events) is distinct from 'array' or jsonb_array_length(events) > 100 or octet_length(events::text) > 524288 then
148
+ raise exception 'genesis_track_events: send a JSON array of at most 100 events and 512 KB' using errcode = '22023';
149
+ end if;
150
+ -- At most 2,000 kept events per login per hour, so one login can't fill the table.
151
+ if (select count(*) from public.genesis_events g where g.user_id = viewer and g.received_at > now() - interval '1 hour') + jsonb_array_length(events) > 2000 then
152
+ raise exception 'genesis_track_events: too many events this hour' using errcode = 'GS429';
153
+ end if;
154
+ for e in select value from jsonb_array_elements(events) loop
155
+ r := private.genesis_event_row(e, false);
156
+ continue when r is null;
157
+ r.user_id := viewer;
158
+ if r.tenant_id is not null then
159
+ -- Only a tenant the person has a record in, and that record is who they were there.
160
+ select v.person_id into r.person_id from private.genesis_viewer_person_ids() v where v.tenant_id = r.tenant_id order by v.person_id limit 1;
161
+ continue when r.person_id is null;
162
+ end if;
163
+ insert into public.genesis_events (occurred_at, received_at, user_id, tenant_id, person_id, name, feature_id, properties, flags, platform, app_version, session_id)
164
+ values (r.occurred_at, r.received_at, r.user_id, r.tenant_id, r.person_id, r.name, r.feature_id, r.properties, r.flags, r.platform, r.app_version, r.session_id);
165
+ kept := kept + 1;
166
+ end loop;
167
+ return kept;
168
+ end;
169
+ $$;
170
+
171
+ comment on function public.genesis_track_events(jsonb) is
172
+ 'Records a signed-in person''s product events (a JSON array of at most 100); returns how many were kept. Events in a tenant the person has no record in, or that fail the checks, are dropped. Genesis events.';
173
+
174
+ revoke execute on function public.genesis_track_events(jsonb) from public, anon;
175
+ grant execute on function public.genesis_track_events(jsonb) to authenticated;
176
+
177
+ create or replace function public.genesis_track_server_events(events jsonb)
178
+ returns integer
179
+ language plpgsql
180
+ volatile
181
+ security definer
182
+ set search_path = ''
183
+ as $$
184
+ declare
185
+ e jsonb;
186
+ r public.genesis_events;
187
+ kept integer := 0;
188
+ begin
189
+ if jsonb_typeof(events) is distinct from 'array' or jsonb_array_length(events) > 1000 or octet_length(events::text) > 4194304 then
190
+ raise exception 'genesis_track_server_events: send a JSON array of at most 1000 events' using errcode = '22023';
191
+ end if;
192
+ for e in select value from jsonb_array_elements(events) loop
193
+ r := private.genesis_event_row(e, true);
194
+ continue when r is null;
195
+ -- A login that no longer exists (or never did) is kept as no login, not an error for the batch.
196
+ if r.user_id is not null and not exists (select 1 from auth.users u where u.id = r.user_id) then
197
+ r.user_id := null;
198
+ end if;
199
+ insert into public.genesis_events (occurred_at, received_at, user_id, tenant_id, person_id, name, feature_id, properties, flags, platform, app_version, session_id)
200
+ values (r.occurred_at, r.received_at, r.user_id, r.tenant_id, r.person_id, r.name, r.feature_id, r.properties, r.flags, r.platform, r.app_version, r.session_id);
201
+ kept := kept + 1;
202
+ end loop;
203
+ return kept;
204
+ end;
205
+ $$;
206
+
207
+ comment on function public.genesis_track_server_events(jsonb) is
208
+ 'Records product events from server code (service role): userId, tenantId and personId are trusted as given. Returns how many were kept. Genesis events.';
209
+
210
+ revoke execute on function public.genesis_track_server_events(jsonb) from public, anon, authenticated;
211
+ grant execute on function public.genesis_track_server_events(jsonb) to service_role;
212
+
213
+ create or replace function public.genesis_feature_usage(tenant uuid, since timestamptz)
214
+ returns table (feature_id text, events bigint, people bigint, last_at timestamptz)
215
+ language sql
216
+ stable
217
+ security definer
218
+ set search_path = ''
219
+ as $$
220
+ -- Two branches so each uses genesis_events_tenant_time: one tenant, or the events with none.
221
+ select e.feature_id, count(*), count(distinct coalesce(e.person_id, e.user_id)), max(e.occurred_at)
222
+ from public.genesis_events e
223
+ where tenant is not null and e.tenant_id = tenant and e.occurred_at >= since and e.feature_id is not null
224
+ group by e.feature_id
225
+ union all
226
+ select e.feature_id, count(*), count(distinct coalesce(e.person_id, e.user_id)), max(e.occurred_at)
227
+ from public.genesis_events e
228
+ where tenant is null and e.tenant_id is null and e.occurred_at >= since and e.feature_id is not null
229
+ group by e.feature_id
230
+ order by 2 desc
231
+ $$;
232
+
233
+ comment on function public.genesis_feature_usage(uuid, timestamptz) is
234
+ 'Per feature in a tenant since a time: events, distinct people and the last event. Service role only. Genesis events.';
235
+
236
+ revoke execute on function public.genesis_feature_usage(uuid, timestamptz) from public, anon, authenticated;
237
+ grant execute on function public.genesis_feature_usage(uuid, timestamptz) to service_role;
238
+
239
+ create or replace function public.genesis_prune_events(older_than interval default '400 days', max_rows integer default 50000)
240
+ returns bigint
241
+ language sql
242
+ volatile
243
+ security definer
244
+ set search_path = ''
245
+ as $$
246
+ -- At most max_rows per call, so one run never holds a long lock; call again until it returns 0.
247
+ with gone as (
248
+ delete from public.genesis_events
249
+ where id in (select e.id from public.genesis_events e
250
+ where older_than > interval '0' and e.occurred_at < now() - older_than
251
+ limit greatest(1, least(max_rows, 500000)))
252
+ returning 1)
253
+ select count(*) from gone
254
+ $$;
255
+
256
+ comment on function public.genesis_prune_events(interval, integer) is
257
+ 'Deletes up to max_rows (default 50,000) events older than older_than (default 400 days) and returns how many; call again until 0. Service role only; run it from a schedule. Genesis events.';
258
+
259
+ revoke execute on function public.genesis_prune_events(interval, integer) from public, anon, authenticated;
260
+ grant execute on function public.genesis_prune_events(interval, integer) to service_role;
@@ -0,0 +1,147 @@
1
+ -- @feat:product-events
2
+ -- pgTAP test for 0018_genesis_events.sql (needs 0016).
3
+ -- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
4
+ -- It writes only its own users, hook and events and rolls everything back. If your app already has
5
+ -- the people hook, it is dropped and replaced inside this transaction only.
6
+ begin;
7
+ create extension if not exists pgtap with schema extensions;
8
+ select plan(32);
9
+
10
+ insert into auth.users (id, aud, role, email, instance_id)
11
+ select ('00000000-0000-4000-8000-0000000018' || n)::uuid, 'authenticated', 'authenticated', 'genesis-events-' || n || '@example.test', '00000000-0000-0000-0000-000000000000'
12
+ from unnest(array['a1', 'b2']) n;
13
+
14
+ create function pg_temp.login(n text) returns uuid language sql immutable as $$ select ('00000000-0000-4000-8000-0000000018' || n)::uuid $$;
15
+ create function pg_temp.as_person(n text) returns void language plpgsql as $$
16
+ begin
17
+ perform set_config('request.jwt.claims', json_build_object('sub', pg_temp.login(n), 'role', 'authenticated')::text, true);
18
+ perform set_config('request.jwt.claim.sub', pg_temp.login(n)::text, true);
19
+ execute 'set local role authenticated';
20
+ end $$;
21
+ create function pg_temp.as_owner() returns void language plpgsql as $$
22
+ begin
23
+ execute 'reset role';
24
+ perform set_config('request.jwt.claims', '', true);
25
+ perform set_config('request.jwt.claim.sub', '', true);
26
+ end $$;
27
+ grant execute on function pg_temp.login(text), pg_temp.as_person(text), pg_temp.as_owner() to authenticated, anon, service_role;
28
+
29
+ -- a1 is a person in tenant 1 only.
30
+ drop function if exists private.genesis_viewer_people(uuid);
31
+ create function private.genesis_viewer_people(viewer uuid)
32
+ returns table (tenant_id uuid, person_id uuid) language sql stable set search_path = '' as $$
33
+ select '00000000-0000-4000-8000-000000000001'::text::uuid, '00000000-0000-4000-8000-000000000101'::text::uuid
34
+ where viewer = '00000000-0000-4000-8000-0000000018a1'
35
+ $$;
36
+
37
+ -- Privileges --------------------------------------------------------------------------------------
38
+ select ok(not has_table_privilege('authenticated', 'public.genesis_events', 'select'), 'a person can''t read events');
39
+ select ok(not has_table_privilege('authenticated', 'public.genesis_events', 'insert'), '... or insert them directly');
40
+ select ok(not has_function_privilege('anon', 'public.genesis_track_events(jsonb)', 'execute'), 'anon can''t track');
41
+ select ok(has_function_privilege('authenticated', 'public.genesis_track_events(jsonb)', 'execute'), 'a signed-in person can');
42
+ select ok(not has_function_privilege('authenticated', 'public.genesis_track_server_events(jsonb)', 'execute'), 'server tracking is the service role''s');
43
+ select ok(not has_function_privilege('authenticated', 'public.genesis_feature_usage(uuid, timestamptz)', 'execute'), 'usage summaries are the service role''s');
44
+ select ok(not has_function_privilege('authenticated', 'public.genesis_prune_events(interval, integer)', 'execute'), 'pruning is the service role''s');
45
+ select ok(not has_function_privilege('anon', 'public.genesis_track_server_events(jsonb)', 'execute')
46
+ and not has_function_privilege('anon', 'public.genesis_feature_usage(uuid, timestamptz)', 'execute')
47
+ and not has_function_privilege('anon', 'public.genesis_prune_events(interval, integer)', 'execute'), 'anon reaches none of the service functions');
48
+ select ok(not has_function_privilege('authenticated', 'private.genesis_event_row(jsonb, boolean)', 'execute')
49
+ and not has_function_privilege('anon', 'private.genesis_event_row(jsonb, boolean)', 'execute'), 'nobody but the owner calls the row check');
50
+
51
+ -- Tracking as a person ----------------------------------------------------------------------------
52
+ select pg_temp.as_person('a1');
53
+ select is(
54
+ public.genesis_track_events(jsonb_build_array(
55
+ jsonb_build_object('name', 'task.completed', 'feature', 'tasks', 'tenantId', '00000000-0000-4000-8000-000000000001', 'properties', jsonb_build_object('count', 3), 'flags', jsonb_build_object('new-list', true), 'platform', 'native', 'appVersion', '1.2.0'),
56
+ jsonb_build_object('name', 'app.opened'),
57
+ -- a tenant a1 has no record in: dropped
58
+ jsonb_build_object('name', 'task.completed', 'feature', 'tasks', 'tenantId', '00000000-0000-4000-8000-000000000002'),
59
+ -- a bad name, oversized properties, a bad platform: dropped
60
+ jsonb_build_object('name', 'Has Spaces'),
61
+ jsonb_build_object('name', 'big', 'properties', jsonb_build_object('text', repeat('x', 5000))),
62
+ jsonb_build_object('name', 'odd', 'platform', 'fridge'),
63
+ '"not an object"'::jsonb
64
+ )),
65
+ 2, 'keeps the valid events in the person''s own tenants, drops the rest');
66
+ select throws_ok($$select public.genesis_track_events('{}'::jsonb)$$, '22023', null, 'refuses a body that isn''t an array');
67
+ select throws_ok(
68
+ $$select public.genesis_track_events((select jsonb_agg(jsonb_build_object('name', 'x')) from generate_series(1, 101)))$$,
69
+ '22023', null, '... and more than 100 events');
70
+ -- What a client can't claim: another login or person, the server platform, nested properties.
71
+ select is(
72
+ public.genesis_track_events(jsonb_build_array(
73
+ jsonb_build_object('name', 'forged.ids', 'tenantId', '00000000-0000-4000-8000-000000000001', 'userId', pg_temp.login('b2'), 'personId', '00000000-0000-4000-8000-000000000999'),
74
+ jsonb_build_object('name', 'forged.platform', 'platform', 'server'),
75
+ jsonb_build_object('name', 'nested', 'properties', jsonb_build_object('a', jsonb_build_object('b', 1)))
76
+ )),
77
+ 1, 'drops the server platform and nested properties from a client');
78
+ select pg_temp.as_owner();
79
+ select is(
80
+ (select user_id::text || ' ' || person_id::text from public.genesis_events where name = 'forged.ids'),
81
+ pg_temp.login('a1')::text || ' 00000000-0000-4000-8000-000000000101',
82
+ 'the login and person come from the session and the hook, never from the event');
83
+
84
+ select is((select person_id from public.genesis_events where name = 'task.completed'), '00000000-0000-4000-8000-000000000101'::uuid, 'the person record comes from the tenant');
85
+ select is((select user_id from public.genesis_events where name = 'app.opened'), pg_temp.login('a1'), 'the login is the caller, whatever the client says');
86
+ select is((select tenant_id from public.genesis_events where name = 'app.opened'), null, 'an event with no tenant keeps none');
87
+ select is((select platform || ' ' || app_version || ' ' || (flags ->> 'new-list') from public.genesis_events where name = 'task.completed'), 'native 1.2.0 true', 'platform, version and flags are kept');
88
+
89
+ -- A clock far off is replaced by now().
90
+ select pg_temp.as_person('a1');
91
+ select public.genesis_track_events(jsonb_build_array(jsonb_build_object('name', 'clock.check', 'occurredAt', '2001-01-01T00:00:00Z')));
92
+ select pg_temp.as_owner();
93
+ select ok((select occurred_at > now() - interval '1 minute' from public.genesis_events where name = 'clock.check'), 'an implausible client time becomes now()');
94
+
95
+ -- Signed out, anon and no role ----------------------------------------------------------------------
96
+ select set_config('request.jwt.claims', '', true);
97
+ select set_config('request.jwt.claim.sub', '', true);
98
+ set local role authenticated;
99
+ select throws_ok($$select public.genesis_track_events('[]'::jsonb)$$, '42501', null, 'tracking needs a signed-in person');
100
+ reset role;
101
+ set local role anon;
102
+ select throws_ok($$select public.genesis_track_events('[]'::jsonb)$$, '42501', null, 'anon can''t track');
103
+ reset role;
104
+ select throws_ok($$select public.genesis_track_events('[]'::jsonb)$$, '42501', null, 'no login and no role: refused');
105
+
106
+ -- Without the people hook, an event naming a tenant is dropped.
107
+ drop function private.genesis_viewer_people(uuid);
108
+ select pg_temp.as_person('a1');
109
+ select is(public.genesis_track_events(jsonb_build_array(jsonb_build_object('name', 'no.hook', 'tenantId', '00000000-0000-4000-8000-000000000001'))), 0, 'no hook: a tenant event is dropped');
110
+ select throws_ok(
111
+ $$select public.genesis_track_events((select jsonb_agg(jsonb_build_object('name', 'x', 'properties', jsonb_build_object('t', repeat('y', 6000)))) from generate_series(1, 100)))$$,
112
+ '22023', null, 'a call over 512 KB is refused before it is read');
113
+ select pg_temp.as_owner();
114
+ insert into public.genesis_events (occurred_at, user_id, name) select now(), pg_temp.login('a1'), 'flood' from generate_series(1, 2000);
115
+ select pg_temp.as_person('a1');
116
+ select throws_ok($$select public.genesis_track_events('[{"name":"one.more"}]'::jsonb)$$, 'GS429', null, 'past 2,000 events an hour a login is refused');
117
+ select pg_temp.as_owner();
118
+ delete from public.genesis_events where name = 'flood';
119
+
120
+ -- Server code -------------------------------------------------------------------------------------
121
+ set local role service_role;
122
+ select is(
123
+ public.genesis_track_server_events(jsonb_build_array(
124
+ jsonb_build_object('name', 'invoice.sent', 'feature', 'invoicing', 'tenantId', '00000000-0000-4000-8000-000000000002', 'personId', '00000000-0000-4000-8000-000000000109', 'userId', pg_temp.login('b2')),
125
+ jsonb_build_object('name', 'invoice.sent', 'feature', 'invoicing', 'tenantId', 'not-a-uuid'),
126
+ jsonb_build_object('name', 'ghost.user', 'userId', '00000000-0000-4000-8000-00000000dead')
127
+ )),
128
+ 2, 'server events trust tenant, person and user, and still drop a malformed one');
129
+ select is(
130
+ (select events::int || ' ' || people::int from public.genesis_feature_usage('00000000-0000-4000-8000-000000000001', now() - interval '1 day') where feature_id = 'tasks'),
131
+ '1 1', 'feature usage counts events and people per feature in a tenant');
132
+ reset role;
133
+
134
+ update public.genesis_events set occurred_at = now() - interval '500 days' where name = 'app.opened';
135
+ set local role service_role;
136
+ select is(public.genesis_prune_events(), 1::bigint, 'pruning deletes events past the retention window');
137
+ reset role;
138
+ select is((select count(*)::int from public.genesis_events where name = 'app.opened'), 0, '... and only those');
139
+ set local role service_role;
140
+ select is(public.genesis_prune_events(interval '0'), 0::bigint, 'a zero window deletes nothing');
141
+ reset role;
142
+ select is((select user_id from public.genesis_events where name = 'ghost.user'), null, 'an unknown login is kept as none');
143
+ delete from auth.users where id = pg_temp.login('a1');
144
+ select is((select count(*)::int from public.genesis_events where user_id is null and name = 'task.completed'), 1, 'deleting a login clears its user_id');
145
+
146
+ select * from finish();
147
+ rollback;
package/package.json CHANGED
@@ -1,10 +1,31 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-supabase",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "Supabase for Genesis apps on web and React Native: a client with PKCE and safe defaults, Keychain session storage that survives interrupted writes, refresh only while the app is in front, native Sign in with Apple and Google, OAuth redirects, in-app account deletion, per-tenant feature switches (tenant_features), a background-job queue with schedules (genesis_jobs) on one outbox engine (/runner, shared with notifications and forms), the feature registry in the database for the feature gate (features, entitlements, flag values, feature_on), a native-to-web sign-in handoff (continue on the web, already signed in: web-handoff), and a result helper. Part of the Genesis framework.",
8
+ "keywords": [
9
+ "genesis",
10
+ "genesis-framework",
11
+ "supabase",
12
+ "auth",
13
+ "postgres",
14
+ "rls",
15
+ "sign-in",
16
+ "account-deletion",
17
+ "apple",
18
+ "feature-toggle",
19
+ "per-tenant",
20
+ "organization-settings",
21
+ "background-jobs",
22
+ "cron",
23
+ "queue"
24
+ ],
25
+ "homepage": "https://github.com/marktiderman/genesis/tree/main/packages/supabase#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/marktiderman/genesis/issues"
28
+ },
8
29
  "repository": {
9
30
  "type": "git",
10
31
  "url": "git+https://github.com/marktiderman/genesis.git",
@@ -36,6 +57,10 @@
36
57
  "types": "./dist/jobs.d.ts",
37
58
  "import": "./dist/jobs.js"
38
59
  },
60
+ "./events": {
61
+ "types": "./dist/events.d.ts",
62
+ "import": "./dist/events.js"
63
+ },
39
64
  "./runner": {
40
65
  "types": "./dist/runner.d.ts",
41
66
  "import": "./dist/runner.js"
@@ -57,7 +82,7 @@
57
82
  "README.md"
58
83
  ],
59
84
  "dependencies": {
60
- "@marktiderman/genesis-features": "^0.7.0"
85
+ "@marktiderman/genesis-features": "^0.8.0"
61
86
  },
62
87
  "peerDependencies": {
63
88
  "@supabase/supabase-js": "^2.118.0",
@@ -67,9 +92,12 @@
67
92
  "@supabase/supabase-js": "^2.118.0",
68
93
  "tsup": "^8.3.0",
69
94
  "typescript": "~6.0.3",
70
- "vitest": "^4.1.12"
95
+ "vitest": "^5.0.5"
71
96
  },
72
97
  "genesis": {
98
+ "layer": "primitive",
99
+ "group": "data",
100
+ "owner": "@marktiderman",
73
101
  "blocks": {
74
102
  "account": {
75
103
  "feature": {
@@ -243,6 +271,37 @@
243
271
  "Add the /auth/handoff page: call takeWebHandoffFragment before analytics or error reporting load, then completeWebHandoff; send Referrer-Policy: no-referrer and frame-ancestors 'none' for it.",
244
272
  "In the native app, call openOnWeb from @marktiderman/genesis-native/web-handoff with the mint route, the session's access token and expo-web-browser."
245
273
  ]
274
+ },
275
+ "events": {
276
+ "feature": {
277
+ "name": "Product events",
278
+ "summary": "The app's own product events in Postgres: who used which feature, in which tenant, when, with the flags that were on; tracked from web, native and server.",
279
+ "keywords": [
280
+ "analytics",
281
+ "events",
282
+ "usage",
283
+ "telemetry",
284
+ "activation"
285
+ ],
286
+ "audience": [
287
+ "developer",
288
+ "admin"
289
+ ]
290
+ },
291
+ "migrations": [
292
+ {
293
+ "file": "migrations/0018_genesis_events.sql",
294
+ "test": "migrations/tests/0018_genesis_events.test.sql"
295
+ }
296
+ ],
297
+ "steps": [
298
+ "Track from the client with createEventTracker from @marktiderman/genesis-supabase/events (and createEventsSink on native). Events in a tenant count only when the app defines the private.genesis_viewer_people hook (0016).",
299
+ "Schedule genesis_prune_events() (default 400 days) from your jobs, e.g. a monthly genesis_schedule_job."
300
+ ],
301
+ "platforms": [
302
+ "web",
303
+ "native"
304
+ ]
246
305
  }
247
306
  },
248
307
  "doctor": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/blocks.ts"],"names":[],"mappings":";;;AAQA,IAAM,OAAA,GAAU,gCAAA;AAST,IAAM,eAAe,WAAA,CAAY;AAAA,EACtC,EAAA,EAAI,SAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,8CAAA;AAAA,QACN,IAAA,EAAM;AAAA,OACR;AAAA;AAAA,MAEA;AAAA,QACE,OAAA,EAAS,OAAA;AAAA,QACT,IAAA,EAAM,oDAAA;AAAA,QACN,IAAA,EAAM;AAAA;AACR,KACF;AAAA,IACA,OAAA,EAAS;AAAA,MACP,QAAA,EAAU;AAAA,QACR;AAAA,UACE,IAAA,EAAM,eAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA,SACZ;AAAA,QACA;AAAA,UACE,IAAA,EAAM,SAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU;AAAA,SACZ;AAAA,QACA;AAAA,UACE,IAAA,EAAM,MAAA;AAAA,UACN,QAAA,EAAU,CAAC,mBAAmB,CAAA;AAAA,UAC9B,MAAA,EAAQ,IAAA;AAAA,U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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;AASM,IAAM,kBAAkB,WAAA,CAAY;AAAA,EACzC,EAAA,EAAI,aAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAA,EAAO,QAAQ,CAAA;AAAA,EAC3B,WAAA,EAAa;AAAA,IACX,UAAA,EAAY;AAAA,MACV,EAAE,OAAA,EAAS,OAAA,EAAS,IAAA,EAAM,yCAAA,EAA2C,MAAM,oDAAA;AAAqD,KAClI;AAAA,IACA,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC","file":"chunk-FWQGZT4S.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 package: PACKAGE,\n file: \"migrations/0014_genesis_feature_registry_hardening.sql\",\n test: \"migrations/tests/0014_genesis_feature_registry_hardening.test.sql\",\n },\n { package: PACKAGE, file: \"migrations/0016_genesis_viewer_people.sql\", test: \"migrations/tests/0016_genesis_viewer_people.test.sql\" },\n {\n package: PACKAGE,\n file: \"migrations/0017_genesis_person_entitlements.sql\",\n test: \"migrations/tests/0017_genesis_person_entitlements.test.sql\",\n },\n ],\n privacy: {\n notes: [\n \"Stores which tenants and which people (the app's person ids) hold which paid features, and flag values.\",\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\n/**\n * The web handoff block: continue on the web, already signed in. The routes are\n * `createWebHandoff` from `/web-handoff/server`, the page uses `/web-handoff`, and the native\n * app calls `openOnWeb` from genesis-native.\n *\n * @stability Beta\n */\nexport const webHandoffBlock = defineBlock({\n id: \"web-handoff\",\n platforms: [\"web\", \"native\"],\n contributes: {\n migrations: [\n { package: PACKAGE, file: \"migrations/0015_genesis_web_handoff.sql\", test: \"migrations/tests/0015_genesis_web_handoff.test.sql\" },\n ],\n privacy: {\n notes: [\n \"Logs each handoff (who, which page, when) for 30 days; keeps a SHA-256 digest of each link's token, never the token or a sign-in token.\",\n ],\n },\n },\n});\n\n"]}