@midsummer-ai/sdk 0.1.0-next.901 → 0.1.0-staging.3106

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.
Files changed (40) hide show
  1. package/auth-1W-SzpD3.mjs +441 -0
  2. package/build-DQo-JrlN.d.mts +120 -0
  3. package/bytes-C2pcyl9u.mjs +280 -0
  4. package/{connection-CDk7H1FL.mjs → connection-Cu2GSOaR.mjs} +171 -31
  5. package/database/build.d.mts +2 -2
  6. package/database/build.mjs +1404 -117
  7. package/database/client.d.mts +85 -9
  8. package/database/client.mjs +550 -32
  9. package/database/contract.d.mts +92 -2
  10. package/database/contract.mjs +2179 -3
  11. package/database/errors.d.mts +1 -22
  12. package/database/react.d.mts +133 -0
  13. package/database/react.mjs +488 -0
  14. package/database/server.d.mts +2 -3
  15. package/database/server.mjs +3 -320
  16. package/database/stand-in.d.mts +95 -9
  17. package/database/stand-in.mjs +1436 -116
  18. package/errors-x2vXKi0u.d.mts +25 -0
  19. package/index-DNNXNny7.d.mts +410 -0
  20. package/key-BrRdFY-n.mjs +11 -0
  21. package/package.json +114 -1
  22. package/schema-CTHQMRsW.mjs +217 -0
  23. package/server-B5HK2Ou9.d.mts +574 -0
  24. package/server-EDRbF2u-.mjs +1893 -0
  25. package/{store-BzI9at5x.mjs → store-lIZ5GxVv.mjs} +1 -1
  26. package/{tabs-D-P8_ci_.mjs → tabs-zCh8kceo.mjs} +1 -1
  27. package/vector/contract.d.mts +1 -1
  28. package/vector/contract.mjs +773 -1
  29. package/vector/index.d.mts +2 -2
  30. package/vector/index.mjs +71 -3
  31. package/vector/stand-in.d.mts +1 -1
  32. package/vector/stand-in.mjs +326 -23
  33. package/vector/wire.d.mts +11 -2
  34. package/vector/wire.mjs +179 -14
  35. package/build-SQ44jwSa.d.mts +0 -41
  36. package/index-DdoK0y7D.d.mts +0 -192
  37. package/schema-BF-Y1EVu.mjs +0 -142
  38. package/schema-DS8x1Dn8.mjs +0 -115
  39. package/schema-f7E9uzUn.d.mts +0 -74
  40. package/server-C7O7CICU.d.mts +0 -182
@@ -1,5 +1,7 @@
1
+ import { n as bytesTagged, r as bytesUntagged } from "../bytes-C2pcyl9u.mjs";
1
2
  import { DatabaseError } from "./errors.mjs";
2
- import { t as Connection } from "../connection-CDk7H1FL.mjs";
3
+ import { i as payloadOf, r as fetchAt, t as Connection } from "../connection-Cu2GSOaR.mjs";
4
+ import { t as callKey } from "../key-BrRdFY-n.mjs";
3
5
  //#region src/database/client.ts
4
6
  /**
5
7
  * `@midsummer-ai/sdk/database`: a Project's Database, from its app or its server.
@@ -11,16 +13,16 @@ import { t as Connection } from "../connection-CDk7H1FL.mjs";
11
13
  * const id = await db.mutation(api.messages.send, { channel: "general", body: "hi" })
12
14
  * const stop = db.watch(api.messages.list, { channel: "general" }, (messages) => render(messages))
13
15
  *
14
- * In your Deployment's server, Midsummer hands in the Databases the Environment binds as
15
- * `context.database`: name one by its binding name, and no key is kept anywhere.
16
+ * Name a Database by the name its Environment binds it under, and no key is kept anywhere. The same
17
+ * call works in a Deployment's server, whatever framework serves it, where the request's own handle
18
+ * proves it; in a CI run or an Agent's run, where the run's Workload token does; and under
19
+ * `midsummer dev`, where every binding reaches the Database's Stand-in.
16
20
  *
17
- * const db = await connect({ database: context.database, binding: "main" })
21
+ * const db = await connect({ binding: "main" })
18
22
  *
19
- * In a CI run or an Agent's run, the run's Environment binds it the same way, and the run's own
20
- * Workload token is what proves it: no key there either. Under `midsummer dev`, every binding
21
- * reaches the Database's Stand-in.
23
+ * A server on Midsummer's own contract is also handed the handle as `context.database`:
22
24
  *
23
- * const db = await connect({ binding: "main" })
25
+ * const db = await connect({ database: context.database, binding: "main" })
24
26
  *
25
27
  * From code outside Midsummer, a Database Key is enough: it is exchanged for a token, and again
26
28
  * before that token runs out.
@@ -29,7 +31,17 @@ import { t as Connection } from "../connection-CDk7H1FL.mjs";
29
31
  *
30
32
  * One connection carries every call. A mutation is tagged, so one sent again after a lost
31
33
  * connection applies once; a watch is given its value now and again after every change. Every
32
- * refusal is a `DatabaseError` whose `code`, a `DatabaseErrorCode`, tells you why.
34
+ * refusal is a `DatabaseError` whose `code`, a `DatabaseErrorCode`, tells you why; a connection the
35
+ * Database refuses is `unauthenticated`, with its reason.
36
+ *
37
+ * In an app whose users sign in with Auth0, Clerk or another OIDC provider, make the client once, at
38
+ * once, and hand it the provider's token as `db/auth.config.ts` trusts it. It connects as no one until
39
+ * then (where the Database admits anonymous callers), and again whenever the token changes:
40
+ *
41
+ * const db = new DatabaseClient(url)
42
+ * db.setAuth(auth0(getAccessTokenSilently), (signedIn) => render(signedIn))
43
+ * db.setAuth(clerk(getToken, { template: "midsummer" }))
44
+ * db.clearAuth() // signed out
33
45
  */
34
46
  const API = "https://api.midsummer.new";
35
47
  /** A token and the Database's address, from the platform, for a key or for a run's binding. */
@@ -46,14 +58,119 @@ async function exchange(api, proof) {
46
58
  url: answer.url
47
59
  };
48
60
  }
61
+ /**
62
+ * A Database Key's token, exchanged once per process and kept until a minute before it expires, so a
63
+ * server that connects on every request asks the platform once per key, and connects made at the same
64
+ * time share one exchange. A refused exchange is forgotten at once.
65
+ */
66
+ const exchanged = /* @__PURE__ */ new Map();
67
+ /** When a token stops working, from its `exp`; a token that says nothing is kept for a minute. */
68
+ function expiryOf(token) {
69
+ try {
70
+ const payload = JSON.parse(atob(token.split(".")[1].replace(/-/gu, "+").replace(/_/gu, "/")));
71
+ if (typeof payload.exp === "number") return payload.exp * 1e3;
72
+ } catch {}
73
+ return Date.now() + 12e4;
74
+ }
75
+ async function keyToken(api, key, fresh = false) {
76
+ const id = `${api}|${key}`;
77
+ const kept = fresh ? void 0 : exchanged.get(id);
78
+ if (kept) {
79
+ const got = await kept.catch(() => void 0);
80
+ if (got && got.until > Date.now()) return got;
81
+ }
82
+ const asked = exchange(api, key).then((answer) => ({
83
+ ...answer,
84
+ until: expiryOf(answer.token) - 6e4
85
+ }));
86
+ exchanged.set(id, asked);
87
+ asked.catch(() => {
88
+ if (exchanged.get(id) === asked) exchanged.delete(id);
89
+ });
90
+ return asked;
91
+ }
49
92
  const refusal = (answer) => new DatabaseError(answer?.why ?? answer?.err ?? "refused", answer?.error ?? answer?.why ?? "refused");
50
- const caught = (error) => ({
93
+ const caught = (error) => error?.answer ?? {
51
94
  ok: false,
52
95
  why: error?.code ?? "refused",
53
96
  error: error?.message
54
- });
97
+ };
98
+ const told = (listener, outcome) => "error" in outcome ? listener.onError?.(outcome.error) : listener.onValue(outcome.value);
99
+ /** Why the Database refused a connection, from the reason it gives at the socket's address over HTTP; null when it gave none. */
100
+ async function refusalAt(url, token) {
101
+ try {
102
+ const response = await fetchAt(`${url.replace(/^ws/u, "http").replace(/\/+$/u, "")}/ws?token=${encodeURIComponent(token ?? "")}`, { signal: AbortSignal.timeout(1e4) });
103
+ if (response.ok) return null;
104
+ const body = await response.json().catch(() => ({}));
105
+ const why = typeof body.why === "string" ? body.why : `the database refused the connection (${response.status})`;
106
+ if (response.status === 401 || body.error === "unauthenticated") return new DatabaseError("unauthenticated", why);
107
+ if (typeof body.error === "string") return new DatabaseError(response.status === 404 ? "unavailable" : body.error, why);
108
+ return null;
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+ /**
114
+ * The claims a token's kept data is kept apart by: who they are, what they may do and when they signed in
115
+ * (`auth_time`), every claim but those each renewal changes.
116
+ */
117
+ const RENEWED = /* @__PURE__ */ new Set([
118
+ "exp",
119
+ "iat",
120
+ "nbf",
121
+ "jti"
122
+ ]);
123
+ async function keyOf(token) {
124
+ const claims = token ? payloadOf(token) : null;
125
+ const kept = claims ? Object.keys(claims).filter((name) => !RENEWED.has(name)).sort().map((name) => [name, claims[name]]) : token ? [["token", token]] : [["anonymous"]];
126
+ return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(kept)))).slice(0, 16)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
127
+ }
128
+ async function verifiedAt(url, token) {
129
+ try {
130
+ const response = await fetchAt(`${url.replace(/^ws/u, "http").replace(/\/+$/u, "")}/ws?token=${encodeURIComponent(token ?? "")}`, { signal: AbortSignal.timeout(1e4) });
131
+ const body = await response.json().catch(() => ({}));
132
+ if (response.ok) {
133
+ const named = token ? payloadOf(token)?.sub : void 0;
134
+ if ((body.sub ?? void 0) !== named) return { unknown: true };
135
+ return { accepted: await keyOf(token) };
136
+ }
137
+ if (response.status === 401 || body.error === "unauthenticated") return { refused: new DatabaseError("unauthenticated", typeof body.why === "string" ? body.why : "the database refused the token") };
138
+ return { unknown: true };
139
+ } catch {
140
+ return { unknown: true };
141
+ }
142
+ }
143
+ /**
144
+ * In a page, the data kept across reloads (watched values and unsent writes) is one sign-in's alone: named by the
145
+ * Database's host and `key`, the caller the Database took and when they signed in. No other caller, and no token
146
+ * the Database refused, reads it; an unsent write is sent again only as the sign-in that made it. A connection
147
+ * with a token never shares its socket with other tabs (`tabs: false`), so every call goes with its own tab's
148
+ * token, its own claims and its own expiry; only callers with no token share one. A caller the Database could not
149
+ * vouch for (`key` null) keeps nothing. Elsewhere nothing is shared or kept, so nothing is given.
150
+ */
151
+ async function isolation(url, key, token) {
152
+ if (typeof globalThis.document === "undefined") return {};
153
+ const own = token ? { tabs: false } : {};
154
+ if (key === null) return {
155
+ ...own,
156
+ tabs: false,
157
+ store: null
158
+ };
159
+ const name = `${new URL(url).host}#${key}`;
160
+ if (typeof globalThis.indexedDB === "undefined") return {
161
+ ...own,
162
+ name
163
+ };
164
+ return {
165
+ ...own,
166
+ name,
167
+ store: (await import("../store-lIZ5GxVv.mjs")).idbStore(name)
168
+ };
169
+ }
170
+ const inPage = () => typeof globalThis.document !== "undefined";
55
171
  async function connect(options) {
56
172
  let url, token, refresh;
173
+ const server = !("url" in options);
57
174
  if ("database" in options) {
58
175
  const first = await options.database.token(options.binding);
59
176
  url = first.url;
@@ -61,7 +178,14 @@ async function connect(options) {
61
178
  refresh = async () => (await options.database.token(options.binding)).token;
62
179
  } else if ("binding" in options) {
63
180
  const env = globalThis.process?.env ?? {};
64
- if (env.MIDSUMMER_DATABASE_URL) {
181
+ const here = globalThis[Symbol.for("midsummer.context")];
182
+ const bound = here?.()?.database;
183
+ if (bound) {
184
+ const first = await bound.token(options.binding);
185
+ url = first.url;
186
+ token = first.token;
187
+ refresh = async () => (await bound.token(options.binding)).token;
188
+ } else if (env.MIDSUMMER_DATABASE_URL) {
65
189
  url = env.MIDSUMMER_DATABASE_URL;
66
190
  token = env.MIDSUMMER_DATABASE_TOKEN;
67
191
  } else {
@@ -79,48 +203,442 @@ async function connect(options) {
79
203
  }
80
204
  } else if ("key" in options) {
81
205
  const api = options.api ?? API;
82
- const first = await exchange(api, options.key);
206
+ const first = await keyToken(api, options.key);
83
207
  url = first.url;
84
208
  token = first.token;
85
- refresh = async () => (await exchange(api, options.key)).token;
209
+ refresh = async () => (await keyToken(api, options.key, true)).token;
86
210
  } else {
87
211
  url = options.url;
88
212
  token = options.token;
89
213
  refresh = options.refresh;
90
214
  }
91
- const connection = await Connection.connect(url, {
92
- ...token !== void 0 ? { token } : {},
93
- ...refresh ? { refresh } : {}
94
- });
215
+ if (server || !inPage()) return opened(url, token, refresh, server, null);
216
+ let seen = await verifiedAt(url, token);
217
+ if ("refused" in seen && refresh) {
218
+ token = await refresh();
219
+ seen = await verifiedAt(url, token);
220
+ }
221
+ if ("refused" in seen) throw seen.refused;
222
+ const key = "accepted" in seen ? seen.accepted : null;
223
+ const expected = key ?? await keyOf(token);
224
+ const renew = refresh;
225
+ return opened(url, token, (renew && (async () => {
226
+ const fresh = await renew();
227
+ const again = await verifiedAt(url, fresh);
228
+ if ("refused" in again) throw again.refused;
229
+ if (("accepted" in again ? again.accepted : await keyOf(fresh)) !== expected) throw new DatabaseError("unauthenticated", "the renewed token is another sign-in's: connect again for it");
230
+ return fresh;
231
+ })) ?? void 0, false, key);
232
+ }
233
+ /** A connection opened for `key`'s caller (null: one the Database did not vouch for), as `connect` describes it. */
234
+ async function opened(url, token, refresh, server, key) {
235
+ let connection;
236
+ try {
237
+ const apart = server ? {} : await isolation(url, key, token);
238
+ connection = await Connection.connect(url, {
239
+ ...token !== void 0 ? { token } : {},
240
+ ...refresh ? { refresh } : {},
241
+ ...server ? { shape: "server" } : {},
242
+ ...apart
243
+ });
244
+ } catch (error) {
245
+ throw await refusalAt(url, token) ?? error;
246
+ }
95
247
  const call = (fn) => ({
96
248
  name: fn.name,
97
249
  kind: fn.kind
98
250
  });
251
+ const sent = (args) => bytesTagged(args ?? {});
252
+ const got = (value) => bytesUntagged(value);
253
+ const watching = /* @__PURE__ */ new Map();
99
254
  return {
100
- async query(fn, args) {
101
- const value = await connection.query(call(fn), args).catch(caught);
255
+ async query(fn, ...[args]) {
256
+ const value = await connection.query(call(fn), sent(args)).catch(caught);
102
257
  if (value && typeof value === "object" && !Array.isArray(value) && value.ok === false) throw refusal(value);
103
- return value;
258
+ return got(value);
104
259
  },
105
- async mutation(fn, args, { tag } = {}) {
106
- const answer = await connection.mutation(call(fn), args, tag ? { tag } : {}).catch(caught);
260
+ async mutation(fn, ...[args, { tag } = {}]) {
261
+ const answer = await connection.mutation(call(fn), sent(args), tag ? { tag } : {}).catch(caught);
107
262
  if (!answer?.ok) throw refusal(answer);
108
- return answer.value ?? null;
263
+ return got(answer.value ?? null);
109
264
  },
110
- async action(fn, args) {
111
- const answer = await connection.mutation(call(fn), args, {}).catch(caught);
265
+ async action(fn, ...[args]) {
266
+ const answer = await connection.mutation(call(fn), sent(args), {}).catch(caught);
112
267
  if (!answer?.ok) throw refusal(answer);
113
- return answer.value ?? null;
268
+ return got(answer.value ?? null);
114
269
  },
115
- watch(fn, args, onValue) {
116
- return connection.watchQuery(call(fn), args, {}, (value) => {
117
- if (value !== void 0) onValue(value);
118
- });
270
+ watch(fn, args, onValue, onError) {
271
+ const key = callKey(fn.name, args);
272
+ let shared = watching.get(key);
273
+ if (!shared) {
274
+ const it = {
275
+ listeners: /* @__PURE__ */ new Set(),
276
+ last: null,
277
+ stop: () => {}
278
+ };
279
+ shared = it;
280
+ watching.set(key, it);
281
+ const tell = (outcome) => {
282
+ it.last = outcome;
283
+ for (const listener of [...it.listeners]) told(listener, outcome);
284
+ };
285
+ let asked = 0;
286
+ it.stop = connection.watchQuery(call(fn), sent(args), {}, (value, meta, item) => {
287
+ if (value !== void 0) {
288
+ tell({ value: got(value) });
289
+ return;
290
+ }
291
+ const held = item?.ok === false ? item : meta?.error;
292
+ if (held) {
293
+ tell({ error: refusal(held) });
294
+ return;
295
+ }
296
+ const n = asked += 1;
297
+ connection.query(call(fn), sent(args)).catch(caught).then((answer) => {
298
+ if (n !== asked || watching.get(key) !== it) return;
299
+ if (answer && typeof answer === "object" && !Array.isArray(answer) && answer.ok === false) tell({ error: refusal(answer) });
300
+ else tell({ value: got(answer ?? null) });
301
+ });
302
+ });
303
+ }
304
+ const it = shared, listener = {
305
+ onValue,
306
+ ...onError ? { onError } : {}
307
+ };
308
+ it.listeners.add(listener);
309
+ if (it.last) told(listener, it.last);
310
+ return () => {
311
+ it.listeners.delete(listener);
312
+ if (it.listeners.size || watching.get(key) !== it) return;
313
+ watching.delete(key);
314
+ it.stop();
315
+ };
119
316
  },
120
317
  close() {
121
318
  connection.close();
122
319
  }
123
320
  };
124
321
  }
322
+ /**
323
+ * A Database for an app whose users sign in with their own provider: made at once (`new DatabaseClient(url)`),
324
+ * connected on first use or on `setAuth`, and connected again, its watches with it, whenever the sign-in
325
+ * changes. A token the Database refuses (or a `fetchToken` that throws) leaves the client connected as no one,
326
+ * and `onChange(false)` tells the app. The client keeps one connection; `close()` ends it.
327
+ */
328
+ var DatabaseClient = class {
329
+ #url;
330
+ #current = null;
331
+ #fetchToken = null;
332
+ #onChange = null;
333
+ #state = {
334
+ isLoading: false,
335
+ isAuthenticated: false
336
+ };
337
+ #listeners = /* @__PURE__ */ new Set();
338
+ #watches = /* @__PURE__ */ new Set();
339
+ #generation = 0;
340
+ #closed = false;
341
+ /** `url`: where the Database serves, as `midsummer db show` gives it, or the development server's address. */
342
+ constructor(url) {
343
+ if (typeof url !== "string" || !/^(?:https?|wss?):\/\//u.test(url)) throw new TypeError(`new DatabaseClient(url): an http(s) address, not ${JSON.stringify(url)}`);
344
+ this.#url = url;
345
+ }
346
+ /** Signs in with the tokens `fetchToken` gives, now and whenever one is about to expire; `onChange` hears whether the Database took them. */
347
+ setAuth(fetchToken, onChange) {
348
+ this.#fetchToken = fetchToken;
349
+ this.#onChange = onChange ?? null;
350
+ this.#reopen(true);
351
+ }
352
+ /** Signs out: the client connects again as no one. */
353
+ clearAuth() {
354
+ this.#fetchToken = null;
355
+ this.#onChange = null;
356
+ this.#reopen(false);
357
+ }
358
+ /** Whether the client is signed in, and whether that is still being decided. */
359
+ get authState() {
360
+ return this.#state;
361
+ }
362
+ /** Hears every change of `authState`; returns a stop. */
363
+ onAuthChange(listener) {
364
+ this.#listeners.add(listener);
365
+ return () => {
366
+ this.#listeners.delete(listener);
367
+ };
368
+ }
369
+ query(fn, args) {
370
+ return this.#db().then((db) => db.query(fn, args));
371
+ }
372
+ mutation(fn, args, options) {
373
+ return this.#db().then((db) => db.mutation(fn, args, options));
374
+ }
375
+ action(fn, args) {
376
+ return this.#db().then((db) => db.action(fn, args));
377
+ }
378
+ /** As `Database.watch`; it goes on across sign-ins, given the value the new caller sees. `onError` hears a connection that could not be made. */
379
+ watch(fn, args, onValue, onError) {
380
+ const watched = {
381
+ fn,
382
+ args,
383
+ onValue,
384
+ ...onError ? { onError } : {},
385
+ stop: () => {}
386
+ };
387
+ this.#watches.add(watched);
388
+ this.#subscribe(watched, this.#db());
389
+ return () => {
390
+ this.#watches.delete(watched);
391
+ watched.stop();
392
+ };
393
+ }
394
+ close() {
395
+ this.#closed = true;
396
+ for (const watched of this.#watches) watched.stop();
397
+ this.#watches.clear();
398
+ const current = this.#current;
399
+ this.#current = null;
400
+ current?.then((db) => db.close(), () => {});
401
+ }
402
+ #db() {
403
+ if (this.#closed) return Promise.reject(new DatabaseError("unavailable", "this client was closed"));
404
+ if (!this.#current) {
405
+ const opening = this.#open();
406
+ this.#current = opening;
407
+ opening.catch(() => {
408
+ if (this.#current === opening) this.#current = null;
409
+ });
410
+ }
411
+ return this.#current;
412
+ }
413
+ #subscribe(watched, db) {
414
+ let stopped = false, stop = () => {};
415
+ watched.stop = () => {
416
+ stopped = true;
417
+ stop();
418
+ };
419
+ db.then((open) => {
420
+ if (!stopped) stop = open.watch(watched.fn, watched.args, watched.onValue, watched.onError);
421
+ }, (error) => {
422
+ if (!stopped) watched.onError?.(error instanceof DatabaseError ? error : new DatabaseError("unavailable", String(error)));
423
+ });
424
+ }
425
+ #tell(state) {
426
+ this.#state = state;
427
+ for (const listener of [...this.#listeners]) listener(state);
428
+ }
429
+ /**
430
+ * Connects again for the sign-in as it is now, moving every watch to the new connection. The old connection is
431
+ * closed at once, not once the new one opens: nothing more is sent on it, and what it still held unanswered is
432
+ * dropped with it (in a page, its kept copy stays under its own sign-in, sent again only as that sign-in).
433
+ */
434
+ #reopen(signingIn) {
435
+ if (this.#closed) return;
436
+ this.#generation += 1;
437
+ const previous = this.#current;
438
+ this.#current = null;
439
+ previous?.then((db) => db.close(), () => {});
440
+ this.#tell({
441
+ isLoading: signingIn,
442
+ isAuthenticated: false
443
+ });
444
+ const next = this.#db();
445
+ for (const watched of this.#watches) {
446
+ watched.stop();
447
+ this.#subscribe(watched, next);
448
+ }
449
+ }
450
+ /**
451
+ * Opens a connection for the sign-in as it is now. The Database checks each token before anything is opened or
452
+ * renewed with it (`verifiedAt`). A refused first token is asked for anew once. A renewal that brings no one, a
453
+ * refused token or another account ends this connection at once, before anything more is sent on it; while the
454
+ * first open is still being made, it is abandoned and made again for whoever the new token names.
455
+ */
456
+ async #open() {
457
+ const generation = this.#generation, fetchToken = this.#fetchToken, onChange = this.#onChange, url = this.#url;
458
+ const anonymous = () => connect({ url });
459
+ if (!fetchToken) return anonymous();
460
+ const settled = (isAuthenticated, error) => {
461
+ if (generation !== this.#generation) return;
462
+ this.#tell({
463
+ isLoading: false,
464
+ isAuthenticated
465
+ });
466
+ onChange?.(isAuthenticated, error);
467
+ };
468
+ let token;
469
+ try {
470
+ token = await fetchToken({ forceRefreshToken: false });
471
+ } catch (error) {
472
+ settled(false, error);
473
+ return anonymous();
474
+ }
475
+ for (let asked = 0;; asked += 1) {
476
+ if (!token) {
477
+ settled(false);
478
+ return anonymous();
479
+ }
480
+ const seen = await verifiedAt(url, token);
481
+ if ("refused" in seen) {
482
+ if (asked > 0) {
483
+ settled(false, seen.refused);
484
+ return anonymous();
485
+ }
486
+ try {
487
+ token = await fetchToken({ forceRefreshToken: true });
488
+ } catch (error) {
489
+ settled(false, error);
490
+ return anonymous();
491
+ }
492
+ continue;
493
+ }
494
+ const key = "accepted" in seen ? seen.accepted : null;
495
+ const expected = key ?? await keyOf(token);
496
+ let open = null;
497
+ /** What a renewal brought while the first open was being made: the open is abandoned for it. */
498
+ let changed = null;
499
+ /** Set once this connection's sign-in has ended: no renewal of it gives a token again. */
500
+ let ended = false;
501
+ const client = this;
502
+ /**
503
+ * This connection's sign-in has ended. The connection is closed whatever has happened since; only the telling,
504
+ * and connecting again, wait on this sign-in still being the client's.
505
+ */
506
+ const leave = (next, error) => {
507
+ ended = true;
508
+ open?.close();
509
+ if (generation !== client.#generation) return;
510
+ if (next === "signed out") {
511
+ settled(false, error);
512
+ client.#fetchToken = null;
513
+ }
514
+ client.#reopen(next === "another account");
515
+ };
516
+ const over = () => ended || generation !== client.#generation;
517
+ const stop = (connection, why, error) => {
518
+ ended = true;
519
+ connection?.close?.();
520
+ throw error ?? new DatabaseError("unauthenticated", why);
521
+ };
522
+ /**
523
+ * A renewal, as the connection asks for one (`this` is the connection). It never gives a token once this sign-in
524
+ * has ended or the client has moved on, not even an empty one: it closes the connection and throws, so nothing
525
+ * it still holds is sent again as anyone else.
526
+ */
527
+ const refresh = async function() {
528
+ if (over()) return stop(this, "this connection's sign-in has ended");
529
+ let fresh;
530
+ try {
531
+ fresh = await fetchToken({ forceRefreshToken: true });
532
+ } catch (error) {
533
+ if (!open) {
534
+ changed = {
535
+ token: null,
536
+ error
537
+ };
538
+ return stop(this, "signed out", error);
539
+ }
540
+ leave("signed out", error);
541
+ return stop(this, "signed out", error);
542
+ }
543
+ if (over()) return stop(this, "this connection's sign-in has ended");
544
+ const again = fresh ? await verifiedAt(url, fresh) : null;
545
+ if (over()) return stop(this, "this connection's sign-in has ended");
546
+ if (!fresh || again && "refused" in again) {
547
+ const error = again && "refused" in again ? again.refused : void 0;
548
+ if (!open) {
549
+ changed = {
550
+ token: null,
551
+ error
552
+ };
553
+ return stop(this, "signed out", error);
554
+ }
555
+ leave("signed out", error);
556
+ return stop(this, "signed out", error);
557
+ }
558
+ if ((again && "accepted" in again ? again.accepted : await keyOf(fresh)) !== expected) {
559
+ if (!open) {
560
+ changed = { token: fresh };
561
+ return stop(this, "another account");
562
+ }
563
+ leave("another account");
564
+ return stop(this, "another account");
565
+ }
566
+ return fresh;
567
+ };
568
+ try {
569
+ const db = await opened(url, token, refresh, false, key);
570
+ open = db;
571
+ settled(true);
572
+ return db;
573
+ } catch (error) {
574
+ const now = changed;
575
+ if (now) {
576
+ if (now.token === null) {
577
+ settled(false, now.error);
578
+ return anonymous();
579
+ }
580
+ token = now.token;
581
+ asked = 0;
582
+ continue;
583
+ }
584
+ if (!(error instanceof DatabaseError && error.code === "unauthenticated")) throw error;
585
+ settled(false, error);
586
+ return anonymous();
587
+ }
588
+ }
589
+ }
590
+ };
591
+ /** The errors an Auth0 client throws when no one is signed in, which mean no token rather than a failure. */
592
+ const SIGNED_OUT = /* @__PURE__ */ new Set([
593
+ "login_required",
594
+ "consent_required",
595
+ "interaction_required",
596
+ "missing_refresh_token"
597
+ ]);
598
+ /**
599
+ * Auth0: the signed-in user's ID token, whose `aud` is your application's client ID, the `applicationID`
600
+ * `db/auth.config.ts` names beside your tenant's `domain`. Give it auth0-react's `getAccessTokenSilently`, or
601
+ * auth0-spa-js's `client.getTokenSilently.bind(client)`.
602
+ *
603
+ * db.setAuth(auth0(getAccessTokenSilently))
604
+ */
605
+ function auth0(getTokenSilently) {
606
+ return async ({ forceRefreshToken }) => {
607
+ let answer;
608
+ try {
609
+ answer = await getTokenSilently({
610
+ detailedResponse: true,
611
+ cacheMode: forceRefreshToken ? "off" : "on"
612
+ });
613
+ } catch (error) {
614
+ if (SIGNED_OUT.has(String(error?.error))) return null;
615
+ throw error;
616
+ }
617
+ const token = answer?.id_token;
618
+ return typeof token === "string" && token ? token : null;
619
+ };
620
+ }
621
+ /**
622
+ * Clerk: a token of the JWT template `template`, which sets `aud` to the `applicationID` `db/auth.config.ts`
623
+ * names beside your Clerk issuer (its Frontend API address). Give it clerk-react's `useAuth().getToken`, or
624
+ * clerk-js's `clerk.session.getToken`.
625
+ *
626
+ * db.setAuth(clerk(getToken, { template: "midsummer" }))
627
+ */
628
+ function clerk(getToken, options = {}) {
629
+ return async ({ forceRefreshToken }) => await getToken({
630
+ ...options.template ? { template: options.template } : {},
631
+ skipCache: forceRefreshToken
632
+ }) || null;
633
+ }
634
+ /**
635
+ * Any OIDC sign-in: `getToken` returns the user's ID token (a new one when `forceRefresh`), or null when no one
636
+ * is signed in. With oidc-client-ts:
637
+ *
638
+ * db.setAuth(oidc(async (fresh) => (fresh ? await manager.signinSilent() : await manager.getUser())?.id_token))
639
+ */
640
+ function oidc(getToken) {
641
+ return async ({ forceRefreshToken }) => await getToken(forceRefreshToken) || null;
642
+ }
125
643
  //#endregion
126
- export { DatabaseError, connect };
644
+ export { DatabaseClient, DatabaseError, auth0, clerk, connect, oidc };