ovr 6.2.4 → 7.0.0-next.0

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 (136) hide show
  1. package/README.md +3 -1
  2. package/dist/app/index.d.ts +51 -7
  3. package/dist/app/index.d.ts.map +1 -1
  4. package/dist/app/index.js +163 -28
  5. package/dist/auth/auth-data.d.ts +26 -0
  6. package/dist/auth/auth-data.d.ts.map +1 -0
  7. package/dist/auth/auth-data.js +42 -0
  8. package/dist/auth/cbor.d.ts +50 -0
  9. package/dist/auth/cbor.d.ts.map +1 -0
  10. package/dist/auth/cbor.js +200 -0
  11. package/dist/auth/client-source.d.ts +3 -0
  12. package/dist/auth/client-source.d.ts.map +1 -0
  13. package/dist/auth/client-source.js +3 -0
  14. package/dist/auth/client.d.ts +3 -0
  15. package/dist/auth/client.d.ts.map +1 -0
  16. package/dist/auth/client.js +186 -0
  17. package/dist/auth/configure.d.ts +28 -0
  18. package/dist/auth/configure.d.ts.map +1 -0
  19. package/dist/auth/configure.js +228 -0
  20. package/dist/auth/der.d.ts +6 -0
  21. package/dist/auth/der.d.ts.map +1 -0
  22. package/dist/auth/der.js +36 -0
  23. package/dist/auth/index.d.ts +242 -0
  24. package/dist/auth/index.d.ts.map +1 -0
  25. package/dist/auth/index.js +152 -0
  26. package/dist/auth/issue.d.ts +36 -0
  27. package/dist/auth/issue.d.ts.map +1 -0
  28. package/dist/auth/issue.js +47 -0
  29. package/dist/auth/metadata.d.ts +22 -0
  30. package/dist/auth/metadata.d.ts.map +1 -0
  31. package/dist/auth/metadata.js +134 -0
  32. package/dist/auth/oauth.d.ts +29 -0
  33. package/dist/auth/oauth.d.ts.map +1 -0
  34. package/dist/auth/oauth.js +724 -0
  35. package/dist/auth/passkey.d.ts +101 -0
  36. package/dist/auth/passkey.d.ts.map +1 -0
  37. package/dist/auth/passkey.js +393 -0
  38. package/dist/auth/state.d.ts +49 -0
  39. package/dist/auth/state.d.ts.map +1 -0
  40. package/dist/auth/state.js +184 -0
  41. package/dist/auth/storage.d.ts +193 -0
  42. package/dist/auth/storage.d.ts.map +1 -0
  43. package/dist/auth/storage.js +410 -0
  44. package/dist/auth/token.d.ts +12 -0
  45. package/dist/auth/token.d.ts.map +1 -0
  46. package/dist/auth/token.js +39 -0
  47. package/dist/context/index.d.ts +86 -16
  48. package/dist/context/index.d.ts.map +1 -1
  49. package/dist/context/index.js +166 -42
  50. package/dist/cookie/index.d.ts +3 -0
  51. package/dist/cookie/index.d.ts.map +1 -1
  52. package/dist/cookie/index.js +1 -0
  53. package/dist/database/index.d.ts +262 -0
  54. package/dist/database/index.d.ts.map +1 -0
  55. package/dist/database/index.js +807 -0
  56. package/dist/form/index.d.ts +699 -0
  57. package/dist/form/index.d.ts.map +1 -0
  58. package/dist/form/index.js +901 -0
  59. package/dist/index.d.ts +10 -3
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +9 -3
  62. package/dist/jsx/elements.d.ts +28 -2
  63. package/dist/jsx/elements.d.ts.map +1 -1
  64. package/dist/jsx/index.d.ts +20 -4
  65. package/dist/jsx/index.d.ts.map +1 -1
  66. package/dist/jsx/index.js +6 -65
  67. package/dist/limiter/index.d.ts +65 -0
  68. package/dist/limiter/index.d.ts.map +1 -0
  69. package/dist/limiter/index.js +157 -0
  70. package/dist/markdown/index.d.ts +61 -0
  71. package/dist/markdown/index.d.ts.map +1 -0
  72. package/dist/markdown/index.js +1160 -0
  73. package/dist/markup/index.d.ts +188 -0
  74. package/dist/markup/index.d.ts.map +1 -0
  75. package/dist/markup/index.js +718 -0
  76. package/dist/mcp/index.d.ts +73 -0
  77. package/dist/mcp/index.d.ts.map +1 -0
  78. package/dist/mcp/index.js +988 -0
  79. package/dist/middleware/index.d.ts +3 -4
  80. package/dist/middleware/index.d.ts.map +1 -1
  81. package/dist/multipart/index.d.ts +53 -7
  82. package/dist/multipart/index.d.ts.map +1 -1
  83. package/dist/multipart/index.js +332 -124
  84. package/dist/route/index.d.ts +226 -80
  85. package/dist/route/index.d.ts.map +1 -1
  86. package/dist/route/index.js +239 -99
  87. package/dist/schema/index.d.ts +307 -734
  88. package/dist/schema/index.d.ts.map +1 -1
  89. package/dist/schema/index.js +783 -1050
  90. package/dist/table/index.d.ts +132 -0
  91. package/dist/table/index.d.ts.map +1 -0
  92. package/dist/table/index.js +188 -0
  93. package/dist/trie/index.js +4 -4
  94. package/dist/util/index.d.ts +37 -5
  95. package/dist/util/index.d.ts.map +1 -1
  96. package/dist/util/index.js +156 -41
  97. package/package.json +11 -4
  98. package/src/app/index.ts +230 -42
  99. package/src/auth/auth-data.ts +56 -0
  100. package/src/auth/cbor.ts +231 -0
  101. package/src/auth/client-source.ts +3 -0
  102. package/src/auth/client.ts +205 -0
  103. package/src/auth/configure.ts +279 -0
  104. package/src/auth/der.ts +35 -0
  105. package/src/auth/index.ts +387 -0
  106. package/src/auth/issue.ts +52 -0
  107. package/src/auth/metadata.ts +149 -0
  108. package/src/auth/oauth.ts +882 -0
  109. package/src/auth/passkey.ts +556 -0
  110. package/src/auth/state.ts +213 -0
  111. package/src/auth/storage.ts +572 -0
  112. package/src/auth/token.ts +67 -0
  113. package/src/context/index.ts +240 -65
  114. package/src/cookie/index.ts +3 -0
  115. package/src/database/index.ts +1193 -0
  116. package/src/form/index.ts +1720 -0
  117. package/src/index.ts +10 -3
  118. package/src/jsx/elements.ts +45 -25
  119. package/src/jsx/index.ts +24 -69
  120. package/src/limiter/index.ts +221 -0
  121. package/src/markdown/index.ts +1322 -0
  122. package/src/markup/index.ts +853 -0
  123. package/src/mcp/conformance.2025-11-25.yml +39 -0
  124. package/src/mcp/conformance.2026-07-28.yml +56 -0
  125. package/src/mcp/index.ts +1262 -0
  126. package/src/middleware/index.ts +5 -6
  127. package/src/multipart/index.ts +410 -158
  128. package/src/route/index.ts +559 -278
  129. package/src/schema/index.ts +1542 -2256
  130. package/src/table/index.ts +387 -0
  131. package/src/trie/index.ts +4 -4
  132. package/src/util/index.ts +163 -49
  133. package/dist/render/index.d.ts +0 -79
  134. package/dist/render/index.d.ts.map +0 -1
  135. package/dist/render/index.js +0 -257
  136. package/src/render/index.ts +0 -314
@@ -0,0 +1,807 @@
1
+ import { Schema, append, exact } from "../schema/index.js";
2
+ import { Column, Table } from "../table/index.js";
3
+ /** Identifier quoting shared by `Sql` and `Database`, not exported. */
4
+ class Identifier {
5
+ /**
6
+ * @param name Identifier
7
+ * @returns Quoted identifier
8
+ */
9
+ static quote(name) {
10
+ // an empty name or a NUL in one is a type error, see `Table.Identifier`
11
+ return `"${name.replaceAll('"', '""')}"`;
12
+ }
13
+ /**
14
+ * @param table Table
15
+ * @returns Quoted, schema-qualified table name
16
+ */
17
+ static table(table) {
18
+ return ((table.options.schema
19
+ ? `${Identifier.quote(table.options.schema)}.`
20
+ : "") + Identifier.quote(table.name));
21
+ }
22
+ }
23
+ /**
24
+ * SQL fragment, a lazy promise that runs once on its client when awaited.
25
+ *
26
+ * @template Row Row type
27
+ */
28
+ export class Sql {
29
+ /** Text segments surrounding the values. */
30
+ #strings;
31
+ /** Interpolated values. */
32
+ #values;
33
+ /** Client used when awaited. */
34
+ #client;
35
+ /** Schema validating each returned row. */
36
+ #schema;
37
+ /** Query result, shared with the fragments `parse` returns so the query runs once. */
38
+ #execution;
39
+ /** Validated rows, started by the first `then`, `catch`, or `finally`. */
40
+ #result;
41
+ [Symbol.toStringTag] = "Sql";
42
+ /**
43
+ * @param strings Text segments, one more than values
44
+ * @param values Interpolated values
45
+ * @param client Client used when awaited
46
+ * @param schema Schema validating each returned row
47
+ * @param execution Query result shared with the source fragment
48
+ */
49
+ constructor(strings, values, client, schema, execution = {}) {
50
+ this.#strings = strings;
51
+ this.#values = values;
52
+ this.#client = client;
53
+ this.#schema = schema;
54
+ this.#execution = execution;
55
+ }
56
+ /**
57
+ * Parse each returned row with a schema, throwing the issues if any fail.
58
+ * The query still runs once, however many fragments `parse` returns.
59
+ *
60
+ * @template O Row type
61
+ * @param schema Row schema, for example a table
62
+ * @returns Fragment returning parsed rows
63
+ */
64
+ parse(schema) {
65
+ return new Sql(this.#strings, this.#values, this.#client, schema, this.#execution);
66
+ }
67
+ /**
68
+ * Compile to parameterized text.
69
+ *
70
+ * @returns Query text and parameter values
71
+ */
72
+ toQuery() {
73
+ const values = [];
74
+ return { text: this.#build(values), values };
75
+ }
76
+ /**
77
+ * Run the query once, the first time the result is requested.
78
+ *
79
+ * @template A Result of `resolve`
80
+ * @template B Result of `reject`
81
+ * @param resolve Receives the rows
82
+ * @param reject Receives the query or validation error
83
+ * @returns Promise of the callback result
84
+ */
85
+ then(resolve, reject) {
86
+ return (this.#result ??= this.#run()).then(resolve, reject);
87
+ }
88
+ /**
89
+ * @template B Result of `reject`
90
+ * @param reject Receives the query or validation error
91
+ * @returns Promise of the rows or the callback result
92
+ */
93
+ catch(reject) {
94
+ return this.then(undefined, reject);
95
+ }
96
+ /**
97
+ * @param fn Called when the query settles
98
+ * @returns Promise of the rows
99
+ */
100
+ finally(fn) {
101
+ return this.then().finally(fn);
102
+ }
103
+ async #run() {
104
+ if (!this.#execution.result) {
105
+ const { text, values } = this.toQuery();
106
+ this.#execution.result = this.#client.query(text, values);
107
+ }
108
+ const { rows, fields } = await this.#execution.result;
109
+ if (!this.#schema)
110
+ return rows;
111
+ const base = Sql.#base(this.#schema.def);
112
+ const decode = base.type === "object" && fields
113
+ ? Sql.#decoder(base.shape, fields)
114
+ : undefined;
115
+ const data = [];
116
+ const issues = [];
117
+ for (let i = 0; i < rows.length; i++) {
118
+ const result = this.#schema.parse(decode ? decode(rows[i]) : rows[i], [
119
+ i,
120
+ ]);
121
+ if (result.issues)
122
+ append(issues, result.issues);
123
+ else
124
+ data.push(result.data);
125
+ }
126
+ if (issues.length)
127
+ throw new Schema.AggregateIssue(issues);
128
+ return data;
129
+ }
130
+ /**
131
+ * @param values Parameter values, appended to
132
+ * @returns Query text using `$n` placeholders
133
+ */
134
+ #build(values) {
135
+ let text = this.#strings[0];
136
+ for (let i = 0; i < this.#values.length; i++) {
137
+ const value = this.#values[i];
138
+ text +=
139
+ (value instanceof Sql
140
+ ? value.#build(values)
141
+ : value instanceof Table
142
+ ? Identifier.table(value)
143
+ : value instanceof Column
144
+ ? `${Identifier.table(value.table)}.${Identifier.quote(value.name)}`
145
+ : `$${values.push(typeof value === "bigint" ? String(value) : value)}`) +
146
+ this.#strings[i + 1];
147
+ }
148
+ return text;
149
+ }
150
+ /**
151
+ * @param def Schema definition
152
+ * @returns Definition that validates the input, without modifiers
153
+ */
154
+ static #base(def) {
155
+ switch (def.type) {
156
+ case "optional":
157
+ case "nullable":
158
+ case "nullish":
159
+ case "default":
160
+ case "check":
161
+ case "pipe":
162
+ case "transform":
163
+ return Sql.#base(def.inner.def);
164
+ }
165
+ return def;
166
+ }
167
+ /**
168
+ * Build the row decoder for one result, converting driver values into the
169
+ * types the row schema expects by each column's Postgres type.
170
+ *
171
+ * @param shape Row schema shape
172
+ * @param fields Returned columns
173
+ * @returns Decoder, or `undefined` when no column needs converting
174
+ */
175
+ static #decoder(shape, fields) {
176
+ const columns = [];
177
+ for (const { name, dataTypeID } of fields) {
178
+ if (!Object.hasOwn(shape, name))
179
+ continue;
180
+ const def = shape[name].def;
181
+ let convert;
182
+ switch (dataTypeID) {
183
+ case 20: // int8
184
+ case 1700: // numeric
185
+ convert = Sql.#number(def);
186
+ break;
187
+ case 1016: // int8[]
188
+ case 1231: // numeric[]
189
+ convert = Sql.#numbers(def);
190
+ break;
191
+ case 114: // json
192
+ case 3802: // jsonb
193
+ case 199: // json[]
194
+ case 3807: // jsonb[]
195
+ convert = Sql.#dates(def);
196
+ }
197
+ if (convert)
198
+ columns.push([name, convert]);
199
+ }
200
+ return Sql.#keys(columns);
201
+ }
202
+ /**
203
+ * @param keys Converter for each key that needs one
204
+ * @returns Converter for an object, `undefined` when no key needs one
205
+ */
206
+ static #keys(keys) {
207
+ if (!keys.length)
208
+ return;
209
+ return (value) => {
210
+ if (value == null || typeof value !== "object" || Array.isArray(value))
211
+ return value;
212
+ // copied, a driver's row may be shared with other views
213
+ const decoded = { ...value };
214
+ for (const [key, convert] of keys) {
215
+ if (Object.hasOwn(decoded, key))
216
+ decoded[key] = convert(decoded[key]);
217
+ }
218
+ return decoded;
219
+ };
220
+ }
221
+ /**
222
+ * @param def Schema definition
223
+ * @returns Converter for a Postgres array, possibly multidimensional
224
+ */
225
+ static #numbers(def) {
226
+ const base = Sql.#base(def);
227
+ if (base.type !== "array")
228
+ return Sql.#number(def);
229
+ return Sql.#each(Sql.#numbers(base.item.def));
230
+ }
231
+ /**
232
+ * @param item Converter for each item
233
+ * @returns Converter for an array, `undefined` when items need none
234
+ */
235
+ static #each(item) {
236
+ return (item && ((value) => (Array.isArray(value) ? value.map(item) : value)));
237
+ }
238
+ /**
239
+ * Drivers return `int8` and `numeric` as strings or bigints, and pg
240
+ * returns `numeric[]` items as numbers.
241
+ *
242
+ * @param def Schema definition
243
+ * @returns Converter to a bigint or number, integers are never rounded
244
+ */
245
+ static #number(def) {
246
+ const base = Sql.#base(def);
247
+ // numbers beyond 2^53 were already rounded by the driver
248
+ if (base.type === "bigint")
249
+ return (value) => (typeof value === "string" && /^-?\d+$/.test(value)) ||
250
+ Number.isSafeInteger(value)
251
+ ? BigInt(value)
252
+ : value;
253
+ if (base.type !== "number")
254
+ return;
255
+ return (value) => {
256
+ if (typeof value !== "string" &&
257
+ typeof value !== "bigint" &&
258
+ typeof value !== "number")
259
+ return value;
260
+ // integers beyond 2^53 may already be rounded
261
+ return exact(value);
262
+ };
263
+ }
264
+ /**
265
+ * JSON has no dates, so they are returned as ISO strings.
266
+ *
267
+ * @param def Schema definition
268
+ * @returns Converter for the branches containing dates, `undefined` without any
269
+ */
270
+ static #dates(def) {
271
+ const base = Sql.#base(def);
272
+ switch (base.type) {
273
+ case "date":
274
+ return (value) => (typeof value === "string" ? new Date(value) : value);
275
+ case "array":
276
+ return Sql.#each(Sql.#dates(base.item.def));
277
+ case "object": {
278
+ const keys = [];
279
+ for (const [key, schema] of Object.entries(base.shape)) {
280
+ const convert = Sql.#dates(schema.def);
281
+ if (convert)
282
+ keys.push([key, convert]);
283
+ }
284
+ return Sql.#keys(keys);
285
+ }
286
+ case "union": {
287
+ const options = base.options.map((option) => [option, Sql.#dates(option.def)]);
288
+ if (!options.some(([, convert]) => convert))
289
+ return;
290
+ // the first branch the converted value matches, so a string
291
+ // in a branch without a date stays a string
292
+ return (value) => {
293
+ for (const [option, convert] of options) {
294
+ const converted = convert ? convert(value) : value;
295
+ if (!option.parse(converted).issues)
296
+ return converted;
297
+ }
298
+ return value;
299
+ };
300
+ }
301
+ }
302
+ }
303
+ }
304
+ /**
305
+ * Migrations a library's tables bring, by table. Tables of one library share
306
+ * one list, applied by `database.migrate` in the order it lists them, before the application's.
307
+ */
308
+ export const owned = new WeakMap();
309
+ /**
310
+ * Columns of a library's tables that must reference the `id` of a table the
311
+ * application chooses, with `ON DELETE CASCADE`, and the library that chooses
312
+ * it, for `database.check`.
313
+ */
314
+ export const referenced = new WeakMap();
315
+ /**
316
+ * The table each such column references, per database, set by the library
317
+ * when it is configured with that database.
318
+ */
319
+ export const references = new WeakMap();
320
+ /**
321
+ * Database members, tables are added by name.
322
+ *
323
+ * @template T Tables of the database
324
+ */
325
+ class Base {
326
+ /** Names database members use. */
327
+ /** Postgres types able to store each kind of column value, preferred first. */
328
+ static #types = {
329
+ string: [
330
+ "text",
331
+ "character varying",
332
+ "character",
333
+ "citext",
334
+ "uuid",
335
+ "enum",
336
+ ],
337
+ number: [
338
+ "double precision",
339
+ "integer",
340
+ "bigint",
341
+ "numeric",
342
+ "real",
343
+ "smallint",
344
+ ],
345
+ bigint: ["bigint", "numeric"],
346
+ boolean: ["boolean"],
347
+ date: ["timestamp with time zone", "timestamp without time zone", "date"],
348
+ json: ["jsonb", "json"],
349
+ };
350
+ /** Insert and update schemas by table. */
351
+ static #writes = new WeakMap();
352
+ #pool;
353
+ #tables;
354
+ /** SQL tag, queries run on the pool when awaited. */
355
+ sql;
356
+ /**
357
+ * @param pool pg-compatible pool, owned by the application
358
+ * @param tables Tables, accessible by name
359
+ */
360
+ constructor(pool, tables) {
361
+ this.#pool = pool;
362
+ this.#tables = tables;
363
+ this.sql = Base.#tag(pool, (fn) => this.#transaction(fn));
364
+ // reserved and repeated names are type errors
365
+ for (const table of tables) {
366
+ Object.defineProperty(this, table.name, {
367
+ value: table,
368
+ enumerable: true,
369
+ });
370
+ }
371
+ }
372
+ /**
373
+ * Run a callback in a transaction on one connection.
374
+ *
375
+ * @template R Callback result
376
+ * @param fn Callback receiving the transaction's client
377
+ * @returns Callback result
378
+ */
379
+ async #transaction(fn) {
380
+ const connection = await this.#pool.connect();
381
+ let open = true;
382
+ let failure;
383
+ let broken;
384
+ /** Queries started and not yet finished */
385
+ const running = new Set();
386
+ // only valid until the transaction ends, the connection returns to the pool
387
+ const client = {
388
+ query: async (text, values) => {
389
+ if (!open)
390
+ throw new Error("Transaction has ended");
391
+ const query = connection.query(text, values);
392
+ const settled = query.catch(() => { });
393
+ running.add(settled);
394
+ try {
395
+ return await query;
396
+ }
397
+ catch (error) {
398
+ // queries after an aborted statement fail too, keep the cause
399
+ if (error?.code !== "25P02")
400
+ failure = error;
401
+ throw error;
402
+ }
403
+ finally {
404
+ running.delete(settled);
405
+ }
406
+ },
407
+ };
408
+ try {
409
+ await connection.query("BEGIN");
410
+ const result = await fn(client).finally(async () => {
411
+ open = false;
412
+ // one the callback did not wait for may still fail and abort it
413
+ await Promise.all(running);
414
+ });
415
+ // COMMIT of an aborted transaction rolls back without an error
416
+ if (failure !== undefined)
417
+ await connection.query("SELECT 1").catch(() => {
418
+ throw failure;
419
+ });
420
+ await connection.query("COMMIT");
421
+ return result;
422
+ }
423
+ catch (error) {
424
+ open = false;
425
+ await connection.query("ROLLBACK").catch((reason) => {
426
+ broken = reason instanceof Error ? reason : new Error(String(reason));
427
+ });
428
+ throw error;
429
+ }
430
+ finally {
431
+ // a connection that cannot roll back is destroyed instead of reused
432
+ connection.release(broken);
433
+ }
434
+ }
435
+ /**
436
+ * Apply pending migrations in ID order. Libraries' tables, such as
437
+ * `Auth.tables`, bring their own migrations, applied first in their own
438
+ * order, so a migration of yours can reference their tables.
439
+ *
440
+ * Each migration and its history record commit together while holding a
441
+ * transaction-level advisory lock, so concurrent runs apply each once.
442
+ *
443
+ * @param migrations Every migration of yours, including applied ones
444
+ * @returns IDs applied by this call
445
+ */
446
+ migrate = async (migrations) => {
447
+ // each library's migrations, in the order their tables are listed, then yours
448
+ const groups = [
449
+ ...new Set(this.#tables.map((table) => owned.get(table))),
450
+ ].filter((group) => group !== undefined);
451
+ groups.push(migrations);
452
+ const checksums = new Map();
453
+ for (const { id, sql } of groups.flat()) {
454
+ if (!id || checksums.has(id))
455
+ throw new TypeError(`Invalid or duplicate migration ID: ${id}`);
456
+ checksums.set(id, new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(sql))).toHex());
457
+ }
458
+ // a library's in the order it lists them, so `auth:10` follows
459
+ // `auth:9`, and yours in ID order, as files are named
460
+ const ordered = groups.map((group, i) => i === groups.length - 1
461
+ ? [...group].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
462
+ : group);
463
+ const applied = [];
464
+ const done = new Set();
465
+ let last = 0;
466
+ // one migration per transaction, history added since the last read is verified every time
467
+ while (await this.#transaction(async (client) => {
468
+ const sql = Base.#tag(client);
469
+ await sql `SELECT pg_advisory_xact_lock(hashtext('migrations'))`;
470
+ // applied in order under the lock, so `n` follows the history
471
+ await sql `CREATE TABLE IF NOT EXISTS migrations (n bigint GENERATED ALWAYS AS IDENTITY, id text PRIMARY KEY, checksum text NOT NULL, applied timestamptz NOT NULL DEFAULT now())`;
472
+ const history = await sql `
473
+ SELECT n, id, checksum FROM migrations WHERE n > ${last} ORDER BY n
474
+ `.parse(Schema.object({
475
+ n: Schema.number().int(),
476
+ id: Schema.string(),
477
+ checksum: Schema.string(),
478
+ }));
479
+ for (const row of history) {
480
+ if (!checksums.has(row.id))
481
+ throw new Error(`Applied migration ${row.id} is missing`);
482
+ if (checksums.get(row.id) !== row.checksum)
483
+ throw new Error(`Applied migration ${row.id} has changed`);
484
+ done.add(row.id);
485
+ last = row.n;
486
+ }
487
+ for (const group of ordered) {
488
+ const index = group.findIndex((migration) => !done.has(migration.id));
489
+ if (index === -1)
490
+ continue;
491
+ const later = group.findLastIndex((migration) => done.has(migration.id));
492
+ if (later > index)
493
+ throw new Error(`Migration ${group[index].id} sorts before applied migration ${group[later].id}`);
494
+ const next = group[index];
495
+ // run by PL/pgSQL, where a COMMIT or ROLLBACK in the migration is an
496
+ // error, instead of ending this transaction and leaving changes
497
+ // applied but unrecorded
498
+ await sql `SELECT set_config('migrate.sql', ${next.sql}, true)`;
499
+ await sql `DO $$ BEGIN EXECUTE current_setting('migrate.sql'); END $$`.catch((error) => {
500
+ const { code, message } = (error ?? {});
501
+ if (code === "0A000" &&
502
+ typeof message === "string" &&
503
+ message.includes("transaction commands"))
504
+ throw new Error(`Migration ${next.id} cannot contain BEGIN, COMMIT, or ROLLBACK, it already runs in a transaction`, { cause: error });
505
+ throw error;
506
+ });
507
+ const [row] = await sql `
508
+ INSERT INTO migrations (id, checksum) VALUES (${next.id}, ${checksums.get(next.id)})
509
+ RETURNING n
510
+ `.parse(Schema.object({ n: Schema.number().int() }));
511
+ applied.push(next.id);
512
+ done.add(next.id);
513
+ last = row.n;
514
+ return true;
515
+ }
516
+ return false;
517
+ }))
518
+ ;
519
+ return applied;
520
+ };
521
+ /**
522
+ * Check that the live database can store and return the tables' rows.
523
+ *
524
+ * Reports missing tables and columns, incompatible types, nullability, and
525
+ * missing defaults, without changing anything. Keys, constraints, and indexes
526
+ * are left to migrations, except the foreign keys a library's tables need,
527
+ * such as Auth's to the users table.
528
+ *
529
+ * @returns One line per difference, empty when they match
530
+ */
531
+ check = async () => {
532
+ const differences = [];
533
+ for (const table of this.#tables) {
534
+ const label = table.name;
535
+ const [{ regclass } = { regclass: null }] = await this
536
+ .sql `SELECT to_regclass(${Identifier.table(table)})::text AS regclass`.parse(Schema.object({ regclass: Schema.string().nullable() }));
537
+ if (!regclass) {
538
+ differences.push(`${label}: missing table`);
539
+ continue;
540
+ }
541
+ // each column's type and the domains it is built on, which may add NOT NULL and defaults
542
+ const columns = await this.sql `
543
+ WITH RECURSIVE chain AS (
544
+ SELECT a.attnum, t.oid, t.typtype, t.typbasetype, t.typnotnull, t.typdefaultbin IS NOT NULL AS "default"
545
+ FROM pg_attribute a JOIN pg_type t ON t.oid = a.atttypid
546
+ WHERE a.attrelid = to_regclass(${regclass}) AND a.attnum > 0 AND NOT a.attisdropped
547
+ UNION ALL
548
+ SELECT c.attnum, t.oid, t.typtype, t.typbasetype, t.typnotnull, t.typdefaultbin IS NOT NULL
549
+ FROM chain c JOIN pg_type t ON t.oid = c.typbasetype
550
+ WHERE c.typtype = 'd'
551
+ )
552
+ SELECT a.attname::text AS name,
553
+ -- domains compare as their base type, enums as "enum"
554
+ (SELECT CASE WHEN c.typtype = 'e' THEN 'enum' ELSE format_type(c.oid, NULL) END
555
+ FROM chain c WHERE c.attnum = a.attnum AND c.typtype <> 'd') AS type,
556
+ NOT (a.attnotnull OR EXISTS (SELECT 1 FROM chain c WHERE c.attnum = a.attnum AND c.typnotnull)) AS nullable,
557
+ a.atthasdef OR a.attidentity <> '' OR a.attgenerated <> ''
558
+ OR EXISTS (SELECT 1 FROM chain c WHERE c.attnum = a.attnum AND c."default") AS "default"
559
+ FROM pg_attribute a
560
+ WHERE a.attrelid = to_regclass(${regclass}) AND a.attnum > 0 AND NOT a.attisdropped
561
+ `.parse(Schema.object({
562
+ name: Schema.string(),
563
+ type: Schema.string(),
564
+ nullable: Schema.boolean(),
565
+ default: Schema.boolean(),
566
+ }));
567
+ const found = new Map(columns.map((column) => [column.name, column]));
568
+ const defaults = new Set(table.options.default ?? []);
569
+ for (const column of Object.values(table.columns)) {
570
+ const name = `${label}.${column.name}`;
571
+ const actual = found.get(column.name);
572
+ const types = Base.#types[column.type];
573
+ const nullable = (value) => (value ? "NULL" : "NOT NULL");
574
+ if (!actual) {
575
+ differences.push(`${name}: missing column (${types[0]} ${nullable(column.nullable)})`);
576
+ continue;
577
+ }
578
+ if (!types.includes(actual.type))
579
+ differences.push(`${name}: ${actual.type} cannot store ${column.type} values, use ${types.join(", ")}`);
580
+ if (actual.nullable !== column.nullable)
581
+ differences.push(`${name}: expected ${nullable(column.nullable)}, found ${nullable(actual.nullable)}`);
582
+ if (defaults.has(column.name) && !actual.default)
583
+ differences.push(`${name}: missing default`);
584
+ }
585
+ // other columns are fine unless inserts cannot omit them
586
+ for (const column of columns) {
587
+ if (!Object.hasOwn(table.columns, column.name) &&
588
+ !column.nullable &&
589
+ !column.default)
590
+ differences.push(`${label}.${column.name}: unexpected NOT NULL column without a default`);
591
+ }
592
+ const reference = referenced.get(table);
593
+ if (reference)
594
+ differences.push(...(await this.#reference(table, regclass, reference)));
595
+ }
596
+ return differences;
597
+ };
598
+ /**
599
+ * Check the foreign key a library's table needs: from its column to the
600
+ * chosen table's `id`, cascading deletes, validated and enforced.
601
+ *
602
+ * @param table Library's table
603
+ * @param regclass Its resolved name
604
+ * @param reference Column that references, and the library choosing what
605
+ * @returns Differences
606
+ */
607
+ async #reference(table, regclass, reference) {
608
+ const label = `${table.name}.${reference.column}`;
609
+ const target = references.get(this)?.get(table);
610
+ if (!target)
611
+ return [
612
+ `${label}: create ${reference.by} with this database before checking it, so it knows the table ${table.name} references`,
613
+ ];
614
+ const expected = `${target.name} (id) ON DELETE CASCADE`;
615
+ const keys = await this.sql `
616
+ SELECT con.confrelid = to_regclass(${Identifier.table(target)}) AS target,
617
+ (SELECT a.attname::text FROM pg_attribute a
618
+ WHERE a.attrelid = con.confrelid AND a.attnum = con.confkey[1]) AS "column",
619
+ con.confdeltype = 'c' AS cascade,
620
+ con.convalidated AS validated,
621
+ -- NOT ENFORCED is new in Postgres 18
622
+ coalesce((to_jsonb(con) ->> 'conenforced')::boolean, true) AS enforced
623
+ FROM pg_constraint con
624
+ WHERE con.contype = 'f' AND con.conrelid = to_regclass(${regclass})
625
+ AND cardinality(con.conkey) = 1
626
+ AND con.conkey[1] = (SELECT a.attnum FROM pg_attribute a
627
+ WHERE a.attrelid = con.conrelid AND a.attname = ${reference.column})
628
+ `.parse(Schema.object({
629
+ target: Schema.boolean().nullable(),
630
+ column: Schema.string().nullable(),
631
+ cascade: Schema.boolean(),
632
+ validated: Schema.boolean(),
633
+ enforced: Schema.boolean(),
634
+ }));
635
+ if (keys.some((key) => key.target &&
636
+ key.column === "id" &&
637
+ key.cascade &&
638
+ key.validated &&
639
+ key.enforced))
640
+ return [];
641
+ const [key] = keys;
642
+ if (!key)
643
+ return [`${label}: missing foreign key to ${expected}`];
644
+ const problems = [
645
+ (!key.target || key.column !== "id") &&
646
+ "references another table or column",
647
+ !key.cascade && "does not cascade deletes",
648
+ !key.validated && "is NOT VALID, validate it",
649
+ !key.enforced && "is NOT ENFORCED",
650
+ ].filter(Boolean);
651
+ return [
652
+ `${label}: foreign key ${problems.join(", ")}, expected ${expected}`,
653
+ ];
654
+ }
655
+ /**
656
+ * @param table Table
657
+ * @returns Cached insert and update schemas
658
+ */
659
+ static #write(table) {
660
+ let write = Base.#writes.get(table);
661
+ if (!write) {
662
+ const insert = {};
663
+ const update = {};
664
+ const defaults = new Set(table.options.default ?? []);
665
+ for (const [key, schema] of Object.entries(table.shape)) {
666
+ // a schema accepting undefined, like unknown, cannot tell an omitted column
667
+ insert[key] =
668
+ defaults.has(key) ||
669
+ (table.columns[key].nullable && schema.parse(undefined).issues)
670
+ ? schema.optional()
671
+ : schema.refine((value) => value !== undefined, "Required");
672
+ update[key] = schema.optional();
673
+ }
674
+ write = {
675
+ insert: Schema.object(insert).strict(),
676
+ update: Schema.object(update).strict(),
677
+ };
678
+ Base.#writes.set(table, write);
679
+ }
680
+ return write;
681
+ }
682
+ /**
683
+ * @param schema Write schema
684
+ * @param value Values to validate
685
+ * @param path Issue path
686
+ * @returns Validated values
687
+ */
688
+ static #parse(schema, value, path = []) {
689
+ const result = schema.parse(value, path);
690
+ if (result.issues)
691
+ throw result;
692
+ return result.data;
693
+ }
694
+ /**
695
+ * @param column Column receiving the value
696
+ * @param value Validated value
697
+ * @returns Driver parameter
698
+ */
699
+ static #encode(column, value) {
700
+ // drivers send arrays as Postgres arrays, so JSON is always serialized,
701
+ // and null is SQL NULL only when the column allows it
702
+ return column.type === "json" && (value !== null || !column.nullable)
703
+ ? JSON.stringify(value)
704
+ : value;
705
+ }
706
+ /**
707
+ * @param client Client queries run on
708
+ * @param transaction Runs a callback in a transaction, only for the pool's tag
709
+ * @returns SQL tag bound to the client
710
+ */
711
+ static #tag(client, transaction) {
712
+ const fragment = (strings, values) => new Sql(strings, values, client);
713
+ const raw = (text) => fragment([text], []);
714
+ return Object.assign((strings, ...values) => {
715
+ // a transaction's own tag has none, transactions do not nest
716
+ if (typeof strings === "function" && transaction) {
717
+ const fn = strings;
718
+ return transaction((inner) => fn({ sql: Base.#tag(inner) }));
719
+ }
720
+ if (!Array.isArray(strings) || !Object.hasOwn(strings, "raw"))
721
+ throw new TypeError("sql is a template tag, write sql`...`, or pass a callback to run a transaction");
722
+ return fragment(strings, values);
723
+ }, {
724
+ values: (table, rows) => {
725
+ const list = (Array.isArray(rows) ? rows : [rows]).map((row, i) => Base.#parse(Base.#write(table).insert, row, Array.isArray(rows) ? [i] : []));
726
+ const keys = Object.keys(table.columns).filter((key) => list.some((row) => Object.hasOwn(row, key)));
727
+ if (!list.length)
728
+ throw new TypeError("sql.values requires a row");
729
+ if (!keys.length) {
730
+ if (list.length > 1)
731
+ throw new TypeError("sql.values requires a column");
732
+ return raw("DEFAULT VALUES");
733
+ }
734
+ // one fragment for every row, text is added to the segment before the next value
735
+ const strings = [
736
+ `(${keys.map(Identifier.quote).join(", ")}) VALUES `,
737
+ ];
738
+ const params = [];
739
+ for (let r = 0; r < list.length; r++) {
740
+ const row = list[r];
741
+ let text = r ? ", (" : "(";
742
+ for (let k = 0; k < keys.length; k++) {
743
+ const key = keys[k];
744
+ if (k)
745
+ text += ", ";
746
+ if (Object.hasOwn(row, key)) {
747
+ strings[strings.length - 1] += text;
748
+ strings.push("");
749
+ params.push(Base.#encode(table.columns[key], row[key]));
750
+ text = "";
751
+ }
752
+ else {
753
+ text += "DEFAULT";
754
+ }
755
+ }
756
+ strings[strings.length - 1] += text + ")";
757
+ }
758
+ return fragment(strings, params);
759
+ },
760
+ set: (table, values) => {
761
+ const data = Base.#parse(Base.#write(table).update, values);
762
+ const keys = Object.keys(data);
763
+ if (!keys.length)
764
+ throw new TypeError("sql.set requires a column");
765
+ return fragment([
766
+ ...keys.map((key, i) => `${i ? ", " : ""}${Identifier.quote(key)} = `),
767
+ "",
768
+ ], keys.map((key) => Base.#encode(table.columns[key], data[key])));
769
+ },
770
+ });
771
+ }
772
+ /**
773
+ * Check whether an error is a unique constraint violation, for example to
774
+ * show it as a form error.
775
+ *
776
+ * ```ts
777
+ * if (Database.unique(error, "users_email_key")) {
778
+ * const invalid = result.invalid({ email: "Already registered" });
779
+ * return c.redirect(invalid.url, 303);
780
+ * }
781
+ * ```
782
+ *
783
+ * @param error Caught error
784
+ * @param constraint Constraint name, any unique constraint when omitted
785
+ * @returns `true` for a matching unique violation
786
+ */
787
+ static unique(error, constraint) {
788
+ if (!(error instanceof Error))
789
+ return false;
790
+ const { code, constraint: name } = error;
791
+ // SQLSTATE unique_violation
792
+ return (code === "23505" && (constraint === undefined || name === constraint));
793
+ }
794
+ }
795
+ /**
796
+ * Postgres database with tables, accessed through an application-owned,
797
+ * pg-compatible pool.
798
+ *
799
+ * ```ts
800
+ * const database = new Database(pool, [users, posts]);
801
+ *
802
+ * const rows = await database.sql`SELECT * FROM ${database.users}`.parse(database.users);
803
+ * ```
804
+ *
805
+ * @template T Tables of the database, each available by name
806
+ */
807
+ export const Database = Base;