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