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.
- package/README.md +1052 -0
- package/dist/cli/bin.d.ts +1 -0
- package/dist/cli/bin.js +18 -0
- package/dist/cli/index.d.ts +330 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli-Cr9686BF.js +630 -0
- package/dist/context/index.d.ts +2 -0
- package/dist/context/index.js +5 -0
- package/dist/context-BuIiIQ6K.js +103 -0
- package/dist/db/index.d.ts +3 -0
- package/dist/db/index.js +760 -0
- package/dist/debug-BZJbKybf.js +49 -0
- package/dist/defineDatabase-CONf4xFC.js +54 -0
- package/dist/defineDatabase-jBv90-Pk.d.ts +188 -0
- package/dist/generator-BUPP9scJ.js +180 -0
- package/dist/index-BFM5d0FP.d.ts +328 -0
- package/dist/index-CqVMaMYY.d.ts +65 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +8 -0
- package/dist/migrations/generator.d.ts +101 -0
- package/dist/migrations/generator.js +5 -0
- package/dist/migrations/snapshot.d.ts +2 -0
- package/dist/migrations/snapshot.js +3 -0
- package/dist/parser-CbX54Flt.js +293 -0
- package/dist/protocol-g_plhPOY.js +35 -0
- package/dist/push-BgQ5cnfH.js +184 -0
- package/dist/push-BkkaslPd.js +8 -0
- package/dist/registry.d.ts +28 -0
- package/dist/registry.js +72 -0
- package/dist/schema-BOtrGnzM.js +8 -0
- package/dist/schema-CpzTOfZ6.d.ts +6 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +3 -0
- package/dist/snapshot-C162qYoA.d.ts +125 -0
- package/dist/snapshot-D170nL7i.js +93 -0
- package/dist/state-BCcvNN-M.js +5 -0
- package/dist/state-FOEjpgJ6.js +203 -0
- package/dist/transport/protocol.d.ts +27 -0
- package/dist/transport/protocol.js +3 -0
- package/dist/transport/websocket.d.ts +31 -0
- package/dist/transport/websocket.js +3 -0
- package/dist/vite/durableDb.d.ts +20 -0
- package/dist/vite/durableDb.js +933 -0
- package/dist/websocket-Dx1fqwnF.js +104 -0
- package/package.json +114 -0
- package/virtual.d.ts +15 -0
|
@@ -0,0 +1,933 @@
|
|
|
1
|
+
import { i as init_debug, r as debugVite } from "../debug-BZJbKybf.js";
|
|
2
|
+
import { _ as saveDevState, c as getDevPaths, d as init_state, m as loadDevState } from "../state-FOEjpgJ6.js";
|
|
3
|
+
import "../snapshot-D170nL7i.js";
|
|
4
|
+
import { a as loadMigrationFiles } from "../generator-BUPP9scJ.js";
|
|
5
|
+
import { i as readFile, n as parseDatabaseFile, r as discoverDatabaseFiles, t as BABEL_PARSER_PLUGINS } from "../parser-CbX54Flt.js";
|
|
6
|
+
import * as fs from "node:fs";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
import { parse } from "@babel/parser";
|
|
9
|
+
import _generate from "@babel/generator";
|
|
10
|
+
import * as t from "@babel/types";
|
|
11
|
+
|
|
12
|
+
//#region src/vite/modules/wrangler.ts
|
|
13
|
+
init_debug();
|
|
14
|
+
/**
|
|
15
|
+
* Find the wrangler config file in a project
|
|
16
|
+
*/
|
|
17
|
+
function findWranglerConfig(projectRoot) {
|
|
18
|
+
for (const candidate of ["wrangler.jsonc", "wrangler.json"]) {
|
|
19
|
+
const configPath = path.join(projectRoot, candidate);
|
|
20
|
+
if (fs.existsSync(configPath)) return configPath;
|
|
21
|
+
}
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Strip JSONC comments while respecting string literals.
|
|
26
|
+
* Tracks whether we're inside a `"..."` so `//` and `/*` inside
|
|
27
|
+
* strings (e.g. URLs) are preserved.
|
|
28
|
+
*/
|
|
29
|
+
function stripJsoncComments(content) {
|
|
30
|
+
let result = "";
|
|
31
|
+
let i = 0;
|
|
32
|
+
const len = content.length;
|
|
33
|
+
while (i < len) {
|
|
34
|
+
const ch = content[i];
|
|
35
|
+
if (ch === "\"") {
|
|
36
|
+
result += "\"";
|
|
37
|
+
i++;
|
|
38
|
+
while (i < len) {
|
|
39
|
+
const sc = content[i];
|
|
40
|
+
result += sc;
|
|
41
|
+
i++;
|
|
42
|
+
if (sc === "\\") {
|
|
43
|
+
if (i < len) {
|
|
44
|
+
result += content[i];
|
|
45
|
+
i++;
|
|
46
|
+
}
|
|
47
|
+
} else if (sc === "\"") break;
|
|
48
|
+
}
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (ch === "/" && i + 1 < len && content[i + 1] === "/") {
|
|
52
|
+
i += 2;
|
|
53
|
+
while (i < len && content[i] !== "\n") i++;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (ch === "/" && i + 1 < len && content[i + 1] === "*") {
|
|
57
|
+
i += 2;
|
|
58
|
+
while (i < len) {
|
|
59
|
+
if (content[i] === "*" && i + 1 < len && content[i + 1] === "/") {
|
|
60
|
+
i += 2;
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
i++;
|
|
64
|
+
}
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
result += ch;
|
|
68
|
+
i++;
|
|
69
|
+
}
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Parse wrangler.jsonc content (strips comments)
|
|
74
|
+
*/
|
|
75
|
+
function parseWranglerConfig(content) {
|
|
76
|
+
return JSON.parse(stripJsoncComments(content));
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Patch wrangler config with Durable Object bindings
|
|
80
|
+
*
|
|
81
|
+
* Adds any missing DO bindings and migration entries
|
|
82
|
+
*/
|
|
83
|
+
function patchWranglerConfig(projectRoot, databases) {
|
|
84
|
+
const configPath = findWranglerConfig(projectRoot);
|
|
85
|
+
if (!configPath) {
|
|
86
|
+
console.warn("[db] wrangler.jsonc/json not found");
|
|
87
|
+
logRequiredConfig(databases);
|
|
88
|
+
return {
|
|
89
|
+
modified: false,
|
|
90
|
+
configPath: null,
|
|
91
|
+
error: null
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
const content = fs.readFileSync(configPath, "utf-8");
|
|
96
|
+
const config = parseWranglerConfig(content);
|
|
97
|
+
let modified = false;
|
|
98
|
+
if (!config.durable_objects) {
|
|
99
|
+
config.durable_objects = { bindings: [] };
|
|
100
|
+
modified = true;
|
|
101
|
+
}
|
|
102
|
+
if (!config.durable_objects.bindings) {
|
|
103
|
+
config.durable_objects.bindings = [];
|
|
104
|
+
modified = true;
|
|
105
|
+
}
|
|
106
|
+
for (const db of databases) if (!config.durable_objects.bindings.some((b) => b.name === db.bindingName || b.class_name === db.className)) {
|
|
107
|
+
config.durable_objects.bindings.push({
|
|
108
|
+
name: db.bindingName,
|
|
109
|
+
class_name: db.className
|
|
110
|
+
});
|
|
111
|
+
modified = true;
|
|
112
|
+
}
|
|
113
|
+
if (!config.migrations) {
|
|
114
|
+
config.migrations = [];
|
|
115
|
+
modified = true;
|
|
116
|
+
}
|
|
117
|
+
const existingClasses = new Set(config.migrations.flatMap((m) => m.new_sqlite_classes ?? []));
|
|
118
|
+
const missingClasses = databases.map((db) => db.className).filter((c) => !existingClasses.has(c));
|
|
119
|
+
if (missingClasses.length > 0) {
|
|
120
|
+
const existingTagNumbers = config.migrations.map((m) => {
|
|
121
|
+
const match = m.tag.match(/^v(\d+)$/);
|
|
122
|
+
return match ? parseInt(match[1], 10) : 0;
|
|
123
|
+
});
|
|
124
|
+
const nextTagNum = existingTagNumbers.length > 0 ? Math.max(...existingTagNumbers) + 1 : 1;
|
|
125
|
+
config.migrations.push({
|
|
126
|
+
tag: `v${nextTagNum}`,
|
|
127
|
+
new_sqlite_classes: missingClasses
|
|
128
|
+
});
|
|
129
|
+
modified = true;
|
|
130
|
+
}
|
|
131
|
+
if (modified) {
|
|
132
|
+
if (contentHasComments(content)) {
|
|
133
|
+
const backupPath = configPath + ".backup";
|
|
134
|
+
if (!fs.existsSync(backupPath)) {
|
|
135
|
+
fs.writeFileSync(backupPath, content, "utf-8");
|
|
136
|
+
debugVite("Original %s contained comments that will be lost during patching. Backup saved to %s", path.basename(configPath), path.basename(backupPath));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const newContent = JSON.stringify(config, null, 2);
|
|
140
|
+
fs.writeFileSync(configPath, newContent, "utf-8");
|
|
141
|
+
debugVite("Updated %s with DO bindings", path.basename(configPath));
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
modified,
|
|
145
|
+
configPath,
|
|
146
|
+
error: null
|
|
147
|
+
};
|
|
148
|
+
} catch (error) {
|
|
149
|
+
debugVite("Failed to patch wrangler config: %O", error);
|
|
150
|
+
logRequiredConfig(databases);
|
|
151
|
+
return {
|
|
152
|
+
modified: false,
|
|
153
|
+
configPath,
|
|
154
|
+
error
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Check whether a JSONC string contains comments (outside of string literals).
|
|
160
|
+
* Used to decide whether a backup is needed before re-serializing.
|
|
161
|
+
*/
|
|
162
|
+
function contentHasComments(content) {
|
|
163
|
+
let i = 0;
|
|
164
|
+
const len = content.length;
|
|
165
|
+
while (i < len) {
|
|
166
|
+
const ch = content[i];
|
|
167
|
+
if (ch === "\"") {
|
|
168
|
+
i++;
|
|
169
|
+
while (i < len) {
|
|
170
|
+
if (content[i] === "\\") {
|
|
171
|
+
i += 2;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (content[i] === "\"") {
|
|
175
|
+
i++;
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
i++;
|
|
179
|
+
}
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (ch === "/" && i + 1 < len && (content[i + 1] === "/" || content[i + 1] === "*")) return true;
|
|
183
|
+
i++;
|
|
184
|
+
}
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Log the required wrangler config for manual setup
|
|
189
|
+
*/
|
|
190
|
+
function logRequiredConfig(databases) {
|
|
191
|
+
const bindings = databases.map((db) => ({
|
|
192
|
+
name: db.bindingName,
|
|
193
|
+
class_name: db.className
|
|
194
|
+
}));
|
|
195
|
+
const migrations = [{
|
|
196
|
+
tag: "v1",
|
|
197
|
+
new_sqlite_classes: databases.map((db) => db.className)
|
|
198
|
+
}];
|
|
199
|
+
debugVite("Required Durable Object config:\n%O", {
|
|
200
|
+
durable_objects: { bindings },
|
|
201
|
+
migrations
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
//#endregion
|
|
206
|
+
//#region src/vite/modules/generator.ts
|
|
207
|
+
const generate = typeof _generate === "function" ? _generate : _generate.default;
|
|
208
|
+
/**
|
|
209
|
+
* Virtual module (served by the Vite plugin) exporting `applyDevEpoch(key)`.
|
|
210
|
+
* In dev it suffixes instance keys with the current dev epoch so `db reset`
|
|
211
|
+
* (which bumps the epoch) yields fresh DO instances; in production builds it
|
|
212
|
+
* is the identity function.
|
|
213
|
+
*/
|
|
214
|
+
const DEV_EPOCH_IMPORT = "virtual:durable-db/__devEpoch";
|
|
215
|
+
function parseProgram(code) {
|
|
216
|
+
return parse(code, {
|
|
217
|
+
sourceType: "module",
|
|
218
|
+
plugins: BABEL_PARSER_PLUGINS
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
function parseExpression(code) {
|
|
222
|
+
const stmt = parse(`(${code.trim().replace(/;\s*$/, "")})`, {
|
|
223
|
+
sourceType: "module",
|
|
224
|
+
plugins: BABEL_PARSER_PLUGINS
|
|
225
|
+
}).program.body[0];
|
|
226
|
+
if (t.isExpressionStatement(stmt)) return stmt.expression;
|
|
227
|
+
throw new Error(`Expected expression, got ${stmt?.type ?? "unknown"}`);
|
|
228
|
+
}
|
|
229
|
+
function createNamedImport(names, source) {
|
|
230
|
+
const specifiers = names.map((name) => t.importSpecifier(t.identifier(name), t.identifier(name)));
|
|
231
|
+
return t.importDeclaration(specifiers, t.stringLiteral(source));
|
|
232
|
+
}
|
|
233
|
+
function ensureNamedImports(body, source, names) {
|
|
234
|
+
const existing = body.find((s) => t.isImportDeclaration(s) && s.source.value === source);
|
|
235
|
+
if (!existing) {
|
|
236
|
+
let insertAt = 0;
|
|
237
|
+
while (insertAt < body.length && t.isImportDeclaration(body[insertAt])) insertAt++;
|
|
238
|
+
body.splice(insertAt, 0, createNamedImport(names, source));
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const have = new Set(existing.specifiers.filter((sp) => t.isImportSpecifier(sp)).map((sp) => sp.imported.name));
|
|
242
|
+
for (const n of names) if (!have.has(n)) existing.specifiers.push(t.importSpecifier(t.identifier(n), t.identifier(n)));
|
|
243
|
+
}
|
|
244
|
+
function buildMigrationsObject(migrations) {
|
|
245
|
+
if (!migrations || migrations.size === 0) return t.objectExpression([]);
|
|
246
|
+
const properties = Array.from(migrations.entries()).sort(([a], [b]) => a.localeCompare(b)).map(([name, chunks]) => {
|
|
247
|
+
const chunksArray = t.arrayExpression(chunks.map((chunk) => t.arrayExpression(chunk.map((stmt) => t.stringLiteral(stmt)))));
|
|
248
|
+
return t.objectProperty(t.stringLiteral(name), t.objectExpression([t.objectProperty(t.identifier("chunks"), chunksArray)]));
|
|
249
|
+
});
|
|
250
|
+
return t.objectExpression(properties);
|
|
251
|
+
}
|
|
252
|
+
function buildBindingNamesObject(databases) {
|
|
253
|
+
const properties = databases.map((db) => t.objectProperty(t.stringLiteral(db.name), t.stringLiteral(db.bindingName)));
|
|
254
|
+
return t.objectExpression(properties);
|
|
255
|
+
}
|
|
256
|
+
function buildDbTransportsObject(databases) {
|
|
257
|
+
const properties = databases.map((db) => t.objectProperty(t.stringLiteral(db.name), t.stringLiteral(db.transport)));
|
|
258
|
+
return t.objectExpression(properties);
|
|
259
|
+
}
|
|
260
|
+
function generateCode(ast) {
|
|
261
|
+
return generate(ast, { comments: true }).code;
|
|
262
|
+
}
|
|
263
|
+
function generateWithMap(ast, sourceFileName) {
|
|
264
|
+
return generate(ast, {
|
|
265
|
+
sourceMaps: true,
|
|
266
|
+
sourceFileName,
|
|
267
|
+
comments: true
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
function generateDurableObjectsModule(databases, registryImport, isDev = false) {
|
|
271
|
+
const bindingNamesExpr = buildBindingNamesObject(databases);
|
|
272
|
+
const dbTransportsExpr = buildDbTransportsObject(databases);
|
|
273
|
+
const anyBrowsable = databases.some((db) => db.browsable === true || db.browsable === "development" && isDev);
|
|
274
|
+
const anyWebSocket = databases.some((db) => db.transport === "websocket");
|
|
275
|
+
const imports = [createNamedImport(["SqliteDurableObject", "type"], "durable-db/db"), createNamedImport(["getAction", "runWithDoContext"], registryImport)];
|
|
276
|
+
if (anyBrowsable) imports.push(createNamedImport(["Browsable"], "@outerbase/browsable-durable-object"));
|
|
277
|
+
if (anyWebSocket) imports.push(createNamedImport(["decodeRequest", "encodeResponse"], "durable-db/transport/protocol"));
|
|
278
|
+
const statements = [...imports];
|
|
279
|
+
for (const db of databases) statements.push(...buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev));
|
|
280
|
+
const program = t.program(statements);
|
|
281
|
+
return generateCode(t.file(program));
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Build an async method that calls this.ensureMigrations() then super.<name>(...args).
|
|
285
|
+
*/
|
|
286
|
+
function buildMigrationGuardMethod(name, params) {
|
|
287
|
+
return t.classMethod("method", t.identifier(name), params, t.blockStatement([t.expressionStatement(t.awaitExpression(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("ensureMigrations")), []))), t.returnStatement(t.callExpression(t.memberExpression(t.super(), t.identifier(name)), params))]), false, false, false, true);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Build statements for a single database's Durable Object class.
|
|
291
|
+
*
|
|
292
|
+
* When browsable is enabled, generates:
|
|
293
|
+
* const _ClassName_Base = Browsable()(class extends SqliteDurableObject { migrations = {...}; });
|
|
294
|
+
* export class ClassName extends _ClassName_Base {
|
|
295
|
+
* async fetch(req) { await this.ensureMigrations(); return super.fetch(req); }
|
|
296
|
+
* async __studio(cmd) { await this.ensureMigrations(); return super.__studio(cmd); }
|
|
297
|
+
* async rpc(...) { ... }
|
|
298
|
+
* }
|
|
299
|
+
*
|
|
300
|
+
* When not browsable:
|
|
301
|
+
* export class ClassName extends SqliteDurableObject {
|
|
302
|
+
* migrations = {...};
|
|
303
|
+
* async rpc(...) { ... }
|
|
304
|
+
* }
|
|
305
|
+
*/
|
|
306
|
+
function buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev) {
|
|
307
|
+
const isBrowsable = db.browsable === true || db.browsable === "development" && isDev;
|
|
308
|
+
const rpcMethod = buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr);
|
|
309
|
+
const migrationsProperty = t.classProperty(t.identifier("migrations"), buildMigrationsObject(db.migrations));
|
|
310
|
+
const classMethods = [rpcMethod, buildSysMethod()];
|
|
311
|
+
if (db.transport === "websocket") classMethods.push(buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr));
|
|
312
|
+
if (!isBrowsable) {
|
|
313
|
+
const classDecl$1 = t.classDeclaration(t.identifier(db.className), t.identifier("SqliteDurableObject"), t.classBody([migrationsProperty, ...classMethods]));
|
|
314
|
+
return [t.exportNamedDeclaration(classDecl$1)];
|
|
315
|
+
}
|
|
316
|
+
const baseName = `_${db.className}_Base`;
|
|
317
|
+
const innerClass = t.classExpression(null, t.identifier("SqliteDurableObject"), t.classBody([migrationsProperty]));
|
|
318
|
+
const browsableWrapped = t.callExpression(t.callExpression(t.identifier("Browsable"), []), [innerClass]);
|
|
319
|
+
const baseDecl = t.variableDeclaration("const", [t.variableDeclarator(t.identifier(baseName), browsableWrapped)]);
|
|
320
|
+
const classDecl = t.classDeclaration(t.identifier(db.className), t.identifier(baseName), t.classBody([
|
|
321
|
+
buildMigrationGuardMethod("fetch", [t.identifier("request")]),
|
|
322
|
+
buildMigrationGuardMethod("__studio", [t.identifier("cmd")]),
|
|
323
|
+
...classMethods
|
|
324
|
+
]));
|
|
325
|
+
return [baseDecl, t.exportNamedDeclaration(classDecl)];
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Build the ctx object expression used inside DO methods (rpc, webSocketMessage).
|
|
329
|
+
*/
|
|
330
|
+
function buildDoCtxObject(dbNameLiteral, bindingNamesExpr, dbTransportsExpr, instanceKeyExpr) {
|
|
331
|
+
return t.objectExpression([
|
|
332
|
+
t.objectProperty(t.identifier("env"), t.memberExpression(t.thisExpression(), t.identifier("env"))),
|
|
333
|
+
t.objectProperty(t.identifier("dbName"), dbNameLiteral),
|
|
334
|
+
t.objectProperty(t.identifier("dbBindingNames"), bindingNamesExpr),
|
|
335
|
+
t.objectProperty(t.identifier("dbTransports"), dbTransportsExpr),
|
|
336
|
+
t.objectProperty(t.identifier("instanceKey"), instanceKeyExpr)
|
|
337
|
+
]);
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Build the `sys(command)` method for system operations like destroyDatabase.
|
|
341
|
+
*
|
|
342
|
+
* Generates:
|
|
343
|
+
* async sys(command) {
|
|
344
|
+
* if (command === "destroyDatabase") {
|
|
345
|
+
* await this.ctx.storage.deleteAll();
|
|
346
|
+
* this.resetMigrationState();
|
|
347
|
+
* return null;
|
|
348
|
+
* }
|
|
349
|
+
* throw new Error(`[db] Unknown system command: "${command}"`);
|
|
350
|
+
* }
|
|
351
|
+
*/
|
|
352
|
+
function buildSysMethod() {
|
|
353
|
+
const body = t.blockStatement([t.ifStatement(t.binaryExpression("===", t.identifier("command"), t.stringLiteral("destroyDatabase")), t.blockStatement([
|
|
354
|
+
t.expressionStatement(t.awaitExpression(t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier("ctx")), t.identifier("storage")), t.identifier("deleteAll")), []))),
|
|
355
|
+
t.expressionStatement(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("resetMigrationState")), [])),
|
|
356
|
+
t.returnStatement(t.nullLiteral())
|
|
357
|
+
])), t.throwStatement(t.newExpression(t.identifier("Error"), [t.templateLiteral([t.templateElement({
|
|
358
|
+
raw: "[db] Unknown system command: \"",
|
|
359
|
+
cooked: "[db] Unknown system command: \""
|
|
360
|
+
}, false), t.templateElement({
|
|
361
|
+
raw: "\"",
|
|
362
|
+
cooked: "\""
|
|
363
|
+
}, true)], [t.identifier("command")])]))]);
|
|
364
|
+
return t.classMethod("method", t.identifier("sys"), [t.identifier("command")], body, false, false, false, true);
|
|
365
|
+
}
|
|
366
|
+
function buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr) {
|
|
367
|
+
const dbNameLiteral = t.stringLiteral(db.name);
|
|
368
|
+
const body = t.blockStatement([
|
|
369
|
+
t.expressionStatement(t.awaitExpression(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("ensureMigrations")), []))),
|
|
370
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("entry"), t.callExpression(t.identifier("getAction"), [dbNameLiteral, t.identifier("method")]))]),
|
|
371
|
+
t.ifStatement(t.unaryExpression("!", t.identifier("entry")), t.blockStatement([t.throwStatement(t.newExpression(t.identifier("Error"), [t.templateLiteral([t.templateElement({
|
|
372
|
+
raw: `[db] Unknown action "`,
|
|
373
|
+
cooked: `[db] Unknown action "`
|
|
374
|
+
}, false), t.templateElement({
|
|
375
|
+
raw: `" for db "${db.name}" (was it imported?)`,
|
|
376
|
+
cooked: `" for db "${db.name}" (was it imported?)`
|
|
377
|
+
}, true)], [t.identifier("method")])]))])),
|
|
378
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("validated"), t.callExpression(t.memberExpression(t.identifier("entry"), t.identifier("validator")), [t.identifier("args")]))]),
|
|
379
|
+
t.ifStatement(t.binaryExpression("instanceof", t.identifier("validated"), t.memberExpression(t.identifier("type"), t.identifier("errors"))), t.blockStatement([t.throwStatement(t.newExpression(t.identifier("Error"), [t.templateLiteral([
|
|
380
|
+
t.templateElement({
|
|
381
|
+
raw: `[db] Invalid args for "`,
|
|
382
|
+
cooked: `[db] Invalid args for "`
|
|
383
|
+
}, false),
|
|
384
|
+
t.templateElement({
|
|
385
|
+
raw: `": `,
|
|
386
|
+
cooked: `": `
|
|
387
|
+
}, false),
|
|
388
|
+
t.templateElement({
|
|
389
|
+
raw: "",
|
|
390
|
+
cooked: ""
|
|
391
|
+
}, true)
|
|
392
|
+
], [t.identifier("method"), t.memberExpression(t.identifier("validated"), t.identifier("summary"))])]))])),
|
|
393
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("ctx"), buildDoCtxObject(dbNameLiteral, bindingNamesExpr, dbTransportsExpr, t.logicalExpression("??", t.optionalMemberExpression(t.identifier("rpcContext"), t.identifier("instanceKey"), false, true), t.stringLiteral("global"))))]),
|
|
394
|
+
t.returnStatement(t.callExpression(t.identifier("runWithDoContext"), [t.objectExpression([
|
|
395
|
+
t.objectProperty(t.identifier("db"), t.memberExpression(t.thisExpression(), t.identifier("db"))),
|
|
396
|
+
t.objectProperty(t.identifier("ctx"), t.identifier("ctx")),
|
|
397
|
+
t.objectProperty(t.identifier("dbName"), dbNameLiteral),
|
|
398
|
+
t.objectProperty(t.identifier("instanceKey"), t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey")))
|
|
399
|
+
]), t.arrowFunctionExpression([], t.callExpression(t.memberExpression(t.identifier("entry"), t.identifier("handler")), [
|
|
400
|
+
t.memberExpression(t.thisExpression(), t.identifier("db")),
|
|
401
|
+
t.identifier("validated"),
|
|
402
|
+
t.identifier("ctx")
|
|
403
|
+
]), true)]))
|
|
404
|
+
]);
|
|
405
|
+
return t.classMethod("method", t.identifier("rpc"), [
|
|
406
|
+
t.identifier("method"),
|
|
407
|
+
t.identifier("args"),
|
|
408
|
+
t.identifier("rpcContext")
|
|
409
|
+
], body, false, false, false, true);
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Build the webSocketMessage method for WebSocket-enabled DOs.
|
|
413
|
+
*
|
|
414
|
+
* Generates:
|
|
415
|
+
* async webSocketMessage(ws, message) {
|
|
416
|
+
* await this.ensureMigrations();
|
|
417
|
+
* const request = decodeRequest(typeof message === "string" ? message : new TextDecoder().decode(message));
|
|
418
|
+
* const { id, action: method, args, instanceKey: reqInstanceKey } = request;
|
|
419
|
+
* try {
|
|
420
|
+
* const entry = getAction("dbName", method);
|
|
421
|
+
* if (!entry) { ws.send(encodeResponse({ id, ok: false, error: "Unknown action" })); return; }
|
|
422
|
+
* const validated = entry.validator(args);
|
|
423
|
+
* if (validated instanceof type.errors) { ws.send(encodeResponse({ id, ok: false, error: validated.summary })); return; }
|
|
424
|
+
* const ctx = { ... };
|
|
425
|
+
* const result = await runWithDoContext({ ... }, async () => entry.handler(this.db, validated, ctx));
|
|
426
|
+
* ws.send(encodeResponse({ id, ok: true, result }));
|
|
427
|
+
* } catch (error) {
|
|
428
|
+
* ws.send(encodeResponse({ id, ok: false, error: error instanceof Error ? error.message : String(error) }));
|
|
429
|
+
* }
|
|
430
|
+
* }
|
|
431
|
+
*/
|
|
432
|
+
function buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr) {
|
|
433
|
+
const dbNameLiteral = t.stringLiteral(db.name);
|
|
434
|
+
function wsSendResponse(props) {
|
|
435
|
+
return t.expressionStatement(t.callExpression(t.memberExpression(t.identifier("ws"), t.identifier("send")), [t.callExpression(t.identifier("encodeResponse"), [t.objectExpression(props)])]));
|
|
436
|
+
}
|
|
437
|
+
function errorResponseProps(errorExpr) {
|
|
438
|
+
return [
|
|
439
|
+
t.objectProperty(t.identifier("id"), t.identifier("id")),
|
|
440
|
+
t.objectProperty(t.identifier("ok"), t.booleanLiteral(false)),
|
|
441
|
+
t.objectProperty(t.identifier("error"), errorExpr)
|
|
442
|
+
];
|
|
443
|
+
}
|
|
444
|
+
const body = t.blockStatement([
|
|
445
|
+
t.expressionStatement(t.awaitExpression(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("ensureMigrations")), []))),
|
|
446
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("request"), t.callExpression(t.identifier("decodeRequest"), [t.conditionalExpression(t.binaryExpression("===", t.unaryExpression("typeof", t.identifier("message")), t.stringLiteral("string")), t.identifier("message"), t.callExpression(t.memberExpression(t.newExpression(t.identifier("TextDecoder"), []), t.identifier("decode")), [t.identifier("message")]))]))]),
|
|
447
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.objectPattern([
|
|
448
|
+
t.objectProperty(t.identifier("id"), t.identifier("id"), false, true),
|
|
449
|
+
t.objectProperty(t.identifier("action"), t.identifier("method")),
|
|
450
|
+
t.objectProperty(t.identifier("args"), t.identifier("args"), false, true),
|
|
451
|
+
t.objectProperty(t.identifier("instanceKey"), t.identifier("reqInstanceKey"))
|
|
452
|
+
]), t.identifier("request"))]),
|
|
453
|
+
t.tryStatement(t.blockStatement([
|
|
454
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("entry"), t.callExpression(t.identifier("getAction"), [dbNameLiteral, t.identifier("method")]))]),
|
|
455
|
+
t.ifStatement(t.unaryExpression("!", t.identifier("entry")), t.blockStatement([wsSendResponse(errorResponseProps(t.templateLiteral([t.templateElement({
|
|
456
|
+
raw: "Unknown action: ",
|
|
457
|
+
cooked: "Unknown action: "
|
|
458
|
+
}, false), t.templateElement({
|
|
459
|
+
raw: "",
|
|
460
|
+
cooked: ""
|
|
461
|
+
}, true)], [t.identifier("method")]))), t.returnStatement(null)])),
|
|
462
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("validated"), t.callExpression(t.memberExpression(t.identifier("entry"), t.identifier("validator")), [t.identifier("args")]))]),
|
|
463
|
+
t.ifStatement(t.binaryExpression("instanceof", t.identifier("validated"), t.memberExpression(t.identifier("type"), t.identifier("errors"))), t.blockStatement([wsSendResponse(errorResponseProps(t.memberExpression(t.identifier("validated"), t.identifier("summary")))), t.returnStatement(null)])),
|
|
464
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("ctx"), buildDoCtxObject(dbNameLiteral, bindingNamesExpr, dbTransportsExpr, t.logicalExpression("??", t.identifier("reqInstanceKey"), t.stringLiteral("global"))))]),
|
|
465
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("result"), t.awaitExpression(t.callExpression(t.identifier("runWithDoContext"), [t.objectExpression([
|
|
466
|
+
t.objectProperty(t.identifier("db"), t.memberExpression(t.thisExpression(), t.identifier("db"))),
|
|
467
|
+
t.objectProperty(t.identifier("ctx"), t.identifier("ctx")),
|
|
468
|
+
t.objectProperty(t.identifier("dbName"), dbNameLiteral),
|
|
469
|
+
t.objectProperty(t.identifier("instanceKey"), t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey")))
|
|
470
|
+
]), t.arrowFunctionExpression([], t.callExpression(t.memberExpression(t.identifier("entry"), t.identifier("handler")), [
|
|
471
|
+
t.memberExpression(t.thisExpression(), t.identifier("db")),
|
|
472
|
+
t.identifier("validated"),
|
|
473
|
+
t.identifier("ctx")
|
|
474
|
+
]), true)])))]),
|
|
475
|
+
wsSendResponse([
|
|
476
|
+
t.objectProperty(t.identifier("id"), t.identifier("id"), false, true),
|
|
477
|
+
t.objectProperty(t.identifier("ok"), t.booleanLiteral(true)),
|
|
478
|
+
t.objectProperty(t.identifier("result"), t.identifier("result"), false, true)
|
|
479
|
+
])
|
|
480
|
+
]), t.catchClause(t.identifier("error"), t.blockStatement([wsSendResponse(errorResponseProps(t.conditionalExpression(t.binaryExpression("instanceof", t.identifier("error"), t.identifier("Error")), t.memberExpression(t.identifier("error"), t.identifier("message")), t.callExpression(t.identifier("String"), [t.identifier("error")]))))])))
|
|
481
|
+
]);
|
|
482
|
+
return t.classMethod("method", t.identifier("webSocketMessage"), [t.identifier("ws"), t.identifier("message")], body, false, false, false, true);
|
|
483
|
+
}
|
|
484
|
+
function buildRpcCall(action) {
|
|
485
|
+
return t.callExpression(t.memberExpression(t.identifier("stub"), t.identifier("rpc")), [
|
|
486
|
+
t.stringLiteral(action.exportName),
|
|
487
|
+
t.identifier("validatedArgs"),
|
|
488
|
+
t.objectExpression([t.objectProperty(t.identifier("instanceKey"), t.identifier("instanceKey"))])
|
|
489
|
+
]);
|
|
490
|
+
}
|
|
491
|
+
function buildDoShortPath(config) {
|
|
492
|
+
const { action, database } = config;
|
|
493
|
+
return [t.variableDeclaration("const", [t.variableDeclarator(t.identifier("__do"), t.callExpression(t.identifier("getDoContext"), []))]), t.ifStatement(t.logicalExpression("&&", t.identifier("__do"), t.binaryExpression("===", t.memberExpression(t.identifier("__do"), t.identifier("dbName")), t.stringLiteral(database.name))), t.blockStatement([t.returnStatement(t.callExpression(t.identifier("callAction"), [
|
|
494
|
+
t.memberExpression(t.identifier("__do"), t.identifier("db")),
|
|
495
|
+
t.stringLiteral(database.name),
|
|
496
|
+
t.stringLiteral(action.exportName),
|
|
497
|
+
t.identifier("validatedArgs"),
|
|
498
|
+
t.memberExpression(t.identifier("__do"), t.identifier("ctx"))
|
|
499
|
+
]))]))];
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Build `applyDevEpoch(<baseKey>)` — instance keys always pass through the
|
|
503
|
+
* dev-epoch helper so `db reset` can rotate to fresh DO instances in dev.
|
|
504
|
+
*/
|
|
505
|
+
function buildInstanceKeyExpr(database) {
|
|
506
|
+
const baseKeyExpr = database.instance === "global" ? t.stringLiteral("global") : t.callExpression(t.identifier("getTenantId"), []);
|
|
507
|
+
return t.callExpression(t.identifier("applyDevEpoch"), [baseKeyExpr]);
|
|
508
|
+
}
|
|
509
|
+
function buildStubBodyStatements(config) {
|
|
510
|
+
const { action, database } = config;
|
|
511
|
+
const bindingExpr = t.memberExpression(t.identifier("env"), t.identifier(database.bindingName));
|
|
512
|
+
const instanceKeyExpr = buildInstanceKeyExpr(database);
|
|
513
|
+
const commonStatements = [
|
|
514
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("argsSchema"), t.callExpression(t.identifier("type"), [parseExpression(action.argsSchemaSource)]))]),
|
|
515
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("validatedArgs"), t.callExpression(t.memberExpression(t.identifier("argsSchema"), t.identifier("assert")), [t.identifier("args")]))]),
|
|
516
|
+
...buildDoShortPath(config),
|
|
517
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("instanceKey"), instanceKeyExpr)]),
|
|
518
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("id"), t.callExpression(t.memberExpression(bindingExpr, t.identifier("idFromName")), [t.identifier("instanceKey")]))]),
|
|
519
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("stub"), t.callExpression(t.memberExpression(bindingExpr, t.identifier("get")), [t.identifier("id")]))])
|
|
520
|
+
];
|
|
521
|
+
if (database.transport === "websocket") return [
|
|
522
|
+
...commonStatements,
|
|
523
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("wsTransport"), t.newExpression(t.identifier("WebSocketTransport"), [t.identifier("stub")]))]),
|
|
524
|
+
t.returnStatement(t.callExpression(t.memberExpression(t.identifier("wsTransport"), t.identifier("call")), [
|
|
525
|
+
t.stringLiteral(action.exportName),
|
|
526
|
+
t.identifier("validatedArgs"),
|
|
527
|
+
t.identifier("instanceKey")
|
|
528
|
+
]))
|
|
529
|
+
];
|
|
530
|
+
return [...commonStatements, t.returnStatement(buildRpcCall(action))];
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Rewrite `export const x = action({...})` declarations in the given program
|
|
534
|
+
* body into validator + handler registration + RPC stub. Mutates `body` in
|
|
535
|
+
* place. Returns whether any transformation was applied.
|
|
536
|
+
*/
|
|
537
|
+
function applyActionTransforms(body, ctx) {
|
|
538
|
+
const { dbName, database, actionsInFile, contextImport, registryImport } = ctx;
|
|
539
|
+
if (actionsInFile.length === 0) return false;
|
|
540
|
+
ensureNamedImports(body, "arktype", ["type"]);
|
|
541
|
+
ensureNamedImports(body, contextImport, ["getTenantId"]);
|
|
542
|
+
ensureNamedImports(body, "cloudflare:workers", ["env"]);
|
|
543
|
+
ensureNamedImports(body, registryImport, [
|
|
544
|
+
"registerAction",
|
|
545
|
+
"getDoContext",
|
|
546
|
+
"callAction"
|
|
547
|
+
]);
|
|
548
|
+
ensureNamedImports(body, DEV_EPOCH_IMPORT, ["applyDevEpoch"]);
|
|
549
|
+
if (database.transport === "websocket") ensureNamedImports(body, "durable-db/transport/websocket", ["WebSocketTransport"]);
|
|
550
|
+
const actionNames = new Set(actionsInFile.map((a) => a.exportName));
|
|
551
|
+
const out = [];
|
|
552
|
+
for (const stmt of body) {
|
|
553
|
+
if (!t.isExportNamedDeclaration(stmt) || !stmt.declaration || !t.isVariableDeclaration(stmt.declaration)) {
|
|
554
|
+
out.push(stmt);
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
const decl = stmt.declaration;
|
|
558
|
+
const replaced = [];
|
|
559
|
+
const remaining = [];
|
|
560
|
+
for (const d of decl.declarations) {
|
|
561
|
+
if (!t.isIdentifier(d.id) || !actionNames.has(d.id.name)) {
|
|
562
|
+
remaining.push(d);
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
const exportName = d.id.name;
|
|
566
|
+
const action = actionsInFile.find((a) => a.exportName === exportName);
|
|
567
|
+
const validatorId = t.identifier(`__validator_${exportName}`);
|
|
568
|
+
const handlerId = t.identifier(`__handler_${exportName}`);
|
|
569
|
+
replaced.push(t.variableDeclaration("const", [t.variableDeclarator(validatorId, t.callExpression(t.identifier("type"), [parseExpression(action.argsSchemaSource)]))]));
|
|
570
|
+
replaced.push(t.variableDeclaration("const", [t.variableDeclarator(handlerId, parseExpression(action.handlerSource))]));
|
|
571
|
+
replaced.push(t.expressionStatement(t.callExpression(t.identifier("registerAction"), [
|
|
572
|
+
t.stringLiteral(dbName),
|
|
573
|
+
t.stringLiteral(exportName),
|
|
574
|
+
t.objectExpression([t.objectProperty(t.identifier("validator"), t.arrowFunctionExpression([t.identifier("args")], t.callExpression(validatorId, [t.identifier("args")]))), t.objectProperty(t.identifier("handler"), handlerId)])
|
|
575
|
+
])));
|
|
576
|
+
const funcDecl = t.functionDeclaration(t.identifier(exportName), [t.identifier("args")], t.blockStatement(buildStubBodyStatements({
|
|
577
|
+
action,
|
|
578
|
+
database
|
|
579
|
+
})), false, true);
|
|
580
|
+
replaced.push(t.exportNamedDeclaration(funcDecl));
|
|
581
|
+
}
|
|
582
|
+
if (replaced.length > 0) {
|
|
583
|
+
if (remaining.length > 0) out.push(t.exportNamedDeclaration(t.variableDeclaration(decl.kind, remaining)));
|
|
584
|
+
out.push(...replaced);
|
|
585
|
+
} else out.push(stmt);
|
|
586
|
+
}
|
|
587
|
+
body.splice(0, body.length, ...out);
|
|
588
|
+
return true;
|
|
589
|
+
}
|
|
590
|
+
function transformActionFile(options) {
|
|
591
|
+
const { code, sourceFileName, ...ctx } = options;
|
|
592
|
+
if (ctx.actionsInFile.length === 0) return null;
|
|
593
|
+
const ast = parseProgram(code);
|
|
594
|
+
applyActionTransforms(ast.program.body, ctx);
|
|
595
|
+
return generateWithMap(ast, sourceFileName);
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Transform a database definition file:
|
|
599
|
+
* - replaces the `destroyDatabase` placeholder (when destructured) with a
|
|
600
|
+
* generated stub that calls the DO's `sys("destroyDatabase")` method
|
|
601
|
+
* - rewrites same-file `action()` definitions into RPC stubs, exactly like
|
|
602
|
+
* action files that import the factory — without this, same-file actions
|
|
603
|
+
* pass discovery but throw "called without transformation" at runtime
|
|
604
|
+
*
|
|
605
|
+
* Returns null when there is nothing to transform.
|
|
606
|
+
*/
|
|
607
|
+
function transformDatabaseFile(options) {
|
|
608
|
+
const { code, sourceFileName, database, contextImport, actionsInFile = [], registryImport = "durable-db/registry" } = options;
|
|
609
|
+
const ast = parseProgram(code);
|
|
610
|
+
const body = ast.program.body;
|
|
611
|
+
const destroyTransformed = applyDestroyDatabaseTransform(body, database, contextImport);
|
|
612
|
+
const actionsTransformed = applyActionTransforms(body, {
|
|
613
|
+
dbName: database.name,
|
|
614
|
+
database,
|
|
615
|
+
actionsInFile,
|
|
616
|
+
contextImport,
|
|
617
|
+
registryImport
|
|
618
|
+
});
|
|
619
|
+
if (!destroyTransformed && !actionsTransformed) return null;
|
|
620
|
+
return generateWithMap(ast, sourceFileName);
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Replace a destructured `destroyDatabase` with a generated stub.
|
|
624
|
+
* Mutates `body` in place. Returns whether the transform was applied.
|
|
625
|
+
*/
|
|
626
|
+
function applyDestroyDatabaseTransform(body, database, contextImport) {
|
|
627
|
+
let found = false;
|
|
628
|
+
for (const stmt of body) {
|
|
629
|
+
if (!t.isExportNamedDeclaration(stmt) || !stmt.declaration || !t.isVariableDeclaration(stmt.declaration)) continue;
|
|
630
|
+
for (const decl of stmt.declaration.declarations) {
|
|
631
|
+
if (!t.isObjectPattern(decl.id) || !isDefineDatabaseCallNode(decl.init)) continue;
|
|
632
|
+
const destroyIdx = decl.id.properties.findIndex((prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "destroyDatabase");
|
|
633
|
+
if (destroyIdx === -1) continue;
|
|
634
|
+
decl.id.properties.splice(destroyIdx, 1);
|
|
635
|
+
found = true;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
if (!found) return false;
|
|
639
|
+
ensureNamedImports(body, "cloudflare:workers", ["env"]);
|
|
640
|
+
ensureNamedImports(body, DEV_EPOCH_IMPORT, ["applyDevEpoch"]);
|
|
641
|
+
if (database.instance === "per-tenant") ensureNamedImports(body, contextImport, ["getTenantId"]);
|
|
642
|
+
const bindingExpr = t.memberExpression(t.identifier("env"), t.identifier(database.bindingName));
|
|
643
|
+
const instanceKeyExpr = buildInstanceKeyExpr(database);
|
|
644
|
+
const stubBody = t.blockStatement([
|
|
645
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("instanceKey"), instanceKeyExpr)]),
|
|
646
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("id"), t.callExpression(t.memberExpression(bindingExpr, t.identifier("idFromName")), [t.identifier("instanceKey")]))]),
|
|
647
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("stub"), t.callExpression(t.memberExpression(bindingExpr, t.identifier("get")), [t.identifier("id")]))]),
|
|
648
|
+
t.returnStatement(t.callExpression(t.memberExpression(t.identifier("stub"), t.identifier("sys")), [t.stringLiteral("destroyDatabase")]))
|
|
649
|
+
]);
|
|
650
|
+
const funcDecl = t.functionDeclaration(t.identifier("destroyDatabase"), [], stubBody, false, true);
|
|
651
|
+
body.push(t.exportNamedDeclaration(funcDecl));
|
|
652
|
+
return true;
|
|
653
|
+
}
|
|
654
|
+
function isDefineDatabaseCallNode(node) {
|
|
655
|
+
return t.isCallExpression(node) && t.isIdentifier(node.callee) && node.callee.name === "defineDatabase";
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
//#endregion
|
|
659
|
+
//#region src/vite/durableDb.ts
|
|
660
|
+
init_debug();
|
|
661
|
+
init_state();
|
|
662
|
+
const DURABLE_OBJECTS_ID = "durable-db/__durableObjects";
|
|
663
|
+
const VIRTUAL_DO_MODULE_ID = "\0virtual:durable-db/__durableObjects.js";
|
|
664
|
+
const DEV_EPOCH_ID = "durable-db/__devEpoch";
|
|
665
|
+
const VIRTUAL_DEV_EPOCH_MODULE_ID = "\0virtual:durable-db/__devEpoch.js";
|
|
666
|
+
/** Old org-prefixed spelling, still resolved for compatibility. */
|
|
667
|
+
const LEGACY_ID_PREFIX = "eagerpatch/";
|
|
668
|
+
/** Match a virtual id in all accepted spellings (`virtual:` optional, legacy prefix). */
|
|
669
|
+
function matchesVirtualId(id, canonicalId) {
|
|
670
|
+
return id === canonicalId || id === `virtual:${canonicalId}` || id === `${LEGACY_ID_PREFIX}${canonicalId}` || id === `virtual:${LEGACY_ID_PREFIX}${canonicalId}`;
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Generate the __devEpoch virtual module. Action stubs route every DO
|
|
674
|
+
* instance key through `applyDevEpoch()`:
|
|
675
|
+
* - dev: suffixes keys with the current epoch (`<key>__dev_<epoch>`), so a
|
|
676
|
+
* `db reset` epoch bump rotates every database to a fresh DO instance
|
|
677
|
+
* - production builds: identity function, zero overhead beyond the call
|
|
678
|
+
*/
|
|
679
|
+
function generateDevEpochModule(epoch) {
|
|
680
|
+
return [
|
|
681
|
+
`export const devEpoch = ${JSON.stringify(epoch)};`,
|
|
682
|
+
`export function applyDevEpoch(key) {`,
|
|
683
|
+
` return devEpoch ? \`\${key}__dev_\${devEpoch}\` : key;`,
|
|
684
|
+
`}`
|
|
685
|
+
].join("\n");
|
|
686
|
+
}
|
|
687
|
+
var PluginState = class {
|
|
688
|
+
databases = /* @__PURE__ */ new Map();
|
|
689
|
+
actions = /* @__PURE__ */ new Map();
|
|
690
|
+
databaseFilePaths = /* @__PURE__ */ new Map();
|
|
691
|
+
initialized = false;
|
|
692
|
+
initPromise = null;
|
|
693
|
+
projectRoot = "";
|
|
694
|
+
config;
|
|
695
|
+
devServer = null;
|
|
696
|
+
constructor(options) {
|
|
697
|
+
this.options = options;
|
|
698
|
+
}
|
|
699
|
+
registerDatabaseFile(filePath, dbName) {
|
|
700
|
+
const abs = path.normalize(filePath);
|
|
701
|
+
this.databaseFilePaths.set(abs, dbName);
|
|
702
|
+
if (this.projectRoot) {
|
|
703
|
+
const rel = path.relative(this.projectRoot, abs);
|
|
704
|
+
this.databaseFilePaths.set(path.normalize(rel), dbName);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
getDatabaseNameForPath(filePath) {
|
|
708
|
+
const normalized = path.normalize(filePath);
|
|
709
|
+
const direct = this.databaseFilePaths.get(normalized);
|
|
710
|
+
if (direct) return direct;
|
|
711
|
+
if (this.projectRoot) {
|
|
712
|
+
const rel = path.relative(this.projectRoot, normalized);
|
|
713
|
+
return this.databaseFilePaths.get(path.normalize(rel));
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
registerAction(action, dbName, sourceFile) {
|
|
717
|
+
action.databaseName = dbName;
|
|
718
|
+
action.sourceFile = path.relative(this.projectRoot, sourceFile);
|
|
719
|
+
this.actions.set(`${dbName}:${action.exportName}`, action);
|
|
720
|
+
}
|
|
721
|
+
reset() {
|
|
722
|
+
this.databases.clear();
|
|
723
|
+
this.actions.clear();
|
|
724
|
+
this.databaseFilePaths.clear();
|
|
725
|
+
this.initialized = false;
|
|
726
|
+
this.initPromise = null;
|
|
727
|
+
}
|
|
728
|
+
async initialize() {
|
|
729
|
+
if (this.initialized) return;
|
|
730
|
+
if (this.initPromise) return this.initPromise;
|
|
731
|
+
this.initPromise = this.doInitialize();
|
|
732
|
+
return this.initPromise;
|
|
733
|
+
}
|
|
734
|
+
async doInitialize() {
|
|
735
|
+
const files = discoverDatabaseFiles({
|
|
736
|
+
projectRoot: this.projectRoot,
|
|
737
|
+
databasesDir: this.options.databasesDir
|
|
738
|
+
});
|
|
739
|
+
for (const file of files) {
|
|
740
|
+
const code = readFile(file.absolutePath);
|
|
741
|
+
const parsed = parseDatabaseFile(file.absolutePath, code);
|
|
742
|
+
if (parsed.database) {
|
|
743
|
+
parsed.database.migrationsDir = path.resolve(this.projectRoot, this.options.migrationsDir, parsed.database.name);
|
|
744
|
+
this.databases.set(parsed.database.name, parsed.database);
|
|
745
|
+
this.registerDatabaseFile(file.absolutePath, parsed.database.name);
|
|
746
|
+
await this.loadMigrations(parsed.database);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
if (this.databases.size > 0) {
|
|
750
|
+
debugVite("Found %d database(s)", this.databases.size);
|
|
751
|
+
patchWranglerConfig(this.projectRoot, Array.from(this.databases.values()));
|
|
752
|
+
}
|
|
753
|
+
this.initialized = true;
|
|
754
|
+
}
|
|
755
|
+
async loadMigrations(db) {
|
|
756
|
+
const migrationsDir = db.migrationsDir;
|
|
757
|
+
const isDev = this.config.command === "serve";
|
|
758
|
+
db.migrations = loadMigrationFiles(migrationsDir);
|
|
759
|
+
if (isDev) try {
|
|
760
|
+
const { loadDevMigrations } = await import("../state-BCcvNN-M.js");
|
|
761
|
+
const devMigrations = loadDevMigrations(this.projectRoot, db.name);
|
|
762
|
+
for (const [name, chunks] of devMigrations) db.migrations.set(`_dev_${name}`, chunks);
|
|
763
|
+
if (devMigrations.size > 0) debugVite("Loaded %d dev migration(s) for %s", devMigrations.size, db.name);
|
|
764
|
+
} catch (error) {}
|
|
765
|
+
if (db.migrations.size > 0) debugVite("Total %d migration(s) for %s", db.migrations.size, db.name);
|
|
766
|
+
}
|
|
767
|
+
invalidateDOModule() {
|
|
768
|
+
this.invalidateVirtualModule(VIRTUAL_DO_MODULE_ID);
|
|
769
|
+
}
|
|
770
|
+
invalidateDevEpochModule() {
|
|
771
|
+
this.invalidateVirtualModule(VIRTUAL_DEV_EPOCH_MODULE_ID);
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Invalidate a virtual module in every module graph.
|
|
775
|
+
*
|
|
776
|
+
* On Vite 6+ each environment (client, ssr, and e.g. the Cloudflare
|
|
777
|
+
* plugin's `worker` environment) has its own module graph — the legacy
|
|
778
|
+
* `server.moduleGraph` only proxies client/ssr, so invalidating there
|
|
779
|
+
* never reaches the worker. On Vite 5 only the legacy graph exists.
|
|
780
|
+
*/
|
|
781
|
+
invalidateVirtualModule(virtualId) {
|
|
782
|
+
if (!this.devServer) return;
|
|
783
|
+
const environments = this.devServer.environments;
|
|
784
|
+
const graphs = environments ? Object.values(environments).map((env) => env.moduleGraph) : [this.devServer.moduleGraph];
|
|
785
|
+
for (const graph of graphs) for (const mod of graph.idToModuleMap.values()) {
|
|
786
|
+
const id = mod.id ?? "";
|
|
787
|
+
if (id === virtualId || id.startsWith(virtualId + "?")) graph.invalidateModule(mod);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Trigger a reload in every environment: the browser via the legacy ws
|
|
792
|
+
* channel, and module-runner environments (like the Cloudflare worker)
|
|
793
|
+
* via their own hot channels — the legacy ws broadcast doesn't reach them.
|
|
794
|
+
*/
|
|
795
|
+
triggerFullReload() {
|
|
796
|
+
if (!this.devServer) return;
|
|
797
|
+
const environments = this.devServer.environments;
|
|
798
|
+
if (environments) for (const env of Object.values(environments)) env.hot?.send({ type: "full-reload" });
|
|
799
|
+
else this.devServer.ws.send({ type: "full-reload" });
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
async function findImportedDatabase(resolve, state, imports, importer) {
|
|
803
|
+
for (const [, info] of imports) {
|
|
804
|
+
if (info.imported !== "action") continue;
|
|
805
|
+
const resolved = await resolve(info.source, importer);
|
|
806
|
+
if (resolved) {
|
|
807
|
+
const cleanId = path.normalize(resolved.id.replace(/^\0+/, "").split("?", 1)[0]);
|
|
808
|
+
const dbName = state.getDatabaseNameForPath(cleanId);
|
|
809
|
+
if (dbName) return dbName;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return null;
|
|
813
|
+
}
|
|
814
|
+
function durableDb(options = {}) {
|
|
815
|
+
const state = new PluginState({
|
|
816
|
+
contextImport: options.contextImport ?? "durable-db/context",
|
|
817
|
+
registryImport: options.registryImport ?? "durable-db/registry",
|
|
818
|
+
databasesDir: options.databasesDir ?? "src/databases",
|
|
819
|
+
migrationsDir: options.migrationsDir ?? "migrations"
|
|
820
|
+
});
|
|
821
|
+
return {
|
|
822
|
+
name: "durable-db",
|
|
823
|
+
enforce: "pre",
|
|
824
|
+
configResolved(config) {
|
|
825
|
+
state.config = config;
|
|
826
|
+
state.projectRoot = config.root;
|
|
827
|
+
},
|
|
828
|
+
configureServer(server) {
|
|
829
|
+
state.devServer = server;
|
|
830
|
+
state.reset();
|
|
831
|
+
const absoluteDbDir = path.join(state.projectRoot, state.options.databasesDir);
|
|
832
|
+
server.watcher.on("change", (file) => {
|
|
833
|
+
const normalized = path.normalize(file);
|
|
834
|
+
if (normalized.startsWith(absoluteDbDir) && /\.tsx?$/.test(normalized)) state.invalidateDOModule();
|
|
835
|
+
});
|
|
836
|
+
const devPaths = getDevPaths(state.projectRoot);
|
|
837
|
+
fs.mkdirSync(devPaths.cacheDir, { recursive: true });
|
|
838
|
+
let reloadTimer = null;
|
|
839
|
+
const onDevStateChange = () => {
|
|
840
|
+
if (reloadTimer) clearTimeout(reloadTimer);
|
|
841
|
+
reloadTimer = setTimeout(() => {
|
|
842
|
+
debugVite("Dev state changed; reloading durable-db modules");
|
|
843
|
+
state.reset();
|
|
844
|
+
state.invalidateDOModule();
|
|
845
|
+
state.invalidateDevEpochModule();
|
|
846
|
+
state.triggerFullReload();
|
|
847
|
+
}, 100);
|
|
848
|
+
};
|
|
849
|
+
try {
|
|
850
|
+
const cacheWatcher = fs.watch(devPaths.cacheDir, { recursive: true }, onDevStateChange);
|
|
851
|
+
server.httpServer?.once("close", () => cacheWatcher.close());
|
|
852
|
+
} catch {
|
|
853
|
+
fs.unwatchFile(devPaths.stateFile);
|
|
854
|
+
fs.watchFile(devPaths.stateFile, { interval: 500 }, onDevStateChange);
|
|
855
|
+
server.httpServer?.once("close", () => fs.unwatchFile(devPaths.stateFile));
|
|
856
|
+
}
|
|
857
|
+
},
|
|
858
|
+
buildStart() {
|
|
859
|
+
state.reset();
|
|
860
|
+
},
|
|
861
|
+
resolveId(id) {
|
|
862
|
+
if (matchesVirtualId(id, DURABLE_OBJECTS_ID)) return VIRTUAL_DO_MODULE_ID;
|
|
863
|
+
if (matchesVirtualId(id, DEV_EPOCH_ID)) return VIRTUAL_DEV_EPOCH_MODULE_ID;
|
|
864
|
+
return null;
|
|
865
|
+
},
|
|
866
|
+
async load(id) {
|
|
867
|
+
if (id === VIRTUAL_DEV_EPOCH_MODULE_ID) {
|
|
868
|
+
const isDev$1 = state.config.command === "serve";
|
|
869
|
+
let epoch = null;
|
|
870
|
+
if (isDev$1) {
|
|
871
|
+
const devState = loadDevState(state.projectRoot);
|
|
872
|
+
if (!fs.existsSync(getDevPaths(state.projectRoot).stateFile)) saveDevState(state.projectRoot, devState);
|
|
873
|
+
epoch = devState.epoch;
|
|
874
|
+
}
|
|
875
|
+
return { code: generateDevEpochModule(epoch) };
|
|
876
|
+
}
|
|
877
|
+
if (id !== VIRTUAL_DO_MODULE_ID) return null;
|
|
878
|
+
await state.initialize();
|
|
879
|
+
const isDev = state.config.command === "serve";
|
|
880
|
+
return { code: generateDurableObjectsModule(Array.from(state.databases.values()), state.options.registryImport, isDev) };
|
|
881
|
+
},
|
|
882
|
+
async transform(code, id) {
|
|
883
|
+
if (id.startsWith("\0") || id.includes("node_modules")) return null;
|
|
884
|
+
if (!/\.tsx?$/.test(id)) return null;
|
|
885
|
+
await state.initialize();
|
|
886
|
+
const cleanId = path.normalize(id.split("?", 1)[0]);
|
|
887
|
+
const dbNameForPath = state.getDatabaseNameForPath(cleanId);
|
|
888
|
+
if (dbNameForPath) {
|
|
889
|
+
const database$1 = state.databases.get(dbNameForPath);
|
|
890
|
+
if (!database$1) return null;
|
|
891
|
+
const parsed$1 = parseDatabaseFile(cleanId, code);
|
|
892
|
+
for (const action of parsed$1.actions) state.registerAction(action, dbNameForPath, cleanId);
|
|
893
|
+
const result$1 = transformDatabaseFile({
|
|
894
|
+
code,
|
|
895
|
+
sourceFileName: cleanId,
|
|
896
|
+
database: database$1,
|
|
897
|
+
actionsInFile: parsed$1.actions,
|
|
898
|
+
contextImport: state.options.contextImport,
|
|
899
|
+
registryImport: state.options.registryImport
|
|
900
|
+
});
|
|
901
|
+
if (result$1 && parsed$1.actions.length > 0 && state.config.command === "serve") state.invalidateDOModule();
|
|
902
|
+
return result$1;
|
|
903
|
+
}
|
|
904
|
+
const parsed = parseDatabaseFile(cleanId, code);
|
|
905
|
+
if (parsed.actions.length === 0) return null;
|
|
906
|
+
const importedDbName = await findImportedDatabase(this.resolve.bind(this), state, parsed.localImports, cleanId);
|
|
907
|
+
if (!importedDbName) return null;
|
|
908
|
+
const database = state.databases.get(importedDbName);
|
|
909
|
+
if (!database) return null;
|
|
910
|
+
for (const action of parsed.actions) state.registerAction(action, importedDbName, cleanId);
|
|
911
|
+
const result = transformActionFile({
|
|
912
|
+
code,
|
|
913
|
+
sourceFileName: cleanId,
|
|
914
|
+
dbName: importedDbName,
|
|
915
|
+
database,
|
|
916
|
+
actionsInFile: parsed.actions,
|
|
917
|
+
contextImport: state.options.contextImport,
|
|
918
|
+
registryImport: state.options.registryImport
|
|
919
|
+
});
|
|
920
|
+
if (result && state.config.command === "serve") state.invalidateDOModule();
|
|
921
|
+
return result;
|
|
922
|
+
},
|
|
923
|
+
buildEnd() {
|
|
924
|
+
if (state.actions.size > 0) debugVite("Discovered %d action(s)", state.actions.size);
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
/** @deprecated Renamed to {@link durableDb}. */
|
|
929
|
+
const databasePlugin = durableDb;
|
|
930
|
+
var durableDb_default = durableDb;
|
|
931
|
+
|
|
932
|
+
//#endregion
|
|
933
|
+
export { databasePlugin, durableDb_default as default, durableDb };
|