@marktiderman/genesis-supabase 0.10.1 → 0.12.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
@@ -179,6 +179,60 @@ if (res.type === "success") {
179
179
  it. That's harmless because of PKCE: a code is useless without the verifier, which never leaves
180
180
  this device. The implicit flow would hand tokens to whoever owns the scheme.
181
181
 
182
+ ### On the web: `AuthForm`
183
+
184
+ genesis-ui's `AuthForm` (inside `AuthPage`) is the web sign-in form; `createAuthFormClient` is its
185
+ client on Supabase Auth. The form never calls `supabase.auth` itself, and `createAuthFormClient`
186
+ makes no client of its own: pass it the app's, from `createGenesisSupabase()`.
187
+
188
+ ```ts
189
+ import { createAuthFormClient } from "@marktiderman/genesis-supabase";
190
+
191
+ const client = createAuthFormClient(supabase, {
192
+ url: SUPABASE_URL,
193
+ publishableKey: SUPABASE_PUBLISHABLE_KEY,
194
+ redirectTo: `${location.origin}/auth/callback`,
195
+ resetRedirectTo: `${location.origin}/auth/new-password`,
196
+ });
197
+ // <AuthForm client={client} methods={["password", "email-code"]} onSuccess={…} />
198
+ ```
199
+
200
+ | The form's call | Supabase Auth |
201
+ | --- | --- |
202
+ | `signInWithPassword` | `signInWithPassword` |
203
+ | `sendMagicLink`, `sendEmailCode` | `signInWithOtp` (`shouldCreateUser` follows the form's `allowSignUp`; without sign-up, an unknown email is answered as sent) |
204
+ | `verifyEmailCode` | `verifyOtp({ email, token, type: "email" })` |
205
+ | `signUp` | `signUp`; `confirmEmail` when no session came back |
206
+ | `sendPasswordReset` | `resetPasswordForEmail` to `resetRedirectTo` |
207
+ | `updatePassword` | `updateUser({ password })`, on the session the reset link opened (`session_not_found` without one) |
208
+ | `signInWithProvider` | `signInWithOAuth` (leaves the page for the provider) |
209
+ | `providers` | `fetchAuthSettings`: `GET /auth/v1/settings`, the OAuth providers turned on (asked once per client) |
210
+
211
+ Every failure resolves as `{ error: { code, message } }` with Auth's code (`network` for a request
212
+ that got no answer, `session_not_found` for `AuthSessionMissingError`), also on a client made with
213
+ `throwOnError: true`. The form shows fixed copy for the code; Auth's `message` is never shown, only
214
+ sent to `reportError` when the form has no copy for the code.
215
+
216
+ - **Codes need the template.** Supabase sends the Magic Link email for a link and for a code alike,
217
+ and the default template has only the link: put `{{ .Token }}` in it to offer `"email-code"`.
218
+ - **The redirects** (`redirectTo`, `resetRedirectTo`) must be in the project's redirect allow list.
219
+ `createGenesisSupabase()` uses the PKCE flow (a plain `createClient` from supabase-js defaults to
220
+ the implicit flow), and its callback page needs nothing more on the web (`detectSessionInUrl`).
221
+ A PKCE link only works in the browser that asked for it, where the code verifier is stored: a
222
+ link opened on another device or in another browser fails.
223
+ - **The new-password page** shows `mode="new-password"` only after the `PASSWORD_RECOVERY` event
224
+ (`supabase.auth.onAuthStateChange`). Shown without the session the reset link opened, saving
225
+ fails with `session_not_found`.
226
+ - **No account enumeration without sign-up.** With `allowSignUp={false}` a magic link or code for an
227
+ email with no account is answered as sent, and the form's copy is neutral ("If … has an account").
228
+ - **Sign-up with auto-confirm does reveal accounts**: when the project confirms emails without a
229
+ link, signing up with an email that has an account answers `user_already_exists`. That is the
230
+ trade-off of auto-confirm; turn confirmation on if account existence must stay private.
231
+ - `fetchAuthSettings({ url, publishableKey, signal })` also says whether sign-up is closed
232
+ (`signUpDisabled`): pass `allowSignUp={!settings.signUpDisabled}`. It gives up after 5 seconds,
233
+ refuses a secret key (`sb_secret_…`), and reports only the OAuth providers in
234
+ `SUPABASE_OAUTH_PROVIDERS` (no `web3_*`, `saml` or `phone`).
235
+
182
236
  ### Deleting the account
183
237
 
184
238
  The database half is a migration this package ships:
@@ -358,6 +412,8 @@ which isn't verified here).
358
412
  no real Sign in with Apple key has been through the exchange and revocation yet (setup step 7).
359
413
  That Apple answers `invalid_client` (not `invalid_grant`) to a live token with wrong secrets is
360
414
  expected, not observed.
415
+ - **Branded auth emails.** The confirm, magic link (with the code) and reset templates are still
416
+ Supabase's own, set by hand in the dashboard.
361
417
  - **Sign in with Apple on the web** (Services ID and redirect) isn't wired: the function accepts a
362
418
  Services ID in `APPLE_CLIENT_IDS`, but exchanges codes without a `redirect_uri`, as a native
363
419
  sign-in needs.
@@ -514,6 +570,10 @@ Functions (templates; copy the folder into `supabase/functions/`):
514
570
 
515
571
  All three deploy with `verify_jwt = false` (each checks its caller or secret itself).
516
572
 
573
+ The intake function keeps a report's severity in its `context`. With genesis-support's migration
574
+ `0003_genesis_support_findings.sql` applied, set `GENESIS_SUPPORT_SEVERITY_COLUMN=true` and it also
575
+ writes the `severity` column.
576
+
517
577
  ### Not covered yet
518
578
 
519
579
  - Not applied to a hosted project yet: the SQL is pgTAP-tested on a local database and the
@@ -857,6 +917,34 @@ The page must send `Referrer-Policy: no-referrer`, `Cache-Control: no-store` and
857
917
  - **No email, no handoff.** Supabase's link sign-in is by email. A phone-only account gets a
858
918
  409 `no_email` with a `fallbackUrl` (the page, signed out), and `openOnWeb` opens that instead.
859
919
 
920
+ ## Product events (the events block)
921
+
922
+ The app's own product events, in its own Postgres (ADR 0010): who used which feature, in which
923
+ tenant, when, with the flags that were on. `genesis add events` copies
924
+ `migrations/0018_genesis_events.sql` and its pgTAP test.
925
+
926
+ ```ts
927
+ import { createEventTracker } from "@marktiderman/genesis-supabase/events";
928
+
929
+ const events = createEventTracker({ client: supabase, platform: "web", appVersion, flags: () => currentFlags() });
930
+ events.track("task.completed", { feature: "tasks", tenantId, properties: { count: 3 } });
931
+ ```
932
+
933
+ - A signed-in person's events go through `genesis_track_events` (at most 100 per call). One that
934
+ names a tenant the person has no record in is dropped, and the person record is filled in from
935
+ the tenant, through the `private.genesis_viewer_people` hook (0016).
936
+ - Server code tracks with a service-role client and `server: true` (`genesis_track_server_events`).
937
+ - On native, `createEventsSink(tracker, { feature, tenantId })` is an observability sink beside Sentry.
938
+ - Properties are flat labels and counts (no nested objects): never typed content or personal data.
939
+ Events carry identifiers only (the login and person ids); deleting a login clears its user_id.
940
+ - A login keeps at most 2,000 events an hour (GS429 past it). Call `tracker.reset()` on sign-out so
941
+ queued events never go out as the next person's.
942
+ - Only the service role reads the table. `genesis_feature_usage(tenant, since)` gives events and
943
+ people per feature for the product hub; `genesis_prune_events(older_than, max_rows)` (default 400 days, 50,000 rows a call) is
944
+ for a schedule; call it until it returns 0.
945
+ - A vendor (PostHog, Amplitude) is a later sink fed from these events; Genesis flags stay the
946
+ source of truth.
947
+
860
948
  ## Testing your schema's data contract (genesis_testing)
861
949
 
862
950
  `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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AAAA;AACR,KACF;AAAA,IACA,OAAA,EAAS;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA;AACF;AACF;AAEJ,CAAC;AAQM,IAAM,YAAY,WAAA,CAAY;AAAA,EACnC,EAAA,EAAI,MAAA;AAAA,EACJ,SAAA,EAAW,CAAC,KAAK,CAAA;AAAA,EACjB,WAAA,EAAa;AAAA,IACX,UAAA,EAAY,CAAC,EAAE,OAAA,EAAS,SAAS,IAAA,EAAM,kCAAA,EAAoC,IAAA,EAAM,6CAAA,EAA+C,CAAA;AAAA,IAChI,OAAA,EAAS,EAAE,KAAA,EAAO,CAAC,2FAA2F,CAAA;AAAE;AAEpH,CAAC;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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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"]}
@@ -1,4 +1,4 @@
1
- import { SupabaseClientOptions, SupabaseClient } from '@supabase/supabase-js';
1
+ import { SupabaseClient, SupabaseClientOptions } from '@supabase/supabase-js';
2
2
  import './blocks.js';
3
3
 
4
4
  /**
@@ -270,6 +270,163 @@ interface SyncFeatureRegistryOptions {
270
270
  */
271
271
  declare function syncFeatureRegistry(client: FeatureRegistryClient, document: FeatureRegistryDocument, options: SyncFeatureRegistryOptions): Promise<boolean>;
272
272
 
273
+ /**
274
+ * Web sign-in on Supabase Auth, for genesis-ui's `AuthForm`: the calls each
275
+ * of its modes makes (password, magic link, emailed code, sign-up, reset, new
276
+ * password, providers) and the provider list read from the project's
277
+ * `/auth/v1/settings`. Platform-neutral; native sign-in is on `/native`.
278
+ */
279
+
280
+ /** The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits. */
281
+ interface AuthFormSupabase {
282
+ auth: Pick<SupabaseClient["auth"], "signInWithPassword" | "signInWithOtp" | "verifyOtp" | "signUp" | "resetPasswordForEmail" | "updateUser" | "signInWithOAuth">;
283
+ }
284
+ /**
285
+ * Why a call failed: Supabase Auth's error `code` (`invalid_credentials`,
286
+ * `otp_expired`, `over_email_send_rate_limit`…), `session_not_found` when
287
+ * there is no session (`AuthSessionMissingError`), or `network` when the
288
+ * request never got an answer. The shape genesis-ui's `AuthFormError` reads.
289
+ * `message` is the server's text: the form never shows it (it is not marked
290
+ * `displayable`), only reports it for a code it has no copy for.
291
+ */
292
+ interface AuthCallError {
293
+ code?: string;
294
+ message?: string;
295
+ }
296
+ /** What each call resolves with. Never throws. */
297
+ interface AuthCallResult {
298
+ error?: AuthCallError | null;
299
+ /** From `signUp`: the account waits for its email to be confirmed. */
300
+ confirmEmail?: boolean;
301
+ }
302
+ /**
303
+ * The calls genesis-ui's `AuthForm` makes (its `AuthFormClient`), on Supabase Auth.
304
+ *
305
+ * @stability Beta
306
+ */
307
+ interface AuthFormSupabaseClient {
308
+ signInWithPassword(input: {
309
+ email: string;
310
+ password: string;
311
+ }): Promise<AuthCallResult>;
312
+ sendMagicLink(input: {
313
+ email: string;
314
+ createUser: boolean;
315
+ }): Promise<AuthCallResult>;
316
+ sendEmailCode(input: {
317
+ email: string;
318
+ createUser: boolean;
319
+ }): Promise<AuthCallResult>;
320
+ verifyEmailCode(input: {
321
+ email: string;
322
+ code: string;
323
+ }): Promise<AuthCallResult>;
324
+ signUp(input: {
325
+ email: string;
326
+ password: string;
327
+ }): Promise<AuthCallResult>;
328
+ sendPasswordReset(input: {
329
+ email: string;
330
+ }): Promise<AuthCallResult>;
331
+ updatePassword(input: {
332
+ password: string;
333
+ }): Promise<AuthCallResult>;
334
+ signInWithProvider(provider: string): Promise<AuthCallResult>;
335
+ /** Present when `url` and `publishableKey` were given. */
336
+ providers?(): Promise<string[]>;
337
+ }
338
+ /** @stability Beta */
339
+ interface CreateAuthFormClientOptions {
340
+ /** The project URL, with `publishableKey`: lets the form discover its providers. */
341
+ url?: string;
342
+ /** The publishable (anon) key. */
343
+ publishableKey?: string;
344
+ /**
345
+ * Where a magic link, a sign-up confirmation and a provider come back to:
346
+ * the app's callback route (`${origin}/auth/callback`). It must be in the
347
+ * project's redirect allow list. Left out: the project's Site URL.
348
+ */
349
+ redirectTo?: string;
350
+ /** Where the password-reset link opens: the page that shows `mode="new-password"`. Default `redirectTo`. */
351
+ resetRedirectTo?: string;
352
+ /** For the settings request. Default the global `fetch`. */
353
+ fetch?: typeof fetch;
354
+ }
355
+ /**
356
+ * genesis-ui's `AuthForm` client on Supabase Auth: password sign-in, magic
357
+ * link and emailed code (`signInWithOtp`, the code checked with `verifyOtp`),
358
+ * sign-up (`confirmEmail` when the project confirms emails), the reset email,
359
+ * the new password (`updateUser`, on the session the reset link opened), and
360
+ * OAuth providers (`signInWithOAuth`, which leaves the page). Every failure is
361
+ * `{ error: { code, message } }`, never a throw, also on a client made with
362
+ * `throwOnError: true`.
363
+ *
364
+ * It takes the app's client (from `createGenesisSupabase()`) and makes no
365
+ * client of its own.
366
+ *
367
+ * Without sign-up (`createUser: false`), an email with no account is answered
368
+ * like one with an account: the link or code is "sent". Saying otherwise would
369
+ * tell anyone which emails have accounts.
370
+ *
371
+ * The new-password page: show `mode="new-password"` only after the client's
372
+ * `PASSWORD_RECOVERY` event (`supabase.auth.onAuthStateChange`). Without the
373
+ * session the reset link opened, `updatePassword` fails with
374
+ * `session_not_found`.
375
+ *
376
+ * One email template serves the link and the code: Supabase sends the Magic
377
+ * Link template for both, so a form offering `"email-code"` needs
378
+ * `{{ .Token }}` in it (the default template has only the link).
379
+ *
380
+ * ```ts
381
+ * const client = createAuthFormClient(supabase, {
382
+ * url: import.meta.env.VITE_SUPABASE_URL,
383
+ * publishableKey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,
384
+ * redirectTo: `${location.origin}/auth/callback`,
385
+ * resetRedirectTo: `${location.origin}/auth/new-password`,
386
+ * });
387
+ * ```
388
+ *
389
+ * @stability Beta
390
+ */
391
+ declare function createAuthFormClient(supabase: AuthFormSupabase, options?: CreateAuthFormClientOptions): AuthFormSupabaseClient;
392
+ /** What a project's Auth allows, from `/auth/v1/settings`. */
393
+ interface AuthSettings {
394
+ /** The OAuth providers turned on, as `signInWithOAuth` names them (`"google"`, `"apple"`…), sorted. */
395
+ providers: string[];
396
+ /** Email sign-in (password, link or code) is on. */
397
+ email: boolean;
398
+ /** Phone sign-in is on. */
399
+ phone: boolean;
400
+ /** New accounts are refused. */
401
+ signUpDisabled: boolean;
402
+ /** Emails are confirmed without a link. */
403
+ autoConfirm: boolean;
404
+ }
405
+ /**
406
+ * The OAuth providers `fetchAuthSettings` reports: the ones `signInWithOAuth`
407
+ * takes and genesis-ui's `AUTH_PROVIDER_NAMES` names. Any other key of the
408
+ * settings' `external` (`email`, `phone`, `saml`, `web3_*`…) isn't a button.
409
+ *
410
+ * @stability Beta
411
+ */
412
+ declare const SUPABASE_OAUTH_PROVIDERS: readonly string[];
413
+ /**
414
+ * Reads a project's public Auth settings (`GET <url>/auth/v1/settings` with
415
+ * the publishable key): which OAuth providers are on, whether email and phone
416
+ * sign-in are, and whether sign-up is closed. Throws when the request fails,
417
+ * takes over 5 seconds or `signal` aborts it, and refuses a secret key
418
+ * (`sb_secret_…`), which must never reach a browser.
419
+ *
420
+ * @stability Beta
421
+ */
422
+ declare function fetchAuthSettings({ url, publishableKey, fetch: fetcher, signal, }: {
423
+ url: string;
424
+ publishableKey: string;
425
+ fetch?: typeof fetch;
426
+ /** Cancels the request (an unmounting form, say). */
427
+ signal?: AbortSignal;
428
+ }): Promise<AuthSettings>;
429
+
273
430
  /**
274
431
  * Supabase for Genesis apps. Platform-neutral: web, React Native and the
275
432
  * server import it. Native-only helpers (Keychain storage, foreground
@@ -399,4 +556,4 @@ interface DeleteMyAccountOptions {
399
556
  */
400
557
  declare function deleteMyAccount(client: DeleteAccountClient, options?: DeleteMyAccountOptions): Promise<void>;
401
558
 
402
- export { APPLE_REVOKE_FUNCTION as A, tenantFeatureHistory as B, tenantFeatureSettings as C, type DeleteAccountClient as D, type ExpoCryptoLike as E, type FeatureGateState as F, type GenesisSupabaseOptions as G, tenantFeatures as H, type PostgrestErrorLike as P, type SessionStorage as S, type TenantFeatureChange as T, type WebCryptoSource as W, assertPkceCrypto as a, isDigestOnlyPolyfill as b, type DeleteMyAccountOptions as c, type FeatureGateStateOptions as d, type FeatureRegistryClient as e, type FeatureRegistryDocument as f, type FlagStateValue as g, hasPkceCrypto as h, installWebCrypto as i, type FunctionsClient as j, type SetTenantFeatureInput as k, type StoreAppleTokenOptions as l, type StoreAppleTokenResult as m, SupabaseQueryError as n, type SyncFeatureRegistryOptions as o, type TenantFeatureSetting as p, type TenantFeatures as q, type TenantFeaturesClient as r, createGenesisSupabase as s, deleteMyAccount as t, featureGateState as u, must as v, requestAppleRevocation as w, setTenantFeature as x, storeAppleToken as y, syncFeatureRegistry as z };
559
+ export { APPLE_REVOKE_FUNCTION as A, deleteMyAccount as B, type CreateAuthFormClientOptions as C, type DeleteAccountClient as D, type ExpoCryptoLike as E, type FeatureGateState as F, type GenesisSupabaseOptions as G, featureGateState as H, fetchAuthSettings as I, must as J, requestAppleRevocation as K, setTenantFeature as L, storeAppleToken as M, syncFeatureRegistry as N, tenantFeatureHistory as O, type PostgrestErrorLike as P, tenantFeatureSettings as Q, tenantFeatures as R, type SessionStorage as S, type TenantFeatureChange as T, type WebCryptoSource as W, assertPkceCrypto as a, isDigestOnlyPolyfill as b, type AuthCallError as c, type AuthCallResult as d, type AuthFormSupabase as e, type AuthFormSupabaseClient as f, type AuthSettings as g, hasPkceCrypto as h, installWebCrypto as i, type DeleteMyAccountOptions as j, type FeatureGateStateOptions as k, type FeatureRegistryClient as l, type FeatureRegistryDocument as m, type FlagStateValue as n, type FunctionsClient as o, SUPABASE_OAUTH_PROVIDERS as p, type SetTenantFeatureInput as q, type StoreAppleTokenOptions as r, type StoreAppleTokenResult as s, SupabaseQueryError as t, type SyncFeatureRegistryOptions as u, type TenantFeatureSetting as v, type TenantFeatures as w, type TenantFeaturesClient as x, createAuthFormClient as y, createGenesisSupabase as z };