@midsummer-ai/sdk 0.1.0-staging.3608 → 0.1.0-staging.3620

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.
@@ -1,3 +1,6 @@
1
+ import { n as bytesTagged, r as bytesUntagged } from "./bytes-C2pcyl9u.mjs";
2
+ import { DatabaseError } from "./database/errors.mjs";
3
+ import { t as callKey } from "./key-BrRdFY-n.mjs";
1
4
  //#region src/database/client/policy.mjs
2
5
  /** The platform's prices in USD, per unit named: an object request, a WebSocket message (billed 20:1 as requests), a SQL row
3
6
  * written, an object awake second (128 MB at $12.50 per million GB-s), a server CPU ms, a server request. And two
@@ -409,8 +412,8 @@ var Connection = class Connection {
409
412
  ...options,
410
413
  shape
411
414
  };
412
- if (o.store === void 0 && typeof indexedDB !== "undefined" && typeof document !== "undefined") o.store = (await import("./store-CsBhnabU.mjs")).idbStore(new URL(url).host);
413
- if (o.tabs !== false && typeof document !== "undefined") return (await import("./tabs-gHJHkhm2.mjs")).ConnectionTabs.connect(url, o);
415
+ if (o.store === void 0 && typeof indexedDB !== "undefined" && typeof document !== "undefined") o.store = (await import("./store-dsVD9VnM.mjs")).idbStore(new URL(url).host);
416
+ if (o.tabs !== false && typeof document !== "undefined") return (await import("./tabs-C85sXTwS.mjs")).ConnectionTabs.connect(url, o);
414
417
  return Connection.open(url, o);
415
418
  }
416
419
  /** A Connection over one socket, of the shape given (default "browser"), no detection (tabs.mjs opens its own so). */
@@ -2009,4 +2012,666 @@ var Connection = class Connection {
2009
2012
  }
2010
2013
  };
2011
2014
  //#endregion
2012
- export { payloadOf as i, TAG_TTL as n, fetchAt as r, Connection as t };
2015
+ //#region src/database/client.ts
2016
+ /**
2017
+ * `@midsummer-ai/sdk/database`: a Project's Database, from its app or its server.
2018
+ *
2019
+ * import { connect } from "@midsummer-ai/sdk/database"
2020
+ * import { api } from "../db/_generated/api"
2021
+ *
2022
+ * const db = await connect({ url, token, refresh })
2023
+ * const id = await db.mutation(api.messages.send, { channel: "general", body: "hi" })
2024
+ * const stop = db.watch(api.messages.list, { channel: "general" }, (messages) => render(messages))
2025
+ *
2026
+ * Name a Database by the name its Environment binds it under, and no key is kept anywhere. The same
2027
+ * call works in a Deployment's server, whatever framework serves it, where the request's own handle
2028
+ * proves it; in a CI run or an Agent's run, where the run's Workload token does; and under
2029
+ * `midsummer dev`, where every binding reaches the Database's Stand-in.
2030
+ *
2031
+ * const db = await connect({ binding: "main" })
2032
+ *
2033
+ * A server on Midsummer's own contract is also handed the handle as `context.database`:
2034
+ *
2035
+ * const db = await connect({ database: context.database, binding: "main" })
2036
+ *
2037
+ * From code outside Midsummer, a Database Key is enough: it is exchanged for a token, and again
2038
+ * before that token runs out.
2039
+ *
2040
+ * const db = await connect({ key: process.env.DATABASE_KEY! })
2041
+ *
2042
+ * One connection carries every call. A mutation is tagged, so one sent again after a lost
2043
+ * connection applies once; a watch is given its value now and again after every change. Every
2044
+ * refusal is a `DatabaseError` whose `code`, a `DatabaseErrorCode`, tells you why; a connection the
2045
+ * Database refuses is `unauthenticated`, with its reason.
2046
+ *
2047
+ * In an app whose users sign in with Auth0, Clerk or another OIDC provider, make the client once, at
2048
+ * once, and hand it the provider's token as `db/auth.config.ts` trusts it. It connects as no one until
2049
+ * then (where the Database admits anonymous callers), and again whenever the token changes:
2050
+ *
2051
+ * const db = new DatabaseClient(url)
2052
+ * db.setAuth(auth0(getAccessTokenSilently), (signedIn) => render(signedIn))
2053
+ * db.setAuth(clerk(getToken, { template: "midsummer" }))
2054
+ * db.clearAuth() // signed out
2055
+ */
2056
+ const API = "https://api.midsummer.new";
2057
+ /** A token and the Database's address, from the platform, for a key (as one of the app's users with `as`) or for a run's binding. */
2058
+ async function exchange(api, proof) {
2059
+ const response = await fetch(`${api}/v1/db/tokens`, {
2060
+ method: "POST",
2061
+ headers: { "Content-Type": "application/json" },
2062
+ body: JSON.stringify(typeof proof === "string" ? { key: proof } : proof)
2063
+ });
2064
+ const answer = await response.json().catch(() => ({}));
2065
+ if (!response.ok || !answer.token || !answer.url) throw new DatabaseError("denied", answer.error ?? `The database key was refused (${response.status}).`);
2066
+ return {
2067
+ token: answer.token,
2068
+ url: answer.url,
2069
+ ...typeof answer.expiresAt === "number" ? { expiresAt: answer.expiresAt } : {}
2070
+ };
2071
+ }
2072
+ /**
2073
+ * A token for one signed-in user of your app, for your server to hand to that user's browser, which connects with
2074
+ * it (`@midsummer-ai/sdk/react`'s `DatabaseProvider`, or `connect({ url, token, refresh })`). Your server keeps the
2075
+ * database key and identifies the user by your own id for them; your functions see that id as `ctx.auth.subject`. The
2076
+ * token runs public functions only, and only queries for a `read` key. It lasts ten minutes: the browser asks your
2077
+ * server again before then.
2078
+ *
2079
+ * app.get("/db-token", async (c) => c.json(await userToken({ key: process.env.DATABASE_KEY!, as: session.userId })))
2080
+ */
2081
+ async function userToken(options) {
2082
+ const given = await exchange(options.api ?? API, {
2083
+ key: options.key,
2084
+ as: options.as
2085
+ });
2086
+ return {
2087
+ token: given.token,
2088
+ url: given.url,
2089
+ expiresAt: given.expiresAt ?? expiryOf(given.token)
2090
+ };
2091
+ }
2092
+ /**
2093
+ * A Database Key's token, exchanged once per process and kept until a minute before it expires, so a
2094
+ * server that connects on every request asks the platform once per key, and connects made at the same
2095
+ * time share one exchange. A refused exchange is forgotten at once.
2096
+ */
2097
+ const exchanged = /* @__PURE__ */ new Map();
2098
+ /** When a token stops working, from its `exp`; a token that says nothing is kept for a minute. */
2099
+ function expiryOf(token) {
2100
+ try {
2101
+ const payload = JSON.parse(atob(token.split(".")[1].replace(/-/gu, "+").replace(/_/gu, "/")));
2102
+ if (typeof payload.exp === "number") return payload.exp * 1e3;
2103
+ } catch {}
2104
+ return Date.now() + 12e4;
2105
+ }
2106
+ async function keyToken(api, key, fresh = false) {
2107
+ const id = `${api}|${key}`;
2108
+ const kept = fresh ? void 0 : exchanged.get(id);
2109
+ if (kept) {
2110
+ const got = await kept.catch(() => void 0);
2111
+ if (got && got.until > Date.now()) return got;
2112
+ }
2113
+ const asked = exchange(api, key).then((answer) => ({
2114
+ ...answer,
2115
+ until: expiryOf(answer.token) - 6e4
2116
+ }));
2117
+ exchanged.set(id, asked);
2118
+ asked.catch(() => {
2119
+ if (exchanged.get(id) === asked) exchanged.delete(id);
2120
+ });
2121
+ return asked;
2122
+ }
2123
+ const refusal = (answer) => new DatabaseError(answer?.why ?? answer?.err ?? "refused", answer?.error ?? answer?.why ?? "refused");
2124
+ const caught = (error) => error?.answer ?? {
2125
+ ok: false,
2126
+ why: error?.code ?? "refused",
2127
+ error: error?.message
2128
+ };
2129
+ const told = (listener, outcome) => "error" in outcome ? listener.onError?.(outcome.error) : listener.onValue(outcome.value);
2130
+ /** Why the Database refused a connection, from the reason it gives at the socket's address over HTTP; null when it gave none. */
2131
+ async function refusalAt(url, token) {
2132
+ try {
2133
+ const response = await fetchAt(`${url.replace(/^ws/u, "http").replace(/\/+$/u, "")}/ws?token=${encodeURIComponent(token ?? "")}`, { signal: AbortSignal.timeout(1e4) });
2134
+ if (response.ok) return null;
2135
+ const body = await response.json().catch(() => ({}));
2136
+ const why = typeof body.why === "string" ? body.why : `the database refused the connection (${response.status})`;
2137
+ if (response.status === 401 || body.error === "unauthenticated") return new DatabaseError("unauthenticated", why);
2138
+ if (typeof body.error === "string") return new DatabaseError(response.status === 404 ? "unavailable" : body.error, why);
2139
+ return null;
2140
+ } catch {
2141
+ return null;
2142
+ }
2143
+ }
2144
+ /**
2145
+ * The claims a token's kept data is kept apart by: who they are, what they may do and when they signed in
2146
+ * (`auth_time`), every claim but those each renewal changes.
2147
+ */
2148
+ const RENEWED = /* @__PURE__ */ new Set([
2149
+ "exp",
2150
+ "iat",
2151
+ "nbf",
2152
+ "jti"
2153
+ ]);
2154
+ async function keyOf(token) {
2155
+ const claims = token ? payloadOf(token) : null;
2156
+ const kept = claims ? Object.keys(claims).filter((name) => !RENEWED.has(name)).sort().map((name) => [name, claims[name]]) : token ? [["token", token]] : [["anonymous"]];
2157
+ 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("");
2158
+ }
2159
+ async function verifiedAt(url, token) {
2160
+ try {
2161
+ const response = await fetchAt(`${url.replace(/^ws/u, "http").replace(/\/+$/u, "")}/ws?token=${encodeURIComponent(token ?? "")}`, { signal: AbortSignal.timeout(1e4) });
2162
+ const body = await response.json().catch(() => ({}));
2163
+ if (response.ok) {
2164
+ const named = token ? payloadOf(token)?.sub : void 0;
2165
+ if ((body.sub ?? void 0) !== named) return { unknown: true };
2166
+ return { accepted: await keyOf(token) };
2167
+ }
2168
+ if (response.status === 401 || body.error === "unauthenticated") return { refused: new DatabaseError("unauthenticated", typeof body.why === "string" ? body.why : "the database refused the token") };
2169
+ return { unknown: true };
2170
+ } catch {
2171
+ return { unknown: true };
2172
+ }
2173
+ }
2174
+ /**
2175
+ * In a page, the data kept across reloads (watched values and unsent writes) is one sign-in's alone: named by the
2176
+ * Database's host and `key`, the caller the Database took and when they signed in. No other caller, and no token
2177
+ * the Database refused, reads it; an unsent write is sent again only as the sign-in that made it. A connection
2178
+ * with a token never shares its socket with other tabs (`tabs: false`), so every call goes with its own tab's
2179
+ * token, its own claims and its own expiry; only callers with no token share one. A caller the Database could not
2180
+ * vouch for (`key` null) keeps nothing. Elsewhere nothing is shared or kept, so nothing is given.
2181
+ */
2182
+ async function isolation(url, key, token) {
2183
+ if (typeof globalThis.document === "undefined") return {};
2184
+ const own = token ? { tabs: false } : {};
2185
+ if (key === null) return {
2186
+ ...own,
2187
+ tabs: false,
2188
+ store: null
2189
+ };
2190
+ const name = `${new URL(url).host}#${key}`;
2191
+ if (typeof globalThis.indexedDB === "undefined") return {
2192
+ ...own,
2193
+ name
2194
+ };
2195
+ return {
2196
+ ...own,
2197
+ name,
2198
+ store: (await import("./store-dsVD9VnM.mjs")).idbStore(name)
2199
+ };
2200
+ }
2201
+ const inPage = () => typeof globalThis.document !== "undefined";
2202
+ async function connect(options) {
2203
+ let url, token, refresh;
2204
+ const server = !("url" in options);
2205
+ if ("database" in options) {
2206
+ const first = await options.database.token(options.binding);
2207
+ url = first.url;
2208
+ token = first.token;
2209
+ refresh = async () => (await options.database.token(options.binding)).token;
2210
+ } else if ("binding" in options) {
2211
+ const env = globalThis.process?.env ?? {};
2212
+ const here = globalThis[Symbol.for("midsummer.context")];
2213
+ const request = here?.();
2214
+ const bound = request?.database;
2215
+ if (request && !bound && !env.MIDSUMMER_DATABASE_URL) throw new DatabaseError("denied", `This address serves no environment, so no database is bound to it as ${options.binding}. A deployment's own address reaches no database: open the site at its environment's address, such as production's.`);
2216
+ if (bound) {
2217
+ const first = await bound.token(options.binding);
2218
+ url = first.url;
2219
+ token = first.token;
2220
+ refresh = async () => (await bound.token(options.binding)).token;
2221
+ } else if (env.MIDSUMMER_DATABASE_URL) {
2222
+ url = env.MIDSUMMER_DATABASE_URL;
2223
+ token = env.MIDSUMMER_DATABASE_TOKEN;
2224
+ } else {
2225
+ const workload = env.MIDSUMMER_IDENTITY_REQUEST_TOKEN, tokenUrl = env.MIDSUMMER_IDENTITY_TOKEN_URL;
2226
+ 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.");
2227
+ const api = options.api ?? new URL(tokenUrl).origin;
2228
+ const proof = {
2229
+ binding: options.binding,
2230
+ workload
2231
+ };
2232
+ const first = await exchange(api, proof);
2233
+ url = first.url;
2234
+ token = first.token;
2235
+ refresh = async () => (await exchange(api, proof)).token;
2236
+ }
2237
+ } else if ("key" in options) {
2238
+ const api = options.api ?? API;
2239
+ const first = await keyToken(api, options.key);
2240
+ url = first.url;
2241
+ token = first.token;
2242
+ refresh = async () => (await keyToken(api, options.key, true)).token;
2243
+ } else {
2244
+ url = options.url;
2245
+ token = options.token;
2246
+ refresh = options.refresh;
2247
+ }
2248
+ if (server || !inPage()) return opened(url, token, refresh, server, null);
2249
+ let seen = await verifiedAt(url, token);
2250
+ if ("refused" in seen && refresh) {
2251
+ token = await refresh();
2252
+ seen = await verifiedAt(url, token);
2253
+ }
2254
+ if ("refused" in seen) throw seen.refused;
2255
+ const key = "accepted" in seen ? seen.accepted : null;
2256
+ const expected = key ?? await keyOf(token);
2257
+ const renew = refresh;
2258
+ return opened(url, token, (renew && (async () => {
2259
+ const fresh = await renew();
2260
+ const again = await verifiedAt(url, fresh);
2261
+ if ("refused" in again) throw again.refused;
2262
+ 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");
2263
+ return fresh;
2264
+ })) ?? void 0, false, key);
2265
+ }
2266
+ /** A connection opened for `key`'s caller (null: one the Database did not vouch for), as `connect` describes it. */
2267
+ async function opened(url, token, refresh, server, key) {
2268
+ let connection;
2269
+ try {
2270
+ const apart = server ? {} : await isolation(url, key, token);
2271
+ connection = await Connection.connect(url, {
2272
+ ...token !== void 0 ? { token } : {},
2273
+ ...refresh ? { refresh } : {},
2274
+ ...server ? { shape: "server" } : {},
2275
+ ...apart
2276
+ });
2277
+ } catch (error) {
2278
+ throw await refusalAt(url, token) ?? error;
2279
+ }
2280
+ const call = (fn) => ({
2281
+ name: fn.name,
2282
+ kind: fn.kind
2283
+ });
2284
+ const sent = (args) => bytesTagged(args ?? {});
2285
+ const got = (value) => bytesUntagged(value);
2286
+ const watching = /* @__PURE__ */ new Map();
2287
+ return {
2288
+ async query(fn, ...[args]) {
2289
+ const value = await connection.query(call(fn), sent(args)).catch(caught);
2290
+ if (value && typeof value === "object" && !Array.isArray(value) && value.ok === false) throw refusal(value);
2291
+ return got(value);
2292
+ },
2293
+ async mutation(fn, ...[args, { tag } = {}]) {
2294
+ const answer = await connection.mutation(call(fn), sent(args), tag ? { tag } : {}).catch(caught);
2295
+ if (!answer?.ok) throw refusal(answer);
2296
+ return got(answer.value ?? null);
2297
+ },
2298
+ async action(fn, ...[args]) {
2299
+ const answer = await connection.mutation(call(fn), sent(args), {}).catch(caught);
2300
+ if (!answer?.ok) throw refusal(answer);
2301
+ return got(answer.value ?? null);
2302
+ },
2303
+ watch(fn, args, onValue, onError) {
2304
+ const key = callKey(fn.name, args);
2305
+ let shared = watching.get(key);
2306
+ if (!shared) {
2307
+ const it = {
2308
+ listeners: /* @__PURE__ */ new Set(),
2309
+ last: null,
2310
+ stop: () => {}
2311
+ };
2312
+ shared = it;
2313
+ watching.set(key, it);
2314
+ const tell = (outcome) => {
2315
+ it.last = outcome;
2316
+ for (const listener of [...it.listeners]) told(listener, outcome);
2317
+ };
2318
+ let asked = 0;
2319
+ it.stop = connection.watchQuery(call(fn), sent(args), {}, (value, meta, item) => {
2320
+ if (value !== void 0) {
2321
+ tell({ value: got(value) });
2322
+ return;
2323
+ }
2324
+ const held = item?.ok === false ? item : meta?.error;
2325
+ if (held) {
2326
+ tell({ error: refusal(held) });
2327
+ return;
2328
+ }
2329
+ const n = asked += 1;
2330
+ connection.query(call(fn), sent(args)).catch(caught).then((answer) => {
2331
+ if (n !== asked || watching.get(key) !== it) return;
2332
+ if (answer && typeof answer === "object" && !Array.isArray(answer) && answer.ok === false) tell({ error: refusal(answer) });
2333
+ else tell({ value: got(answer ?? null) });
2334
+ });
2335
+ });
2336
+ }
2337
+ const it = shared, listener = {
2338
+ onValue,
2339
+ ...onError ? { onError } : {}
2340
+ };
2341
+ it.listeners.add(listener);
2342
+ if (it.last) told(listener, it.last);
2343
+ return () => {
2344
+ it.listeners.delete(listener);
2345
+ if (it.listeners.size || watching.get(key) !== it) return;
2346
+ watching.delete(key);
2347
+ it.stop();
2348
+ };
2349
+ },
2350
+ close() {
2351
+ connection.close();
2352
+ }
2353
+ };
2354
+ }
2355
+ /**
2356
+ * A Database for an app whose users sign in with their own provider: made at once (`new DatabaseClient(url)`),
2357
+ * connected on first use or on `setAuth`, and connected again, its watches with it, whenever the sign-in
2358
+ * changes. A token the Database refuses (or a `fetchToken` that throws) leaves the client connected as no one,
2359
+ * and `onChange(false)` tells the app. The client keeps one connection; `close()` ends it.
2360
+ */
2361
+ var DatabaseClient = class {
2362
+ #url;
2363
+ #current = null;
2364
+ #fetchToken = null;
2365
+ #onChange = null;
2366
+ #state = {
2367
+ isLoading: false,
2368
+ isAuthenticated: false
2369
+ };
2370
+ #listeners = /* @__PURE__ */ new Set();
2371
+ #watches = /* @__PURE__ */ new Set();
2372
+ #generation = 0;
2373
+ #closed = false;
2374
+ /** `url`: where the Database serves, as `midsummer db show` gives it, or the development server's address. */
2375
+ constructor(url) {
2376
+ if (typeof url !== "string" || !/^(?:https?|wss?):\/\//u.test(url)) throw new TypeError(`new DatabaseClient(url): an http(s) address, not ${JSON.stringify(url)}`);
2377
+ this.#url = url;
2378
+ }
2379
+ /** Signs in with the tokens `fetchToken` gives, now and whenever one is about to expire; `onChange` hears whether the Database took them. */
2380
+ setAuth(fetchToken, onChange) {
2381
+ this.#fetchToken = fetchToken;
2382
+ this.#onChange = onChange ?? null;
2383
+ this.#reopen(true);
2384
+ }
2385
+ /** Signs out: the client connects again as no one. */
2386
+ clearAuth() {
2387
+ this.#fetchToken = null;
2388
+ this.#onChange = null;
2389
+ this.#reopen(false);
2390
+ }
2391
+ /** Whether the client is signed in, and whether that is still being decided. */
2392
+ get authState() {
2393
+ return this.#state;
2394
+ }
2395
+ /** Hears every change of `authState`; returns a stop. */
2396
+ onAuthChange(listener) {
2397
+ this.#listeners.add(listener);
2398
+ return () => {
2399
+ this.#listeners.delete(listener);
2400
+ };
2401
+ }
2402
+ query(fn, args) {
2403
+ return this.#db().then((db) => db.query(fn, args));
2404
+ }
2405
+ mutation(fn, args, options) {
2406
+ return this.#db().then((db) => db.mutation(fn, args, options));
2407
+ }
2408
+ action(fn, args) {
2409
+ return this.#db().then((db) => db.action(fn, args));
2410
+ }
2411
+ /** 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. */
2412
+ watch(fn, args, onValue, onError) {
2413
+ const watched = {
2414
+ fn,
2415
+ args,
2416
+ onValue,
2417
+ ...onError ? { onError } : {},
2418
+ stop: () => {}
2419
+ };
2420
+ this.#watches.add(watched);
2421
+ this.#subscribe(watched, this.#db());
2422
+ return () => {
2423
+ this.#watches.delete(watched);
2424
+ watched.stop();
2425
+ };
2426
+ }
2427
+ close() {
2428
+ this.#closed = true;
2429
+ for (const watched of this.#watches) watched.stop();
2430
+ this.#watches.clear();
2431
+ const current = this.#current;
2432
+ this.#current = null;
2433
+ current?.then((db) => db.close(), () => {});
2434
+ }
2435
+ #db() {
2436
+ if (this.#closed) return Promise.reject(new DatabaseError("unavailable", "this client was closed"));
2437
+ if (!this.#current) {
2438
+ const opening = this.#open();
2439
+ this.#current = opening;
2440
+ opening.catch(() => {
2441
+ if (this.#current === opening) this.#current = null;
2442
+ });
2443
+ }
2444
+ return this.#current;
2445
+ }
2446
+ #subscribe(watched, db) {
2447
+ let stopped = false, stop = () => {};
2448
+ watched.stop = () => {
2449
+ stopped = true;
2450
+ stop();
2451
+ };
2452
+ db.then((open) => {
2453
+ if (!stopped) stop = open.watch(watched.fn, watched.args, watched.onValue, watched.onError);
2454
+ }, (error) => {
2455
+ if (!stopped) watched.onError?.(error instanceof DatabaseError ? error : new DatabaseError("unavailable", String(error)));
2456
+ });
2457
+ }
2458
+ #tell(state) {
2459
+ this.#state = state;
2460
+ for (const listener of [...this.#listeners]) listener(state);
2461
+ }
2462
+ /**
2463
+ * Connects again for the sign-in as it is now, moving every watch to the new connection. The old connection is
2464
+ * closed at once, not once the new one opens: nothing more is sent on it, and what it still held unanswered is
2465
+ * dropped with it (in a page, its kept copy stays under its own sign-in, sent again only as that sign-in).
2466
+ */
2467
+ #reopen(signingIn) {
2468
+ if (this.#closed) return;
2469
+ this.#generation += 1;
2470
+ const previous = this.#current;
2471
+ this.#current = null;
2472
+ previous?.then((db) => db.close(), () => {});
2473
+ this.#tell({
2474
+ isLoading: signingIn,
2475
+ isAuthenticated: false
2476
+ });
2477
+ const next = this.#db();
2478
+ for (const watched of this.#watches) {
2479
+ watched.stop();
2480
+ this.#subscribe(watched, next);
2481
+ }
2482
+ }
2483
+ /**
2484
+ * Opens a connection for the sign-in as it is now. The Database checks each token before anything is opened or
2485
+ * renewed with it (`verifiedAt`). A refused first token is asked for anew once. A renewal that brings no one, a
2486
+ * refused token or another account ends this connection at once, before anything more is sent on it; while the
2487
+ * first open is still being made, it is abandoned and made again for whoever the new token names.
2488
+ */
2489
+ async #open() {
2490
+ const generation = this.#generation, fetchToken = this.#fetchToken, onChange = this.#onChange, url = this.#url;
2491
+ const anonymous = () => connect({ url });
2492
+ if (!fetchToken) return anonymous();
2493
+ const settled = (isAuthenticated, error) => {
2494
+ if (generation !== this.#generation) return;
2495
+ this.#tell({
2496
+ isLoading: false,
2497
+ isAuthenticated
2498
+ });
2499
+ onChange?.(isAuthenticated, error);
2500
+ };
2501
+ let token;
2502
+ try {
2503
+ token = await fetchToken({ forceRefreshToken: false });
2504
+ } catch (error) {
2505
+ settled(false, error);
2506
+ return anonymous();
2507
+ }
2508
+ for (let asked = 0;; asked += 1) {
2509
+ if (!token) {
2510
+ settled(false);
2511
+ return anonymous();
2512
+ }
2513
+ const seen = await verifiedAt(url, token);
2514
+ if ("refused" in seen) {
2515
+ if (asked > 0) {
2516
+ settled(false, seen.refused);
2517
+ return anonymous();
2518
+ }
2519
+ try {
2520
+ token = await fetchToken({ forceRefreshToken: true });
2521
+ } catch (error) {
2522
+ settled(false, error);
2523
+ return anonymous();
2524
+ }
2525
+ continue;
2526
+ }
2527
+ const key = "accepted" in seen ? seen.accepted : null;
2528
+ const expected = key ?? await keyOf(token);
2529
+ let open = null;
2530
+ /** What a renewal brought while the first open was being made: the open is abandoned for it. */
2531
+ let changed = null;
2532
+ /** Set once this connection's sign-in has ended: no renewal of it gives a token again. */
2533
+ let ended = false;
2534
+ const client = this;
2535
+ /**
2536
+ * This connection's sign-in has ended. The connection is closed whatever has happened since; only the telling,
2537
+ * and connecting again, wait on this sign-in still being the client's.
2538
+ */
2539
+ const leave = (next, error) => {
2540
+ ended = true;
2541
+ open?.close();
2542
+ if (generation !== client.#generation) return;
2543
+ if (next === "signed out") {
2544
+ settled(false, error);
2545
+ client.#fetchToken = null;
2546
+ }
2547
+ client.#reopen(next === "another account");
2548
+ };
2549
+ const over = () => ended || generation !== client.#generation;
2550
+ const stop = (connection, why, error) => {
2551
+ ended = true;
2552
+ connection?.close?.();
2553
+ throw error ?? new DatabaseError("unauthenticated", why);
2554
+ };
2555
+ /**
2556
+ * A renewal, as the connection asks for one (`this` is the connection). It never gives a token once this sign-in
2557
+ * has ended or the client has moved on, not even an empty one: it closes the connection and throws, so nothing
2558
+ * it still holds is sent again as anyone else.
2559
+ */
2560
+ const refresh = async function() {
2561
+ if (over()) return stop(this, "this connection's sign-in has ended");
2562
+ let fresh;
2563
+ try {
2564
+ fresh = await fetchToken({ forceRefreshToken: true });
2565
+ } catch (error) {
2566
+ if (!open) {
2567
+ changed = {
2568
+ token: null,
2569
+ error
2570
+ };
2571
+ return stop(this, "signed out", error);
2572
+ }
2573
+ leave("signed out", error);
2574
+ return stop(this, "signed out", error);
2575
+ }
2576
+ if (over()) return stop(this, "this connection's sign-in has ended");
2577
+ const again = fresh ? await verifiedAt(url, fresh) : null;
2578
+ if (over()) return stop(this, "this connection's sign-in has ended");
2579
+ if (!fresh || again && "refused" in again) {
2580
+ const error = again && "refused" in again ? again.refused : void 0;
2581
+ if (!open) {
2582
+ changed = {
2583
+ token: null,
2584
+ error
2585
+ };
2586
+ return stop(this, "signed out", error);
2587
+ }
2588
+ leave("signed out", error);
2589
+ return stop(this, "signed out", error);
2590
+ }
2591
+ if ((again && "accepted" in again ? again.accepted : await keyOf(fresh)) !== expected) {
2592
+ if (!open) {
2593
+ changed = { token: fresh };
2594
+ return stop(this, "another account");
2595
+ }
2596
+ leave("another account");
2597
+ return stop(this, "another account");
2598
+ }
2599
+ return fresh;
2600
+ };
2601
+ try {
2602
+ const db = await opened(url, token, refresh, false, key);
2603
+ open = db;
2604
+ settled(true);
2605
+ return db;
2606
+ } catch (error) {
2607
+ const now = changed;
2608
+ if (now) {
2609
+ if (now.token === null) {
2610
+ settled(false, now.error);
2611
+ return anonymous();
2612
+ }
2613
+ token = now.token;
2614
+ asked = 0;
2615
+ continue;
2616
+ }
2617
+ if (!(error instanceof DatabaseError && error.code === "unauthenticated")) throw error;
2618
+ settled(false, error);
2619
+ return anonymous();
2620
+ }
2621
+ }
2622
+ }
2623
+ };
2624
+ /** The errors an Auth0 client throws when no one is signed in, which mean no token rather than a failure. */
2625
+ const SIGNED_OUT = /* @__PURE__ */ new Set([
2626
+ "login_required",
2627
+ "consent_required",
2628
+ "interaction_required",
2629
+ "missing_refresh_token"
2630
+ ]);
2631
+ /**
2632
+ * Auth0: the signed-in user's ID token, whose `aud` is your application's client ID, the `applicationID`
2633
+ * `db/auth.config.ts` names beside your tenant's `domain`. Give it auth0-react's `getAccessTokenSilently`, or
2634
+ * auth0-spa-js's `client.getTokenSilently.bind(client)`.
2635
+ *
2636
+ * db.setAuth(auth0(getAccessTokenSilently))
2637
+ */
2638
+ function auth0(getTokenSilently) {
2639
+ return async ({ forceRefreshToken }) => {
2640
+ let answer;
2641
+ try {
2642
+ answer = await getTokenSilently({
2643
+ detailedResponse: true,
2644
+ cacheMode: forceRefreshToken ? "off" : "on"
2645
+ });
2646
+ } catch (error) {
2647
+ if (SIGNED_OUT.has(String(error?.error))) return null;
2648
+ throw error;
2649
+ }
2650
+ const token = answer?.id_token;
2651
+ return typeof token === "string" && token ? token : null;
2652
+ };
2653
+ }
2654
+ /**
2655
+ * Clerk: a token of the JWT template `template`, which sets `aud` to the `applicationID` `db/auth.config.ts`
2656
+ * names beside your Clerk issuer (its Frontend API address). Give it clerk-react's `useAuth().getToken`, or
2657
+ * clerk-js's `clerk.session.getToken`.
2658
+ *
2659
+ * db.setAuth(clerk(getToken, { template: "midsummer" }))
2660
+ */
2661
+ function clerk(getToken, options = {}) {
2662
+ return async ({ forceRefreshToken }) => await getToken({
2663
+ ...options.template ? { template: options.template } : {},
2664
+ skipCache: forceRefreshToken
2665
+ }) || null;
2666
+ }
2667
+ /**
2668
+ * Any OIDC sign-in: `getToken` returns the user's ID token (a new one when `forceRefresh`), or null when no one
2669
+ * is signed in. With oidc-client-ts:
2670
+ *
2671
+ * db.setAuth(oidc(async (fresh) => (fresh ? await manager.signinSilent() : await manager.getUser())?.id_token))
2672
+ */
2673
+ function oidc(getToken) {
2674
+ return async ({ forceRefreshToken }) => await getToken(forceRefreshToken) || null;
2675
+ }
2676
+ //#endregion
2677
+ export { oidc as a, TAG_TTL as c, connect as i, auth0 as n, userToken as o, clerk as r, Connection as s, DatabaseClient as t };