@fabrika/auth-core 0.9.0-dev.1 → 0.9.0-dev.10

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 (44) hide show
  1. package/package.json +4 -3
  2. package/src/contract-canonical.ts +1 -0
  3. package/src/contract.ts +6 -0
  4. package/src/dev-environment.ts +6 -0
  5. package/src/framework-release.ts +2 -0
  6. package/src/framework-variables.ts +9 -0
  7. package/src/index.ts +4 -0
  8. package/src/managed-environment.ts +136 -0
  9. package/src/ops.ts +1933 -0
  10. package/src/rpc.ts +8 -8
  11. package/src/terminal.ts +105 -0
  12. package/src/token.ts +73 -13
  13. package/src/types.ts +5 -2
  14. package/src/wire.ts +6 -0
  15. package/types/src/app-environment.d.ts +24 -0
  16. package/types/src/canonical-path.d.ts +20 -0
  17. package/types/src/contract-canonical.d.ts +19 -0
  18. package/types/src/contract.d.ts +800 -0
  19. package/types/src/dev-environment.d.ts +37 -0
  20. package/types/src/device.d.ts +144 -0
  21. package/types/src/endpoint-digest.d.ts +58 -0
  22. package/types/src/endpoints.d.ts +65 -0
  23. package/types/src/environment.d.ts +58 -0
  24. package/types/src/framework-release.d.ts +2 -0
  25. package/types/src/framework-variables.d.ts +86 -0
  26. package/types/src/index.d.ts +28 -0
  27. package/types/src/installation-endpoint.d.ts +46 -0
  28. package/types/src/json.d.ts +13 -0
  29. package/types/src/locale.d.ts +14 -0
  30. package/types/src/mail.d.ts +67 -0
  31. package/types/src/managed-environment.d.ts +32 -0
  32. package/types/src/membership.d.ts +318 -0
  33. package/types/src/oauth.d.ts +7 -0
  34. package/types/src/ops.d.ts +657 -0
  35. package/types/src/path-segment.d.ts +5 -0
  36. package/types/src/permissions.d.ts +50 -0
  37. package/types/src/requirement.d.ts +24 -0
  38. package/types/src/rpc.d.ts +283 -0
  39. package/types/src/sha256.d.ts +2 -0
  40. package/types/src/terminal.d.ts +72 -0
  41. package/types/src/token.d.ts +240 -0
  42. package/types/src/types.d.ts +196 -0
  43. package/types/src/wire.d.ts +65 -0
  44. package/types/src/workloads.d.ts +25 -0
package/src/ops.ts ADDED
@@ -0,0 +1,1933 @@
1
+ // The ops wire (ADR-0069): the one platform-composed row through which Control reaches an application environment's
2
+ // object on Cloudflare, the requests it sends there and the answers the object gives. Control and the framework both
3
+ // import it, so the two sides parse one shape. Every parser is strict: an unknown key, a missing field or a wrong type
4
+ // refuses the whole value.
5
+
6
+ import { isDigest } from './endpoint-digest'
7
+ import { FRAMEWORK_RELEASE_PATTERN } from './framework-release'
8
+ import { prop } from './json'
9
+ import { sha256Hex } from './sha256'
10
+ import { WORKLOAD_NAME } from './workloads'
11
+
12
+ /** Every ops request's path lies under this prefix, on the environment's own domain. */
13
+ export const OPS_PREFIX = '/__fabrika/ops/'
14
+
15
+ /**
16
+ * The fixed id of the composed row. An authored endpoint id starts with a letter, so no contract can take it. The row's
17
+ * digest is not a constant: proxy-core computes it where every row is digested, from these fields.
18
+ */
19
+ export const OPS_ROW_ID = '__fabrika.ops'
20
+
21
+ /** The composed row's path. */
22
+ export const OPS_ROW_PATH = `${OPS_PREFIX}*`
23
+
24
+ /** The composed row's method. */
25
+ export const OPS_METHOD = 'POST'
26
+
27
+ /** The one content type the composed row admits. */
28
+ export const OPS_CONTENT_TYPE = 'application/json'
29
+
30
+ /** The operations the object serves, each at `opsPath(operation)`. */
31
+ export const OPS_OPERATIONS = ['inspect', 'state', 'migrate', 'export', 'import', 'restore', 'timers'] as const
32
+
33
+ export type OpsOperation = (typeof OPS_OPERATIONS)[number]
34
+
35
+ export function opsPath(operation: OpsOperation): string {
36
+ return `${OPS_PREFIX}${operation}`
37
+ }
38
+
39
+ /** The operation a request path names, or `null` for any other path, which gets `opsRefusal()`. */
40
+ export function parseOpsOperation(path: string): OpsOperation | null {
41
+ return OPS_OPERATIONS.find((operation) => opsPath(operation) === path) ?? null
42
+ }
43
+
44
+ /**
45
+ * The one answer inside the prefix to a missing or wrong key, a wrong endpoint header, an unknown operation and a
46
+ * refused object name: the same status, no body and no headers, so none of them tells the caller which it was.
47
+ */
48
+ export const OPS_REFUSAL_STATUS = 404
49
+
50
+ export function opsRefusal(): Response {
51
+ return new Response(null, { status: OPS_REFUSAL_STATUS })
52
+ }
53
+
54
+ /** Ops key digests: `sha256:<64 hex>` of each key, joined by `,`; one, or two while a rotation reconciles. */
55
+ export type OpsKeyDigests = readonly [string] | readonly [string, string]
56
+
57
+ /** The digest of an ops key, the only form the object holds (`FABRIKA_OPS_KEY_DIGESTS`). */
58
+ export function opsKeyDigest(key: string): string {
59
+ return `sha256:${sha256Hex(key)}`
60
+ }
61
+
62
+ /** The value of `FABRIKA_OPS_KEY_DIGESTS`, or `null` unless it holds one or two distinct digests. */
63
+ export function parseOpsKeyDigests(value: string): OpsKeyDigests | null {
64
+ const [first, second, ...rest] = value.split(',')
65
+ if (first === undefined || !isDigest(first) || rest.length > 0) return null
66
+ if (second === undefined) return [first]
67
+ return isDigest(second) && second !== first ? [first, second] : null
68
+ }
69
+
70
+ /** The value Control writes into `FABRIKA_OPS_KEY_DIGESTS`; throws on a list `parseOpsKeyDigests` would refuse. */
71
+ export function formatOpsKeyDigests(digests: OpsKeyDigests): string {
72
+ const value = digests.join(',')
73
+ if (parseOpsKeyDigests(value) === null) throw new Error('ops key digests must be one or two distinct sha256 digests')
74
+ return value
75
+ }
76
+
77
+ /** The object of ordinary traffic without `FABRIKA_APPLICATION_OBJECT`, and the only one an ops request may name then. */
78
+ export const DEFAULT_APPLICATION_OBJECT = 'application'
79
+
80
+ /** The most names `FABRIKA_APPLICATION_OBJECTS` holds. */
81
+ export const MAX_APPLICATION_OBJECTS = 16
82
+
83
+ /** An object name: lowercase, at most 63 characters, safe as one segment of an R2 key. */
84
+ const APPLICATION_OBJECT_NAME = /^[a-z][a-z0-9-]{0,62}$/
85
+
86
+ export function parseApplicationObjectName(value: unknown): string | null {
87
+ return typeof value === 'string' && APPLICATION_OBJECT_NAME.test(value) ? value : null
88
+ }
89
+
90
+ /** The object of ordinary traffic, and the objects an ops request may name, which include it. */
91
+ export interface ApplicationObjects {
92
+ readonly object: string
93
+ readonly objects: readonly string[]
94
+ }
95
+
96
+ /**
97
+ * `FABRIKA_APPLICATION_OBJECT` and `FABRIKA_APPLICATION_OBJECTS` (distinct names joined by `,`, 1 to 16, holding the
98
+ * first), or `null`. Without either the object is `application`; a deploy writes both, so one alone is refused.
99
+ */
100
+ export function parseApplicationObjects(object: string | undefined, objects: string | undefined): ApplicationObjects | null {
101
+ if (object === undefined && objects === undefined) return { object: DEFAULT_APPLICATION_OBJECT, objects: [DEFAULT_APPLICATION_OBJECT] }
102
+ if (object === undefined || objects === undefined || parseApplicationObjectName(object) === null) return null
103
+ const names = objects.split(',')
104
+ const valid = names.length <= MAX_APPLICATION_OBJECTS && names.every((name) => parseApplicationObjectName(name) !== null)
105
+ return valid && new Set(names).size === names.length && names.includes(object) ? { object, objects: names } : null
106
+ }
107
+
108
+ /** The R2 key, in the environment's bucket, of the maintenance state of `object`. */
109
+ export function OPS_STATE_KEY(object: string): string {
110
+ if (parseApplicationObjectName(object) === null) throw new Error('an ops state key needs a valid object name')
111
+ return `__fabrika/ops/${object}.json`
112
+ }
113
+
114
+ /** The maintenance modes, from the most permissive. */
115
+ export const OPS_MODES = ['open', 'read-only', 'closed', 'inspect'] as const
116
+
117
+ export type OpsMode = (typeof OPS_MODES)[number]
118
+
119
+ /** A table's row count is capped here: a full count bills every row read. A count at the cap means at least the cap. */
120
+ export const OPS_ROW_COUNT_CAP = 100_000
121
+
122
+ /** `POST /__fabrika/ops/inspect`: the projection, or with `content` the content-bearing view (`data.content.read`). */
123
+ export interface OpsInspectRequest {
124
+ readonly object: string
125
+ readonly content: boolean
126
+ }
127
+
128
+ /** `POST /__fabrika/ops/state`: a maintenance transition under a generation Control allocated. */
129
+ export interface OpsStateRequest {
130
+ readonly object: string
131
+ readonly generation: number
132
+ readonly mode: OpsMode
133
+ }
134
+
135
+ /** Sent once the state is published and the drain is over; `stillRunning` counts what ran past the drain's bound. */
136
+ export interface OpsStateAck {
137
+ readonly generation: number
138
+ readonly mode: OpsMode
139
+ readonly stillRunning: number
140
+ }
141
+
142
+ /** `POST /__fabrika/ops/migrate`: run the pending migrations under the published generation. */
143
+ export interface OpsMigrateRequest {
144
+ readonly object: string
145
+ readonly generation: number
146
+ }
147
+
148
+ /** The state a transition is judged against: the object's current generation and mode, `null` before the first. */
149
+ export interface OpsPublishedState {
150
+ readonly generation: number
151
+ readonly mode: OpsMode
152
+ }
153
+
154
+ /**
155
+ * Whether a transition is stale: a lower generation, or the same with another mode. The same generation and mode is a
156
+ * retry, which the object replays.
157
+ */
158
+ export function opsTransitionRefused(current: OpsPublishedState | null, request: OpsPublishedState): boolean {
159
+ if (current === null) return false
160
+ return request.generation < current.generation || (request.generation === current.generation && request.mode !== current.mode)
161
+ }
162
+
163
+ /** The status of a stale refusal. It is answered only after authentication, so it may say what is published. */
164
+ export const OPS_STALE_STATUS = 409
165
+
166
+ /** The body of a stale refusal of a transition or a migration. */
167
+ export interface OpsStaleRefusal {
168
+ readonly refused: 'stale_generation'
169
+ readonly published: OpsPublishedState | null
170
+ }
171
+
172
+ /** One row of the object's migration ledger. */
173
+ export interface OpsMigration {
174
+ readonly bundle: string
175
+ readonly name: string
176
+ readonly checksum: string
177
+ readonly appliedAt: string
178
+ }
179
+
180
+ /** Sent once the migrations ran and the application booted, with the new ledger. */
181
+ export interface OpsMigrateAck {
182
+ readonly generation: number
183
+ readonly migrations: readonly OpsMigration[]
184
+ }
185
+
186
+ export interface OpsMaintenance {
187
+ readonly mode: OpsMode
188
+ /** `null` while no transition was ever published: the object is `open`. */
189
+ readonly generation: number | null
190
+ /** Whether R2 holds this state; `false` while its put is pending. */
191
+ readonly published: boolean
192
+ }
193
+
194
+ export interface OpsTableCount {
195
+ readonly name: string
196
+ /** At most `OPS_ROW_COUNT_CAP`. */
197
+ readonly rows: number
198
+ }
199
+
200
+ export interface OpsDatabase {
201
+ readonly sizeBytes: number
202
+ readonly tables: readonly OpsTableCount[]
203
+ }
204
+
205
+ export interface OpsScheduler {
206
+ /** The current alarm, or `null` when none is set. */
207
+ readonly alarm: string | null
208
+ }
209
+
210
+ /** A job's last run and its outcome: a contract job, or a framework job such as `fabrika-file-sweep`. */
211
+ export interface OpsJob {
212
+ readonly job: string
213
+ readonly lastStatus: 'succeeded' | 'failed' | null
214
+ readonly lastStartedAt: string | null
215
+ readonly lastFinishedAt: string | null
216
+ readonly lastDurationMs: number | null
217
+ }
218
+
219
+ export type OpsFileStatus = 'pending' | 'quarantined' | 'live' | 'rejected'
220
+
221
+ export interface OpsFileCount {
222
+ readonly kind: string
223
+ readonly status: OpsFileStatus
224
+ readonly count: number
225
+ }
226
+
227
+ /** A delivery is `claimed` while it holds a lease, `completed` once its handler's transaction cleared it. */
228
+ export interface OpsWebhookCount {
229
+ readonly webhook: string
230
+ readonly state: 'claimed' | 'completed'
231
+ readonly count: number
232
+ }
233
+
234
+ export interface OpsBootFailure {
235
+ readonly at: string
236
+ }
237
+
238
+ /** The boot failure with the application's error text, which is content. */
239
+ export interface OpsBootFailureContent extends OpsBootFailure {
240
+ readonly message: string
241
+ readonly stack: string | null
242
+ }
243
+
244
+ /**
245
+ * The allowlisted projection (`data.read`): counts, sizes, timestamps, the identifiers the platform or the contract
246
+ * names, and status codes. Every timestamp is ISO 8601 in UTC with milliseconds.
247
+ */
248
+ export interface OpsView {
249
+ readonly release: string
250
+ readonly maintenance: OpsMaintenance
251
+ readonly database: OpsDatabase
252
+ readonly migrations: readonly OpsMigration[]
253
+ readonly scheduler: OpsScheduler
254
+ readonly jobs: readonly OpsJob[]
255
+ readonly files: readonly OpsFileCount[]
256
+ readonly webhooks: readonly OpsWebhookCount[]
257
+ readonly bootFailure: OpsBootFailure | null
258
+ }
259
+
260
+ /** The view a `data.content.read` caller gets: the projection, with the application's error text. */
261
+ export interface OpsContentView extends Omit<OpsView, 'bootFailure'> {
262
+ readonly bootFailure: OpsBootFailureContent | null
263
+ }
264
+
265
+ // A request's `object` is only well-formed here; the handler refuses a name its list does not hold with `opsRefusal()`.
266
+ export function parseOpsInspectRequest(body: unknown): OpsInspectRequest | null {
267
+ const object = parseApplicationObjectName(prop(body, 'object'))
268
+ const content = prop(body, 'content')
269
+ return exactKeys(body, ['object', 'content']) && object !== null && typeof content === 'boolean' ? { object, content } : null
270
+ }
271
+
272
+ export function parseOpsStateRequest(body: unknown): OpsStateRequest | null {
273
+ if (!exactKeys(body, ['object', 'generation', 'mode'])) return null
274
+ const object = parseApplicationObjectName(prop(body, 'object'))
275
+ const generation = readGeneration(prop(body, 'generation'))
276
+ const mode = readMode(prop(body, 'mode'))
277
+ return object === null || generation === null || mode === null ? null : { object, generation, mode }
278
+ }
279
+
280
+ export function parseOpsStateAck(body: unknown): OpsStateAck | null {
281
+ if (!exactKeys(body, ['generation', 'mode', 'stillRunning'])) return null
282
+ const generation = readGeneration(prop(body, 'generation'))
283
+ const mode = readMode(prop(body, 'mode'))
284
+ const stillRunning = readCount(prop(body, 'stillRunning'))
285
+ return generation === null || mode === null || stillRunning === null ? null : { generation, mode, stillRunning }
286
+ }
287
+
288
+ export function parseOpsMigrateRequest(body: unknown): OpsMigrateRequest | null {
289
+ const object = parseApplicationObjectName(prop(body, 'object'))
290
+ const generation = readGeneration(prop(body, 'generation'))
291
+ return exactKeys(body, ['object', 'generation']) && object !== null && generation !== null ? { object, generation } : null
292
+ }
293
+
294
+ export function parseOpsStaleRefusal(body: unknown): OpsStaleRefusal | null {
295
+ if (!exactKeys(body, ['refused', 'published']) || prop(body, 'refused') !== 'stale_generation') return null
296
+ const raw = prop(body, 'published')
297
+ if (raw === null) return { refused: 'stale_generation', published: null }
298
+ if (!exactKeys(raw, ['generation', 'mode'])) return null
299
+ const generation = readGeneration(prop(raw, 'generation'))
300
+ const mode = readMode(prop(raw, 'mode'))
301
+ return generation === null || mode === null ? null : { refused: 'stale_generation', published: { generation, mode } }
302
+ }
303
+
304
+ export function parseOpsMigrateAck(body: unknown): OpsMigrateAck | null {
305
+ if (!exactKeys(body, ['generation', 'migrations'])) return null
306
+ const generation = readGeneration(prop(body, 'generation'))
307
+ const migrations = readList(prop(body, 'migrations'), readMigration)
308
+ return generation === null || migrations === null ? null : { generation, migrations }
309
+ }
310
+
311
+ export function parseOpsView(body: unknown): OpsView | null {
312
+ const failure = prop(body, 'bootFailure')
313
+ const bootFailure = failure === null ? null : readBootFailure(failure)
314
+ if (bootFailure === undefined) return null
315
+ const view = readViewFields(body)
316
+ return view === null ? null : { ...view, bootFailure }
317
+ }
318
+
319
+ export function parseOpsContentView(body: unknown): OpsContentView | null {
320
+ const failure = prop(body, 'bootFailure')
321
+ const bootFailure = failure === null ? null : readBootFailureContent(failure)
322
+ if (bootFailure === undefined) return null
323
+ const view = readViewFields(body)
324
+ return view === null ? null : { ...view, bootFailure }
325
+ }
326
+
327
+ // Dumps (ADR-0070): a consistent backup or a diagnostic export of an object's SQLite, which Control writes step by step
328
+ // into the environment's bucket, and the importer that loads a consistent one into a fresh object. No type here carries
329
+ // a row's values or a file's bytes, except the line and row encodings, which only the object and a download read.
330
+
331
+ /** The version of the dump format: the value, row and line encodings, the table hash and the manifest. */
332
+ export const OPS_DUMP_FORMAT = 1
333
+
334
+ /** The most rows one keyset page reads. */
335
+ export const OPS_DUMP_PAGE_ROWS = 1000
336
+
337
+ /**
338
+ * The size of every part of a dump's data object but the last, which is at most this. R2 refuses a multipart upload
339
+ * whose parts differ in size, and a part below 5 MiB; a 2 MB row, its text and blobs as hex, fits one part uncompressed.
340
+ */
341
+ export const OPS_DUMP_PART_SIZE = 8 * 1024 * 1024
342
+
343
+ /**
344
+ * The most bytes one part decompresses to: its lines, each with its newline. An import step holds a part's every form
345
+ * at once (compressed, decompressed, the lines, the values, the bound bytes), so this bounds its memory well inside an
346
+ * isolate's 128 MB.
347
+ */
348
+ export const OPS_DUMP_PART_MAX_RAW_BYTES = 16 * 1024 * 1024
349
+
350
+ /** The most rows one part holds, which bounds the inserts, and the link updates, of one import step. */
351
+ export const OPS_DUMP_PART_MAX_ROWS = 50_000
352
+
353
+ /** R2's most parts in one multipart upload. */
354
+ export const OPS_DUMP_MAX_PARTS = 10_000
355
+
356
+ /** The largest manifest a reader accepts, in UTF-8 bytes. */
357
+ export const OPS_DUMP_MANIFEST_MAX_BYTES = 4 * 1024 * 1024
358
+
359
+ /** The object a scheduled backup is rehearsed in. Every deploy at a gated release lists it; nothing serves from it. */
360
+ export const OPS_REHEARSAL_OBJECT = 'rehearsal'
361
+
362
+ /** A dump: the object it was taken from, the id Control gave it (a UUID), and whether it is a consistent backup. */
363
+ export interface OpsDumpRef {
364
+ readonly object: string
365
+ readonly dump: string
366
+ readonly consistent: boolean
367
+ }
368
+
369
+ /** The R2 key of a dump's data or manifest: a consistent backup under `__fabrika/backups/`, a diagnostic export under `__fabrika/exports/`. */
370
+ export function OPS_DUMP_KEY(ref: OpsDumpRef, file: 'data' | 'manifest'): string {
371
+ if (parseApplicationObjectName(ref.object) === null || !UUID.test(ref.dump)) throw new Error('a dump key needs a valid object name and dump id')
372
+ return `__fabrika/${ref.consistent ? 'backups' : 'exports'}/${ref.object}/${ref.dump}/${file === 'data' ? 'data.ndjson.gz' : 'manifest.json'}`
373
+ }
374
+
375
+ /**
376
+ * One stored value, as `typeof()` names it. An integer travels as its decimal text, because workerd reads an int64 into
377
+ * a double; a real travels as the double workerd reads exactly. Text and a blob travel as the upper-case hex of their
378
+ * bytes, so text that is not valid UTF-8 keeps every byte.
379
+ */
380
+ export type OpsDumpValue =
381
+ | null
382
+ | { readonly type: 'integer'; readonly value: string }
383
+ | { readonly type: 'real'; readonly value: number }
384
+ | { readonly type: 'text'; readonly value: string }
385
+ | { readonly type: 'blob'; readonly value: string }
386
+
387
+ /**
388
+ * The two result columns a dump reads for `column`: `typeof()` and the value in the form `readOpsDumpValue` takes, an
389
+ * integer as `CAST(c AS TEXT)`, a real as itself, text as `hex(CAST(c AS BLOB))` and a blob as `hex(c)`.
390
+ */
391
+ export function opsDumpColumnProjection(column: string): string {
392
+ const c = quoteIdentifier(column)
393
+ return `typeof(${c}), CASE typeof(${c}) WHEN 'integer' THEN CAST(${c} AS TEXT) WHEN 'real' THEN ${c} WHEN 'text' THEN hex(CAST(${c} AS BLOB)) WHEN 'blob' THEN hex(${c}) END`
394
+ }
395
+
396
+ /** The value `opsDumpColumnProjection` read. Throws, naming no value, on a pair it would not produce. */
397
+ export function readOpsDumpValue(type: unknown, value: unknown): OpsDumpValue {
398
+ if (type === 'null' && value === null) return null
399
+ if (type === 'integer' && typeof value === 'string' && isInt64Text(value)) return { type, value }
400
+ if (type === 'real' && typeof value === 'number' && !Number.isNaN(value)) return { type, value }
401
+ if ((type === 'text' || type === 'blob') && typeof value === 'string' && isBytesHex(value)) return { type, value }
402
+ throw new Error('a projected dump value does not match its type')
403
+ }
404
+
405
+ /**
406
+ * The most result columns, and the most parameters, one statement of workerd's SQLite takes; a table holds at most as
407
+ * many columns.
408
+ */
409
+ export const OPS_SQLITE_MAX_COLUMNS = 100
410
+
411
+ /** The most columns of a table one statement of a page read projects: two result columns each, beside the rowid twice. */
412
+ export const OPS_DUMP_READ_COLUMNS = (OPS_SQLITE_MAX_COLUMNS - 2) / 2
413
+
414
+ /** One row of a keyset page: its rowid as decimal text, then the rowid and every column as the dump writes them. */
415
+ export interface OpsDumpPageRow {
416
+ readonly rowid: string
417
+ readonly values: readonly OpsDumpValue[]
418
+ }
419
+
420
+ /** Runs one statement of a page read, with the parameters of the read's condition, and answers its rows. */
421
+ export type OpsDumpPageQuery = (sql: string) => readonly Readonly<Record<string, unknown>>[]
422
+
423
+ /**
424
+ * One keyset page of `table`: the first `limit` rows by rowid that `condition` (`WHERE …`, or empty) admits, read the
425
+ * way the producer and the importer's verification both read them. Each column reads as two result columns, so a table
426
+ * wider than `OPS_DUMP_READ_COLUMNS` reads in several statements over the same rows, which the caller runs in one
427
+ * synchronous turn, so no write falls between them. The common table expression names every result column, which an
428
+ * expression alone does not.
429
+ */
430
+ export function readOpsDumpPage(query: OpsDumpPageQuery, table: OpsDumpTablePlan, condition: string, limit: number): OpsDumpPageRow[] {
431
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new Error('a dump page reads at least one row')
432
+ const keyset = quoteIdentifier(table.keyset)
433
+ const reads: { readonly start: number; readonly count: number; readonly rows: readonly Readonly<Record<string, unknown>>[] }[] = []
434
+ for (let start = 0; start === 0 || start < table.columns.length; start += OPS_DUMP_READ_COLUMNS) {
435
+ const columns = table.columns.slice(start, start + OPS_DUMP_READ_COLUMNS)
436
+ const names = columns.flatMap((_, offset) => [`t${start + offset}`, `v${start + offset}`])
437
+ const projections = [keyset, `CAST(${keyset} AS TEXT)`, ...columns.map(opsDumpColumnProjection)]
438
+ const rows = query(
439
+ `WITH page(${['k', 'r', ...names].join(', ')}) AS (SELECT ${projections.join(', ')} FROM main.${quoteIdentifier(table.name)} ${condition}
440
+ ORDER BY ${keyset} LIMIT ${limit}) SELECT ${['r', ...names].join(', ')} FROM page ORDER BY k`,
441
+ )
442
+ reads.push({ start, count: columns.length, rows })
443
+ }
444
+ const first = reads[0]?.rows ?? []
445
+ if (reads.some(({ rows }) => rows.length !== first.length)) throw new Error('the reads of one dump page disagree on its rows')
446
+ return first.map((row, index) => {
447
+ const rowid = readOpsDumpValue('integer', row['r'])
448
+ if (rowid === null || rowid.type !== 'integer') throw new Error('a rowid reads as an integer')
449
+ const values: OpsDumpValue[] = [rowid]
450
+ for (const { start, count, rows } of reads) {
451
+ const read = rows[index]
452
+ if (read?.['r'] !== rowid.value) throw new Error('the reads of one dump page disagree on its rows')
453
+ for (let column = start; column < start + count; column++) {
454
+ values.push(readOpsDumpValue(read[`t${column}`], read[`v${column}`]))
455
+ }
456
+ }
457
+ return { rowid: rowid.value, values }
458
+ })
459
+ }
460
+
461
+ /**
462
+ * The SQL that names a dump's rowid inline, so a row of a table at `OPS_SQLITE_MAX_COLUMNS` binds no more parameters
463
+ * than it has columns. It is the checked decimal text in a string literal, cast as `opsDumpValueBinding` casts it.
464
+ */
465
+ export function opsDumpRowidSql(rowid: OpsDumpValue): string {
466
+ if (rowid === null || rowid.type !== 'integer' || !isInt64Text(rowid.value)) throw new Error('a dump rowid must be an integer')
467
+ return `CAST('${rowid.value}' AS INTEGER)`
468
+ }
469
+
470
+ /** What a statement binds for one value of a dump. */
471
+ export type OpsDumpParam = string | number | Uint8Array | null
472
+
473
+ /** The SQL expression that writes a value back and the parameter its `?` binds. */
474
+ export interface OpsDumpBinding {
475
+ readonly sql: string
476
+ readonly param: OpsDumpParam
477
+ }
478
+
479
+ /**
480
+ * How the importer writes a value back, a rowid included, without a double or a JavaScript string in between: an
481
+ * integer as its decimal text through `CAST(? AS INTEGER)`, a real through `CAST(? AS REAL)` (a binder may bind an
482
+ * integral double as an integer), text as its bytes through `CAST(? AS TEXT)`, and a blob as its bytes.
483
+ */
484
+ export function opsDumpValueBinding(value: OpsDumpValue): OpsDumpBinding {
485
+ if (value === null) return { sql: '?', param: null }
486
+ switch (value.type) {
487
+ case 'integer':
488
+ return { sql: 'CAST(? AS INTEGER)', param: value.value }
489
+ case 'real':
490
+ return { sql: 'CAST(? AS REAL)', param: value.value }
491
+ case 'text':
492
+ return { sql: 'CAST(? AS TEXT)', param: hexBytes(value.value) }
493
+ case 'blob':
494
+ return { sql: '?', param: hexBytes(value.value) }
495
+ }
496
+ }
497
+
498
+ /**
499
+ * The canonical encoding of a row, the text a table hash is computed over: a JSON array (`JSON.stringify`, so no
500
+ * whitespace) of `null` or a tagged string per value, `i:<decimal>`, `r:<shortest round-trip double>`, `t:<HEX>` or
501
+ * `b:<HEX>`. A real keeps `-0`, `Infinity` and `-Infinity`; NaN is never stored. Throws, naming no value, on a value
502
+ * outside these rules.
503
+ */
504
+ export function encodeOpsDumpRow(values: readonly OpsDumpValue[]): string {
505
+ return JSON.stringify(values.map(encodeValue))
506
+ }
507
+
508
+ /** The values of a row's canonical encoding, or `null` for any other text, a different spelling of the same row included. */
509
+ export function decodeOpsDumpRow(text: string): readonly OpsDumpValue[] | null {
510
+ const values = readRowValues(parseJson(text))
511
+ return values !== null && encodeOpsDumpRow(values) === text ? values : null
512
+ }
513
+
514
+ /** One line of a dump's NDJSON: a table's row, which is its rowid, then every column that is not generated. */
515
+ export interface OpsDumpLine {
516
+ readonly table: string
517
+ readonly row: readonly OpsDumpValue[]
518
+ }
519
+
520
+ /** The line `{"table":"<name>","row":<canonical row>}`. Throws on a table name outside the data layer's identifier rule. */
521
+ export function encodeOpsDumpLine(line: OpsDumpLine): string {
522
+ if (!TABLE_NAME.test(line.table)) throw new Error('a dump line needs a plain table name')
523
+ return `{"table":${JSON.stringify(line.table)},"row":${encodeOpsDumpRow(line.row)}}`
524
+ }
525
+
526
+ /** A line, or `null` for anything `encodeOpsDumpLine` would not write. */
527
+ export function decodeOpsDumpLine(text: string): OpsDumpLine | null {
528
+ const parsed = parseJson(text)
529
+ if (!exactKeys(parsed, ['table', 'row'])) return null
530
+ const table = readMatch(prop(parsed, 'table'), TABLE_NAME)
531
+ const row = readRowValues(prop(parsed, 'row'))
532
+ if (table === null || row === null) return null
533
+ return encodeOpsDumpLine({ table, row }) === text ? { table, row } : null
534
+ }
535
+
536
+ /** The hash of a table without rows: the SHA-256 of the empty string. */
537
+ export const OPS_EMPTY_TABLE_HASH = sha256Hex('')
538
+
539
+ /**
540
+ * Folds rows, each in its canonical encoding and in keyset order, into a table's hash. Each row's step is the SHA-256 of
541
+ * the previous hash's hex, a newline and the row, so a table read page by page, across steps, folds to one value.
542
+ */
543
+ export function foldOpsTableHash(hash: string, rows: Iterable<string>): string {
544
+ if (!SHA256_HEX.test(hash)) throw new Error('a table hash is 64 lower-case hex digits')
545
+ let current = hash
546
+ for (const row of rows) current = sha256Hex(`${current}\n${row}`)
547
+ return current
548
+ }
549
+
550
+ /** A column as `PRAGMA table_xinfo` describes it. */
551
+ export interface OpsDumpSchemaColumn {
552
+ readonly name: string
553
+ /** The declared type, as written. */
554
+ readonly type: string
555
+ readonly notNull: boolean
556
+ /** The column's position in the primary key from 1, `0` outside it. */
557
+ readonly primaryKey: number
558
+ /** A generated column (`hidden` 2 or 3), which a dump does not carry. */
559
+ readonly generated: boolean
560
+ }
561
+
562
+ /** An index as `PRAGMA index_list` and `PRAGMA index_xinfo` (its key columns) describe it. */
563
+ export interface OpsDumpSchemaIndex {
564
+ readonly unique: boolean
565
+ readonly origin: 'c' | 'u' | 'pk'
566
+ readonly partial: boolean
567
+ /** The key columns in order, `null` for an expression. */
568
+ readonly columns: readonly (string | null)[]
569
+ }
570
+
571
+ /** A foreign key as `PRAGMA foreign_key_list` describes it, its rows grouped by `id` and ordered by `seq`. */
572
+ export interface OpsDumpSchemaForeignKey {
573
+ readonly parent: string
574
+ readonly columns: readonly string[]
575
+ /** The parent's columns (`to`), or `null` when the key names the parent's primary key implicitly. */
576
+ readonly references: readonly string[] | null
577
+ /**
578
+ * Whether the key is `DEFERRABLE INITIALLY DEFERRED`. No PRAGMA reports it: a reader takes it from the table's SQL,
579
+ * and one that cannot tell which key a clause belongs to marks every key of that table.
580
+ */
581
+ readonly initiallyDeferred: boolean
582
+ }
583
+
584
+ /** A table as `PRAGMA table_list` (`type`, `wr`) and the PRAGMAs above describe it. */
585
+ export interface OpsDumpSchemaTable {
586
+ readonly name: string
587
+ readonly virtual: boolean
588
+ readonly withoutRowid: boolean
589
+ /**
590
+ * Every name a `CHECK` constraint of the table's SQL reads, ASCII-lowercase and unquoted (keywords included), so a
591
+ * column it does not list cannot change what a `CHECK` answers. Empty for a table without one; `null` from a reader
592
+ * that cannot tell, which counts as naming every column.
593
+ */
594
+ readonly checkNames: readonly string[] | null
595
+ readonly columns: readonly OpsDumpSchemaColumn[]
596
+ readonly indexes: readonly OpsDumpSchemaIndex[]
597
+ readonly foreignKeys: readonly OpsDumpSchemaForeignKey[]
598
+ }
599
+
600
+ /** Every table a dump holds: `sqlite_schema`'s tables but SQLite's internal ones, `sqlite_sequence` excepted, and `_cf_`'s. */
601
+ export interface OpsDumpSchema {
602
+ readonly tables: readonly OpsDumpSchemaTable[]
603
+ }
604
+
605
+ /** How one table is dumped and loaded. */
606
+ export interface OpsDumpTablePlan {
607
+ readonly name: string
608
+ /** The name that reads the rowid: the `INTEGER PRIMARY KEY` column, else the first of `rowid`, `_rowid_`, `oid` no column takes. */
609
+ readonly keyset: string
610
+ /** Every column that is not generated, in declaration order: a row is the rowid, then these. */
611
+ readonly columns: readonly string[]
612
+ /** The columns of the foreign keys inside a cycle, which a part writes `NULL` and the link pass sets, in declaration order. */
613
+ readonly deferred: readonly string[]
614
+ }
615
+
616
+ /** The tables of a dump in load order: every parent outside a table's own cycle comes before it. */
617
+ export interface OpsDumpPlan {
618
+ readonly tables: readonly OpsDumpTablePlan[]
619
+ }
620
+
621
+ /**
622
+ * The one rule both the producer, at export `begin`, and the importer, at import `begin`, apply to a schema: the plan
623
+ * a dump is written and loaded by, or an `unsupported_schema` refusal naming the table. A foreign key whose parent lies
624
+ * in its own table's cycle (the table itself included) is loaded `NULL` and linked once every row is in, so each of its
625
+ * columns must take a temporary `NULL`: nullable, outside the primary key, referenced by no foreign key, named by no
626
+ * `CHECK`, in a table without a `NOT NULL` generated column, a generated column a `CHECK` names, or a partial, expression
627
+ * or generated-column unique index. A `WITHOUT ROWID` or
628
+ * virtual table, a table without a name that reads its rowid, a foreign key to a table outside the dump or without the
629
+ * named key, and a foreign key checked only at commit are refused.
630
+ */
631
+ export function planOpsDump(schema: OpsDumpSchema): OpsDumpPlan | OpsDataRefusal {
632
+ const sorted = [...schema.tables].sort((left, right) => compareNames(left.name, right.name))
633
+ if (!sorted.every((table) => TABLE_NAME.test(table.name)) || !distinct(sorted.map((table) => table.name))) return unsupported(null)
634
+ const byName = new Map(sorted.map((table) => [table.name, table]))
635
+ const tables: DescribedTable[] = []
636
+ for (const table of sorted) {
637
+ const keyset = table.virtual || table.withoutRowid ? null : rowidName(table)
638
+ const parents = resolveForeignKeys(table, byName)
639
+ if (keyset === null || parents === null) return unsupported(table.name)
640
+ tables.push({ table, keyset, parents })
641
+ }
642
+ const cycle = cycleIds(tables)
643
+ const referenced = new Set(tables.flatMap(({ parents }) => parents.flatMap((key) => key.references.map((column) => columnKey(key.parent, column)))))
644
+ const plans: OpsDumpTablePlan[] = []
645
+ for (const { table, keyset, parents } of loadOrder(tables, cycle)) {
646
+ const inCycle = parents.filter((key) => cycle.get(key.parent) === cycle.get(table.name))
647
+ const deferredNames = new Set(inCycle.flatMap((key) => key.columns.map(asciiLower)))
648
+ const deferred = table.columns.filter((column) => deferredNames.has(asciiLower(column.name)))
649
+ if (deferred.length > 0 && !takesTemporaryNull(table, deferred, referenced)) return unsupported(table.name)
650
+ plans.push({
651
+ name: table.name,
652
+ keyset,
653
+ columns: table.columns.filter((column) => !column.generated).map((column) => column.name),
654
+ deferred: deferred.map((column) => column.name),
655
+ })
656
+ }
657
+ return { tables: plans }
658
+ }
659
+
660
+ /** Where a dump or a verification stands in a table: the last rowid read, and the count and hash folded so far. */
661
+ export interface OpsDumpCursor {
662
+ readonly table: string
663
+ /** The rowid of the last row read, as decimal text; `null` before the table's first row. */
664
+ readonly after: string | null
665
+ readonly rows: number
666
+ readonly hash: string
667
+ }
668
+
669
+ /** A table a dump holds, with its exact row count and its hash. */
670
+ export interface OpsDumpTable {
671
+ readonly name: string
672
+ readonly rows: number
673
+ readonly hash: string
674
+ }
675
+
676
+ /** A part of a dump's data object: its number from 1, its size in bytes and the SHA-256 hex of its bytes. */
677
+ export interface OpsDumpPart {
678
+ readonly part: number
679
+ readonly size: number
680
+ readonly sha256: string
681
+ }
682
+
683
+ /** A part as R2 accepted it; Control completes the upload with the ETags. */
684
+ export interface OpsUploadedPart extends OpsDumpPart {
685
+ readonly etag: string
686
+ }
687
+
688
+ /** One `sqlite_schema` entry with SQL: an automatic index has none and is not listed. */
689
+ export interface OpsDumpSchemaEntry {
690
+ readonly type: 'table' | 'index' | 'trigger' | 'view'
691
+ readonly name: string
692
+ readonly table: string
693
+ readonly sql: string
694
+ }
695
+
696
+ /** `manifest.json`, written beside the data once its upload completed. `tables` is in load order. */
697
+ export interface OpsDumpManifest {
698
+ readonly format: typeof OPS_DUMP_FORMAT
699
+ readonly dump: string
700
+ readonly object: string
701
+ readonly consistent: boolean
702
+ readonly createdAt: string
703
+ /** The object's bookmark when the dump began. */
704
+ readonly bookmark: string
705
+ readonly release: string
706
+ readonly contractDigest: string
707
+ readonly ddl: readonly OpsDumpSchemaEntry[]
708
+ readonly migrations: readonly OpsMigration[]
709
+ readonly tables: readonly OpsDumpTable[]
710
+ readonly parts: readonly OpsDumpPart[]
711
+ }
712
+
713
+ /**
714
+ * A manifest Control holds or an answer carries; every table's DDL lists it, its parts are whole, and its
715
+ * `JSON.stringify` is at most `OPS_DUMP_MANIFEST_MAX_BYTES` in UTF-8, wherever it came from.
716
+ */
717
+ export function parseOpsDumpManifest(body: unknown): OpsDumpManifest | null {
718
+ if (!exactKeys(body, MANIFEST_KEYS) || prop(body, 'format') !== OPS_DUMP_FORMAT) return null
719
+ const dump = readMatch(prop(body, 'dump'), UUID)
720
+ const object = parseApplicationObjectName(prop(body, 'object'))
721
+ const consistent = prop(body, 'consistent')
722
+ const createdAt = readTimestamp(prop(body, 'createdAt'))
723
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
724
+ const release = readMatch(prop(body, 'release'), FRAMEWORK_RELEASE_PATTERN)
725
+ const contractDigest = prop(body, 'contractDigest')
726
+ const ddl = readList(prop(body, 'ddl'), readSchemaEntry)
727
+ const migrations = readList(prop(body, 'migrations'), readMigration)
728
+ const tables = readTables(prop(body, 'tables'))
729
+ const parts = readWholeParts(prop(body, 'parts'), readDumpPart)
730
+ if (
731
+ dump === null || object === null || typeof consistent !== 'boolean' || createdAt === null || bookmark === null || release === null
732
+ || typeof contractDigest !== 'string' || !isDigest(contractDigest) || ddl === null || migrations === null || tables === null || parts === null
733
+ ) {
734
+ return null
735
+ }
736
+ const declared = ddl.filter((entry) => entry.type === 'table').map((entry) => entry.name)
737
+ if (!distinct(ddl.map((entry) => `${entry.type} ${entry.name}`)) || !sameNames(declared, tables.map((table) => table.name))) return null
738
+ const manifest: OpsDumpManifest = {
739
+ format: OPS_DUMP_FORMAT,
740
+ dump,
741
+ object,
742
+ consistent,
743
+ createdAt,
744
+ bookmark,
745
+ release,
746
+ contractDigest,
747
+ ddl,
748
+ migrations,
749
+ tables,
750
+ parts,
751
+ }
752
+ return utf8Length(JSON.stringify(manifest)) <= OPS_DUMP_MANIFEST_MAX_BYTES ? manifest : null
753
+ }
754
+
755
+ /** A manifest's text as R2 holds it, refused above `OPS_DUMP_MANIFEST_MAX_BYTES` before it is parsed. */
756
+ export function readOpsDumpManifest(text: string): OpsDumpManifest | null {
757
+ if (utf8Length(text) > OPS_DUMP_MANIFEST_MAX_BYTES) return null
758
+ return parseOpsDumpManifest(parseJson(text))
759
+ }
760
+
761
+ /** What every export step names: a consistent backup carries the published generation, a diagnostic export none. */
762
+ export interface OpsExportScope {
763
+ readonly object: string
764
+ readonly generation: number | null
765
+ readonly consistent: boolean
766
+ readonly dump: string
767
+ }
768
+
769
+ /** Starts the multipart upload of the dump's data. */
770
+ export interface OpsExportBegin extends OpsExportScope {
771
+ readonly step: 'begin'
772
+ }
773
+
774
+ /** Fills part `part` from `cursor`, `null` only for the first part; a retry replaces the part. */
775
+ export interface OpsExportPart extends OpsExportScope {
776
+ readonly step: 'part'
777
+ readonly uploadId: string
778
+ readonly part: number
779
+ readonly cursor: OpsDumpCursor | null
780
+ }
781
+
782
+ /** Completes the upload from the parts and tables Control recorded, and writes the manifest. */
783
+ export interface OpsExportComplete extends OpsExportScope {
784
+ readonly step: 'complete'
785
+ readonly uploadId: string
786
+ readonly bookmark: string
787
+ readonly parts: readonly OpsUploadedPart[]
788
+ readonly tables: readonly OpsDumpTable[]
789
+ }
790
+
791
+ /** `POST /__fabrika/ops/export`: one step of a dump. */
792
+ export type OpsExportRequest = OpsExportBegin | OpsExportPart | OpsExportComplete
793
+
794
+ export interface OpsExportBeginAck {
795
+ readonly step: 'begin'
796
+ readonly uploadId: string
797
+ readonly bookmark: string
798
+ }
799
+
800
+ /** The part written, the tables it finished in load order, and where the next part starts: `null` once all is read. */
801
+ export interface OpsExportPartAck {
802
+ readonly step: 'part'
803
+ readonly uploaded: OpsUploadedPart
804
+ readonly tables: readonly OpsDumpTable[]
805
+ readonly next: OpsDumpCursor | null
806
+ }
807
+
808
+ export interface OpsExportCompleteAck {
809
+ readonly step: 'complete'
810
+ readonly manifest: OpsDumpManifest
811
+ }
812
+
813
+ export function parseOpsExportRequest(body: unknown): OpsExportRequest | null {
814
+ const scope = readExportScope(body)
815
+ if (scope === null) return null
816
+ switch (prop(body, 'step')) {
817
+ case 'begin':
818
+ return exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step']) ? { ...scope, step: 'begin' } : null
819
+ case 'part': {
820
+ if (!exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step', 'uploadId', 'part', 'cursor'])) return null
821
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
822
+ const part = readPartNumber(prop(body, 'part'))
823
+ const cursor = readNullable(prop(body, 'cursor'), readCursor)
824
+ if (uploadId === null || part === null || cursor === undefined || (part === 1) !== (cursor === null)) return null
825
+ return { ...scope, step: 'part', uploadId, part, cursor }
826
+ }
827
+ case 'complete': {
828
+ if (!exactKeys(body, [...EXPORT_SCOPE_KEYS, 'step', 'uploadId', 'bookmark', 'parts', 'tables'])) return null
829
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
830
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
831
+ const parts = readWholeParts(prop(body, 'parts'), readUploadedPart)
832
+ const tables = readTables(prop(body, 'tables'))
833
+ if (uploadId === null || bookmark === null || parts === null || tables === null) return null
834
+ return { ...scope, step: 'complete', uploadId, bookmark, parts, tables }
835
+ }
836
+ default:
837
+ return null
838
+ }
839
+ }
840
+
841
+ export function parseOpsExportBeginAck(body: unknown): OpsExportBeginAck | null {
842
+ if (!exactKeys(body, ['step', 'uploadId', 'bookmark']) || prop(body, 'step') !== 'begin') return null
843
+ const uploadId = readMatch(prop(body, 'uploadId'), OPAQUE_TOKEN)
844
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
845
+ return uploadId === null || bookmark === null ? null : { step: 'begin', uploadId, bookmark }
846
+ }
847
+
848
+ export function parseOpsExportPartAck(body: unknown): OpsExportPartAck | null {
849
+ if (!exactKeys(body, ['step', 'uploaded', 'tables', 'next']) || prop(body, 'step') !== 'part') return null
850
+ const uploaded = readUploadedPart(prop(body, 'uploaded'))
851
+ const tables = readTables(prop(body, 'tables'))
852
+ const next = readNullable(prop(body, 'next'), readCursor)
853
+ if (uploaded === null || tables === null || next === undefined || continuesFinished(tables, next)) return null
854
+ // Only the last part may be short: R2 refuses an upload whose other parts differ in size.
855
+ if (next !== null && uploaded.size !== OPS_DUMP_PART_SIZE) return null
856
+ return { step: 'part', uploaded, tables, next }
857
+ }
858
+
859
+ export function parseOpsExportCompleteAck(body: unknown): OpsExportCompleteAck | null {
860
+ if (!exactKeys(body, ['step', 'manifest']) || prop(body, 'step') !== 'complete') return null
861
+ const manifest = parseOpsDumpManifest(prop(body, 'manifest'))
862
+ return manifest === null ? null : { step: 'complete', manifest }
863
+ }
864
+
865
+ /** The consistent backup an import loads: always under `__fabrika/backups/`. */
866
+ export interface OpsDumpSource {
867
+ readonly object: string
868
+ readonly dump: string
869
+ }
870
+
871
+ /** What every import step names: the fresh target, published `inspect` under the operation's generation, and the backup. */
872
+ export interface OpsImportScope {
873
+ readonly object: string
874
+ readonly generation: number
875
+ readonly source: OpsDumpSource
876
+ }
877
+
878
+ /** Verifies the manifest, checks the target is fresh, and migrates it to the manifest's ledger. */
879
+ export interface OpsImportBegin extends OpsImportScope {
880
+ readonly step: 'begin'
881
+ }
882
+
883
+ /** Loads part `part`, writing a foreign key the load order cannot satisfy as `NULL`. */
884
+ export interface OpsImportPart extends OpsImportScope {
885
+ readonly step: 'part'
886
+ readonly part: number
887
+ }
888
+
889
+ /** Sets the foreign keys part `part` wrote as `NULL`, once every part is loaded. */
890
+ export interface OpsImportLink extends OpsImportScope {
891
+ readonly step: 'link'
892
+ readonly part: number
893
+ }
894
+
895
+ /** Reads the loaded tables back from `cursor`, `null` at the start, and compares counts and hashes with the manifest. */
896
+ export interface OpsImportVerify extends OpsImportScope {
897
+ readonly step: 'verify'
898
+ readonly cursor: OpsDumpCursor | null
899
+ }
900
+
901
+ /** Clears the import marker once every table verified, so Control may open the object. */
902
+ export interface OpsImportComplete extends OpsImportScope {
903
+ readonly step: 'complete'
904
+ }
905
+
906
+ /** Wipes an `inspect` object that holds an import marker and serves no traffic, with `deleteAll()`. */
907
+ export interface OpsImportDiscard {
908
+ readonly step: 'discard'
909
+ readonly object: string
910
+ readonly generation: number
911
+ }
912
+
913
+ /** `POST /__fabrika/ops/import`: one step of loading a consistent backup into a fresh object. */
914
+ export type OpsImportRequest = OpsImportBegin | OpsImportPart | OpsImportLink | OpsImportVerify | OpsImportComplete | OpsImportDiscard
915
+
916
+ export interface OpsImportBeginAck {
917
+ readonly step: 'begin'
918
+ readonly parts: number
919
+ }
920
+
921
+ /** `deferred` counts the loaded rows whose deferred foreign keys wait for the link pass. */
922
+ export interface OpsImportPartAck {
923
+ readonly step: 'part'
924
+ readonly part: number
925
+ readonly rows: number
926
+ readonly deferred: number
927
+ }
928
+
929
+ export interface OpsImportLinkAck {
930
+ readonly step: 'link'
931
+ readonly part: number
932
+ readonly rows: number
933
+ }
934
+
935
+ /** The tables verified in this step, each matching the manifest, and where the next step starts: `null` once all match. */
936
+ export interface OpsImportVerifyAck {
937
+ readonly step: 'verify'
938
+ readonly tables: readonly OpsDumpTable[]
939
+ readonly next: OpsDumpCursor | null
940
+ }
941
+
942
+ export interface OpsImportCompleteAck {
943
+ readonly step: 'complete'
944
+ readonly source: OpsDumpSource
945
+ }
946
+
947
+ export interface OpsImportDiscardAck {
948
+ readonly step: 'discard'
949
+ }
950
+
951
+ export function parseOpsImportRequest(body: unknown): OpsImportRequest | null {
952
+ const step = prop(body, 'step')
953
+ const object = parseApplicationObjectName(prop(body, 'object'))
954
+ const generation = readGeneration(prop(body, 'generation'))
955
+ if (object === null || generation === null) return null
956
+ if (step === 'discard') return exactKeys(body, ['step', 'object', 'generation']) ? { step, object, generation } : null
957
+ const source = readSource(prop(body, 'source'))
958
+ if (source === null) return null
959
+ const scope = { object, generation, source }
960
+ switch (step) {
961
+ case 'begin':
962
+ case 'complete':
963
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step']) ? { ...scope, step } : null
964
+ case 'part':
965
+ case 'link': {
966
+ const part = readPartNumber(prop(body, 'part'))
967
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step', 'part']) && part !== null ? { ...scope, step, part } : null
968
+ }
969
+ case 'verify': {
970
+ const cursor = readNullable(prop(body, 'cursor'), readCursor)
971
+ return exactKeys(body, [...IMPORT_SCOPE_KEYS, 'step', 'cursor']) && cursor !== undefined ? { ...scope, step, cursor } : null
972
+ }
973
+ default:
974
+ return null
975
+ }
976
+ }
977
+
978
+ export function parseOpsImportBeginAck(body: unknown): OpsImportBeginAck | null {
979
+ const parts = readPartNumber(prop(body, 'parts'))
980
+ return exactKeys(body, ['step', 'parts']) && prop(body, 'step') === 'begin' && parts !== null ? { step: 'begin', parts } : null
981
+ }
982
+
983
+ export function parseOpsImportPartAck(body: unknown): OpsImportPartAck | null {
984
+ if (!exactKeys(body, ['step', 'part', 'rows', 'deferred']) || prop(body, 'step') !== 'part') return null
985
+ const part = readPartNumber(prop(body, 'part'))
986
+ const rows = readCount(prop(body, 'rows'))
987
+ const deferred = readCount(prop(body, 'deferred'))
988
+ return part === null || rows === null || deferred === null ? null : { step: 'part', part, rows, deferred }
989
+ }
990
+
991
+ export function parseOpsImportLinkAck(body: unknown): OpsImportLinkAck | null {
992
+ if (!exactKeys(body, ['step', 'part', 'rows']) || prop(body, 'step') !== 'link') return null
993
+ const part = readPartNumber(prop(body, 'part'))
994
+ const rows = readCount(prop(body, 'rows'))
995
+ return part === null || rows === null ? null : { step: 'link', part, rows }
996
+ }
997
+
998
+ export function parseOpsImportVerifyAck(body: unknown): OpsImportVerifyAck | null {
999
+ if (!exactKeys(body, ['step', 'tables', 'next']) || prop(body, 'step') !== 'verify') return null
1000
+ const tables = readTables(prop(body, 'tables'))
1001
+ const next = readNullable(prop(body, 'next'), readCursor)
1002
+ if (tables === null || next === undefined || continuesFinished(tables, next)) return null
1003
+ return { step: 'verify', tables, next }
1004
+ }
1005
+
1006
+ export function parseOpsImportCompleteAck(body: unknown): OpsImportCompleteAck | null {
1007
+ const source = readSource(prop(body, 'source'))
1008
+ return exactKeys(body, ['step', 'source']) && prop(body, 'step') === 'complete' && source !== null ? { step: 'complete', source } : null
1009
+ }
1010
+
1011
+ export function parseOpsImportDiscardAck(body: unknown): OpsImportDiscardAck | null {
1012
+ return exactKeys(body, ['step']) && prop(body, 'step') === 'discard' ? { step: 'discard' } : null
1013
+ }
1014
+
1015
+ /**
1016
+ * Writes the sentinel (the operation's id) into the object's KV storage, and answers the current bookmark and the
1017
+ * bookmark of `at`, which Control records before it arms anything.
1018
+ */
1019
+ export interface OpsRestorePrepare {
1020
+ readonly step: 'prepare'
1021
+ readonly object: string
1022
+ readonly generation: number
1023
+ readonly sentinel: string
1024
+ readonly at: string
1025
+ }
1026
+
1027
+ /** Arms the restore of `target` for the next session, answers, then resets the object. */
1028
+ export interface OpsRestoreArm {
1029
+ readonly step: 'arm'
1030
+ readonly object: string
1031
+ readonly generation: number
1032
+ readonly sentinel: string
1033
+ readonly target: string
1034
+ }
1035
+
1036
+ /** Reads, after the reset, whether the sentinel is still there. It writes nothing, so it carries no generation. */
1037
+ export interface OpsRestoreVerify {
1038
+ readonly step: 'verify'
1039
+ readonly object: string
1040
+ readonly sentinel: string
1041
+ }
1042
+
1043
+ /** `POST /__fabrika/ops/restore`: one step of rewinding an `inspect` object that serves no traffic. */
1044
+ export type OpsRestoreRequest = OpsRestorePrepare | OpsRestoreArm | OpsRestoreVerify
1045
+
1046
+ export interface OpsRestorePrepareAck {
1047
+ readonly step: 'prepare'
1048
+ readonly current: string
1049
+ readonly target: string
1050
+ }
1051
+
1052
+ /** May be lost to the reset; `verify` reconciles. */
1053
+ export interface OpsRestoreArmAck {
1054
+ readonly step: 'arm'
1055
+ readonly undo: string
1056
+ }
1057
+
1058
+ /** A sentinel still present means the restore did not happen. */
1059
+ export interface OpsRestoreVerifyAck {
1060
+ readonly step: 'verify'
1061
+ readonly sentinel: 'present' | 'absent'
1062
+ readonly bookmark: string
1063
+ }
1064
+
1065
+ export function parseOpsRestoreRequest(body: unknown): OpsRestoreRequest | null {
1066
+ const step = prop(body, 'step')
1067
+ const object = parseApplicationObjectName(prop(body, 'object'))
1068
+ const sentinel = readMatch(prop(body, 'sentinel'), UUID)
1069
+ if (object === null || sentinel === null) return null
1070
+ if (step === 'verify') return exactKeys(body, ['step', 'object', 'sentinel']) ? { step, object, sentinel } : null
1071
+ const generation = readGeneration(prop(body, 'generation'))
1072
+ if (generation === null) return null
1073
+ if (step === 'prepare') {
1074
+ const at = readTimestamp(prop(body, 'at'))
1075
+ return exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'at']) && at !== null ? { step, object, generation, sentinel, at } : null
1076
+ }
1077
+ if (step === 'arm') {
1078
+ const target = readMatch(prop(body, 'target'), OPAQUE_TOKEN)
1079
+ return exactKeys(body, ['step', 'object', 'generation', 'sentinel', 'target']) && target !== null
1080
+ ? { step, object, generation, sentinel, target }
1081
+ : null
1082
+ }
1083
+ return null
1084
+ }
1085
+
1086
+ export function parseOpsRestorePrepareAck(body: unknown): OpsRestorePrepareAck | null {
1087
+ if (!exactKeys(body, ['step', 'current', 'target']) || prop(body, 'step') !== 'prepare') return null
1088
+ const current = readMatch(prop(body, 'current'), OPAQUE_TOKEN)
1089
+ const target = readMatch(prop(body, 'target'), OPAQUE_TOKEN)
1090
+ return current === null || target === null ? null : { step: 'prepare', current, target }
1091
+ }
1092
+
1093
+ export function parseOpsRestoreArmAck(body: unknown): OpsRestoreArmAck | null {
1094
+ const undo = readMatch(prop(body, 'undo'), OPAQUE_TOKEN)
1095
+ return exactKeys(body, ['step', 'undo']) && prop(body, 'step') === 'arm' && undo !== null ? { step: 'arm', undo } : null
1096
+ }
1097
+
1098
+ export function parseOpsRestoreVerifyAck(body: unknown): OpsRestoreVerifyAck | null {
1099
+ if (!exactKeys(body, ['step', 'sentinel', 'bookmark']) || prop(body, 'step') !== 'verify') return null
1100
+ const sentinel = readEnum(prop(body, 'sentinel'), SENTINEL_STATES)
1101
+ const bookmark = readMatch(prop(body, 'bookmark'), OPAQUE_TOKEN)
1102
+ return sentinel === null || bookmark === null ? null : { step: 'verify', sentinel, bookmark }
1103
+ }
1104
+
1105
+ /** The most timers one answer lists; the rest are counted in `omitted`. */
1106
+ export const OPS_TIMERS_CAP = 500
1107
+ /** A timer's stack keeps at most this many frames, the ones nearest the call that registered the work. */
1108
+ export const OPS_TIMER_STACK_MAX_FRAMES = 20
1109
+ /** A timer's stack is at most this many UTF-8 bytes, cut after it is scrubbed. */
1110
+ export const OPS_TIMER_STACK_MAX_BYTES = 4 * 1024
1111
+
1112
+ /** `POST /__fabrika/ops/timers`: reads the tracker, or with `track` switches it on or off first. In memory only. */
1113
+ export interface OpsTimersRequest {
1114
+ readonly object: string
1115
+ readonly track: boolean | null
1116
+ }
1117
+
1118
+ /** A pending timer or `waitUntil` promise and the stack that registered it, which may name application code: content. */
1119
+ export interface OpsTimer {
1120
+ readonly kind: 'timeout' | 'interval' | 'waitUntil'
1121
+ readonly since: string
1122
+ /** `null` exactly for `waitUntil`. */
1123
+ readonly delayMs: number | null
1124
+ readonly stack: string
1125
+ }
1126
+
1127
+ /** The object's live timers, oldest first (`data.content.read`). */
1128
+ export interface OpsTimersView {
1129
+ readonly tracking: boolean
1130
+ readonly timers: readonly OpsTimer[]
1131
+ readonly omitted: number
1132
+ }
1133
+
1134
+ export function parseOpsTimersRequest(body: unknown): OpsTimersRequest | null {
1135
+ const object = parseApplicationObjectName(prop(body, 'object'))
1136
+ const track = prop(body, 'track')
1137
+ return exactKeys(body, ['object', 'track']) && object !== null && (track === null || typeof track === 'boolean') ? { object, track } : null
1138
+ }
1139
+
1140
+ export function parseOpsTimersView(body: unknown): OpsTimersView | null {
1141
+ if (!exactKeys(body, ['tracking', 'timers', 'omitted'])) return null
1142
+ const tracking = prop(body, 'tracking')
1143
+ const raw = prop(body, 'timers')
1144
+ const timers = Array.isArray(raw) && raw.length <= OPS_TIMERS_CAP ? readList(raw, readTimer) : null
1145
+ const omitted = readCount(prop(body, 'omitted'))
1146
+ return typeof tracking !== 'boolean' || timers === null || omitted === null ? null : { tracking, timers, omitted }
1147
+ }
1148
+
1149
+ /** The status of a data operation's refusal. It is answered only after authentication. */
1150
+ export const OPS_DATA_REFUSED_STATUS = 422
1151
+
1152
+ /** Why the object refused an export, import or restore step. */
1153
+ export const OPS_DATA_REFUSALS = [
1154
+ 'wrong_mode',
1155
+ 'serving_object',
1156
+ 'unsupported_schema',
1157
+ 'not_fresh',
1158
+ 'no_import',
1159
+ 'invalid_manifest',
1160
+ 'fuzzy_dump',
1161
+ 'part_mismatch',
1162
+ 'ledger_mismatch',
1163
+ 'schema_mismatch',
1164
+ 'verify_mismatch',
1165
+ 'bookmark_unavailable',
1166
+ 'row_too_large',
1167
+ ] as const
1168
+
1169
+ export type OpsDataRefusalReason = (typeof OPS_DATA_REFUSALS)[number]
1170
+
1171
+ /** The body of a data refusal; `table` names the table at fault, an identifier and never a value. */
1172
+ export interface OpsDataRefusal {
1173
+ readonly refused: OpsDataRefusalReason
1174
+ readonly table: string | null
1175
+ }
1176
+
1177
+ export function parseOpsDataRefusal(body: unknown): OpsDataRefusal | null {
1178
+ const refused = readEnum(prop(body, 'refused'), OPS_DATA_REFUSALS)
1179
+ const table = readNullable(prop(body, 'table'), (value) => readMatch(value, TABLE_NAME))
1180
+ return exactKeys(body, ['refused', 'table']) && refused !== null && table !== undefined ? { refused, table } : null
1181
+ }
1182
+
1183
+ const VIEW_KEYS = ['release', 'maintenance', 'database', 'migrations', 'scheduler', 'jobs', 'files', 'webhooks', 'bootFailure']
1184
+ const FILE_STATUSES: readonly OpsFileStatus[] = ['pending', 'quarantined', 'live', 'rejected']
1185
+ const WEBHOOK_STATES = ['claimed', 'completed'] as const
1186
+ const JOB_STATUSES = ['succeeded', 'failed'] as const
1187
+ /** The form `Date.prototype.toISOString` and SQLite's `%Y-%m-%dT%H:%M:%fZ` both write. */
1188
+ const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
1189
+ /** `@fabrika/db`'s `isPlainIdentifier`: the only table names the data layer admits. */
1190
+ const TABLE_NAME = /^[a-z_][a-z0-9_]{0,62}$/
1191
+ /** The contract build's authored-name rule (`@fabrika/app/contract`), which a file kind follows. */
1192
+ const CONTRACT_NAME = /^[A-Za-z][A-Za-z0-9_]*$/
1193
+ /** `@fabrika/db`'s SQLite migration runner: a bundle name, a migration file name and a file's SHA-256 hex. */
1194
+ const MIGRATION_BUNDLE = /^[a-z][a-z0-9-]*$/
1195
+ const MIGRATION_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.sql$/
1196
+ const MIGRATION_CHECKSUM = /^[0-9a-f]{64}$/
1197
+ const SHA256_HEX = /^[0-9a-f]{64}$/
1198
+ /** A dump id or a sentinel: a UUID as Control writes one. */
1199
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
1200
+ /** A token R2 or the object hands out and nobody reads into: an upload id, an ETag, a bookmark. Printable ASCII, no space. */
1201
+ const OPAQUE_TOKEN = /^[!-~]{1,1024}$/
1202
+ /** The decimal text `cast(c as text)` writes for an integer: no leading zero, no `-0`. */
1203
+ const INT64_TEXT = /^(?:0|-?[1-9][0-9]{0,18})$/
1204
+ const INT64_MIN = -(2n ** 63n)
1205
+ const INT64_MAX = 2n ** 63n - 1n
1206
+ /**
1207
+ * `hex(c)` of a blob, and `hex(CAST(c AS BLOB))` of text. Bun's regex engine answers `false` for `^(?:[0-9A-F]{2})*$`
1208
+ * on a string of a few megabytes, so the pairing is a length check.
1209
+ */
1210
+ function isBytesHex(value: string): boolean {
1211
+ return value.length % 2 === 0 && /^[0-9A-F]*$/.test(value)
1212
+ }
1213
+ const MANIFEST_KEYS = [
1214
+ 'format',
1215
+ 'dump',
1216
+ 'object',
1217
+ 'consistent',
1218
+ 'createdAt',
1219
+ 'bookmark',
1220
+ 'release',
1221
+ 'contractDigest',
1222
+ 'ddl',
1223
+ 'migrations',
1224
+ 'tables',
1225
+ 'parts',
1226
+ ]
1227
+ const EXPORT_SCOPE_KEYS = ['object', 'generation', 'consistent', 'dump']
1228
+ const IMPORT_SCOPE_KEYS = ['object', 'generation', 'source']
1229
+ const SCHEMA_TYPES = ['table', 'index', 'trigger', 'view'] as const
1230
+ const SENTINEL_STATES = ['present', 'absent'] as const
1231
+ const TIMER_KINDS = ['timeout', 'interval', 'waitUntil'] as const
1232
+
1233
+ /** Every field of the view but the boot failure, whose form differs between the two views. */
1234
+ function readViewFields(body: unknown): Omit<OpsView, 'bootFailure'> | null {
1235
+ if (!exactKeys(body, VIEW_KEYS)) return null
1236
+ const release = prop(body, 'release')
1237
+ const maintenance = readMaintenance(prop(body, 'maintenance'))
1238
+ const database = readDatabase(prop(body, 'database'))
1239
+ const migrations = readList(prop(body, 'migrations'), readMigration)
1240
+ const scheduler = readScheduler(prop(body, 'scheduler'))
1241
+ const jobs = readList(prop(body, 'jobs'), readJob)
1242
+ const files = readList(prop(body, 'files'), readFileCount)
1243
+ const webhooks = readList(prop(body, 'webhooks'), readWebhookCount)
1244
+ if (
1245
+ typeof release !== 'string' || !FRAMEWORK_RELEASE_PATTERN.test(release) || maintenance === null || database === null || migrations === null
1246
+ || scheduler === null || jobs === null || files === null || webhooks === null
1247
+ ) {
1248
+ return null
1249
+ }
1250
+ return { release, maintenance, database, migrations, scheduler, jobs, files, webhooks }
1251
+ }
1252
+
1253
+ function readMaintenance(value: unknown): OpsMaintenance | null {
1254
+ if (!exactKeys(value, ['mode', 'generation', 'published'])) return null
1255
+ const mode = readMode(prop(value, 'mode'))
1256
+ const rawGeneration = prop(value, 'generation')
1257
+ const generation = rawGeneration === null ? null : readGeneration(rawGeneration)
1258
+ const published = prop(value, 'published')
1259
+ if (mode === null || (rawGeneration !== null && generation === null) || typeof published !== 'boolean') return null
1260
+ return { mode, generation, published }
1261
+ }
1262
+
1263
+ function readDatabase(value: unknown): OpsDatabase | null {
1264
+ if (!exactKeys(value, ['sizeBytes', 'tables'])) return null
1265
+ const sizeBytes = readCount(prop(value, 'sizeBytes'))
1266
+ const tables = readList(prop(value, 'tables'), readTableCount)
1267
+ return sizeBytes === null || tables === null ? null : { sizeBytes, tables }
1268
+ }
1269
+
1270
+ function readTableCount(value: unknown): OpsTableCount | null {
1271
+ if (!exactKeys(value, ['name', 'rows'])) return null
1272
+ const name = readMatch(prop(value, 'name'), TABLE_NAME)
1273
+ const rows = readCount(prop(value, 'rows'))
1274
+ return name === null || rows === null || rows > OPS_ROW_COUNT_CAP ? null : { name, rows }
1275
+ }
1276
+
1277
+ function readMigration(value: unknown): OpsMigration | null {
1278
+ if (!exactKeys(value, ['bundle', 'name', 'checksum', 'appliedAt'])) return null
1279
+ const bundle = readMatch(prop(value, 'bundle'), MIGRATION_BUNDLE)
1280
+ const name = readMatch(prop(value, 'name'), MIGRATION_NAME)
1281
+ const checksum = readMatch(prop(value, 'checksum'), MIGRATION_CHECKSUM)
1282
+ const appliedAt = readTimestamp(prop(value, 'appliedAt'))
1283
+ return bundle === null || name === null || checksum === null || appliedAt === null ? null : { bundle, name, checksum, appliedAt }
1284
+ }
1285
+
1286
+ function readScheduler(value: unknown): OpsScheduler | null {
1287
+ if (!exactKeys(value, ['alarm'])) return null
1288
+ const raw = prop(value, 'alarm')
1289
+ const alarm = raw === null ? null : readTimestamp(raw)
1290
+ return raw !== null && alarm === null ? null : { alarm }
1291
+ }
1292
+
1293
+ /** A framework job of the application runtime (`fabrika-file-sweep`): reserved by its `-`, which no contract job name holds. */
1294
+ const FRAMEWORK_JOB_NAME = /^fabrika-[a-z][a-z0-9-]{0,55}$/
1295
+
1296
+ function readJob(value: unknown): OpsJob | null {
1297
+ if (!exactKeys(value, ['job', 'lastStatus', 'lastStartedAt', 'lastFinishedAt', 'lastDurationMs'])) return null
1298
+ const raw = prop(value, 'job')
1299
+ const job = readMatch(raw, WORKLOAD_NAME) ?? readMatch(raw, FRAMEWORK_JOB_NAME)
1300
+ const lastStatus = readNullable(prop(value, 'lastStatus'), (status) => readEnum(status, JOB_STATUSES))
1301
+ const lastStartedAt = readNullable(prop(value, 'lastStartedAt'), readTimestamp)
1302
+ const lastFinishedAt = readNullable(prop(value, 'lastFinishedAt'), readTimestamp)
1303
+ const lastDurationMs = readNullable(prop(value, 'lastDurationMs'), readCount)
1304
+ if (job === null || lastStatus === undefined || lastStartedAt === undefined || lastFinishedAt === undefined || lastDurationMs === undefined) {
1305
+ return null
1306
+ }
1307
+ return { job, lastStatus, lastStartedAt, lastFinishedAt, lastDurationMs }
1308
+ }
1309
+
1310
+ function readFileCount(value: unknown): OpsFileCount | null {
1311
+ if (!exactKeys(value, ['kind', 'status', 'count'])) return null
1312
+ const kind = readMatch(prop(value, 'kind'), CONTRACT_NAME)
1313
+ const status = readEnum(prop(value, 'status'), FILE_STATUSES)
1314
+ const count = readCount(prop(value, 'count'))
1315
+ return kind === null || status === null || count === null ? null : { kind, status, count }
1316
+ }
1317
+
1318
+ function readWebhookCount(value: unknown): OpsWebhookCount | null {
1319
+ if (!exactKeys(value, ['webhook', 'state', 'count'])) return null
1320
+ const webhook = readMatch(prop(value, 'webhook'), WORKLOAD_NAME)
1321
+ const state = readEnum(prop(value, 'state'), WEBHOOK_STATES)
1322
+ const count = readCount(prop(value, 'count'))
1323
+ return webhook === null || state === null || count === null ? null : { webhook, state, count }
1324
+ }
1325
+
1326
+ /** `undefined` for a value that is no boot failure; the caller reads `null` as none before calling. */
1327
+ function readBootFailure(value: unknown): OpsBootFailure | undefined {
1328
+ const at = readTimestamp(prop(value, 'at'))
1329
+ return exactKeys(value, ['at']) && at !== null ? { at } : undefined
1330
+ }
1331
+
1332
+ function readBootFailureContent(value: unknown): OpsBootFailureContent | undefined {
1333
+ if (!exactKeys(value, ['at', 'message', 'stack'])) return undefined
1334
+ const at = readTimestamp(prop(value, 'at'))
1335
+ const message = prop(value, 'message')
1336
+ const stack = prop(value, 'stack')
1337
+ if (at === null || typeof message !== 'string' || (stack !== null && typeof stack !== 'string')) return undefined
1338
+ return { at, message, stack }
1339
+ }
1340
+
1341
+ /** Whether `value` is a plain object holding exactly `keys`: no key missing, none unknown. */
1342
+ function exactKeys(value: unknown, keys: readonly string[]): boolean {
1343
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
1344
+ const own = Object.keys(value)
1345
+ return own.length === keys.length && keys.every((key) => Object.hasOwn(value, key))
1346
+ }
1347
+
1348
+ function readList<T>(value: unknown, read: (item: unknown) => T | null): readonly T[] | null {
1349
+ if (!Array.isArray(value)) return null
1350
+ const items: T[] = []
1351
+ for (const item of value) {
1352
+ const parsed = read(item)
1353
+ if (parsed === null) return null
1354
+ items.push(parsed)
1355
+ }
1356
+ return items
1357
+ }
1358
+
1359
+ /** `null` stays `null`; anything else is read, and `undefined` marks a value `read` refused. */
1360
+ function readNullable<T>(value: unknown, read: (value: unknown) => T | null): T | null | undefined {
1361
+ if (value === null) return null
1362
+ return read(value) ?? undefined
1363
+ }
1364
+
1365
+ function readEnum<T extends string>(value: unknown, members: readonly T[]): T | null {
1366
+ return members.find((member) => member === value) ?? null
1367
+ }
1368
+
1369
+ function readMode(value: unknown): OpsMode | null {
1370
+ return readEnum(value, OPS_MODES)
1371
+ }
1372
+
1373
+ /** A generation Control allocated: a positive safe integer. */
1374
+ function readGeneration(value: unknown): number | null {
1375
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : null
1376
+ }
1377
+
1378
+ function readCount(value: unknown): number | null {
1379
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null
1380
+ }
1381
+
1382
+ /** An identifier the platform or the contract names, in its owner's format: free text never fits one. */
1383
+ function readMatch(value: unknown, pattern: RegExp): string | null {
1384
+ return typeof value === 'string' && pattern.test(value) ? value : null
1385
+ }
1386
+
1387
+ /** `Date` rolls an impossible date over (`02-31` to `03-03`), so the instant must print back as the same text. */
1388
+ function readTimestamp(value: unknown): string | null {
1389
+ if (typeof value !== 'string' || !TIMESTAMP.test(value)) return null
1390
+ const instant = new Date(value)
1391
+ return !Number.isNaN(instant.getTime()) && instant.toISOString() === value ? value : null
1392
+ }
1393
+
1394
+ /** `undefined` for text that is no JSON; every reader refuses it. */
1395
+ function parseJson(text: string): unknown {
1396
+ try {
1397
+ return JSON.parse(text)
1398
+ } catch {
1399
+ return undefined
1400
+ }
1401
+ }
1402
+
1403
+ // The errors name the rule a value broke and never the value, which is a tenant's data.
1404
+ function encodeValue(value: OpsDumpValue): string | null {
1405
+ if (value === null) return null
1406
+ switch (value.type) {
1407
+ case 'integer':
1408
+ if (!isInt64Text(value.value)) throw new Error('a dump integer must be the decimal text of a 64-bit integer')
1409
+ return `i:${value.value}`
1410
+ case 'real':
1411
+ if (Number.isNaN(value.value)) throw new Error('a dump real must not be NaN')
1412
+ return `r:${realText(value.value)}`
1413
+ case 'text':
1414
+ if (!isBytesHex(value.value)) throw new Error('dump text must be the upper-case hex of its bytes')
1415
+ return `t:${value.value}`
1416
+ case 'blob':
1417
+ if (!isBytesHex(value.value)) throw new Error('a dump blob must be upper-case hex')
1418
+ return `b:${value.value}`
1419
+ }
1420
+ }
1421
+
1422
+ /** ECMAScript's shortest text that reads back as the same double, with the sign of a negative zero kept. */
1423
+ function realText(value: number): string {
1424
+ return Object.is(value, -0) ? '-0' : String(value)
1425
+ }
1426
+
1427
+ function isInt64Text(text: string): boolean {
1428
+ if (!INT64_TEXT.test(text)) return false
1429
+ const value = BigInt(text)
1430
+ return value >= INT64_MIN && value <= INT64_MAX
1431
+ }
1432
+
1433
+ /** `undefined` for an encoded value outside the rules; `null` is SQL's NULL. */
1434
+ function readValue(raw: unknown): OpsDumpValue | undefined {
1435
+ if (raw === null) return null
1436
+ if (typeof raw !== 'string') return undefined
1437
+ const text = raw.slice(2)
1438
+ switch (raw.slice(0, 2)) {
1439
+ case 'i:':
1440
+ return isInt64Text(text) ? { type: 'integer', value: text } : undefined
1441
+ case 'r:': {
1442
+ const value = Number(text)
1443
+ return !Number.isNaN(value) && realText(value) === text ? { type: 'real', value } : undefined
1444
+ }
1445
+ case 't:':
1446
+ return isBytesHex(text) ? { type: 'text', value: text } : undefined
1447
+ case 'b:':
1448
+ return isBytesHex(text) ? { type: 'blob', value: text } : undefined
1449
+ default:
1450
+ return undefined
1451
+ }
1452
+ }
1453
+
1454
+ function readRowValues(raw: unknown): OpsDumpValue[] | null {
1455
+ if (!Array.isArray(raw)) return null
1456
+ const values: OpsDumpValue[] = []
1457
+ for (const item of raw) {
1458
+ const value = readValue(item)
1459
+ if (value === undefined) return null
1460
+ values.push(value)
1461
+ }
1462
+ return values
1463
+ }
1464
+
1465
+ function readCursor(value: unknown): OpsDumpCursor | null {
1466
+ if (!exactKeys(value, ['table', 'after', 'rows', 'hash'])) return null
1467
+ const table = readMatch(prop(value, 'table'), TABLE_NAME)
1468
+ const after = readNullable(prop(value, 'after'), readRowid)
1469
+ const rows = readCount(prop(value, 'rows'))
1470
+ const hash = readMatch(prop(value, 'hash'), SHA256_HEX)
1471
+ if (table === null || after === undefined || rows === null || hash === null) return null
1472
+ // Before a table's first row nothing is folded; past a row, at least that row is.
1473
+ if ((after === null) !== (rows === 0) || (rows === 0 && hash !== OPS_EMPTY_TABLE_HASH)) return null
1474
+ return { table, after, rows, hash }
1475
+ }
1476
+
1477
+ function readRowid(value: unknown): string | null {
1478
+ return typeof value === 'string' && isInt64Text(value) ? value : null
1479
+ }
1480
+
1481
+ /** Tables in load order, each named once. */
1482
+ function readTables(value: unknown): readonly OpsDumpTable[] | null {
1483
+ const tables = readList(value, readDumpTable)
1484
+ return tables !== null && distinct(tables.map((table) => table.name)) ? tables : null
1485
+ }
1486
+
1487
+ function readDumpTable(value: unknown): OpsDumpTable | null {
1488
+ if (!exactKeys(value, ['name', 'rows', 'hash'])) return null
1489
+ const name = readMatch(prop(value, 'name'), TABLE_NAME)
1490
+ const rows = readCount(prop(value, 'rows'))
1491
+ const hash = readMatch(prop(value, 'hash'), SHA256_HEX)
1492
+ if (name === null || rows === null || hash === null || (rows === 0 && hash !== OPS_EMPTY_TABLE_HASH)) return null
1493
+ return { name, rows, hash }
1494
+ }
1495
+
1496
+ function readDumpPart(value: unknown): OpsDumpPart | null {
1497
+ if (!exactKeys(value, ['part', 'size', 'sha256'])) return null
1498
+ return readPartFields(value)
1499
+ }
1500
+
1501
+ function readUploadedPart(value: unknown): OpsUploadedPart | null {
1502
+ if (!exactKeys(value, ['part', 'size', 'sha256', 'etag'])) return null
1503
+ const fields = readPartFields(value)
1504
+ const etag = readMatch(prop(value, 'etag'), OPAQUE_TOKEN)
1505
+ return fields === null || etag === null ? null : { ...fields, etag }
1506
+ }
1507
+
1508
+ function readPartFields(value: unknown): OpsDumpPart | null {
1509
+ const part = readPartNumber(prop(value, 'part'))
1510
+ const size = readCount(prop(value, 'size'))
1511
+ const sha256 = readMatch(prop(value, 'sha256'), SHA256_HEX)
1512
+ return part === null || size === null || size === 0 || size > OPS_DUMP_PART_SIZE || sha256 === null ? null : { part, size, sha256 }
1513
+ }
1514
+
1515
+ /** Every part of an upload: numbered 1 to n without a gap, each of the fixed size but the last. */
1516
+ function readWholeParts<T extends OpsDumpPart>(value: unknown, read: (item: unknown) => T | null): readonly T[] | null {
1517
+ const parts = readList(value, read)
1518
+ if (parts === null || parts.length === 0 || parts.length > OPS_DUMP_MAX_PARTS) return null
1519
+ const whole = parts.every((part, index) => part.part === index + 1 && (index === parts.length - 1 || part.size === OPS_DUMP_PART_SIZE))
1520
+ return whole ? parts : null
1521
+ }
1522
+
1523
+ function readPartNumber(value: unknown): number | null {
1524
+ const part = readGeneration(value)
1525
+ return part !== null && part <= OPS_DUMP_MAX_PARTS ? part : null
1526
+ }
1527
+
1528
+ function readSchemaEntry(value: unknown): OpsDumpSchemaEntry | null {
1529
+ if (!exactKeys(value, ['type', 'name', 'table', 'sql'])) return null
1530
+ const type = readEnum(prop(value, 'type'), SCHEMA_TYPES)
1531
+ const name = prop(value, 'name')
1532
+ const table = prop(value, 'table')
1533
+ const sql = prop(value, 'sql')
1534
+ if (type === null || typeof name !== 'string' || name === '' || typeof table !== 'string' || table === '' || typeof sql !== 'string' || sql === '') {
1535
+ return null
1536
+ }
1537
+ // A table's entry names itself; an index or a trigger names any table or view, which the importer compares as text.
1538
+ if (type === 'table' && (name !== table || !TABLE_NAME.test(name))) return null
1539
+ return { type, name, table, sql }
1540
+ }
1541
+
1542
+ function readExportScope(body: unknown): OpsExportScope | null {
1543
+ const object = parseApplicationObjectName(prop(body, 'object'))
1544
+ const generation = readNullable(prop(body, 'generation'), readGeneration)
1545
+ const consistent = prop(body, 'consistent')
1546
+ const dump = readMatch(prop(body, 'dump'), UUID)
1547
+ if (object === null || generation === undefined || typeof consistent !== 'boolean' || dump === null) return null
1548
+ return consistent === (generation !== null) ? { object, generation, consistent, dump } : null
1549
+ }
1550
+
1551
+ function readSource(value: unknown): OpsDumpSource | null {
1552
+ if (!exactKeys(value, ['object', 'dump'])) return null
1553
+ const object = parseApplicationObjectName(prop(value, 'object'))
1554
+ const dump = readMatch(prop(value, 'dump'), UUID)
1555
+ return object === null || dump === null ? null : { object, dump }
1556
+ }
1557
+
1558
+ function boundedStack(stack: string): boolean {
1559
+ return new TextEncoder().encode(stack).length <= OPS_TIMER_STACK_MAX_BYTES && stack.split('\n').length <= OPS_TIMER_STACK_MAX_FRAMES
1560
+ }
1561
+
1562
+ function readTimer(value: unknown): OpsTimer | null {
1563
+ if (!exactKeys(value, ['kind', 'since', 'delayMs', 'stack'])) return null
1564
+ const kind = readEnum(prop(value, 'kind'), TIMER_KINDS)
1565
+ const since = readTimestamp(prop(value, 'since'))
1566
+ const delayMs = readNullable(prop(value, 'delayMs'), readCount)
1567
+ const stack = prop(value, 'stack')
1568
+ if (kind === null || since === null || delayMs === undefined || typeof stack !== 'string' || !boundedStack(stack)) return null
1569
+ return (kind === 'waitUntil') === (delayMs === null) ? { kind, since, delayMs, stack } : null
1570
+ }
1571
+
1572
+ /** A foreign key with its parent's columns named. */
1573
+ interface ResolvedForeignKey {
1574
+ readonly parent: string
1575
+ readonly columns: readonly string[]
1576
+ readonly references: readonly string[]
1577
+ }
1578
+
1579
+ interface DescribedTable {
1580
+ readonly table: OpsDumpSchemaTable
1581
+ readonly keyset: string
1582
+ readonly parents: readonly ResolvedForeignKey[]
1583
+ }
1584
+
1585
+ const ROWID_NAMES = ['rowid', '_rowid_', 'oid']
1586
+
1587
+ function unsupported(table: string | null): OpsDataRefusal {
1588
+ return { refused: 'unsupported_schema', table }
1589
+ }
1590
+
1591
+ /** A rowid table's `INTEGER PRIMARY KEY` is the rowid itself; any other primary key gets an automatic index (`origin` `pk`). */
1592
+ function rowidName(table: OpsDumpSchemaTable): string | null {
1593
+ const key = table.columns.filter((column) => column.primaryKey > 0)
1594
+ const [only] = key
1595
+ if (key.length === 1 && only !== undefined && asciiLower(only.type) === 'integer' && !table.indexes.some((index) => index.origin === 'pk')) {
1596
+ return only.name
1597
+ }
1598
+ const taken = new Set(table.columns.map((column) => asciiLower(column.name)))
1599
+ return ROWID_NAMES.find((name) => !taken.has(name)) ?? null
1600
+ }
1601
+
1602
+ function resolveForeignKeys(table: OpsDumpSchemaTable, tables: ReadonlyMap<string, OpsDumpSchemaTable>): readonly ResolvedForeignKey[] | null {
1603
+ const keys: ResolvedForeignKey[] = []
1604
+ for (const key of table.foreignKeys) {
1605
+ const parent = tables.get(asciiLower(key.parent))
1606
+ if (parent === undefined || key.initiallyDeferred || key.columns.length === 0) return null
1607
+ const primaryKey = parent.columns.filter((column) => column.primaryKey > 0).sort((left, right) => left.primaryKey - right.primaryKey)
1608
+ const references = key.references ?? primaryKey.map((column) => column.name)
1609
+ if (references.length !== key.columns.length) return null
1610
+ keys.push({ parent: parent.name, columns: key.columns, references })
1611
+ }
1612
+ return keys
1613
+ }
1614
+
1615
+ /** Each table's cycle, named by its first table: two tables share one exactly when each reaches the other through parents. */
1616
+ function cycleIds(tables: readonly DescribedTable[]): ReadonlyMap<string, string> {
1617
+ const parents = new Map(tables.map(({ table, parents }) => [table.name, parents]))
1618
+ const reach = new Map<string, ReadonlySet<string>>()
1619
+ for (const { table } of tables) {
1620
+ const seen = new Set<string>()
1621
+ const pending = [table.name]
1622
+ for (let name = pending.pop(); name !== undefined; name = pending.pop()) {
1623
+ for (const key of parents.get(name) ?? []) {
1624
+ if (!seen.has(key.parent)) {
1625
+ seen.add(key.parent)
1626
+ pending.push(key.parent)
1627
+ }
1628
+ }
1629
+ }
1630
+ reach.set(table.name, seen)
1631
+ }
1632
+ const ids = new Map<string, string>()
1633
+ for (const { table } of tables) {
1634
+ const first = tables.find(({ table: other }) => reach.get(table.name)?.has(other.name) === true && reach.get(other.name)?.has(table.name) === true)
1635
+ ids.set(table.name, first === undefined || compareNames(first.table.name, table.name) > 0 ? table.name : first.table.name)
1636
+ }
1637
+ return ids
1638
+ }
1639
+
1640
+ /** Repeatedly the first table by name whose every parent outside its own cycle is placed. */
1641
+ function loadOrder(tables: readonly DescribedTable[], cycle: ReadonlyMap<string, string>): readonly DescribedTable[] {
1642
+ const placed = new Set<string>()
1643
+ const order: DescribedTable[] = []
1644
+ while (order.length < tables.length) {
1645
+ const next = tables.find(({ table, parents }) =>
1646
+ !placed.has(table.name) && parents.every((key) => placed.has(key.parent) || cycle.get(key.parent) === cycle.get(table.name))
1647
+ )
1648
+ // The cycles form a directed acyclic graph, so one always has every outside parent placed.
1649
+ if (next === undefined) throw new Error('a foreign-key graph without a table to place')
1650
+ placed.add(next.table.name)
1651
+ order.push(next)
1652
+ }
1653
+ return order
1654
+ }
1655
+
1656
+ /**
1657
+ * The schema `planOpsDump` reads, from the PRAGMAs workerd admits, of every table a dump holds. An `INITIALLY DEFERRED`
1658
+ * clause is read from the table's SQL outside its quotes and comments, and marks every foreign key of its table; the
1659
+ * names a `CHECK` reads come from the same SQL (`checkNamesOf`).
1660
+ */
1661
+ export function describeOpsDumpSchema(query: OpsDumpSchemaQuery): OpsDumpSchema {
1662
+ const tables: OpsDumpSchemaTable[] = []
1663
+ for (const row of query('PRAGMA table_list')) {
1664
+ const name = schemaText(row['name'])
1665
+ const type = schemaText(row['type'])
1666
+ if (schemaText(row['schema']) !== 'main' || type === 'view' || !dumpedTable(name)) {
1667
+ continue
1668
+ }
1669
+ const virtual = type === 'virtual'
1670
+ const sql = query(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?`, name)[0]?.['sql']
1671
+ const clauses = typeof sql === 'string' ? unquotedSql(sql) : null
1672
+ tables.push({
1673
+ name,
1674
+ virtual,
1675
+ withoutRowid: schemaFlag(row['wr']),
1676
+ checkNames: typeof sql === 'string' ? checkNamesOf(sql) : null,
1677
+ // A virtual table is refused whatever it holds, and its module may not be loaded to describe it.
1678
+ columns: virtual ? [] : describeColumns(query, name),
1679
+ indexes: virtual ? [] : describeIndexes(query, name),
1680
+ foreignKeys: virtual ? [] : describeForeignKeys(query, name, clauses === null || /\binitially\s+deferred\b/i.test(clauses)),
1681
+ })
1682
+ }
1683
+ return { tables }
1684
+ }
1685
+
1686
+ function describeColumns(query: OpsDumpSchemaQuery, table: string): OpsDumpSchemaColumn[] {
1687
+ return query(`PRAGMA table_xinfo(${sqlLiteral(table)})`).map((row) => {
1688
+ const hidden = schemaInteger(row['hidden'])
1689
+ return {
1690
+ name: schemaText(row['name']),
1691
+ type: schemaText(row['type']),
1692
+ notNull: schemaFlag(row['notnull']),
1693
+ primaryKey: schemaInteger(row['pk']),
1694
+ generated: hidden === 2 || hidden === 3,
1695
+ }
1696
+ })
1697
+ }
1698
+
1699
+ function describeIndexes(query: OpsDumpSchemaQuery, table: string): OpsDumpSchemaIndex[] {
1700
+ return query(`PRAGMA index_list(${sqlLiteral(table)})`).map((row) => {
1701
+ const origin = row['origin']
1702
+ if (origin !== 'c' && origin !== 'u' && origin !== 'pk') {
1703
+ throw new Error('PRAGMA index_list answered an origin SQLite does not write')
1704
+ }
1705
+ const columns = query(`PRAGMA index_xinfo(${sqlLiteral(schemaText(row['name']))})`)
1706
+ .filter((column) => schemaFlag(column['key']))
1707
+ .sort((left, right) => schemaInteger(left['seqno']) - schemaInteger(right['seqno']))
1708
+ .map((column) => typeof column['name'] === 'string' ? column['name'] : null)
1709
+ return { unique: schemaFlag(row['unique']), origin, partial: schemaFlag(row['partial']), columns }
1710
+ })
1711
+ }
1712
+
1713
+ function describeForeignKeys(query: OpsDumpSchemaQuery, table: string, initiallyDeferred: boolean): OpsDumpSchemaForeignKey[] {
1714
+ const keys = new Map<number, { parent: string; rows: { seq: number; from: string; to: string | null }[] }>()
1715
+ for (const row of query(`PRAGMA foreign_key_list(${sqlLiteral(table)})`)) {
1716
+ const id = schemaInteger(row['id'])
1717
+ const to = row['to']
1718
+ const entry = { seq: schemaInteger(row['seq']), from: schemaText(row['from']), to: typeof to === 'string' ? to : null }
1719
+ const key = keys.get(id)
1720
+ if (key === undefined) {
1721
+ keys.set(id, { parent: schemaText(row['table']), rows: [entry] })
1722
+ } else {
1723
+ key.rows.push(entry)
1724
+ }
1725
+ }
1726
+ return [...keys.entries()].sort(([left], [right]) => left - right).map(([, key]) => {
1727
+ const rows = key.rows.sort((left, right) => left.seq - right.seq)
1728
+ const references = rows.flatMap((row) => row.to === null ? [] : [row.to])
1729
+ if (references.length !== 0 && references.length !== rows.length) {
1730
+ throw new Error('PRAGMA foreign_key_list named the parent columns of a key only in part')
1731
+ }
1732
+ return { parent: key.parent, columns: rows.map((row) => row.from), references: references.length === 0 ? null : references, initiallyDeferred }
1733
+ })
1734
+ }
1735
+
1736
+ type SqlToken =
1737
+ | { readonly kind: 'name'; readonly text: string; readonly quoted: boolean }
1738
+ | { readonly kind: 'open' | 'close' | 'other' }
1739
+
1740
+ const WORD_CHAR = /[A-Za-z0-9_$\u0080-\uffff]/
1741
+
1742
+ /**
1743
+ * The names the `CHECK` clauses of a table's `sql` read: every word and quoted identifier between a `CHECK` keyword's
1744
+ * parentheses, ASCII-lowercase, keywords and numbers included, so it lists at least every column a `CHECK` reads. A
1745
+ * string literal and a comment name nothing; a double-quoted string, which SQLite may read as either, counts as a name.
1746
+ * `null` when the text does not scan (an unclosed quote, comment or parenthesis), which counts as naming every column.
1747
+ */
1748
+ export function checkNamesOf(sql: string): string[] | null {
1749
+ const tokens = sqlTokens(sql)
1750
+ if (tokens === null) return null
1751
+ const names: string[] = []
1752
+ for (let index = 0; index < tokens.length; index++) {
1753
+ const token = tokens[index]
1754
+ if (token?.kind !== 'name' || token.quoted || asciiLower(token.text) !== 'check' || tokens[index + 1]?.kind !== 'open') continue
1755
+ let depth = 0
1756
+ let end = index + 1
1757
+ for (; end < tokens.length; end++) {
1758
+ const inner = tokens[end]
1759
+ if (inner?.kind === 'open') depth++
1760
+ else if (inner?.kind === 'close' && --depth === 0) break
1761
+ else if (inner?.kind === 'name') names.push(asciiLower(inner.text))
1762
+ }
1763
+ if (end === tokens.length) return null
1764
+ index = end
1765
+ }
1766
+ return names
1767
+ }
1768
+
1769
+ /** `sql` as words, quoted identifiers and parentheses; string literals, comments and whitespace dropped. */
1770
+ function sqlTokens(sql: string): SqlToken[] | null {
1771
+ const tokens: SqlToken[] = []
1772
+ let index = 0
1773
+ while (index < sql.length) {
1774
+ const char = sql.charAt(index)
1775
+ if (sql.startsWith('--', index)) {
1776
+ const end = sql.indexOf('\n', index)
1777
+ index = end < 0 ? sql.length : end + 1
1778
+ } else if (sql.startsWith('/*', index)) {
1779
+ const end = sql.indexOf('*/', index + 2)
1780
+ if (end < 0) return null
1781
+ index = end + 2
1782
+ } else if (char === "'" || char === '"' || char === '`' || char === '[') {
1783
+ const close = char === '[' ? ']' : char
1784
+ let end = index + 1
1785
+ let text = ''
1786
+ for (;;) {
1787
+ const next = sql.indexOf(close, end)
1788
+ if (next < 0) return null
1789
+ text += sql.slice(end, next)
1790
+ if (close !== ']' && sql.charAt(next + 1) === close) {
1791
+ text += close
1792
+ end = next + 2
1793
+ continue
1794
+ }
1795
+ end = next + 1
1796
+ break
1797
+ }
1798
+ if (char !== "'") tokens.push({ kind: 'name', text, quoted: true })
1799
+ index = end
1800
+ } else if (WORD_CHAR.test(char)) {
1801
+ let end = index + 1
1802
+ while (end < sql.length && WORD_CHAR.test(sql.charAt(end))) end++
1803
+ tokens.push({ kind: 'name', text: sql.slice(index, end), quoted: false })
1804
+ index = end
1805
+ } else {
1806
+ if (char === '(') tokens.push({ kind: 'open' })
1807
+ else if (char === ')') tokens.push({ kind: 'close' })
1808
+ else if (!/\s/.test(char)) tokens.push({ kind: 'other' })
1809
+ index++
1810
+ }
1811
+ }
1812
+ return tokens
1813
+ }
1814
+
1815
+ /** `sql` with its string literals, quoted identifiers and comments blanked, so a keyword search finds only clauses. */
1816
+ function unquotedSql(sql: string): string {
1817
+ let out = ''
1818
+ let index = 0
1819
+ while (index < sql.length) {
1820
+ const char = sql.charAt(index)
1821
+ const close = char === "'" ? "'" : char === '"' ? '"' : char === '`' ? '`' : char === '[' ? ']' : null
1822
+ if (close !== null) {
1823
+ let end = index + 1
1824
+ for (;;) {
1825
+ end = sql.indexOf(close, end)
1826
+ if (end < 0 || close === ']' || sql.charAt(end + 1) !== close) break
1827
+ end += 2
1828
+ }
1829
+ index = end < 0 ? sql.length : end + 1
1830
+ out += ' '
1831
+ } else if (sql.startsWith('--', index)) {
1832
+ const end = sql.indexOf('\n', index)
1833
+ index = end < 0 ? sql.length : end + 1
1834
+ out += ' '
1835
+ } else if (sql.startsWith('/*', index)) {
1836
+ const end = sql.indexOf('*/', index + 2)
1837
+ index = end < 0 ? sql.length : end + 2
1838
+ out += ' '
1839
+ } else {
1840
+ out += char
1841
+ index++
1842
+ }
1843
+ }
1844
+ return out
1845
+ }
1846
+
1847
+ /** One statement's rows, as a Durable Object's `sql.exec(...).toArray()` or a `bun:sqlite` query answers them. */
1848
+ export type OpsDumpSchemaQuery = (sql: string, ...bindings: string[]) => readonly Readonly<Record<string, unknown>>[]
1849
+
1850
+ /** Whether a dump holds `name`: no SQLite internal table but `sqlite_sequence`, and none of Cloudflare's `_cf_` ones. */
1851
+ function dumpedTable(name: string): boolean {
1852
+ return !name.startsWith('_cf_') && (!name.startsWith('sqlite_') || name === 'sqlite_sequence')
1853
+ }
1854
+
1855
+ function sqlLiteral(value: string): string {
1856
+ return `'${value.replaceAll("'", "''")}'`
1857
+ }
1858
+
1859
+ // SQLite's own answers: a value of another type is a broken runtime, never input to refuse.
1860
+ function schemaText(value: unknown): string {
1861
+ if (typeof value !== 'string') {
1862
+ throw new Error('SQLite answered a schema name or SQL that is not text')
1863
+ }
1864
+ return value
1865
+ }
1866
+
1867
+ function schemaInteger(value: unknown): number {
1868
+ if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
1869
+ throw new Error('SQLite answered a schema number that is not an integer')
1870
+ }
1871
+ return value
1872
+ }
1873
+
1874
+ function schemaFlag(value: unknown): boolean {
1875
+ return schemaInteger(value) !== 0
1876
+ }
1877
+
1878
+ /** Whether every deferred column of `table` can hold `NULL` from its part until the link pass, with nothing to violate. */
1879
+ function takesTemporaryNull(table: OpsDumpSchemaTable, deferred: readonly OpsDumpSchemaColumn[], referenced: ReadonlySet<string>): boolean {
1880
+ // A `CHECK` answers the same for a `NULL` in a column it does not read; a generated column may read a deferred one.
1881
+ const checkReads = (column: OpsDumpSchemaColumn): boolean => table.checkNames === null || table.checkNames.includes(asciiLower(column.name))
1882
+ if (table.columns.some((column) => column.generated && (column.notNull || checkReads(column)))) return false
1883
+ // A generated column that reads a deferred one may take one value for many rows while that column is `NULL`.
1884
+ const generated = new Set(table.columns.filter((column) => column.generated).map((column) => asciiLower(column.name)))
1885
+ const indexedGenerated = (index: OpsDumpSchemaIndex): boolean => index.columns.some((name) => name !== null && generated.has(asciiLower(name)))
1886
+ if (table.indexes.some((index) => index.unique && (index.partial || index.columns.includes(null) || indexedGenerated(index)))) return false
1887
+ return deferred.every((column) =>
1888
+ !column.notNull && column.primaryKey === 0 && !referenced.has(columnKey(table.name, column.name)) && !checkReads(column)
1889
+ )
1890
+ }
1891
+
1892
+ function columnKey(table: string, column: string): string {
1893
+ return `${table}\n${asciiLower(column)}`
1894
+ }
1895
+
1896
+ /** SQLite compares identifiers case-insensitively in ASCII only. */
1897
+ function asciiLower(value: string): string {
1898
+ return value.replace(/[A-Z]/g, (letter) => letter.toLowerCase())
1899
+ }
1900
+
1901
+ /** Code-unit order, which no locale changes. */
1902
+ function compareNames(left: string, right: string): number {
1903
+ return left < right ? -1 : left > right ? 1 : 0
1904
+ }
1905
+
1906
+ function quoteIdentifier(name: string): string {
1907
+ return `"${name.replaceAll('"', '""')}"`
1908
+ }
1909
+
1910
+ function hexBytes(hex: string): Uint8Array {
1911
+ if (!isBytesHex(hex)) throw new Error('dump bytes must be upper-case hex')
1912
+ const bytes = new Uint8Array(hex.length / 2)
1913
+ for (let index = 0; index < bytes.length; index++) bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16)
1914
+ return bytes
1915
+ }
1916
+
1917
+ /** Whether a cursor resumes a table the same answer reports finished. */
1918
+ function continuesFinished(tables: readonly OpsDumpTable[], next: OpsDumpCursor | null): boolean {
1919
+ return next !== null && tables.some((table) => table.name === next.table)
1920
+ }
1921
+
1922
+ function utf8Length(text: string): number {
1923
+ return new TextEncoder().encode(text).length
1924
+ }
1925
+
1926
+ function distinct(values: readonly string[]): boolean {
1927
+ return new Set(values).size === values.length
1928
+ }
1929
+
1930
+ function sameNames(left: readonly string[], right: readonly string[]): boolean {
1931
+ const names = new Set(left)
1932
+ return distinct(left) && distinct(right) && left.length === right.length && right.every((name) => names.has(name))
1933
+ }