@midsummer-ai/sdk 0.1.0-next.900 → 0.1.0-staging.3100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/auth-1W-SzpD3.mjs +441 -0
  2. package/build-DQo-JrlN.d.mts +120 -0
  3. package/bytes-C2pcyl9u.mjs +280 -0
  4. package/{connection-CDk7H1FL.mjs → connection-Cu2GSOaR.mjs} +171 -31
  5. package/database/build.d.mts +2 -2
  6. package/database/build.mjs +1404 -117
  7. package/database/client.d.mts +85 -9
  8. package/database/client.mjs +550 -32
  9. package/database/contract.d.mts +92 -2
  10. package/database/contract.mjs +2179 -3
  11. package/database/errors.d.mts +1 -22
  12. package/database/react.d.mts +133 -0
  13. package/database/react.mjs +488 -0
  14. package/database/server.d.mts +2 -3
  15. package/database/server.mjs +3 -320
  16. package/database/stand-in.d.mts +95 -9
  17. package/database/stand-in.mjs +1436 -116
  18. package/errors-x2vXKi0u.d.mts +25 -0
  19. package/index-DNNXNny7.d.mts +410 -0
  20. package/key-BrRdFY-n.mjs +11 -0
  21. package/package.json +114 -1
  22. package/schema-CTHQMRsW.mjs +217 -0
  23. package/server-B5HK2Ou9.d.mts +574 -0
  24. package/server-EDRbF2u-.mjs +1893 -0
  25. package/{store-BzI9at5x.mjs → store-lIZ5GxVv.mjs} +1 -1
  26. package/{tabs-D-P8_ci_.mjs → tabs-zCh8kceo.mjs} +1 -1
  27. package/vector/contract.d.mts +1 -1
  28. package/vector/contract.mjs +773 -1
  29. package/vector/index.d.mts +2 -2
  30. package/vector/index.mjs +71 -3
  31. package/vector/stand-in.d.mts +1 -1
  32. package/vector/stand-in.mjs +326 -23
  33. package/vector/wire.d.mts +11 -2
  34. package/vector/wire.mjs +179 -14
  35. package/build-SQ44jwSa.d.mts +0 -41
  36. package/index-DdoK0y7D.d.mts +0 -192
  37. package/schema-BF-Y1EVu.mjs +0 -142
  38. package/schema-DS8x1Dn8.mjs +0 -115
  39. package/schema-f7E9uzUn.d.mts +0 -74
  40. package/server-C7O7CICU.d.mts +0 -182
@@ -1,320 +1,3 @@
1
- import { a as shapeError, i as indexFields, n as defineSchema, o as v, r as defineTable, t as TABLE } from "../schema-BF-Y1EVu.mjs";
2
- //#region src/database/server.ts
3
- /**
4
- * `@midsummer-ai/sdk/server`: what a Project's `db/` functions are written with. Each file of `db/` is
5
- * a module of functions, each export a function named `<file>.<export>`, referred to by the client
6
- * as `api.<file>.<export>`:
7
- *
8
- * import { mutation, query, v } from "./_generated/server"
9
- *
10
- * export const send = mutation({
11
- * args: { channel: v.string(), body: v.string() },
12
- * handler: async (ctx, { channel, body }) => ctx.db.messages.insert({ channel, body }),
13
- * })
14
- * export const list = query({
15
- * args: { channel: v.string() },
16
- * handler: async (ctx, { channel }) => ctx.db.messages.range("by_channel", "channel", { eq: channel }).rows,
17
- * })
18
- *
19
- * `./_generated/server` is this module typed by the Project's schema; `db/schema.ts` is
20
- * `export default defineSchema({ ... })`.
21
- *
22
- * You write what you mean, and the Database does the concurrency. A query reads rows and never writes them;
23
- * watched, it is run again when anything it read changes. A mutation is one serializable step: its
24
- * reads see the rows as they are, its writes are saved together or not at all, and it is run again when
25
- * a row it read changed, so there is no conflict to handle and no retry loop. A mutation sent again
26
- * under the same call tag applies once. Neither sees a clock, the network or randomness: `ctx.now`
27
- * is the call's own time, and its body may run more than once. An action may wait on the network
28
- * (`ctx.fetch`, https only); its writes are the mutations it runs with `ctx.run`.
29
- *
30
- * ctx.db.<table>: get(id), range(index, field, { eq, gte, gt, lte, lt, order, limit }), where
31
- * index "" is the table's own order by id; in a mutation also insert(doc) (its id at once),
32
- * patch(id, fields) (a field's value may be `increment(n)`, `take(n)` or `give(n)`),
33
- * replace(id, doc) and delete(id). A document is `{ _id, _version, ...fields }`.
34
- * ctx.auth: the signed-in caller, `{ subject, issuer }`, or null.
35
- * ctx.scheduler: runAfter(ms, fn, args), runAt(time, fn, args), status(id), cancel(id).
36
- * cron: "minute hour day month weekday" (UTC) on a mutation or an action runs it on a schedule.
37
- */
38
- const FUNCTION = /^[A-Za-z][A-Za-z0-9_]{0,63}(?:\.[A-Za-z][A-Za-z0-9_]{0,63})?$/u;
39
- function defineFunction(name, handler, options) {
40
- if (name !== null && (typeof name !== "string" || !FUNCTION.test(name))) throw new TypeError("a function's name: [A-Za-z][A-Za-z0-9_]{0,63}");
41
- const { kind, args = null, returns = null, internal = false, cron = null } = options;
42
- if (args !== null && (typeof args !== "object" || Array.isArray(args))) throw new TypeError(`${name}: args is an object of shapes (v.string(), ...)`);
43
- if (cron !== null && (kind === "query" || typeof cron !== "string" || cron.trim().split(/\s+/u).length !== 5 || !/^[0-9*/,\- ]{9,100}$/u.test(cron.trim()))) throw new TypeError(`${name}: cron is "minute hour day month weekday" (a mutation or an action)`);
44
- return Object.freeze({
45
- name,
46
- handler,
47
- options: Object.freeze({
48
- kind,
49
- args: args && Object.freeze({ object: args }),
50
- returns,
51
- internal: internal === true,
52
- cron: cron && cron.trim()
53
- })
54
- });
55
- }
56
- const OPERATOR = Symbol("operator");
57
- function operator(kind, n) {
58
- if (!Number.isFinite(n) || n < 0) throw new TypeError(`${kind}(n): n is a number of at least 0`);
59
- return Object.freeze({
60
- [OPERATOR]: kind,
61
- n
62
- });
63
- }
64
- /** A field's value plus `n` (a field not yet there counts as 0). */
65
- const increment = (n = 1) => operator("increment", n);
66
- /** A field's value minus `n`; below zero the whole mutation fails with `InsufficientError` and writes nothing. */
67
- const take = (n = 1) => operator("take", n);
68
- /** A field's value plus `n`: the inverse of `take`. */
69
- const give = (n = 1) => operator("give", n);
70
- /** A `take` asked for more than the field holds: the mutation wrote nothing. */
71
- var InsufficientError = class extends Error {
72
- detail;
73
- constructor(detail) {
74
- super(`not enough ${detail.table}.${detail.field}: has ${detail.has}, asked ${detail.asked}`);
75
- this.detail = detail;
76
- this.name = "InsufficientError";
77
- }
78
- };
79
- /** A mutation patched or replaced a row that is not there. */
80
- var NotFoundError = class extends Error {
81
- detail;
82
- constructor(detail) {
83
- super(`no ${detail.table} row ${detail.id}`);
84
- this.detail = detail;
85
- this.name = "NotFoundError";
86
- }
87
- };
88
- /** A call the Database refused: `why` is its reason, as the client's `DatabaseError` carries it. */
89
- var Refusal = class extends Error {
90
- why;
91
- detail;
92
- constructor(why, message, detail) {
93
- super(message);
94
- this.why = why;
95
- this.detail = detail;
96
- this.name = "Refusal";
97
- }
98
- };
99
- const documentOf = (id, row) => {
100
- if (row === null || row === void 0) return null;
101
- const fields = Object.fromEntries(Object.entries(row).filter(([key]) => !key.startsWith("_")));
102
- return Object.freeze({
103
- ...fields,
104
- _id: id,
105
- _version: Number(row._version ?? 0)
106
- });
107
- };
108
- const fieldsOf = (doc) => Object.fromEntries(Object.entries(doc ?? {}).filter(([key]) => !key.startsWith("_")));
109
- function applied(current, value, where) {
110
- if (value === null || typeof value !== "object" || !(OPERATOR in value)) return value;
111
- const op = value;
112
- const has = current === void 0 || current === null ? 0 : Number(current);
113
- if (!Number.isFinite(has)) throw new TypeError(`${where.table}.${where.field} is not a number: ${op[OPERATOR]}() needs one`);
114
- if (op[OPERATOR] === "take") {
115
- if (has - op.n < 0) throw new InsufficientError({
116
- ...where,
117
- has,
118
- asked: op.n
119
- });
120
- return has - op.n;
121
- }
122
- return has + op.n;
123
- }
124
- function tablesOf(make) {
125
- const cache = /* @__PURE__ */ new Map();
126
- const table = (name) => {
127
- if (typeof name !== "string" || !TABLE.test(name)) throw new TypeError(`a table name: ${JSON.stringify(name)}`);
128
- if (!cache.has(name)) cache.set(name, make(name));
129
- return cache.get(name);
130
- };
131
- return new Proxy(Object.freeze({ table }), { get: (target, key) => key in target || typeof key !== "string" ? target[key] : table(key) });
132
- }
133
- const boundsOf = (options = {}) => ({
134
- ...options.eq === void 0 ? {} : { eq: [options.eq] },
135
- gte: options.gte,
136
- gt: options.gt,
137
- lte: options.lte,
138
- lt: options.lt,
139
- ...options.order ? { order: options.order } : {},
140
- limit: options.limit ?? 1e3
141
- });
142
- const rangeOf = (rows, name, index, _field, options) => ({
143
- ok: true,
144
- rows: rows.range(name, index || "_id", boundsOf(options)).map((row) => documentOf(row._id, row))
145
- });
146
- const readDb = (rows) => tablesOf((name) => Object.freeze({
147
- get: (id) => documentOf(String(id), rows.get(name, String(id))),
148
- range: (index, field, options) => rangeOf(rows, name, index, field, options)
149
- }));
150
- /** A short, stable text of a string (FNV-1a, base 36): the ids a call inserts. */
151
- function fnv(text) {
152
- let hash = 2166136261;
153
- for (let i = 0; i < text.length; i += 1) hash = Math.imul(hash ^ text.charCodeAt(i), 16777619) >>> 0;
154
- return hash.toString(36);
155
- }
156
- /** A write's document checked against its table in the schema; a table the schema does not declare takes no writes. */
157
- function fits(schema, name, doc) {
158
- if (!schema) return;
159
- const fields = schema[name];
160
- if (!fields) throw new Refusal("invalid", `${name}: no such table in the schema`, { table: name });
161
- const why = shapeError({ object: fields }, doc, name);
162
- if (why) throw new Refusal("invalid", why, { table: name });
163
- }
164
- function writeDb(rows) {
165
- let inserts = 0;
166
- return tablesOf((name) => Object.freeze({
167
- get: (id) => documentOf(String(id), rows.get(name, String(id))),
168
- range: (index, field, options) => rangeOf(rows, name, index, field, options),
169
- insert: (doc) => {
170
- const id = `${fnv(`${rows.call}:${name}`)}${(inserts++).toString(36).padStart(2, "0")}`;
171
- const fields = fieldsOf(doc);
172
- fits(rows.schema, name, fields);
173
- rows.set(name, id, fields);
174
- return id;
175
- },
176
- patch: (id, change) => {
177
- const row = rows.get(name, String(id));
178
- if (row === null || row === void 0) throw new NotFoundError({
179
- table: name,
180
- id
181
- });
182
- const current = fieldsOf(row);
183
- const next = { ...current };
184
- for (const [field, value] of Object.entries(change ?? {})) if (value === void 0) delete next[field];
185
- else next[field] = applied(current[field], value, {
186
- table: name,
187
- id,
188
- field
189
- });
190
- fits(rows.schema, name, next);
191
- rows.set(name, String(id), next);
192
- },
193
- replace: (id, doc) => {
194
- if (rows.get(name, String(id)) === null) throw new NotFoundError({
195
- table: name,
196
- id
197
- });
198
- const fields = fieldsOf(doc);
199
- fits(rows.schema, name, fields);
200
- rows.set(name, String(id), fields);
201
- },
202
- delete: (id) => {
203
- rows.delete(name, String(id));
204
- }
205
- }));
206
- }
207
- function spec(kind, name, given) {
208
- if (given === null || typeof given !== "object" || typeof given.handler !== "function") throw new TypeError(`${kind}(${name ? `"${name}", ` : ""}{ args, returns, cron, handler })`);
209
- return given;
210
- }
211
- /** A definer's arguments: `({ ... })`, named by its export, or `("name", { ... })`. */
212
- const named = (name, given) => given === void 0 && name !== null && typeof name === "object" ? [null, name] : [name, given];
213
- const fnName = (fn) => fn !== null && typeof fn === "object" && typeof fn.name === "string" ? fn.name : String(fn);
214
- function schedulerOf(rows) {
215
- return Object.freeze({
216
- runAfter: (ms, fn, args) => rows.runAfter(Math.max(0, Number(ms) || 0), fnName(fn), args ?? null),
217
- runAt: (at, fn, args) => rows.runAfter(Math.max(0, (Number(at) || 0) - rows.now), fnName(fn), args ?? null),
218
- status: (id) => {
219
- const row = rows.scheduledRow(String(id));
220
- return row ? Object.freeze({
221
- name: row.name,
222
- args: row.args ?? null,
223
- at: row.due,
224
- state: row.state,
225
- ...row.error ? { error: row.error } : {}
226
- }) : null;
227
- },
228
- cancel: (id) => rows.cancelScheduled(String(id))
229
- });
230
- }
231
- const authOf = (user, issuer) => user ? Object.freeze({
232
- subject: user,
233
- issuer: issuer ?? null
234
- }) : null;
235
- const contextOf = (rows, tables, scheduler) => Object.freeze({
236
- db: tables,
237
- identity: Object.freeze({
238
- user: rows.user ?? null,
239
- server: !!rows.server
240
- }),
241
- auth: authOf(rows.server ? null : rows.user, rows.issuer),
242
- now: rows.now,
243
- ...scheduler ? { scheduler } : {}
244
- });
245
- /** A function that reads rows and never writes them: `export const list = query({ args, returns, handler: (ctx, args) => ... })`. */
246
- function query(name, given, extra = {}) {
247
- const [own, definition] = named(name, given);
248
- const { handler, args = null, returns = null } = spec("query", own, definition);
249
- return defineFunction(own, (rows, a) => handler(contextOf(rows, readDb(rows)), a ?? {}), {
250
- kind: "query",
251
- args,
252
- returns,
253
- ...extra
254
- });
255
- }
256
- /** One serializable transaction: `export const send = mutation({ args, returns, handler: (ctx, args) => ... })`. */
257
- function mutation(name, given, extra = {}) {
258
- const [own, definition] = named(name, given);
259
- const { handler, args = null, returns = null, cron = null } = spec("mutation", own, definition);
260
- return defineFunction(own, (rows, a) => handler(contextOf(rows, writeDb(rows), schedulerOf(rows)), a ?? {}), {
261
- kind: "mutation",
262
- args,
263
- returns,
264
- cron,
265
- ...extra
266
- });
267
- }
268
- /** May wait on the network: `export const charge = action({ args, returns, handler: async (ctx, args) => ... })`. */
269
- function action(name, given, extra = {}) {
270
- const [own, definition] = named(name, given);
271
- const { handler, args = null, returns = null, cron = null } = spec("action", own, definition);
272
- return defineFunction(own, (cap, a) => {
273
- const tables = tablesOf((table) => Object.freeze({
274
- get: async (id) => documentOf(String(id), await cap.get(table, String(id))),
275
- range: async (index, _field, options) => ({
276
- ok: true,
277
- rows: (await cap.range(table, index || "_id", boundsOf(options))).map((row) => documentOf(row._id, row))
278
- })
279
- }));
280
- const ctx = Object.freeze({
281
- db: tables,
282
- identity: Object.freeze({
283
- user: cap.user ?? null,
284
- server: !!cap.server
285
- }),
286
- auth: authOf(cap.server ? null : cap.user, cap.issuer),
287
- fetch: async (url, init) => {
288
- const target = new URL(String(url));
289
- if (target.protocol !== "https:") throw new TypeError("ctx.fetch: an https URL");
290
- return cap.fetch(target, init);
291
- },
292
- now: () => cap.now(),
293
- random: (n = 16) => cap.random(n),
294
- run: (fn, args) => cap.run(fnName(fn), args ?? null),
295
- scheduler: Object.freeze({
296
- runAfter: (ms, fn, args) => cap.schedule(Math.max(0, Number(ms) || 0), fnName(fn), args ?? null),
297
- runAt: (at, fn, args) => cap.schedule(Math.max(0, (Number(at) || 0) - cap.now()), fnName(fn), args ?? null),
298
- status: (id) => cap.scheduled(String(id)),
299
- cancel: (id) => cap.cancel(String(id))
300
- })
301
- });
302
- return handler(ctx, a ?? {});
303
- }, {
304
- kind: "action",
305
- args,
306
- returns,
307
- cron,
308
- ...extra
309
- });
310
- }
311
- /** As `query`, callable only by another function, never a client. */
312
- const internalQuery = (name, given) => query(name, given, { internal: true });
313
- /** As `mutation`, callable only by another function, never a client. */
314
- const internalMutation = (name, given) => mutation(name, given, { internal: true });
315
- /** As `action`, callable only by another function, never a client. */
316
- const internalAction = (name, given) => action(name, given, { internal: true });
317
- /** Whether a value is a function defined here, as a module of `db/` exports it. */
318
- const isFunction = (value) => value !== null && typeof value === "object" && typeof value.handler === "function" && typeof value.options?.kind === "string";
319
- //#endregion
320
- export { InsufficientError, NotFoundError, Refusal, action, defineSchema, defineTable, give, increment, indexFields, internalAction, internalMutation, internalQuery, isFunction, mutation, query, shapeError, take, v };
1
+ import { _ as shapeError, f as indexFields, l as defineSchema, m as isIdForm, s as ID_FORM, u as defineTable, v as tableCode, y as v } from "../bytes-C2pcyl9u.mjs";
2
+ import { C as paginationOptsValidator, D as take, E as scheduleOf, S as nextCron, T as readLimited, _ as isFunction, a as Refusal, b as limits, c as cronJobs, d as httpAction, f as httpRouter, g as internalQuery, h as internalMutation, i as NotFoundError, l as fetchOver, m as internalAction, n as HttpRouter, o as TooLarge, p as increment, r as InsufficientError, s as action, t as Crons, u as give, v as isIdOf, w as query, x as mutation, y as isRouter } from "../server-EDRbF2u-.mjs";
3
+ export { Crons, HttpRouter, ID_FORM, InsufficientError, NotFoundError, Refusal, TooLarge, action, cronJobs, defineSchema, defineTable, fetchOver, give, httpAction, httpRouter, increment, indexFields, internalAction, internalMutation, internalQuery, isFunction, isIdForm, isIdOf, isRouter, limits, mutation, nextCron, paginationOptsValidator, query, readLimited, scheduleOf, shapeError, tableCode, take, v };
@@ -1,5 +1,8 @@
1
- import { t as Built } from "../build-SQ44jwSa.mjs";
2
- import { d as Row, i as FunctionReference, r as FunctionKind, u as RegisteredFunction } from "../server-C7O7CICU.mjs";
1
+ import { p as Storage } from "../index-sgdyoA2P.mjs";
2
+ import { h as AuthConfig, r as Built } from "../build-DQo-JrlN.mjs";
3
+ 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
+ import { t as DatabaseError } from "../errors-x2vXKi0u.mjs";
5
+ import { A as VectorControl, M as VectorEngine } from "../index-DNNXNny7.mjs";
3
6
  //#region src/database/stand-in.d.ts
4
7
  /** A Database as its client reaches it: by function name or reference. A refusal throws `DatabaseError`. */
5
8
  interface DatabaseClient {
@@ -12,10 +15,19 @@ interface DatabaseClient {
12
15
  action(fn: string | FunctionReference, args?: unknown, options?: {
13
16
  readonly tag?: string;
14
17
  }): Promise<unknown>;
15
- /** Gives `onValue` the query's value now and again after every change it sees; returns a stop. */
16
- watch(fn: string | FunctionReference, args: unknown, onValue: (value: unknown) => void): () => void;
18
+ /**
19
+ * Gives `onValue` the query's value now and again after every change it sees, and `onError` the
20
+ * `DatabaseError` of a run that is refused; returns a stop.
21
+ */
22
+ watch(fn: string | FunctionReference, args: unknown, onValue: (value: unknown) => void, onError?: (error: DatabaseError) => void): () => void;
17
23
  /** The same client for a signed-in caller, by the Project's sign-in's subject. */
18
24
  as(subject: string): DatabaseClient;
25
+ /**
26
+ * The same client for whoever `token` signs in, as the Database checks it: a provider's token its
27
+ * `auth.config.ts` trusts, or null for none. A token the Database refuses, or no token where it admits
28
+ * no anonymous callers, refuses every call with `unauthenticated`.
29
+ */
30
+ withToken(token: string | null): DatabaseClient;
19
31
  /** A new call identity. */
20
32
  tag(): Promise<string>;
21
33
  }
@@ -24,6 +36,18 @@ interface Loaded {
24
36
  readonly functions: ReadonlyMap<string, RegisteredFunction>;
25
37
  readonly tables: Built["tables"];
26
38
  readonly indexes: Built["indexes"];
39
+ readonly search?: Built["search"];
40
+ readonly vector?: Built["vector"];
41
+ /** `http.ts`'s router; none without it. */
42
+ readonly http?: HttpRouter | null;
43
+ /** Points its actions' global `fetch` at a Stand-in's network; until then it reaches none. */
44
+ readonly useNetwork?: (network: (url: URL, init?: RequestInit) => Promise<Response>) => void;
45
+ /** Whom the Database trusts to sign its users in; none, when it takes no provider's tokens. */
46
+ readonly auth?: AuthConfig | null;
47
+ /** `crons.ts`'s scheduled runs; none without it. */
48
+ readonly crons?: ReadonlyArray<CronJob>;
49
+ /** The environment's values it was loaded with, a frozen copy, which its `auth.config.ts` reads too; none when loaded without them. */
50
+ readonly env?: Readonly<Record<string, string>> | null;
27
51
  }
28
52
  interface StandIn {
29
53
  /** Serves `loaded`'s functions from now on. The rows stay. */
@@ -36,6 +60,15 @@ interface StandIn {
36
60
  exclusive<T>(work: () => T | Promise<T>): Promise<T>;
37
61
  /** A client with no signed-in caller. */
38
62
  readonly client: DatabaseClient;
63
+ /**
64
+ * The caller a token signs in, as a Database takes it: a provider's token checked against the providers
65
+ * the served `auth.config.ts` trusts, or no token where it admits anonymous callers. Throws
66
+ * `DatabaseError` `unauthenticated` saying why it was refused, or `unavailable` when the provider's keys
67
+ * or a variable its values read could not be had.
68
+ */
69
+ identify(token: string | null): Promise<Caller>;
70
+ /** The served `auth.config.ts`, or null when it has none. */
71
+ readonly auth: AuthConfig | null;
39
72
  /**
40
73
  * A client for any caller: `user` signed in, or the server's own code (`server`), with
41
74
  * `internal` functions too. What a Database Key or a run by hand calls as.
@@ -45,20 +78,46 @@ interface StandIn {
45
78
  kind(name: string): FunctionKind | undefined;
46
79
  /** Every row, by table and id. */
47
80
  rows(): Record<string, Record<string, Row>>;
81
+ /** Each scheduled job of the served build: its runs so far, the runs skipped because one was still going, and the last run's error, if it failed. */
82
+ crons(): ReadonlyArray<{
83
+ readonly name: string;
84
+ readonly runs: number;
85
+ readonly skipped: number;
86
+ readonly running: boolean;
87
+ readonly error: string | null;
88
+ }>;
89
+ /** Every stored file's metadata, by storage id; its bytes are in the Stand-in's Storage. */
90
+ files(): Record<string, FileMetadata>;
48
91
  /**
49
92
  * Commits what `write` returns, between mutations, as one commit of its own as a mutation's would
50
93
  * be: told to `committed` and seen by every watch. `write` is given the rows as they are then, and
51
94
  * may throw to commit nothing. How a Database's rows are put back as a restore point held them.
52
95
  */
53
96
  commit(write: (rows: Record<string, Record<string, Stored>>) => ReadonlyArray<Change>): Promise<ReadonlyArray<Change>>;
97
+ /**
98
+ * The Database's HTTP side: `POST /files?upload=<token>` (an upload URL), `GET /files/<id>` (a
99
+ * file's URL) and `/http<path>` (its HTTP actions). Anything else is 404.
100
+ */
101
+ fetch(request: Request): Promise<Response>;
54
102
  /** Stops the scheduler's timers. */
55
103
  close(): void;
56
104
  }
57
105
  /**
58
- * Writes a build's files under `folder` and loads them, each import of the surface naming this SDK.
59
- * Each load is a folder of its own, so a module loaded before never stands in for a newer one.
106
+ * Writes a build's files under `folder` and loads them, each import of the surface naming this SDK's
107
+ * `server.ts`. They reach it through a shim beside them, `_generated/server.mjs`, that re-exports the
108
+ * module loaded here: a file on disk can't import one inside a compiled CLI, where this SDK's files
109
+ * live only in the binary. Each load is a folder of its own, so a module loaded before never stands in
110
+ * for a newer one.
111
+ *
112
+ * `env` is the environment's values, each module's `process.env` (a copy: a module that sets one sets
113
+ * it for this load only). It is never written to disk; a change to it is a new load, as a deploy is.
114
+ * A module's global `fetch` is the network of the Stand-in that serves the load, https only, as
115
+ * `ctx.fetch` is, while an action runs; while a query or a mutation runs, or the module loads, it is
116
+ * refused, whichever module calls it. A module that binds `process` or `fetch` itself keeps its own.
60
117
  */
61
- declare function loadDatabase(built: Built, folder: string): Promise<Loaded>;
118
+ declare function loadDatabase(built: Built, folder: string, options?: {
119
+ readonly env?: Readonly<Record<string, string>>;
120
+ }): Promise<Loaded>;
62
121
  /** A row as the Stand-in keeps it: its fields and its version, which counts its writes. */
63
122
  type Stored = Row & {
64
123
  readonly _version: number;
@@ -69,28 +128,55 @@ interface Change {
69
128
  readonly id: string;
70
129
  readonly row: Stored | null;
71
130
  }
131
+ /** Who calls: `user`, by subject; `issuer` and `claims`, a provider's verified token's, when it signed them in. */
72
132
  interface Caller {
73
133
  readonly user: string | null;
74
134
  readonly server: boolean;
75
135
  readonly internal: boolean;
136
+ readonly issuer?: string | null;
137
+ readonly claims?: Readonly<Record<string, unknown>> | null;
76
138
  }
77
- /** Orders index keys as the Database does: by type (null, numbers, strings, booleans), then by value. */
139
+ /** Orders index keys by value type, then by value, with missing fields before null. */
78
140
  declare function compare(a: unknown, b: unknown): number;
79
141
  /**
80
142
  * `rows` are the rows it starts with, as `rows()` gave them (a branch's, from its parent);
81
- * `committed` is told every mutation's changes as it commits them, in order. `admits` is asked as a
143
+ * `committed` is told every mutation's changes as it commits them, in order, before they apply: one
144
+ * that throws refuses the commit, and nothing the mutation wrote is kept. `admits` is asked as a
82
145
  * mutation starts, and what it returns is asked in the same step as the mutation commits, with nothing
83
146
  * between: so the commit can require what held at the start (a Database's lifecycle version). A reason
84
147
  * refuses the commit, and the mutation is refused as `unavailable` with nothing it wrote kept.
85
148
  * `read` is told how many rows each read gave a function, a mutation's own writes included.
149
+ * Legacy rows without creation metadata read as time 0. Their first later write stores 0 and keeps it.
150
+ * `network` is what an action's `ctx.fetch` and global `fetch` reach (the real network unless given).
151
+ * `storage` keeps the files, in its bucket `database-files` under `database/` (a random name unless
152
+ * given), so Databases that share a Storage never reach each other's files. `origin` is where `fetch`
153
+ * is served, which the files' and upload URLs start with. `verify` turns an HTTP request's bearer
154
+ * token into its caller's subject, or null when it does not verify; without it every HTTP action's
155
+ * caller is anonymous. `limits.fileBytes` lowers the largest file (`limits.fileBytes` of the server).
86
156
  */
87
157
  declare function databaseStandIn(options?: {
88
158
  readonly clock?: () => number;
89
159
  readonly random?: (bytes: number) => Uint8Array;
90
160
  readonly rows?: Readonly<Record<string, Readonly<Record<string, Stored>>>>;
161
+ /** The files it starts with, by storage id: their bytes must be in `storage`, under `database`. */
162
+ readonly files?: Readonly<Record<string, FileMetadata>>;
91
163
  readonly committed?: (changes: ReadonlyArray<Change>) => void;
92
164
  readonly admits?: () => () => string | null;
93
165
  readonly read?: (rows: number) => void;
166
+ /** The Vector engine that serves vector indexes; the Vector Stand-in when not given. */
167
+ readonly vector?: VectorEngine & VectorControl;
168
+ readonly network?: (url: URL, init?: RequestInit) => Promise<Response>;
169
+ readonly storage?: Storage;
170
+ readonly database?: string;
171
+ readonly origin?: () => string;
172
+ readonly verify?: (token: string) => string | null | Promise<string | null>;
173
+ readonly limits?: {
174
+ readonly fileBytes?: number;
175
+ };
176
+ /** How `identify` fetches a provider's discovery document and keys; the global `fetch` when left out. */
177
+ readonly fetch?: (url: string, init: RequestInit) => Promise<Response>;
178
+ /** The variables `auth.config.ts`'s `process.env.NAME` values read, when a deployment is served without its own; this process's when left out. */
179
+ readonly env?: (name: string) => string | undefined;
94
180
  }): StandIn;
95
181
  //#endregion
96
182
  export { Caller, Change, DatabaseClient, Loaded, StandIn, Stored, compare, databaseStandIn, loadDatabase };