durable-db 0.0.1

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 (46) hide show
  1. package/README.md +1052 -0
  2. package/dist/cli/bin.d.ts +1 -0
  3. package/dist/cli/bin.js +18 -0
  4. package/dist/cli/index.d.ts +330 -0
  5. package/dist/cli/index.js +9 -0
  6. package/dist/cli-Cr9686BF.js +630 -0
  7. package/dist/context/index.d.ts +2 -0
  8. package/dist/context/index.js +5 -0
  9. package/dist/context-BuIiIQ6K.js +103 -0
  10. package/dist/db/index.d.ts +3 -0
  11. package/dist/db/index.js +760 -0
  12. package/dist/debug-BZJbKybf.js +49 -0
  13. package/dist/defineDatabase-CONf4xFC.js +54 -0
  14. package/dist/defineDatabase-jBv90-Pk.d.ts +188 -0
  15. package/dist/generator-BUPP9scJ.js +180 -0
  16. package/dist/index-BFM5d0FP.d.ts +328 -0
  17. package/dist/index-CqVMaMYY.d.ts +65 -0
  18. package/dist/index.d.ts +6 -0
  19. package/dist/index.js +8 -0
  20. package/dist/migrations/generator.d.ts +101 -0
  21. package/dist/migrations/generator.js +5 -0
  22. package/dist/migrations/snapshot.d.ts +2 -0
  23. package/dist/migrations/snapshot.js +3 -0
  24. package/dist/parser-CbX54Flt.js +293 -0
  25. package/dist/protocol-g_plhPOY.js +35 -0
  26. package/dist/push-BgQ5cnfH.js +184 -0
  27. package/dist/push-BkkaslPd.js +8 -0
  28. package/dist/registry.d.ts +28 -0
  29. package/dist/registry.js +72 -0
  30. package/dist/schema-BOtrGnzM.js +8 -0
  31. package/dist/schema-CpzTOfZ6.d.ts +6 -0
  32. package/dist/schema.d.ts +2 -0
  33. package/dist/schema.js +3 -0
  34. package/dist/snapshot-C162qYoA.d.ts +125 -0
  35. package/dist/snapshot-D170nL7i.js +93 -0
  36. package/dist/state-BCcvNN-M.js +5 -0
  37. package/dist/state-FOEjpgJ6.js +203 -0
  38. package/dist/transport/protocol.d.ts +27 -0
  39. package/dist/transport/protocol.js +3 -0
  40. package/dist/transport/websocket.d.ts +31 -0
  41. package/dist/transport/websocket.js +3 -0
  42. package/dist/vite/durableDb.d.ts +20 -0
  43. package/dist/vite/durableDb.js +933 -0
  44. package/dist/websocket-Dx1fqwnF.js +104 -0
  45. package/package.json +114 -0
  46. package/virtual.d.ts +15 -0
@@ -0,0 +1,760 @@
1
+ import { i as init_debug, n as debugMigrations } from "../debug-BZJbKybf.js";
2
+ import { t as defineDatabase } from "../defineDatabase-CONf4xFC.js";
3
+ import { type } from "arktype";
4
+ import { SQLiteSyncDialect, getTableConfig } from "drizzle-orm/sqlite-core";
5
+ import { toCamelCase, toSnakeCase } from "drizzle-orm/casing";
6
+ import { DurableObject } from "cloudflare:workers";
7
+ import { CamelCasePlugin, CamelCasePlugin as CamelCasePlugin$1, ColumnNode, ColumnUpdateNode, InsertQueryNode, Kysely, PrimitiveValueListNode, SqliteDialect, TableNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
8
+ import { Table, getTableColumns, getTableName, is, isSQLWrapper } from "drizzle-orm";
9
+ import { studio } from "@outerbase/browsable-durable-object";
10
+
11
+ //#region src/db/plugins.ts
12
+ /**
13
+ * Schema-aware CamelCasePlugin that uses Drizzle schema for column name mapping.
14
+ *
15
+ * Extends CamelCasePlugin to handle non-standard column names that don't follow
16
+ * simple camelCase ↔ snake_case conversion. For example, a JS property `userId`
17
+ * mapped to SQL column `user_identifier` would be handled correctly.
18
+ *
19
+ * Falls back to standard CamelCasePlugin behavior for columns not in the schema.
20
+ */
21
+ var SchemaPlugin = class extends CamelCasePlugin$1 {
22
+ jsToSql;
23
+ sqlToJs;
24
+ constructor(schema) {
25
+ super();
26
+ this.jsToSql = /* @__PURE__ */ new Map();
27
+ this.sqlToJs = /* @__PURE__ */ new Map();
28
+ for (const [schemaKey, table] of Object.entries(schema)) {
29
+ const tableConfig = getTableConfig(table);
30
+ const sqlTableName = tableConfig.name;
31
+ if (schemaKey !== sqlTableName) {
32
+ this.jsToSql.set(schemaKey, sqlTableName);
33
+ this.sqlToJs.set(sqlTableName, schemaKey);
34
+ }
35
+ const sqlColumnNames = new Set(tableConfig.columns.map((c) => c.name));
36
+ for (const [propertyName, value] of Object.entries(table)) if (value && typeof value === "object" && "name" in value && typeof value.name === "string" && sqlColumnNames.has(value.name) && propertyName !== value.name) {
37
+ this.jsToSql.set(propertyName, value.name);
38
+ this.sqlToJs.set(value.name, propertyName);
39
+ }
40
+ }
41
+ }
42
+ snakeCase(str) {
43
+ return this.jsToSql.get(str) ?? super.snakeCase(str);
44
+ }
45
+ camelCase(str) {
46
+ return this.sqlToJs.get(str) ?? super.camelCase(str);
47
+ }
48
+ };
49
+ function getKyselyTableName(node) {
50
+ if (node && TableNode.is(node)) return node.table.identifier.name;
51
+ return null;
52
+ }
53
+ function getKyselyColumnName(node) {
54
+ if (!node) return null;
55
+ if (ColumnNode.is(node)) return node.column.name;
56
+ if (ColumnUpdateNode.is(node) && node.column) return getKyselyColumnName(node.column);
57
+ return null;
58
+ }
59
+ function convertDrizzleSql(drizzleSql) {
60
+ return drizzleSql.sql.split("?").reduce((acc, part, index) => {
61
+ const param = index < drizzleSql.params.length ? drizzleSql.params[index] : "";
62
+ return acc + part + param;
63
+ }, "");
64
+ }
65
+ function createValueNode(val) {
66
+ if (isSQLWrapper(val)) {
67
+ const drizzleSql = new SQLiteSyncDialect().sqlToQuery(val);
68
+ return sql.raw(convertDrizzleSql(drizzleSql)).toOperationNode();
69
+ }
70
+ return ValueNode.create(val);
71
+ }
72
+ function extractDefaults(schemas) {
73
+ const defaults = /* @__PURE__ */ new Map();
74
+ for (const schema of Object.values(schemas)) {
75
+ const tableName = toCamelCase(getTableName(schema));
76
+ const columns = getTableColumns(schema);
77
+ const tableDefaults = {};
78
+ for (const column of Object.values(columns)) {
79
+ const { defaultFn, onUpdateFn, name } = column;
80
+ if (defaultFn || onUpdateFn) tableDefaults[name] = {
81
+ defaultFn,
82
+ onUpdateFn
83
+ };
84
+ }
85
+ if (Object.keys(tableDefaults).length > 0) defaults.set(tableName, tableDefaults);
86
+ }
87
+ return defaults;
88
+ }
89
+ /**
90
+ * Plugin that handles Drizzle's defaultFn and onUpdateFn during Kysely queries.
91
+ *
92
+ * On INSERT: auto-populates columns that have a defaultFn but weren't provided,
93
+ * and resolves DefaultInsertValueNode markers to actual values.
94
+ *
95
+ * On UPDATE: auto-adds column updates for columns with onUpdateFn that weren't
96
+ * already included in the SET clause.
97
+ */
98
+ var DrizzleDefaultsPlugin = class {
99
+ defaults;
100
+ constructor(drizzleSchemas) {
101
+ this.defaults = extractDefaults(drizzleSchemas);
102
+ }
103
+ transformInsertQuery(node) {
104
+ const tableName = getKyselyTableName(node.into);
105
+ if (!tableName) return node;
106
+ const tableDefaults = this.defaults.get(tableName);
107
+ if (!tableDefaults) return node;
108
+ if (!node.values || !ValuesNode.is(node.values)) return node;
109
+ const providedColumns = node.columns ?? [];
110
+ const providedColumnNames = providedColumns.map((col) => col.column.name);
111
+ const missingDefaults = Object.entries(tableDefaults).filter(([colName, { defaultFn }]) => defaultFn && !providedColumnNames.includes(colName)).map(([colName, { defaultFn }]) => ({
112
+ name: colName,
113
+ defaultFn
114
+ }));
115
+ const newColumns = [...providedColumns, ...missingDefaults.map(({ name }) => ColumnNode.create(name))];
116
+ const newRows = node.values.values.map((rowNode) => {
117
+ if (missingDefaults.length === 0 && PrimitiveValueListNode.is(rowNode)) return rowNode;
118
+ let originalValues;
119
+ if (PrimitiveValueListNode.is(rowNode)) originalValues = rowNode.values.map((val) => ValueNode.create(val));
120
+ else if (ValueListNode.is(rowNode)) originalValues = [...rowNode.values];
121
+ else throw new Error("Unsupported row node type in insert query");
122
+ const processedValues = originalValues.map((val, idx) => {
123
+ if (val.kind === "DefaultInsertValueNode") {
124
+ const colDef = tableDefaults[providedColumns[idx].column.name];
125
+ if (colDef?.defaultFn) return createValueNode(colDef.defaultFn());
126
+ }
127
+ return val;
128
+ });
129
+ const missingValues = missingDefaults.map(({ defaultFn }) => createValueNode(defaultFn()));
130
+ return ValueListNode.create([...processedValues, ...missingValues]);
131
+ });
132
+ return InsertQueryNode.cloneWith(node, {
133
+ columns: newColumns,
134
+ values: ValuesNode.create(newRows)
135
+ });
136
+ }
137
+ transformUpdateQuery(node) {
138
+ const tableName = getKyselyTableName(node.table);
139
+ if (!tableName) return node;
140
+ const tableDefaults = this.defaults.get(tableName);
141
+ if (!tableDefaults) return node;
142
+ const existingUpdates = new Set(node.updates?.map(getKyselyColumnName) || []);
143
+ const newUpdates = node.updates ? [...node.updates] : [];
144
+ for (const [colName, { onUpdateFn }] of Object.entries(tableDefaults)) {
145
+ if (!onUpdateFn || existingUpdates.has(colName)) continue;
146
+ newUpdates.push(ColumnUpdateNode.create(ColumnNode.create(colName), createValueNode(onUpdateFn())));
147
+ }
148
+ if (newUpdates.length === (node.updates?.length || 0)) return node;
149
+ return {
150
+ ...node,
151
+ updates: newUpdates
152
+ };
153
+ }
154
+ transformQuery(args) {
155
+ const { node } = args;
156
+ switch (node.kind) {
157
+ case "InsertQueryNode": return this.transformInsertQuery(node);
158
+ case "UpdateQueryNode": return this.transformUpdateQuery(node);
159
+ default: return node;
160
+ }
161
+ }
162
+ async transformResult(args) {
163
+ return args.result;
164
+ }
165
+ };
166
+ /**
167
+ * Date serialization helpers for SQLite
168
+ * SQLite stores dates as TEXT in ISO format (without timezone)
169
+ */
170
+ const dateSerializers = {
171
+ serialize(value) {
172
+ return value.toISOString().replace("T", " ").slice(0, 19);
173
+ },
174
+ deserialize(value) {
175
+ const normalized = value.replace(" ", "T");
176
+ if (/(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized)) return new Date(normalized);
177
+ return /* @__PURE__ */ new Date(normalized + "Z");
178
+ },
179
+ isDateString(value) {
180
+ return /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/.test(value);
181
+ },
182
+ isSerializedDateString(value) {
183
+ return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value);
184
+ }
185
+ };
186
+ /**
187
+ * Collect the names of columns that Drizzle declares as date-typed
188
+ * (e.g. `integer({ mode: 'timestamp' })`). Includes both the SQL column
189
+ * name and the JS property name, since result rows may be seen in either
190
+ * form depending on where this plugin sits relative to CamelCasePlugin.
191
+ */
192
+ function collectDateColumnNames(schema) {
193
+ const dateColumns = /* @__PURE__ */ new Set();
194
+ for (const table of Object.values(schema)) {
195
+ const columns = getTableColumns(table);
196
+ for (const [propertyName, column] of Object.entries(columns)) if (column.dataType === "date") {
197
+ dateColumns.add(column.name);
198
+ dateColumns.add(propertyName);
199
+ dateColumns.add(toSnakeCase(propertyName));
200
+ }
201
+ }
202
+ return dateColumns;
203
+ }
204
+ /**
205
+ * Plugin that serializes/deserializes Date objects for SQLite
206
+ *
207
+ * On query: Converts Date objects to ISO strings
208
+ * On result: Converts stored date strings back to Date objects — but only
209
+ * for values in the exact format the write path produces, and (when a schema
210
+ * is provided) only for columns Drizzle declares as date-typed. Plain text
211
+ * columns holding date-looking strings round-trip verbatim.
212
+ */
213
+ var DateSerializePlugin = class {
214
+ /**
215
+ * Names of date-typed columns (SQL and JS forms) when constructed with a
216
+ * schema; null means "no schema available", which falls back to matching
217
+ * on value format alone.
218
+ */
219
+ dateColumns;
220
+ constructor(schema) {
221
+ this.dateColumns = schema ? collectDateColumnNames(schema) : null;
222
+ }
223
+ transformQuery(args) {
224
+ return this.transformNode(args.node);
225
+ }
226
+ transformNode(node) {
227
+ if (node === null || node === void 0) return node;
228
+ if (node instanceof Date) return dateSerializers.serialize(node);
229
+ if (Array.isArray(node)) return node.map((item) => this.transformNode(item));
230
+ if (typeof node === "object") {
231
+ const result = {};
232
+ for (const [key, value] of Object.entries(node)) result[key] = this.transformNode(value);
233
+ return result;
234
+ }
235
+ return node;
236
+ }
237
+ async transformResult(args) {
238
+ return {
239
+ ...args.result,
240
+ rows: args.result.rows.map((row) => this.transformRow(row))
241
+ };
242
+ }
243
+ transformRow(row) {
244
+ const result = {};
245
+ for (const [key, value] of Object.entries(row)) if (typeof value === "string" && this.shouldDeserialize(key, value)) result[key] = dateSerializers.deserialize(value);
246
+ else result[key] = value;
247
+ return result;
248
+ }
249
+ shouldDeserialize(key, value) {
250
+ if (this.dateColumns && !this.dateColumns.has(key)) return false;
251
+ return dateSerializers.isSerializedDateString(value);
252
+ }
253
+ };
254
+ /**
255
+ * Validate that a schema object is shaped like a record of Drizzle tables.
256
+ *
257
+ * Throws a descriptive error pointing at the offending key when the schema
258
+ * is not a plain object or when any value isn't a Drizzle `Table`. This
259
+ * catches the common foot-guns (passing a Drizzle relations helper, a plain
260
+ * column builder, or `undefined` because of a missing import) before Kysely
261
+ * plugins crash with an unhelpful stack deep inside their constructors.
262
+ */
263
+ function assertValidSchema(schema) {
264
+ if (schema === null || typeof schema !== "object" || Array.isArray(schema)) throw new Error(`[db] Invalid schema: expected a record of Drizzle tables (e.g. { users, posts }), got ${Array.isArray(schema) ? "array" : schema === null ? "null" : typeof schema}.`);
265
+ for (const [key, value] of Object.entries(schema)) if (!is(value, Table)) {
266
+ const got = value === null ? "null" : value === void 0 ? "undefined" : typeof value;
267
+ throw new Error(`[db] Invalid schema: '${key}' is not a Drizzle table (got ${got}). Make sure every value is defined with table() from 'durable-db/schema'.`);
268
+ }
269
+ }
270
+ /**
271
+ * Create all recommended plugins for use with Drizzle schemas.
272
+ *
273
+ * Includes:
274
+ * - DrizzleDefaultsPlugin: auto-populates defaultFn/onUpdateFn values
275
+ * - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
276
+ * - DateSerializePlugin: Date ↔ SQLite text serialization
277
+ *
278
+ * When camelCase is false, SchemaPlugin is omitted.
279
+ */
280
+ function createDrizzlePlugins(schema, camelCase = true) {
281
+ assertValidSchema(schema);
282
+ const plugins = [];
283
+ plugins.push(new DrizzleDefaultsPlugin(schema));
284
+ if (camelCase) plugins.push(new SchemaPlugin(schema));
285
+ plugins.push(new DateSerializePlugin(schema));
286
+ return plugins;
287
+ }
288
+
289
+ //#endregion
290
+ //#region src/db/SqliteDurableObject.ts
291
+ init_debug();
292
+ /**
293
+ * A Kysely driver that uses Cloudflare DO SQLite storage
294
+ */
295
+ var CloudflareSqliteDriver = class {
296
+ sql;
297
+ constructor(sql$1) {
298
+ this.sql = sql$1;
299
+ }
300
+ async init() {}
301
+ async acquireConnection() {
302
+ return new CloudflareSqliteConnection(this.sql);
303
+ }
304
+ async beginTransaction(connection, settings) {
305
+ if (settings.isolationLevel) throw new Error("SQLite does not support isolation levels");
306
+ await connection.executeQuery(createCompiledQuery("BEGIN"));
307
+ }
308
+ async commitTransaction(connection) {
309
+ await connection.executeQuery(createCompiledQuery("COMMIT"));
310
+ }
311
+ async rollbackTransaction(connection) {
312
+ await connection.executeQuery(createCompiledQuery("ROLLBACK"));
313
+ }
314
+ async releaseConnection() {}
315
+ async destroy() {}
316
+ };
317
+ /**
318
+ * Helper to create a CompiledQuery object
319
+ */
320
+ function createCompiledQuery(sql$1, parameters = []) {
321
+ return {
322
+ sql: sql$1,
323
+ parameters,
324
+ query: {
325
+ kind: "RawNode",
326
+ sqlFragments: [sql$1],
327
+ parameters: []
328
+ }
329
+ };
330
+ }
331
+ /**
332
+ * A Kysely connection that wraps Cloudflare's SqlStorage
333
+ */
334
+ var CloudflareSqliteConnection = class {
335
+ sql;
336
+ constructor(sql$1) {
337
+ this.sql = sql$1;
338
+ }
339
+ async executeQuery(compiledQuery) {
340
+ const { sql: queryStr, parameters } = compiledQuery;
341
+ const isSelect = /^\s*(SELECT|RETURNING)/i.test(queryStr) || /\s+RETURNING\s+/i.test(queryStr);
342
+ try {
343
+ if (isSelect) return {
344
+ rows: this.sql.exec(queryStr, ...parameters).toArray(),
345
+ numAffectedRows: void 0,
346
+ insertId: void 0
347
+ };
348
+ else {
349
+ this.sql.exec(queryStr, ...parameters);
350
+ const changes = this.sql.exec("SELECT changes() as changes").toArray()[0]?.changes ?? 0;
351
+ const lastId = this.sql.exec("SELECT last_insert_rowid() as id").toArray()[0]?.id;
352
+ return {
353
+ rows: [],
354
+ numAffectedRows: BigInt(changes),
355
+ insertId: typeof lastId === "number" || typeof lastId === "bigint" ? BigInt(lastId) : void 0
356
+ };
357
+ }
358
+ } catch (error) {
359
+ throw error;
360
+ }
361
+ }
362
+ streamQuery() {
363
+ throw new Error("Streaming is not supported in Cloudflare SQLite");
364
+ }
365
+ };
366
+ /**
367
+ * Create a Kysely instance from Cloudflare SqlStorage
368
+ *
369
+ * @param sqlStorage - The Cloudflare SqlStorage instance
370
+ * @param options - Configuration options including schema for plugins
371
+ */
372
+ function createKyselyFromSql(sqlStorage, options = {}) {
373
+ const { schema, plugins = [], camelCase = true } = options;
374
+ const sqliteDialect = new SqliteDialect({ database: null });
375
+ const allPlugins = [];
376
+ if (schema) allPlugins.push(...createDrizzlePlugins(schema, camelCase));
377
+ else if (camelCase) {
378
+ allPlugins.push(new CamelCasePlugin$1());
379
+ allPlugins.push(new DateSerializePlugin());
380
+ } else allPlugins.push(new DateSerializePlugin());
381
+ allPlugins.push(...plugins);
382
+ return new Kysely({
383
+ dialect: {
384
+ createAdapter: () => sqliteDialect.createAdapter(),
385
+ createDriver: () => new CloudflareSqliteDriver(sqlStorage),
386
+ createIntrospector: (db) => sqliteDialect.createIntrospector(db),
387
+ createQueryCompiler: () => sqliteDialect.createQueryCompiler()
388
+ },
389
+ plugins: allPlugins
390
+ });
391
+ }
392
+ /**
393
+ * Maximum number of PITR restore attempts before giving up
394
+ */
395
+ const MAX_PITR_ATTEMPTS = 3;
396
+ /**
397
+ * Truncate a SQL statement for logging. Collapses whitespace so multi-line
398
+ * statements render on one log line.
399
+ */
400
+ function formatStatementForLog(statement, max = 120) {
401
+ const collapsed = statement.replace(/\s+/g, " ").trim();
402
+ return collapsed.length > max ? `${collapsed.slice(0, max)}…` : collapsed;
403
+ }
404
+ /**
405
+ * Base class for SQLite Durable Objects with migration support
406
+ *
407
+ * Extend this class and set the `migrations` property to define your schema.
408
+ * Migrations run automatically when the DO is first accessed.
409
+ *
410
+ * Migrations are SQL-based with breakpoint support for long-running migrations.
411
+ * Breakpoints allow migrations to be resumed if the DO restarts mid-migration.
412
+ *
413
+ * When running on Cloudflare with PITR (Point-in-Time Recovery) support,
414
+ * migrations are protected with automatic snapshots. If a migration fails,
415
+ * the DO is restored to the pre-migration state and retried on next access.
416
+ * After {@link MAX_PITR_ATTEMPTS} consecutive failures, PITR is skipped and
417
+ * the error propagates so the developer can fix the migration and redeploy.
418
+ *
419
+ * @example
420
+ * ```ts
421
+ * import { SqliteDurableObject } from 'durable-db/db';
422
+ *
423
+ * export class MyDatabaseDO extends SqliteDurableObject {
424
+ * migrations = {
425
+ * '20240101000000_initial': {
426
+ * chunks: [
427
+ * // First chunk - create users table
428
+ * ['CREATE TABLE users (id TEXT PRIMARY KEY, name TEXT NOT NULL)'],
429
+ * // Second chunk (after breakpoint) - create posts table
430
+ * ['CREATE TABLE posts (id TEXT PRIMARY KEY, author_id TEXT REFERENCES users(id))'],
431
+ * ]
432
+ * }
433
+ * };
434
+ * }
435
+ * ```
436
+ */
437
+ var SqliteDurableObject = class extends DurableObject {
438
+ /**
439
+ * The Kysely database instance - available after migrations run
440
+ */
441
+ db;
442
+ /**
443
+ * Raw SQLite storage access
444
+ */
445
+ sql;
446
+ /**
447
+ * Whether migrations have been run for this instance
448
+ */
449
+ migrationsApplied = false;
450
+ /**
451
+ * Cached result of PITR availability check (null = not yet checked)
452
+ */
453
+ pitrAvailable = null;
454
+ /**
455
+ * Reason PITR was determined unavailable, if known. Null when PITR is
456
+ * available or hasn't been checked yet. Surfaced via getMigrationStatus()
457
+ * so operators can distinguish "not supported by the runtime" from
458
+ * "unexpected error at detection time".
459
+ */
460
+ pitrUnavailableReason = null;
461
+ constructor(ctx, env) {
462
+ super(ctx, env);
463
+ this.sql = ctx.storage.sql;
464
+ this.db = createKyselyFromSql(this.sql);
465
+ }
466
+ /**
467
+ * Check if PITR is available on this DO's storage.
468
+ * Result is cached after the first call.
469
+ */
470
+ async checkPitrAvailable() {
471
+ if (this.pitrAvailable !== null) return this.pitrAvailable;
472
+ try {
473
+ await this.ctx.storage.getCurrentBookmark();
474
+ this.pitrAvailable = true;
475
+ this.pitrUnavailableReason = null;
476
+ } catch (e) {
477
+ this.pitrAvailable = false;
478
+ this.pitrUnavailableReason = e instanceof Error ? e.message : String(e);
479
+ debugMigrations("PITR unavailable: %s", this.pitrUnavailableReason);
480
+ }
481
+ return this.pitrAvailable;
482
+ }
483
+ /**
484
+ * Reset the in-memory migration flag so that the next operation
485
+ * will re-run migrations. Used after `ctx.storage.deleteAll()` to
486
+ * ensure a fresh start.
487
+ */
488
+ resetMigrationState() {
489
+ this.migrationsApplied = false;
490
+ debugMigrations("Migration state reset; migrations will re-run on next access");
491
+ }
492
+ /**
493
+ * Ensure migrations are applied before any operation
494
+ */
495
+ async ensureMigrations() {
496
+ if (this.migrationsApplied) return;
497
+ await this.runMigrations();
498
+ this.migrationsApplied = true;
499
+ }
500
+ /**
501
+ * Execute raw SQL statement
502
+ * Used by migrations for direct SQL execution
503
+ */
504
+ execSql(sql$1) {
505
+ this.sql.exec(sql$1);
506
+ }
507
+ /**
508
+ * Run pending migrations with PITR safety.
509
+ *
510
+ * Two-write strategy for retry guard:
511
+ * 1. WRITE 1: Increment retry counter in __migration_attempts
512
+ * 2. Take PITR bookmark (captures state including the counter)
513
+ * 3. WRITE 2: Apply the actual migrations
514
+ * On failure → restore to bookmark → counter value survives
515
+ * After MAX_PITR_ATTEMPTS, stop restoring and let the error propagate
516
+ */
517
+ async runMigrations() {
518
+ this.sql.exec(`
519
+ CREATE TABLE IF NOT EXISTS __migrations (
520
+ name TEXT NOT NULL,
521
+ chunk_index INTEGER NOT NULL,
522
+ applied_at TEXT NOT NULL,
523
+ PRIMARY KEY (name, chunk_index)
524
+ )
525
+ `);
526
+ this.sql.exec(`
527
+ CREATE TABLE IF NOT EXISTS __migration_attempts (
528
+ id TEXT PRIMARY KEY DEFAULT 'current',
529
+ attempt_count INTEGER NOT NULL DEFAULT 0,
530
+ last_attempt_at TEXT,
531
+ last_error TEXT
532
+ )
533
+ `);
534
+ this.sql.exec(`
535
+ INSERT OR IGNORE INTO __migration_attempts (id, attempt_count) VALUES ('current', 0)
536
+ `);
537
+ const pending = this.collectPendingMigrations();
538
+ if (pending.length === 0) return;
539
+ const hasPitr = await this.checkPitrAvailable();
540
+ let bookmark;
541
+ if (hasPitr) {
542
+ this.sql.exec(`
543
+ UPDATE __migration_attempts
544
+ SET attempt_count = attempt_count + 1,
545
+ last_attempt_at = ?
546
+ WHERE id = 'current'
547
+ `, (/* @__PURE__ */ new Date()).toISOString());
548
+ const attemptCount = this.sql.exec("SELECT attempt_count FROM __migration_attempts WHERE id = ?", "current").toArray()[0]?.attempt_count ?? 0;
549
+ if (attemptCount > MAX_PITR_ATTEMPTS) {
550
+ const lastError = this.readLastMigrationError();
551
+ const pendingNames = pending.map((p) => p.name);
552
+ const uniquePending = Array.from(new Set(pendingNames));
553
+ console.error(`[database] Migration has failed ${attemptCount} times. PITR restore disabled — fix the migration and redeploy. Pending: ${uniquePending.join(", ") || "(none)"}. Last error: ${lastError ?? "(unknown)"}`);
554
+ } else {
555
+ bookmark = await this.ctx.storage.getCurrentBookmark();
556
+ debugMigrations("PITR bookmark taken (attempt %d/%d)", attemptCount, MAX_PITR_ATTEMPTS);
557
+ }
558
+ }
559
+ const startedAt = Date.now();
560
+ try {
561
+ this.applyMigrations(pending);
562
+ this.sql.exec(`
563
+ UPDATE __migration_attempts
564
+ SET attempt_count = 0, last_error = NULL
565
+ WHERE id = 'current'
566
+ `);
567
+ const uniqueNames = Array.from(new Set(pending.map((p) => p.name)));
568
+ const elapsed = Date.now() - startedAt;
569
+ console.log(`[database] Applied ${pending.length} migration chunk(s) across ${uniqueNames.length} migration(s) in ${elapsed}ms: ${uniqueNames.join(", ")}` + (hasPitr ? "" : " (PITR unavailable — migrations ran unprotected)"));
570
+ } catch (error) {
571
+ const errorMessage = error instanceof Error ? error.message : String(error);
572
+ if (bookmark) {
573
+ this.sql.exec(`
574
+ UPDATE __migration_attempts SET last_error = ? WHERE id = 'current'
575
+ `, errorMessage);
576
+ const attempts = this.getMigrationAttempts();
577
+ const remaining = Math.max(0, MAX_PITR_ATTEMPTS + 1 - attempts.attemptCount);
578
+ const pendingNames = Array.from(new Set(pending.map((p) => p.name))).join(", ");
579
+ console.error(`[database] Migration failed (attempt ${attempts.attemptCount}/${MAX_PITR_ATTEMPTS + 1}, ${remaining} PITR-protected retries remaining). Restoring to pre-migration bookmark. Pending: ${pendingNames || "(none)"}.`, error);
580
+ try {
581
+ await this.ctx.storage.onNextSessionRestoreBookmark(bookmark);
582
+ this.ctx.abort("Restoring to pre-migration bookmark");
583
+ } catch (pitrErr) {
584
+ const pitrMessage = pitrErr instanceof Error ? pitrErr.message : String(pitrErr);
585
+ if (pitrMessage.includes("Restoring to pre-migration bookmark")) throw pitrErr;
586
+ console.error(`[database] PITR restore failed (${pitrMessage}). Propagating the original migration error instead so you can fix the root cause.`);
587
+ }
588
+ }
589
+ throw error;
590
+ }
591
+ }
592
+ /**
593
+ * Collect pending migration chunks that haven't been applied yet.
594
+ */
595
+ collectPendingMigrations() {
596
+ const applied = this.sql.exec("SELECT name, chunk_index FROM __migrations").toArray();
597
+ const appliedMap = /* @__PURE__ */ new Map();
598
+ for (const row of applied) {
599
+ if (!appliedMap.has(row.name)) appliedMap.set(row.name, /* @__PURE__ */ new Set());
600
+ appliedMap.get(row.name).add(row.chunk_index);
601
+ }
602
+ const pending = [];
603
+ const migrationNames = Object.keys(this.migrations).sort();
604
+ for (const name of migrationNames) {
605
+ const migration = this.migrations[name];
606
+ const appliedChunks = appliedMap.get(name) ?? /* @__PURE__ */ new Set();
607
+ for (let chunkIndex = 0; chunkIndex < migration.chunks.length; chunkIndex++) if (!appliedChunks.has(chunkIndex)) pending.push({
608
+ name,
609
+ chunkIndex,
610
+ statements: migration.chunks[chunkIndex]
611
+ });
612
+ }
613
+ return pending;
614
+ }
615
+ /**
616
+ * Apply a list of pending migration chunks.
617
+ */
618
+ applyMigrations(pending) {
619
+ for (const { name, chunkIndex, statements } of pending) {
620
+ let currentIndex = -1;
621
+ let currentStatement = null;
622
+ try {
623
+ for (let i = 0; i < statements.length; i++) {
624
+ const statement = statements[i];
625
+ if (!statement.trim()) continue;
626
+ currentIndex = i;
627
+ currentStatement = statement;
628
+ this.sql.exec(statement);
629
+ }
630
+ currentIndex = -1;
631
+ currentStatement = null;
632
+ this.sql.exec("INSERT INTO __migrations (name, chunk_index, applied_at) VALUES (?, ?, ?)", name, chunkIndex, (/* @__PURE__ */ new Date()).toISOString());
633
+ debugMigrations("Migration chunk applied: %s[%d]", name, chunkIndex);
634
+ } catch (error) {
635
+ const location = currentStatement !== null ? ` stmt ${currentIndex}: ${formatStatementForLog(currentStatement)}` : " (while recording chunk as applied)";
636
+ console.error(`[database] Migration chunk failed: ${name}[${chunkIndex}]${location}`, error);
637
+ throw error;
638
+ }
639
+ }
640
+ }
641
+ /**
642
+ * Manually restore the DO to a specific PITR bookmark.
643
+ * The DO will restart on next access with the restored state.
644
+ */
645
+ async restoreToBookmark(bookmark) {
646
+ await this.ctx.storage.onNextSessionRestoreBookmark(bookmark);
647
+ this.ctx.abort("Restoring to pre-migration bookmark");
648
+ }
649
+ /**
650
+ * Get the current PITR bookmark for diagnostic purposes.
651
+ * Returns null if PITR is not available.
652
+ */
653
+ async getMigrationBookmark() {
654
+ if (!await this.checkPitrAvailable()) return null;
655
+ return this.ctx.storage.getCurrentBookmark();
656
+ }
657
+ /**
658
+ * Get migration attempt diagnostics.
659
+ * Returns the current retry counter and last error info.
660
+ */
661
+ getMigrationAttempts() {
662
+ try {
663
+ const rows = this.sql.exec("SELECT attempt_count, last_attempt_at, last_error FROM __migration_attempts WHERE id = ?", "current").toArray();
664
+ if (rows.length === 0) return {
665
+ attemptCount: 0,
666
+ lastAttemptAt: null,
667
+ lastError: null
668
+ };
669
+ return {
670
+ attemptCount: rows[0].attempt_count,
671
+ lastAttemptAt: rows[0].last_attempt_at,
672
+ lastError: rows[0].last_error
673
+ };
674
+ } catch {
675
+ return {
676
+ attemptCount: 0,
677
+ lastAttemptAt: null,
678
+ lastError: null
679
+ };
680
+ }
681
+ }
682
+ /**
683
+ * Read the last recorded migration error, or null if unavailable.
684
+ * Used for enriching PITR-exhausted log output.
685
+ */
686
+ readLastMigrationError() {
687
+ try {
688
+ return this.getMigrationAttempts().lastError;
689
+ } catch {
690
+ return null;
691
+ }
692
+ }
693
+ /**
694
+ * Get a consolidated snapshot of migration state: attempts, pending and
695
+ * applied migration names, and PITR availability. Useful for building
696
+ * admin/debug endpoints without exposing internal SQL.
697
+ */
698
+ async getMigrationStatus() {
699
+ const attempts = this.getMigrationAttempts();
700
+ const pitrAvailable = await this.checkPitrAvailable();
701
+ const pitrAttemptsRemaining = pitrAvailable ? Math.max(0, MAX_PITR_ATTEMPTS + 1 - attempts.attemptCount) : 0;
702
+ const appliedSet = /* @__PURE__ */ new Set();
703
+ try {
704
+ const rows = this.sql.exec("SELECT DISTINCT name FROM __migrations").toArray();
705
+ for (const row of rows) appliedSet.add(row.name);
706
+ } catch {}
707
+ const migrationNames = Object.keys(this.migrations).sort();
708
+ const applied = [];
709
+ const pending = [];
710
+ for (const name of migrationNames) if (appliedSet.has(name)) applied.push(name);
711
+ else pending.push(name);
712
+ return {
713
+ attempts,
714
+ pending,
715
+ applied,
716
+ pitrAvailable,
717
+ pitrUnavailableReason: pitrAvailable ? null : this.pitrUnavailableReason,
718
+ pitrAttemptsRemaining
719
+ };
720
+ }
721
+ /**
722
+ * Override fetch to ensure migrations run before any request.
723
+ * Handles WebSocket upgrade requests for websocket transport.
724
+ * Subclasses (e.g. Browsable-wrapped DOs) should call ensureMigrations()
725
+ * before delegating to super.fetch().
726
+ */
727
+ async fetch(request) {
728
+ await this.ensureMigrations();
729
+ if (request.headers.get("Upgrade") === "websocket") {
730
+ const pair = new WebSocketPair();
731
+ const [client, server] = Object.values(pair);
732
+ this.ctx.acceptWebSocket(server);
733
+ return new Response(null, {
734
+ status: 101,
735
+ webSocket: client
736
+ });
737
+ }
738
+ return new Response("OK");
739
+ }
740
+ /**
741
+ * Handle incoming WebSocket messages.
742
+ * Subclasses (generated DO classes) override this to dispatch actions.
743
+ */
744
+ async webSocketMessage(_ws, _message) {}
745
+ /**
746
+ * Handle WebSocket close. Echoes close back to the client.
747
+ */
748
+ async webSocketClose(ws, code, reason, _wasClean) {
749
+ ws.close(code, reason);
750
+ }
751
+ /**
752
+ * Handle WebSocket error. Closes with error code.
753
+ */
754
+ async webSocketError(ws, _error) {
755
+ ws.close(1011, "Unexpected error");
756
+ }
757
+ };
758
+
759
+ //#endregion
760
+ export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };