@midsummer-ai/sdk 0.1.0-staging.3728 → 0.1.0-staging.3734

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 (47) hide show
  1. package/ai/contract.mjs +1 -1
  2. package/ai/index.d.mts +3 -2
  3. package/ai/index.mjs +1 -262
  4. package/ai/stand-in.mjs +1 -62
  5. package/ai-2Llbc56l.mjs +328 -0
  6. package/apps.d.mts +0 -15
  7. package/apps.mjs +19 -2
  8. package/auth/contract.d.mts +2 -2
  9. package/auth/contract.mjs +1 -1
  10. package/auth/index.d.mts +2 -2
  11. package/auth/index.mjs +1 -1
  12. package/auth/mail.mjs +2 -2
  13. package/auth/password.mjs +1 -1
  14. package/auth/react.d.mts +7 -2
  15. package/auth/react.mjs +44 -8
  16. package/auth/stand-in.d.mts +1 -1
  17. package/{auth-BA5Xdi-4.mjs → auth-BaGXVRYd.mjs} +38 -8
  18. package/billing/index.mjs +1 -1
  19. package/client-_Al5bpqX.mjs +877 -0
  20. package/{client-D3BZs3LA.d.mts → client-oAVg6vn_.d.mts} +64 -20
  21. package/client.mjs +1 -1
  22. package/contract.mjs +1 -1
  23. package/database/client.d.mts +2 -2
  24. package/database/client.mjs +2 -711
  25. package/database/react.d.mts +1 -1
  26. package/database/stand-in.mjs +1 -1
  27. package/email/client.mjs +1 -1
  28. package/email/contract.mjs +1 -1
  29. package/email/inbox.mjs +1 -1
  30. package/email/index.mjs +1 -1
  31. package/email/smtp.mjs +1 -1
  32. package/email/stand-in.mjs +1 -1
  33. package/{email-ynNo0HqT.mjs → email-DmWG_Ug-.mjs} +16 -2
  34. package/{engine-DDPJ2CET.mjs → engine-BmiPioJ2.mjs} +13 -2
  35. package/{here-1plIxb0D.mjs → here-BKjizr_N.mjs} +9 -1
  36. package/{index-C2Jo3JqT.d.mts → index-C8Ti5raa.d.mts} +2 -2
  37. package/index.mjs +1 -1
  38. package/package.json +1 -1
  39. package/{qr-CBh0LP2_.mjs → qr-Br1sOBmT.mjs} +1 -0
  40. package/queues/index.mjs +1 -1
  41. package/s3.mjs +1 -1
  42. package/socket.mjs +1 -1
  43. package/{src-BKKy9km-.mjs → src-DgX-tCDn.mjs} +2 -2
  44. package/storage/files.d.mts +1 -1
  45. package/storage/files.mjs +2 -2
  46. package/{store-CLGBhEpO.d.mts → store-Bx4dOx66.d.mts} +1 -1
  47. package/vector/index.mjs +1 -1
@@ -0,0 +1,877 @@
1
+ import { r as platformApi } from "./here-BKjizr_N.mjs";
2
+ import { n as bytesTagged, r as bytesUntagged } from "./bytes-C2pcyl9u.mjs";
3
+ import { DatabaseError } from "./database/errors.mjs";
4
+ import { i as payloadOf, r as fetchAt, t as Connection } from "./connection-C_JSWUrt.mjs";
5
+ import { t as callKey } from "./key-BrRdFY-n.mjs";
6
+ //#region src/database/dev-token.ts
7
+ /**
8
+ * The development server's tokens (`./dev-server.ts`): an unsigned JWT naming its caller, which only the development
9
+ * server takes and no Database ever accepts. Here apart from the server, so the client can make one for a signed-in
10
+ * user under `midsummer dev` (`userToken`) without the server's code.
11
+ *
12
+ * const token = devToken("ada") // as one of the app's users
13
+ * const server = devToken("site:dev") // as the app's server, as `midsummer dev` hands its servers
14
+ */
15
+ /** A token for the development server: an unsigned JWT naming `subject`, good for a day. Never accepted by a Database. */
16
+ function devToken(subject) {
17
+ const encode = (value) => btoa(JSON.stringify(value)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
18
+ return `${encode({
19
+ alg: "none",
20
+ typ: "JWT"
21
+ })}.${encode({
22
+ iss: "midsummer-dev",
23
+ sub: subject,
24
+ exp: Math.floor(Date.now() / 1e3) + 86400
25
+ })}.`;
26
+ }
27
+ //#endregion
28
+ //#region src/database/client.ts
29
+ /**
30
+ * `@midsummer-ai/sdk/database`: a Project's Database, from its app or its server.
31
+ *
32
+ * import { connect } from "@midsummer-ai/sdk/database"
33
+ * import { api } from "../db/_generated/api"
34
+ *
35
+ * const db = await connect({ url, token, refresh })
36
+ * const id = await db.mutation(api.messages.send, { channel: "general", body: "hi" })
37
+ * const stop = db.watch(api.messages.list, { channel: "general" }, (messages) => render(messages))
38
+ *
39
+ * Name a Database by the name its Environment binds it under, and no key is kept anywhere. The same
40
+ * call works in a Deployment's server, whatever framework serves it, where the request's own handle
41
+ * proves it; in a CI run or an Agent's run, where the run's Workload token does; and under
42
+ * `midsummer dev`, where every binding reaches the Database's Stand-in.
43
+ *
44
+ * const db = await connect({ binding: "main" })
45
+ *
46
+ * A server on Midsummer's own contract is also handed the handle as `context.database`:
47
+ *
48
+ * const db = await connect({ database: context.database, binding: "main" })
49
+ *
50
+ * From code outside Midsummer, a Database Key is enough: it is exchanged for a token, and again
51
+ * before that token runs out.
52
+ *
53
+ * const db = await connect({ key: process.env.DATABASE_KEY! })
54
+ *
55
+ * One connection carries every call. A mutation is tagged, so one sent again after a lost
56
+ * connection applies once; a watch is given its value now and again after every change. A query or a
57
+ * watch the Database refuses while it catches up after a restart is read again for a few seconds
58
+ * before it gives `history_unavailable`; a mutation or an action refused so throws at once. Every
59
+ * refusal is a `DatabaseError` whose `code`, a `DatabaseErrorCode`, tells you why; a connection the
60
+ * Database refuses is `unauthenticated`, with its reason.
61
+ *
62
+ * In an app whose users sign in with Auth, a page connects as whoever is signed in, its token from the app's own
63
+ * `auth.handler`, with no key and no route of your own:
64
+ *
65
+ * const db = signedInDatabase()
66
+ *
67
+ * In an app whose users sign in with Auth0, Clerk or another OIDC provider, make the client once, at
68
+ * once, and hand it the provider's token as `db/auth.config.ts` trusts it. It connects as no one until
69
+ * then (where the Database admits anonymous callers), and again whenever the token changes:
70
+ *
71
+ * const db = new DatabaseClient(url)
72
+ * db.setAuth(auth0(getAccessTokenSilently), (signedIn) => render(signedIn))
73
+ * db.setAuth(clerk(getToken, { template: "midsummer" }))
74
+ * db.clearAuth() // signed out
75
+ */
76
+ /** The subjects the platform's own tokens use, which never name one of an app's users. */
77
+ const SERVER_SUBJECT = /^(?:key|site|workload):/u;
78
+ /** Why `as` can't name one of the app's users, or undefined when it can: the platform's rule for them. */
79
+ function userProblem(as) {
80
+ if (typeof as !== "string" || as.length < 1 || as.length > 256 || SERVER_SUBJECT.test(as)) return `A user is named by your app's own id for them, 1 to 256 characters, not starting key:, site: or workload:. This one is ${JSON.stringify(as)}.`;
81
+ }
82
+ /**
83
+ * A token and the Database's address, from the platform's API at `api`, for a key (as one of the app's users with
84
+ * `as`) or for a run's binding (with `as` too). What goes wrong says which API it asked and why, so a wrong one, such
85
+ * as another site's, never reads as a refused key.
86
+ */
87
+ async function exchange(api, proof) {
88
+ const asked = `${api}/v1/db/tokens`;
89
+ const response = await fetch(asked, {
90
+ method: "POST",
91
+ headers: { "Content-Type": "application/json" },
92
+ body: JSON.stringify(typeof proof === "string" ? { key: proof } : proof)
93
+ }).catch((error) => {
94
+ throw new DatabaseError("unavailable", `Couldn't reach ${new URL(api).host} for a database token (${error instanceof Error ? error.message : String(error)}). It should be the API of the Midsummer site your database is on: set MIDSUMMER_API, or pass api.`);
95
+ });
96
+ const answer = await response.json().catch(() => void 0);
97
+ if (response.ok && answer?.token && answer.url) return {
98
+ token: answer.token,
99
+ url: answer.url,
100
+ ...typeof answer.expiresAt === "number" ? { expiresAt: answer.expiresAt } : {}
101
+ };
102
+ const said = typeof answer?.error === "string" ? answer.error : answer?.error?.message;
103
+ if (said) throw new DatabaseError(response.status >= 500 ? "unavailable" : "denied", `${said} (${new URL(api).host})`);
104
+ throw new DatabaseError("unavailable", `${new URL(api).host} returned ${response.status} and no database token for POST /v1/db/tokens, so it isn't the API of the Midsummer site your database is on, or it couldn't answer. Set MIDSUMMER_API to that site's API, or pass api.`);
105
+ }
106
+ /**
107
+ * A token for one signed-in user of your app, for your server to hand to that user's browser, which connects with
108
+ * it (`signedInDatabase()`, `@midsummer-ai/sdk/react`'s `DatabaseProvider`, or `connect({ url, token, refresh })`).
109
+ * Your server gives the user's id as `as`; your functions see that id as `ctx.auth.subject`. The token
110
+ * runs public functions only, never internal ones. It lasts ten minutes: the browser asks your server again before
111
+ * then. With Auth, `auth.handler` serves it already, at `/api/auth/database-token`.
112
+ *
113
+ * On Midsummer it needs no key: the database is the one the environment binds as `binding` (`main` unless named),
114
+ * in a deployment, a preview (its own copy), a CI run and under `midsummer dev` (the local database) alike. Outside
115
+ * Midsummer, give a database key, whose token runs queries only for a `read` key.
116
+ *
117
+ * app.get("/db-token", async (c) => c.json(await userToken({ as: session.userId })))
118
+ * app.get("/db-token", async (c) => c.json(await userToken({ key: process.env.DATABASE_KEY!, as: session.userId })))
119
+ */
120
+ async function userToken(options) {
121
+ const problem = userProblem(options.as);
122
+ if (problem) throw new DatabaseError("invalid", problem);
123
+ if (options.key !== void 0) {
124
+ const given = await exchange(options.api ?? platformApi(), {
125
+ key: options.key,
126
+ as: options.as
127
+ });
128
+ return {
129
+ token: given.token,
130
+ url: given.url,
131
+ expiresAt: given.expiresAt ?? expiryOf(given.token)
132
+ };
133
+ }
134
+ const binding = options.binding ?? "main";
135
+ const found = bound(binding);
136
+ if ("handle" in found) {
137
+ if (!found.handle.userToken) throw new DatabaseError("unavailable", `This deployment's runtime gives no user tokens for the database bound as ${binding}. That's Midsummer's fault, not your code's: ship again, and if it goes on, tell Midsummer.`);
138
+ return found.handle.userToken(binding, options.as);
139
+ }
140
+ if ("dev" in found) return {
141
+ token: devToken(options.as),
142
+ url: found.dev,
143
+ expiresAt: Date.now() + 864e5
144
+ };
145
+ const given = await exchange(options.api ?? found.api, {
146
+ binding,
147
+ workload: found.workload,
148
+ as: options.as
149
+ });
150
+ return {
151
+ token: given.token,
152
+ url: given.url,
153
+ expiresAt: given.expiresAt ?? expiryOf(given.token)
154
+ };
155
+ }
156
+ /**
157
+ * Where the code runs, for a binding's database: a deployment's request handle, `midsummer dev`'s local database, or a
158
+ * run's workload session with the API it came from. Throws when it runs outside Midsummer, or in a request Midsummer
159
+ * handed no bindings.
160
+ */
161
+ function bound(binding) {
162
+ const env = globalThis.process?.env ?? {};
163
+ const here = globalThis[Symbol.for("midsummer.context")];
164
+ const request = here?.();
165
+ const handle = request?.database;
166
+ if (request && !handle && !env.MIDSUMMER_DATABASE_URL) throw new DatabaseError("unavailable", `This request reached your server without the bindings of the environment its address serves, so no database is bound to it as ${binding}. That's Midsummer's fault, not your code's: ship again, and if it goes on, tell Midsummer.`);
167
+ if (handle) return { handle };
168
+ if (env.MIDSUMMER_DATABASE_URL) return {
169
+ dev: env.MIDSUMMER_DATABASE_URL,
170
+ token: env.MIDSUMMER_DATABASE_TOKEN
171
+ };
172
+ const workload = env.MIDSUMMER_IDENTITY_REQUEST_TOKEN, tokenUrl = env.MIDSUMMER_IDENTITY_TOKEN_URL;
173
+ if (!workload || !tokenUrl) throw new DatabaseError("denied", "This code runs outside Midsummer, so no environment binds a database for it. Connect with a database key, connect({ key }), or run it under midsummer dev.");
174
+ return {
175
+ workload,
176
+ api: new URL(tokenUrl).origin
177
+ };
178
+ }
179
+ /**
180
+ * Where the database bound as `binding` (`main` unless named) serves, or the one a key reaches: what a page connects
181
+ * to as no one, as `auth.handler`'s `/api/auth/database-token` returns it to a visitor who isn't signed in.
182
+ */
183
+ async function databaseUrl(options = {}) {
184
+ if (options.key !== void 0) return (await keyToken(options.api ?? platformApi(), options.key)).url;
185
+ const binding = options.binding ?? "main";
186
+ const found = bound(binding);
187
+ if ("handle" in found) return (await found.handle.token(binding)).url;
188
+ if ("dev" in found) return found.dev;
189
+ return (await exchange(options.api ?? found.api, {
190
+ binding,
191
+ workload: found.workload
192
+ })).url;
193
+ }
194
+ /**
195
+ * A Database Key's token, exchanged once per process and kept until a minute before it expires, so a
196
+ * server that connects on every request asks the platform once per key, and connects made at the same
197
+ * time share one exchange. A refused exchange is forgotten at once.
198
+ */
199
+ const exchanged = /* @__PURE__ */ new Map();
200
+ /** When a token stops working, from its `exp`; a token that says nothing is kept for a minute. */
201
+ function expiryOf(token) {
202
+ try {
203
+ const payload = JSON.parse(atob(token.split(".")[1].replace(/-/gu, "+").replace(/_/gu, "/")));
204
+ if (typeof payload.exp === "number") return payload.exp * 1e3;
205
+ } catch {}
206
+ return Date.now() + 12e4;
207
+ }
208
+ async function keyToken(api, key, fresh = false) {
209
+ const id = `${api}|${key}`;
210
+ const kept = fresh ? void 0 : exchanged.get(id);
211
+ if (kept) {
212
+ const got = await kept.catch(() => void 0);
213
+ if (got && got.until > Date.now()) return got;
214
+ }
215
+ const asked = exchange(api, key).then((answer) => ({
216
+ ...answer,
217
+ until: expiryOf(answer.token) - 6e4
218
+ }));
219
+ exchanged.set(id, asked);
220
+ asked.catch(() => {
221
+ if (exchanged.get(id) === asked) exchanged.delete(id);
222
+ });
223
+ return asked;
224
+ }
225
+ const isRefusal = (value) => !!value && typeof value === "object" && !Array.isArray(value) && value.ok === false;
226
+ /**
227
+ * Whether the database refused a call for now: `unavailable` (or `history_unavailable`) means it could not finish the
228
+ * call at this moment, as while it catches up after a restart, and clears within seconds, so a read refused so is
229
+ * tried again. The engine's code decides this, never its message.
230
+ */
231
+ const unavailable = (answer) => ["unavailable", "history_unavailable"].includes(answer.why ?? answer.err ?? "");
232
+ /**
233
+ * Whether that refusal was the database rebuilding what it keeps after a restart, which it says as
234
+ * `reads below lsn <n> are no longer kept` (or, once it codes it, `history_unavailable`): such a refusal is
235
+ * reported as `history_unavailable`, with its docs.
236
+ */
237
+ const HISTORY_GONE = /reads below lsn \d+ are no longer kept/u;
238
+ const historyGone = (answer) => (answer.why ?? answer.err) === "history_unavailable" || unavailable(answer) && HISTORY_GONE.test(answer.error ?? "");
239
+ /** How long a read refused `unavailable` waits before each try again: 3 seconds in all. */
240
+ const HISTORY_RETRY_MS = [
241
+ 100,
242
+ 200,
243
+ 400,
244
+ 800,
245
+ 1500
246
+ ];
247
+ const HISTORY_DOCS = "https://docs.staging.midsummer.new/guides/database/troubleshooting#history-unavailable";
248
+ /** The `DatabaseError` for a refused call; `retried` is set for a read the client already tried again. */
249
+ const refusal = (answer, retried = false) => {
250
+ if (answer && historyGone(answer)) {
251
+ const tried = retried ? `The client tried again for ${HISTORY_RETRY_MS.reduce((sum, ms) => sum + ms, 0) / 1e3} seconds. ` : "";
252
+ return new DatabaseError("history_unavailable", `The database couldn't read the rows this call needs because it's catching up after a restart. This is temporary. ${tried}Try again in a moment; a mutation sent again with the same tag applies once. If it keeps happening, see ${HISTORY_DOCS}`, { why: answer.error });
253
+ }
254
+ return new DatabaseError(answer?.why ?? answer?.err ?? "refused", answer?.error ?? answer?.why ?? "refused");
255
+ };
256
+ const caught = (error) => error?.answer ?? {
257
+ ok: false,
258
+ why: error?.code ?? "refused",
259
+ error: error?.message
260
+ };
261
+ /**
262
+ * A read's value, or its refusal as an `Answer`, tried again while the database refuses it `unavailable`, at the
263
+ * waits of `HISTORY_RETRY_MS`. Only reads come here: a mutation or an action refused so is thrown at once.
264
+ */
265
+ async function readAgain(read) {
266
+ let value = await read().catch(caught);
267
+ for (const wait of HISTORY_RETRY_MS) {
268
+ if (!isRefusal(value) || !unavailable(value)) return value;
269
+ await new Promise((resolve) => setTimeout(resolve, wait));
270
+ value = await read().catch(caught);
271
+ }
272
+ return value;
273
+ }
274
+ const told = (listener, outcome) => "error" in outcome ? listener.onError?.(outcome.error) : listener.onValue(outcome.value);
275
+ /** Why the Database refused a connection, from the reason it gives at the socket's address over HTTP; null when it gave none. */
276
+ async function refusalAt(url, token) {
277
+ try {
278
+ const response = await fetchAt(`${url.replace(/^ws/u, "http").replace(/\/+$/u, "")}/ws?token=${encodeURIComponent(token ?? "")}`, { signal: AbortSignal.timeout(1e4) });
279
+ if (response.ok) return null;
280
+ const body = await response.json().catch(() => ({}));
281
+ const why = typeof body.why === "string" ? body.why : `the database refused the connection (${response.status})`;
282
+ if (response.status === 401 || body.error === "unauthenticated") return new DatabaseError("unauthenticated", why);
283
+ if (typeof body.error === "string") return new DatabaseError(response.status === 404 ? "unavailable" : body.error, why);
284
+ return null;
285
+ } catch {
286
+ return null;
287
+ }
288
+ }
289
+ /**
290
+ * The claims a token's kept data is kept apart by: who they are, what they may do and when they signed in
291
+ * (`auth_time`), every claim but those each renewal changes.
292
+ */
293
+ const RENEWED = /* @__PURE__ */ new Set([
294
+ "exp",
295
+ "iat",
296
+ "nbf",
297
+ "jti"
298
+ ]);
299
+ async function keyOf(token) {
300
+ const claims = token ? payloadOf(token) : null;
301
+ const kept = claims ? Object.keys(claims).filter((name) => !RENEWED.has(name)).sort().map((name) => [name, claims[name]]) : token ? [["token", token]] : [["anonymous"]];
302
+ 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("");
303
+ }
304
+ async function verifiedAt(url, token) {
305
+ try {
306
+ const response = await fetchAt(`${url.replace(/^ws/u, "http").replace(/\/+$/u, "")}/ws?token=${encodeURIComponent(token ?? "")}`, { signal: AbortSignal.timeout(1e4) });
307
+ const body = await response.json().catch(() => ({}));
308
+ if (response.ok) {
309
+ const named = token ? payloadOf(token)?.sub : void 0;
310
+ if ((body.sub ?? void 0) !== named) return { unknown: true };
311
+ return { accepted: await keyOf(token) };
312
+ }
313
+ if (response.status === 401 || body.error === "unauthenticated") return { refused: new DatabaseError("unauthenticated", typeof body.why === "string" ? body.why : "the database refused the token") };
314
+ return { unknown: true };
315
+ } catch {
316
+ return { unknown: true };
317
+ }
318
+ }
319
+ /**
320
+ * In a page, the data kept across reloads (watched values and unsent writes) is one sign-in's alone: named by the
321
+ * Database's host and `key`, the caller the Database took and when they signed in. No other caller, and no token
322
+ * the Database refused, reads it; an unsent write is sent again only as the sign-in that made it. A connection
323
+ * with a token never shares its socket with other tabs (`tabs: false`), so every call goes with its own tab's
324
+ * token, its own claims and its own expiry; only callers with no token share one. A caller the Database could not
325
+ * vouch for (`key` null) keeps nothing. Elsewhere nothing is shared or kept, so nothing is given.
326
+ */
327
+ async function isolation(url, key, token) {
328
+ if (typeof globalThis.document === "undefined") return {};
329
+ const own = token ? { tabs: false } : {};
330
+ if (key === null) return {
331
+ ...own,
332
+ tabs: false,
333
+ store: null
334
+ };
335
+ const name = `${new URL(url).host}#${key}`;
336
+ if (typeof globalThis.indexedDB === "undefined") return {
337
+ ...own,
338
+ name
339
+ };
340
+ return {
341
+ ...own,
342
+ name,
343
+ store: (await import("./store-CsBhnabU.mjs")).idbStore(name)
344
+ };
345
+ }
346
+ const inPage = () => typeof globalThis.document !== "undefined";
347
+ async function connect(options) {
348
+ let url, token, refresh;
349
+ const server = !("url" in options);
350
+ if ("database" in options) {
351
+ const first = await options.database.token(options.binding);
352
+ url = first.url;
353
+ token = first.token;
354
+ refresh = async () => (await options.database.token(options.binding)).token;
355
+ } else if ("binding" in options) {
356
+ const found = bound(options.binding);
357
+ if ("handle" in found) {
358
+ const first = await found.handle.token(options.binding);
359
+ url = first.url;
360
+ token = first.token;
361
+ refresh = async () => (await found.handle.token(options.binding)).token;
362
+ } else if ("dev" in found) {
363
+ url = found.dev;
364
+ token = found.token;
365
+ } else {
366
+ const api = options.api ?? found.api;
367
+ const proof = {
368
+ binding: options.binding,
369
+ workload: found.workload
370
+ };
371
+ const first = await exchange(api, proof);
372
+ url = first.url;
373
+ token = first.token;
374
+ refresh = async () => (await exchange(api, proof)).token;
375
+ }
376
+ } else if ("key" in options) {
377
+ const api = options.api ?? platformApi();
378
+ const first = await keyToken(api, options.key);
379
+ url = first.url;
380
+ token = first.token;
381
+ refresh = async () => (await keyToken(api, options.key, true)).token;
382
+ } else {
383
+ url = options.url;
384
+ token = options.token;
385
+ refresh = options.refresh;
386
+ }
387
+ if (server || !inPage()) return opened(url, token, refresh, server, null);
388
+ let seen = await verifiedAt(url, token);
389
+ if ("refused" in seen && refresh) {
390
+ token = await refresh();
391
+ seen = await verifiedAt(url, token);
392
+ }
393
+ if ("refused" in seen) throw seen.refused;
394
+ const key = "accepted" in seen ? seen.accepted : null;
395
+ const expected = key ?? await keyOf(token);
396
+ const renew = refresh;
397
+ return opened(url, token, (renew && (async () => {
398
+ const fresh = await renew();
399
+ const again = await verifiedAt(url, fresh);
400
+ if ("refused" in again) throw again.refused;
401
+ 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");
402
+ return fresh;
403
+ })) ?? void 0, false, key);
404
+ }
405
+ /** A connection opened for `key`'s caller (null: one the Database did not vouch for), as `connect` describes it. */
406
+ async function opened(url, token, refresh, server, key) {
407
+ let connection;
408
+ try {
409
+ const apart = server ? {} : await isolation(url, key, token);
410
+ connection = await Connection.connect(url, {
411
+ ...token !== void 0 ? { token } : {},
412
+ ...refresh ? { refresh } : {},
413
+ ...server ? { shape: "server" } : {},
414
+ ...apart
415
+ });
416
+ } catch (error) {
417
+ throw await refusalAt(url, token) ?? error;
418
+ }
419
+ const call = (fn) => ({
420
+ name: fn.name,
421
+ kind: fn.kind
422
+ });
423
+ const sent = (args) => bytesTagged(args ?? {});
424
+ const got = (value) => bytesUntagged(value);
425
+ const watching = /* @__PURE__ */ new Map();
426
+ return {
427
+ async query(fn, ...[args]) {
428
+ const value = await readAgain(() => connection.query(call(fn), sent(args)));
429
+ if (isRefusal(value)) throw refusal(value, true);
430
+ return got(value);
431
+ },
432
+ async mutation(fn, ...[args, { tag } = {}]) {
433
+ const answer = await connection.mutation(call(fn), sent(args), tag ? { tag } : {}).catch(caught);
434
+ if (!answer?.ok) throw refusal(answer);
435
+ return got(answer.value ?? null);
436
+ },
437
+ async action(fn, ...[args]) {
438
+ const answer = await connection.mutation(call(fn), sent(args), {}).catch(caught);
439
+ if (!answer?.ok) throw refusal(answer);
440
+ return got(answer.value ?? null);
441
+ },
442
+ watch(fn, args, onValue, onError) {
443
+ const key = callKey(fn.name, args);
444
+ let shared = watching.get(key);
445
+ if (!shared) {
446
+ const it = {
447
+ listeners: /* @__PURE__ */ new Set(),
448
+ last: null,
449
+ stop: () => {}
450
+ };
451
+ shared = it;
452
+ watching.set(key, it);
453
+ const tell = (outcome) => {
454
+ it.last = outcome;
455
+ for (const listener of [...it.listeners]) told(listener, outcome);
456
+ };
457
+ let asked = 0;
458
+ it.stop = connection.watchQuery(call(fn), sent(args), {}, (value, meta, item) => {
459
+ if (value !== void 0) {
460
+ tell({ value: got(value) });
461
+ return;
462
+ }
463
+ const held = item?.ok === false ? item : meta?.error;
464
+ if (held && !unavailable(held)) {
465
+ tell({ error: refusal(held) });
466
+ return;
467
+ }
468
+ const n = asked += 1;
469
+ readAgain(() => connection.query(call(fn), sent(args))).then((answer) => {
470
+ if (n !== asked || watching.get(key) !== it) return;
471
+ if (isRefusal(answer)) tell({ error: refusal(answer, true) });
472
+ else tell({ value: got(answer ?? null) });
473
+ });
474
+ });
475
+ }
476
+ const it = shared, listener = {
477
+ onValue,
478
+ ...onError ? { onError } : {}
479
+ };
480
+ it.listeners.add(listener);
481
+ if (it.last) told(listener, it.last);
482
+ return () => {
483
+ it.listeners.delete(listener);
484
+ if (it.listeners.size || watching.get(key) !== it) return;
485
+ watching.delete(key);
486
+ it.stop();
487
+ };
488
+ },
489
+ close() {
490
+ connection.close();
491
+ }
492
+ };
493
+ }
494
+ /**
495
+ * A Database for an app whose users sign in with their own provider: made at once (`new DatabaseClient(url)`),
496
+ * connected on first use or on `setAuth`, and connected again, its watches with it, whenever the sign-in
497
+ * changes. A token the Database refuses (or a `fetchToken` that throws) leaves the client connected as no one,
498
+ * and `onChange(false)` tells the app. The client keeps one connection; `close()` ends it.
499
+ */
500
+ var DatabaseClient = class {
501
+ #url;
502
+ #current = null;
503
+ #fetchToken = null;
504
+ #onChange = null;
505
+ #state = {
506
+ isLoading: false,
507
+ isAuthenticated: false
508
+ };
509
+ #listeners = /* @__PURE__ */ new Set();
510
+ #watches = /* @__PURE__ */ new Set();
511
+ #generation = 0;
512
+ #closed = false;
513
+ /**
514
+ * `url`: where the Database serves, as `midsummer db show` gives it, or the development server's address; or a
515
+ * function that gives it, asked each time the client connects, for a page that learns it from its server. With
516
+ * `fetchToken`, the first connection, made on first use, is signed in with it, as after `setAuth`.
517
+ */
518
+ constructor(url, fetchToken) {
519
+ if (typeof url !== "function" && (typeof url !== "string" || !/^(?:https?|wss?):\/\//u.test(url))) throw new TypeError(`new DatabaseClient(url): an http(s) address, not ${JSON.stringify(url)}`);
520
+ this.#url = url;
521
+ if (fetchToken) {
522
+ this.#fetchToken = fetchToken;
523
+ this.#state = {
524
+ isLoading: true,
525
+ isAuthenticated: false
526
+ };
527
+ }
528
+ }
529
+ /** Signs in with the tokens `fetchToken` gives, now and whenever one is about to expire; `onChange` hears whether the Database took them. */
530
+ setAuth(fetchToken, onChange) {
531
+ this.#fetchToken = fetchToken;
532
+ this.#onChange = onChange ?? null;
533
+ this.#reopen(true);
534
+ }
535
+ /** Signs out: the client connects again as no one. */
536
+ clearAuth() {
537
+ this.#fetchToken = null;
538
+ this.#onChange = null;
539
+ this.#reopen(false);
540
+ }
541
+ /** Whether the client is signed in, and whether that is still being decided. */
542
+ get authState() {
543
+ return this.#state;
544
+ }
545
+ /** Hears every change of `authState`; returns a stop. */
546
+ onAuthChange(listener) {
547
+ this.#listeners.add(listener);
548
+ return () => {
549
+ this.#listeners.delete(listener);
550
+ };
551
+ }
552
+ query(fn, args) {
553
+ return this.#db().then((db) => db.query(fn, args));
554
+ }
555
+ mutation(fn, args, options) {
556
+ return this.#db().then((db) => db.mutation(fn, args, options));
557
+ }
558
+ action(fn, args) {
559
+ return this.#db().then((db) => db.action(fn, args));
560
+ }
561
+ /** 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. */
562
+ watch(fn, args, onValue, onError) {
563
+ const watched = {
564
+ fn,
565
+ args,
566
+ onValue,
567
+ ...onError ? { onError } : {},
568
+ stop: () => {}
569
+ };
570
+ this.#watches.add(watched);
571
+ this.#subscribe(watched, this.#db());
572
+ return () => {
573
+ this.#watches.delete(watched);
574
+ watched.stop();
575
+ };
576
+ }
577
+ close() {
578
+ this.#closed = true;
579
+ for (const watched of this.#watches) watched.stop();
580
+ this.#watches.clear();
581
+ const current = this.#current;
582
+ this.#current = null;
583
+ current?.then((db) => db.close(), () => {});
584
+ }
585
+ #db() {
586
+ if (this.#closed) return Promise.reject(new DatabaseError("unavailable", "this client was closed"));
587
+ if (!this.#current) {
588
+ const opening = this.#open();
589
+ this.#current = opening;
590
+ opening.catch(() => {
591
+ if (this.#current === opening) this.#current = null;
592
+ });
593
+ }
594
+ return this.#current;
595
+ }
596
+ #subscribe(watched, db) {
597
+ let stopped = false, stop = () => {};
598
+ watched.stop = () => {
599
+ stopped = true;
600
+ stop();
601
+ };
602
+ db.then((open) => {
603
+ if (!stopped) stop = open.watch(watched.fn, watched.args, watched.onValue, watched.onError);
604
+ }, (error) => {
605
+ if (!stopped) watched.onError?.(error instanceof DatabaseError ? error : new DatabaseError("unavailable", String(error)));
606
+ });
607
+ }
608
+ #tell(state) {
609
+ this.#state = state;
610
+ for (const listener of [...this.#listeners]) listener(state);
611
+ }
612
+ /**
613
+ * Connects again for the sign-in as it is now, moving every watch to the new connection. The old connection is
614
+ * closed at once, not once the new one opens: nothing more is sent on it, and what it still held unanswered is
615
+ * dropped with it (in a page, its kept copy stays under its own sign-in, sent again only as that sign-in).
616
+ */
617
+ #reopen(signingIn) {
618
+ if (this.#closed) return;
619
+ this.#generation += 1;
620
+ const previous = this.#current;
621
+ this.#current = null;
622
+ previous?.then((db) => db.close(), () => {});
623
+ this.#tell({
624
+ isLoading: signingIn,
625
+ isAuthenticated: false
626
+ });
627
+ const next = this.#db();
628
+ for (const watched of this.#watches) {
629
+ watched.stop();
630
+ this.#subscribe(watched, next);
631
+ }
632
+ }
633
+ /**
634
+ * Opens a connection for the sign-in as it is now. The Database checks each token before anything is opened or
635
+ * renewed with it (`verifiedAt`). A refused first token is asked for anew once. A renewal that brings no one, a
636
+ * refused token or another account ends this connection at once, before anything more is sent on it; while the
637
+ * first open is still being made, it is abandoned and made again for whoever the new token names.
638
+ */
639
+ async #open() {
640
+ const generation = this.#generation, fetchToken = this.#fetchToken, onChange = this.#onChange;
641
+ const url = typeof this.#url === "string" ? this.#url : await this.#url();
642
+ const anonymous = () => connect({ url });
643
+ if (!fetchToken) return anonymous();
644
+ const settled = (isAuthenticated, error) => {
645
+ if (generation !== this.#generation) return;
646
+ this.#tell({
647
+ isLoading: false,
648
+ isAuthenticated
649
+ });
650
+ onChange?.(isAuthenticated, error);
651
+ };
652
+ let token;
653
+ try {
654
+ token = await fetchToken({ forceRefreshToken: false });
655
+ } catch (error) {
656
+ settled(false, error);
657
+ return anonymous();
658
+ }
659
+ for (let asked = 0;; asked += 1) {
660
+ if (!token) {
661
+ settled(false);
662
+ return anonymous();
663
+ }
664
+ const seen = await verifiedAt(url, token);
665
+ if ("refused" in seen) {
666
+ if (asked > 0) {
667
+ settled(false, seen.refused);
668
+ return anonymous();
669
+ }
670
+ try {
671
+ token = await fetchToken({ forceRefreshToken: true });
672
+ } catch (error) {
673
+ settled(false, error);
674
+ return anonymous();
675
+ }
676
+ continue;
677
+ }
678
+ const key = "accepted" in seen ? seen.accepted : null;
679
+ const expected = key ?? await keyOf(token);
680
+ let open = null;
681
+ /** What a renewal brought while the first open was being made: the open is abandoned for it. */
682
+ let changed = null;
683
+ /** Set once this connection's sign-in has ended: no renewal of it gives a token again. */
684
+ let ended = false;
685
+ const client = this;
686
+ /**
687
+ * This connection's sign-in has ended. The connection is closed whatever has happened since; only the telling,
688
+ * and connecting again, wait on this sign-in still being the client's.
689
+ */
690
+ const leave = (next, error) => {
691
+ ended = true;
692
+ open?.close();
693
+ if (generation !== client.#generation) return;
694
+ if (next === "signed out") {
695
+ settled(false, error);
696
+ client.#fetchToken = null;
697
+ }
698
+ client.#reopen(next === "another account");
699
+ };
700
+ const over = () => ended || generation !== client.#generation;
701
+ const stop = (connection, why, error) => {
702
+ ended = true;
703
+ connection?.close?.();
704
+ throw error ?? new DatabaseError("unauthenticated", why);
705
+ };
706
+ /**
707
+ * A renewal, as the connection asks for one (`this` is the connection). It never gives a token once this sign-in
708
+ * has ended or the client has moved on, not even an empty one: it closes the connection and throws, so nothing
709
+ * it still holds is sent again as anyone else.
710
+ */
711
+ const refresh = async function() {
712
+ if (over()) return stop(this, "this connection's sign-in has ended");
713
+ let fresh;
714
+ try {
715
+ fresh = await fetchToken({ forceRefreshToken: true });
716
+ } catch (error) {
717
+ if (!open) {
718
+ changed = {
719
+ token: null,
720
+ error
721
+ };
722
+ return stop(this, "signed out", error);
723
+ }
724
+ leave("signed out", error);
725
+ return stop(this, "signed out", error);
726
+ }
727
+ if (over()) return stop(this, "this connection's sign-in has ended");
728
+ const again = fresh ? await verifiedAt(url, fresh) : null;
729
+ if (over()) return stop(this, "this connection's sign-in has ended");
730
+ if (!fresh || again && "refused" in again) {
731
+ const error = again && "refused" in again ? again.refused : void 0;
732
+ if (!open) {
733
+ changed = {
734
+ token: null,
735
+ error
736
+ };
737
+ return stop(this, "signed out", error);
738
+ }
739
+ leave("signed out", error);
740
+ return stop(this, "signed out", error);
741
+ }
742
+ if ((again && "accepted" in again ? again.accepted : await keyOf(fresh)) !== expected) {
743
+ if (!open) {
744
+ changed = { token: fresh };
745
+ return stop(this, "another account");
746
+ }
747
+ leave("another account");
748
+ return stop(this, "another account");
749
+ }
750
+ return fresh;
751
+ };
752
+ try {
753
+ const db = await opened(url, token, refresh, false, key);
754
+ open = db;
755
+ settled(true);
756
+ return db;
757
+ } catch (error) {
758
+ const now = changed;
759
+ if (now) {
760
+ if (now.token === null) {
761
+ settled(false, now.error);
762
+ return anonymous();
763
+ }
764
+ token = now.token;
765
+ asked = 0;
766
+ continue;
767
+ }
768
+ if (!(error instanceof DatabaseError && error.code === "unauthenticated")) throw error;
769
+ settled(false, error);
770
+ return anonymous();
771
+ }
772
+ }
773
+ }
774
+ };
775
+ /** Where `auth.handler` gives a page the database's address and, for someone signed in, their token. */
776
+ const DATABASE_TOKEN_PATH = "/api/auth/database-token";
777
+ /**
778
+ * In the browser of an app whose users sign in with Auth: the database as whoever is signed in, with no key and no
779
+ * route of your own. The database's address and the user's ten-minute token come from your server's `auth.handler`
780
+ * (`GET /api/auth/database-token`), asked again before the token runs out, so it follows a preview's own copy of the
781
+ * database and the local one under `midsummer dev`. Someone not signed in connects as no one. `<AuthProvider
782
+ * database>` makes one and calls `signedInChanged()` for you; elsewhere, call it after a sign-in or a sign-out.
783
+ *
784
+ * const db = signedInDatabase()
785
+ * const notes = await db.query(api.notes.list, {})
786
+ *
787
+ * `url` is where the route is, when your server is on another address: `https://app.example.com/api/auth/database-token`.
788
+ */
789
+ function signedInDatabase(options = {}) {
790
+ const at = options.url ?? "/api/auth/database-token";
791
+ const send = options.fetch ?? ((url, init) => fetch(url, init));
792
+ let given = null;
793
+ const read = async () => {
794
+ const response = await send(at, {
795
+ credentials: "include",
796
+ headers: { accept: "application/json" }
797
+ }).catch(() => void 0);
798
+ if (!response) throw new DatabaseError("unavailable", `Couldn't reach ${at} for the database's address.`);
799
+ const answer = await response.json().catch(() => void 0);
800
+ if (!response.ok || typeof answer?.url !== "string") throw new DatabaseError("unavailable", typeof answer?.message === "string" ? answer.message : `${at} returned ${response.status} and no database address. Serve it with auth.handler on /api/auth/*.`);
801
+ return {
802
+ url: answer.url,
803
+ ...typeof answer.token === "string" ? { token: answer.token } : {}
804
+ };
805
+ };
806
+ const ask = (fresh) => {
807
+ if (fresh || !given) {
808
+ const asked = read();
809
+ given = asked;
810
+ asked.catch(() => {
811
+ if (given === asked) given = null;
812
+ });
813
+ }
814
+ return given;
815
+ };
816
+ const fetchToken = async ({ forceRefreshToken }) => (await ask(forceRefreshToken)).token ?? null;
817
+ const client = new DatabaseClient(async () => (await ask(false)).url, fetchToken);
818
+ client.signedInChanged = () => {
819
+ given = null;
820
+ client.setAuth(fetchToken);
821
+ };
822
+ return client;
823
+ }
824
+ /** The errors an Auth0 client throws when no one is signed in, which mean no token rather than a failure. */
825
+ const SIGNED_OUT = /* @__PURE__ */ new Set([
826
+ "login_required",
827
+ "consent_required",
828
+ "interaction_required",
829
+ "missing_refresh_token"
830
+ ]);
831
+ /**
832
+ * Auth0: the signed-in user's ID token, whose `aud` is your application's client ID, the `applicationID`
833
+ * `db/auth.config.ts` names beside your tenant's `domain`. Give it auth0-react's `getAccessTokenSilently`, or
834
+ * auth0-spa-js's `client.getTokenSilently.bind(client)`.
835
+ *
836
+ * db.setAuth(auth0(getAccessTokenSilently))
837
+ */
838
+ function auth0(getTokenSilently) {
839
+ return async ({ forceRefreshToken }) => {
840
+ let answer;
841
+ try {
842
+ answer = await getTokenSilently({
843
+ detailedResponse: true,
844
+ cacheMode: forceRefreshToken ? "off" : "on"
845
+ });
846
+ } catch (error) {
847
+ if (SIGNED_OUT.has(String(error?.error))) return null;
848
+ throw error;
849
+ }
850
+ const token = answer?.id_token;
851
+ return typeof token === "string" && token ? token : null;
852
+ };
853
+ }
854
+ /**
855
+ * Clerk: a token of the JWT template `template`, which sets `aud` to the `applicationID` `db/auth.config.ts`
856
+ * names beside your Clerk issuer (its Frontend API address). Give it clerk-react's `useAuth().getToken`, or
857
+ * clerk-js's `clerk.session.getToken`.
858
+ *
859
+ * db.setAuth(clerk(getToken, { template: "midsummer" }))
860
+ */
861
+ function clerk(getToken, options = {}) {
862
+ return async ({ forceRefreshToken }) => await getToken({
863
+ ...options.template ? { template: options.template } : {},
864
+ skipCache: forceRefreshToken
865
+ }) || null;
866
+ }
867
+ /**
868
+ * Any OIDC sign-in: `getToken` returns the user's ID token (a new one when `forceRefresh`), or null when no one
869
+ * is signed in. With oidc-client-ts:
870
+ *
871
+ * db.setAuth(oidc(async (fresh) => (fresh ? await manager.signinSilent() : await manager.getUser())?.id_token))
872
+ */
873
+ function oidc(getToken) {
874
+ return async ({ forceRefreshToken }) => await getToken(forceRefreshToken) || null;
875
+ }
876
+ //#endregion
877
+ export { connect as a, signedInDatabase as c, clerk as i, userToken as l, DatabaseClient as n, databaseUrl as o, auth0 as r, oidc as s, DATABASE_TOKEN_PATH as t };