durable-db 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +175 -25
- package/dist/{arktypeConfig-DxP0OcV_.js → actionArgs-1hEaDUia.js} +35 -1
- package/dist/cli/bin.js +1 -1
- package/dist/cli/index.d.ts +204 -62
- package/dist/cli/index.js +4 -3
- package/dist/{cli-BUSZTS2D.js → cli-CVS0b2im.js} +272 -95
- package/dist/context/index.js +14 -8
- package/dist/db/index.d.ts +2 -3
- package/dist/db/index.js +216 -25
- package/dist/defineDatabase-D_RpcKj1.js +109 -0
- package/dist/{defineDatabase-IUthY3Ex.d.ts → defineDatabase-zrUJrMd5.d.ts} +10 -3
- package/dist/{index-BdrcuAU7.d.ts → index-CJ6Focq4.d.ts} +70 -17
- package/dist/index.d.ts +1 -2
- package/dist/index.js +2 -2
- package/dist/{kysely-Be6KwFZC.js → kysely-CYmmiwDm.js} +25 -5
- package/dist/migrations/generator.d.ts +1 -1
- package/dist/migrations/generator.js +1 -1
- package/dist/migrations/snapshot.d.ts +2 -2
- package/dist/migrations/snapshot.js +1 -91
- package/dist/{parser-DR57GOjv.js → parser-DyepmXzE.js} +1 -1
- package/dist/registry.d.ts +29 -2
- package/dist/registry.js +2 -2
- package/dist/snapshot-B9Ae2TrS.d.ts +180 -0
- package/dist/snapshot-D_z95s6E.js +459 -0
- package/dist/{state-OVuoHRC9.js → state-DGYycIoJ.js} +106 -9
- package/dist/testing/index.d.ts +8 -1
- package/dist/testing/index.js +30 -11
- package/dist/vite/durableDb.d.ts +130 -1
- package/dist/vite/durableDb.js +725 -178
- package/package.json +3 -2
- package/virtual.d.ts +4 -2
- package/dist/arktypeConfig-AXvobTPL.d.ts +0 -5
- package/dist/defineDatabase-CHmzpzFf.js +0 -70
- package/dist/snapshot-CaG5xnE2.d.ts +0 -48
package/dist/vite/durableDb.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { i as init_debug, r as debugVite } from "../debug-Cz8KzMft.js";
|
|
2
|
-
import {
|
|
2
|
+
import { _ as saveDevState, d as init_state, l as getDevPaths, m as removeDevServerLock, p as loadDevState, s as getDatabaseEpochs, y as writeDevServerLock } from "../state-DGYycIoJ.js";
|
|
3
3
|
import { loadMigrationFiles } from "../migrations/generator.js";
|
|
4
|
-
import { a as
|
|
4
|
+
import { a as discoverActionFiles, i as databaseSources, n as parseDatabaseFile, o as discoverDatabaseFiles, r as toPascalCase, s as readFile, t as BABEL_PARSER_PLUGINS } from "../parser-DyepmXzE.js";
|
|
5
5
|
import * as fs from "node:fs";
|
|
6
6
|
import path, * as path$1 from "node:path";
|
|
7
7
|
import { parse } from "@babel/parser";
|
|
8
8
|
import _generate from "@babel/generator";
|
|
9
9
|
import * as t from "@babel/types";
|
|
10
|
+
import { findNodeAtLocation, parse as parse$1, parseTree, printParseErrorCode } from "jsonc-parser";
|
|
10
11
|
//#region src/vite/modules/wrangler.ts
|
|
11
12
|
init_debug();
|
|
12
13
|
/**
|
|
@@ -20,167 +21,509 @@ function findWranglerConfig(projectRoot) {
|
|
|
20
21
|
return null;
|
|
21
22
|
}
|
|
22
23
|
/**
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* strings (e.g. URLs) are preserved.
|
|
24
|
+
* Parse wrangler.jsonc content: comments and trailing commas allowed, as
|
|
25
|
+
* wrangler allows them. Throws on a syntax error.
|
|
26
26
|
*/
|
|
27
|
-
function
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
27
|
+
function parseWranglerConfig(content) {
|
|
28
|
+
const errors = [];
|
|
29
|
+
const config = parse$1(content, errors, {
|
|
30
|
+
allowTrailingComma: true,
|
|
31
|
+
disallowComments: false
|
|
32
|
+
});
|
|
33
|
+
if (errors.length > 0) {
|
|
34
|
+
const { error, offset } = errors[0];
|
|
35
|
+
throw new SyntaxError(`Invalid wrangler config: ${printParseErrorCode(error)} at offset ${offset}`);
|
|
36
|
+
}
|
|
37
|
+
if (config === null || typeof config !== "object" || Array.isArray(config)) throw new SyntaxError("Invalid wrangler config: the top level is not an object");
|
|
38
|
+
return config;
|
|
39
|
+
}
|
|
40
|
+
const CLASS_SUFFIX = "DatabaseDO";
|
|
41
|
+
const BINDING_SUFFIX = "_DATABASE_DO";
|
|
42
|
+
/**
|
|
43
|
+
* Whether a binding follows durable-db's naming — class `<Pascal>DatabaseDO`,
|
|
44
|
+
* binding `<SCREAMING_SNAKE>_DATABASE_DO` of the same database name — and
|
|
45
|
+
* binds a class of this worker (no `script_name`). Only these are reconciled;
|
|
46
|
+
* every other binding is the user's.
|
|
47
|
+
*/
|
|
48
|
+
function isDurableDbBinding(binding) {
|
|
49
|
+
if (binding.script_name) return false;
|
|
50
|
+
if (!isDurableDbClassName(binding.class_name) || !binding.name.endsWith(BINDING_SUFFIX)) return false;
|
|
51
|
+
const classStem = binding.class_name.slice(0, -10);
|
|
52
|
+
const bindingStem = binding.name.slice(0, -12);
|
|
53
|
+
return bindingStem.length > 0 && bindingStem.replace(/_/g, "") === classStem.toUpperCase();
|
|
54
|
+
}
|
|
55
|
+
function isDurableDbClassName(className) {
|
|
56
|
+
return /^[A-Z][A-Za-z0-9]*DatabaseDO$/.test(className) && className.length > 10;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The classes the migrations declare and have not deleted, walked in order:
|
|
60
|
+
* created (`new_classes`, `new_sqlite_classes`, `transferred_classes`),
|
|
61
|
+
* renamed, deleted.
|
|
62
|
+
*/
|
|
63
|
+
function declaredClasses(migrations) {
|
|
64
|
+
const declared = /* @__PURE__ */ new Set();
|
|
65
|
+
if (!Array.isArray(migrations)) return declared;
|
|
66
|
+
for (const migration of migrations) {
|
|
67
|
+
if (migration === null || typeof migration !== "object") continue;
|
|
68
|
+
const list = (value) => Array.isArray(value) ? value : [];
|
|
69
|
+
for (const c of list(migration.new_classes)) declared.add(c);
|
|
70
|
+
for (const c of list(migration.new_sqlite_classes)) declared.add(c);
|
|
71
|
+
for (const r of list(migration.renamed_classes)) {
|
|
72
|
+
if (r === null || typeof r !== "object") continue;
|
|
73
|
+
declared.delete(r.from);
|
|
74
|
+
declared.add(r.to);
|
|
48
75
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
76
|
+
for (const t of list(migration.transferred_classes)) if (t && typeof t === "object") declared.add(t.to);
|
|
77
|
+
for (const c of list(migration.deleted_classes)) declared.delete(c);
|
|
78
|
+
}
|
|
79
|
+
return declared;
|
|
80
|
+
}
|
|
81
|
+
/** The database's file name without its extension: its name without a source's prefix. */
|
|
82
|
+
function fileStem(db) {
|
|
83
|
+
return path$1.basename(db.filePath).replace(/\.(ts|js)$/, "");
|
|
84
|
+
}
|
|
85
|
+
/** The class a database would have without its source's prefix (`feedback` → `FeedbackDatabaseDO`). */
|
|
86
|
+
function unprefixedClassName(db) {
|
|
87
|
+
return toPascalCase(fileStem(db)) + CLASS_SUFFIX;
|
|
88
|
+
}
|
|
89
|
+
/** Whether the database comes from a mounted source (`<prefix>-<file>`). */
|
|
90
|
+
function isPrefixed(db) {
|
|
91
|
+
return db.name !== fileStem(db);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The migrations directories, next to `db`'s own, of the database whose class
|
|
95
|
+
* is `className` — every subdirectory whose name gives that class
|
|
96
|
+
* (`reviews-feedback` → `ReviewsFeedbackDatabaseDO`). Exact: no name is
|
|
97
|
+
* guessed, and more than one match is the caller's to refuse. Empty when `db`
|
|
98
|
+
* has no migrations directory configured or none matches.
|
|
99
|
+
*/
|
|
100
|
+
function migrationsDirsOfClass(db, className) {
|
|
101
|
+
if (!db.migrationsDir) return [];
|
|
102
|
+
const root = path$1.dirname(db.migrationsDir);
|
|
103
|
+
let entries;
|
|
104
|
+
try {
|
|
105
|
+
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
106
|
+
} catch {
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
return entries.filter((entry) => entry.isDirectory() && toPascalCase(entry.name) + CLASS_SUFFIX === className).map((entry) => path$1.join(root, entry.name)).sort();
|
|
110
|
+
}
|
|
111
|
+
/** Whether `dir` exists with anything in it. */
|
|
112
|
+
function hasEntries(dir) {
|
|
113
|
+
try {
|
|
114
|
+
return fs.readdirSync(dir).length > 0;
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** The next free `v<N>` tag. */
|
|
120
|
+
function nextTag(migrations) {
|
|
121
|
+
const numbers = (Array.isArray(migrations) ? migrations : []).map((m) => {
|
|
122
|
+
const match = /^v(\d+)$/.exec(typeof m?.tag === "string" ? m.tag : "");
|
|
123
|
+
return match ? parseInt(match[1], 10) : 0;
|
|
124
|
+
});
|
|
125
|
+
return `v${numbers.length > 0 ? Math.max(...numbers) + 1 : 1}`;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* What it takes for the config to match the discovered databases: bindings to
|
|
129
|
+
* add and remove, classes to create and rename, and classes of removed
|
|
130
|
+
* databases that only a hand-written `deleted_classes` migration can drop.
|
|
131
|
+
*/
|
|
132
|
+
function reconcile(config, databases) {
|
|
133
|
+
const rawBindings = Array.isArray(config.durable_objects?.bindings) ? config.durable_objects.bindings : [];
|
|
134
|
+
const isBinding = (b) => b !== null && typeof b === "object" && typeof b.name === "string" && typeof b.class_name === "string";
|
|
135
|
+
const migrations = (Array.isArray(config.migrations) ? config.migrations : []).filter((m) => m !== null && typeof m === "object");
|
|
136
|
+
const discoveredClasses = new Set(databases.map((db) => db.className));
|
|
137
|
+
const removeBindingIndexes = [];
|
|
138
|
+
const removedBindings = [];
|
|
139
|
+
rawBindings.forEach((binding, index) => {
|
|
140
|
+
if (isBinding(binding) && isDurableDbBinding(binding) && !discoveredClasses.has(binding.class_name)) {
|
|
141
|
+
removeBindingIndexes.push(index);
|
|
142
|
+
removedBindings.push({
|
|
143
|
+
name: binding.name,
|
|
144
|
+
class_name: binding.class_name
|
|
145
|
+
});
|
|
53
146
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
147
|
+
});
|
|
148
|
+
const remaining = rawBindings.filter((binding, index) => isBinding(binding) && !removeBindingIndexes.includes(index));
|
|
149
|
+
const addBindings = databases.filter((db) => !remaining.some((b) => b.name === db.bindingName || b.class_name === db.className)).map((db) => ({
|
|
150
|
+
name: db.bindingName,
|
|
151
|
+
class_name: db.className
|
|
152
|
+
}));
|
|
153
|
+
const declared = declaredClasses(migrations);
|
|
154
|
+
const boundClasses = new Set(remaining.map((b) => b.class_name));
|
|
155
|
+
const stale = [...declared].filter((c) => isDurableDbClassName(c) && !discoveredClasses.has(c) && !boundClasses.has(c));
|
|
156
|
+
const missing = databases.filter((db) => !declared.has(db.className));
|
|
157
|
+
const candidatesOf = (staleClass) => missing.filter((db) => isPrefixed(db) && staleClass !== db.className && staleClass.endsWith(unprefixedClassName(db)));
|
|
158
|
+
const renamedClasses = [];
|
|
159
|
+
const migrationsMoves = /* @__PURE__ */ new Map();
|
|
160
|
+
const conflicts = [];
|
|
161
|
+
for (const staleClass of stale) {
|
|
162
|
+
const candidates = candidatesOf(staleClass);
|
|
163
|
+
if (candidates.length !== 1) continue;
|
|
164
|
+
const [db] = candidates;
|
|
165
|
+
if (stale.filter((other) => candidatesOf(other).includes(db)).length !== 1) continue;
|
|
166
|
+
const rename = {
|
|
167
|
+
from: staleClass,
|
|
168
|
+
to: db.className
|
|
169
|
+
};
|
|
170
|
+
const oldDirs = migrationsDirsOfClass(db, staleClass);
|
|
171
|
+
if (oldDirs.length > 1) conflicts.push({
|
|
172
|
+
...rename,
|
|
173
|
+
reason: `several migrations directories belong to ${staleClass}: ${oldDirs.join(", ")}`
|
|
174
|
+
});
|
|
175
|
+
else if (oldDirs.length === 1 && hasEntries(db.migrationsDir)) conflicts.push({
|
|
176
|
+
...rename,
|
|
177
|
+
reason: `both ${oldDirs[0]} and ${db.migrationsDir} exist`
|
|
178
|
+
});
|
|
179
|
+
else {
|
|
180
|
+
renamedClasses.push(rename);
|
|
181
|
+
if (oldDirs.length === 1) migrationsMoves.set(db.className, {
|
|
182
|
+
from: oldDirs[0],
|
|
183
|
+
to: db.migrationsDir
|
|
184
|
+
});
|
|
64
185
|
}
|
|
65
|
-
result += ch;
|
|
66
|
-
i++;
|
|
67
186
|
}
|
|
68
|
-
|
|
187
|
+
const renamedTo = new Set(renamedClasses.map((r) => r.to));
|
|
188
|
+
const renamedFrom = new Set(renamedClasses.map((r) => r.from));
|
|
189
|
+
const conflictTo = new Set(conflicts.map((c) => c.to));
|
|
190
|
+
const conflictFrom = new Set(conflicts.map((c) => c.from));
|
|
191
|
+
return {
|
|
192
|
+
addBindings,
|
|
193
|
+
removeBindingIndexes,
|
|
194
|
+
removedBindings,
|
|
195
|
+
newClasses: missing.map((db) => db.className).filter((c) => !renamedTo.has(c) && !conflictTo.has(c)),
|
|
196
|
+
renamedClasses,
|
|
197
|
+
migrationsMoves,
|
|
198
|
+
conflicts,
|
|
199
|
+
deletedClasses: stale.filter((c) => !renamedFrom.has(c) && !conflictFrom.has(c))
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
/** `dir` relative to the project root, for messages and commands. */
|
|
203
|
+
function relativeDir(projectRoot, dir) {
|
|
204
|
+
const relative = path$1.relative(projectRoot, dir);
|
|
205
|
+
return relative && !relative.startsWith("..") && !path$1.isAbsolute(relative) ? relative : dir;
|
|
206
|
+
}
|
|
207
|
+
/** A path as one shell word. */
|
|
208
|
+
function shellWord(value) {
|
|
209
|
+
return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
|
|
210
|
+
}
|
|
211
|
+
/** The warning for a rename refused, with both ways out. */
|
|
212
|
+
function renameConflictWarning(file, projectRoot, conflict, databases, tag) {
|
|
213
|
+
const db = databases.find((d) => d.className === conflict.to);
|
|
214
|
+
const newDir = db?.migrationsDir ? relativeDir(projectRoot, db.migrationsDir) : null;
|
|
215
|
+
const oldDirs = db ? migrationsDirsOfClass(db, conflict.from).map((dir) => relativeDir(projectRoot, dir)) : [];
|
|
216
|
+
const reason = conflict.reason.split(projectRoot + path$1.sep).join("");
|
|
217
|
+
const keep = newDir && oldDirs.length === 1 ? `rm -r ${shellWord(newDir)} && mv ${shellWord(oldDirs[0])} ${shellWord(newDir)}` : `keep exactly one migrations directory for ${conflict.from} and move it to ${newDir ?? "the new database's"}`;
|
|
218
|
+
return `[durable-db] ${file}: ${conflict.to} looks like ${conflict.from} under a new mount, but its data cannot move with it: ${reason}. A renamed_classes migration hands the new class the old storage and its __migrations journal, which names the migrations of the old directory — deployed with other migrations it would fail. Neither a rename nor a new class is written until you choose:\n- keep the data (when ${newDir ?? "the new directory"} was never deployed): ${keep}, then restart;\n- start empty and DELETE the old data: add ${JSON.stringify({
|
|
219
|
+
tag,
|
|
220
|
+
deleted_classes: [conflict.from]
|
|
221
|
+
})} to "migrations"${oldDirs.length > 0 ? ` and remove ${oldDirs.join(", ")}` : ""}.`;
|
|
222
|
+
}
|
|
223
|
+
/** The log line for a rename written, with its migrations move and what dev keeps. */
|
|
224
|
+
function renameLog(file, projectRoot, rename, move) {
|
|
225
|
+
return `[durable-db] ${file}: renamed the Durable Object class ${rename.from} to ${rename.to} (a renamed_classes migration): on deploy, Cloudflare moves its deployed data to the new class` + (move ? `, and ${relativeDir(projectRoot, move.from)} moved to ${relativeDir(projectRoot, move.to)} so its migrations still match the journal that data carries.` : ` (it has no migrations directory, so there is no deployed data to carry).`) + ` Local dev storage is kept per class name: in dev the database starts empty.`;
|
|
226
|
+
}
|
|
227
|
+
function layoutOf(content) {
|
|
228
|
+
const eol = content.includes("\r\n") ? "\r\n" : "\n";
|
|
229
|
+
const indent = /^([ \t]+)["{[]/m.exec(content)?.[1];
|
|
230
|
+
if (indent?.startsWith(" ")) return {
|
|
231
|
+
unit: " ",
|
|
232
|
+
eol
|
|
233
|
+
};
|
|
234
|
+
return {
|
|
235
|
+
unit: indent ? " ".repeat(Math.min(indent.length, 8)) : " ",
|
|
236
|
+
eol
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/** Leading whitespace of the line holding `offset`. */
|
|
240
|
+
function lineIndent(text, offset) {
|
|
241
|
+
const start = text.lastIndexOf("\n", offset - 1) + 1;
|
|
242
|
+
return /^[ \t]*/.exec(text.slice(start))[0];
|
|
243
|
+
}
|
|
244
|
+
/** Whether only whitespace precedes `offset` on its line. */
|
|
245
|
+
function startsLine(text, offset) {
|
|
246
|
+
const start = text.lastIndexOf("\n", offset - 1) + 1;
|
|
247
|
+
return /^[ \t]*$/.test(text.slice(start, offset));
|
|
248
|
+
}
|
|
249
|
+
/** The offset of the line break ending the line holding `offset` (or the end of the text). */
|
|
250
|
+
function lineEnd(text, offset) {
|
|
251
|
+
const newline = text.indexOf("\n", offset);
|
|
252
|
+
const end = newline === -1 ? text.length : newline;
|
|
253
|
+
return end > offset && text[end - 1] === "\r" ? end - 1 : end;
|
|
254
|
+
}
|
|
255
|
+
/** Whether the rest of the line from `offset` is whitespace or a line comment. */
|
|
256
|
+
function restOfLineIsTrivia(text, offset) {
|
|
257
|
+
let i = offset;
|
|
258
|
+
while (i < text.length && (text[i] === " " || text[i] === " " || text[i] === "\r")) i++;
|
|
259
|
+
return i >= text.length || text[i] === "\n" || text[i] === "/" && text[i + 1] === "/";
|
|
260
|
+
}
|
|
261
|
+
/** The offset of the next character that is not whitespace or a comment. */
|
|
262
|
+
function nextSignificant(text, offset) {
|
|
263
|
+
let i = offset;
|
|
264
|
+
while (i < text.length) {
|
|
265
|
+
const ch = text[i];
|
|
266
|
+
if (ch === " " || ch === " " || ch === "\r" || ch === "\n") i++;
|
|
267
|
+
else if (ch === "/" && text[i + 1] === "/") while (i < text.length && text[i] !== "\n") i++;
|
|
268
|
+
else if (ch === "/" && text[i + 1] === "*") {
|
|
269
|
+
const end = text.indexOf("*/", i + 2);
|
|
270
|
+
i = end === -1 ? text.length : end + 2;
|
|
271
|
+
} else break;
|
|
272
|
+
}
|
|
273
|
+
return i;
|
|
274
|
+
}
|
|
275
|
+
/** `value` as one line of JSON in hand-written style: `{ "name": "X", "class_name": "Y" }`. */
|
|
276
|
+
function inlineJson(value) {
|
|
277
|
+
if (Array.isArray(value)) return `[${value.map(inlineJson).join(", ")}]`;
|
|
278
|
+
if (value !== null && typeof value === "object") {
|
|
279
|
+
const entries = Object.entries(value).filter(([, v]) => v !== void 0);
|
|
280
|
+
if (entries.length === 0) return "{}";
|
|
281
|
+
return `{ ${entries.map(([k, v]) => `${JSON.stringify(k)}: ${inlineJson(v)}`).join(", ")} }`;
|
|
282
|
+
}
|
|
283
|
+
return JSON.stringify(value);
|
|
284
|
+
}
|
|
285
|
+
/** `value` as pretty JSON whose continuation lines start at `indent`. */
|
|
286
|
+
function prettyJson(value, indent, layout) {
|
|
287
|
+
return JSON.stringify(value, null, layout.unit).split("\n").join(layout.eol + indent);
|
|
288
|
+
}
|
|
289
|
+
function treeOf(text) {
|
|
290
|
+
const root = parseTree(text, [], {
|
|
291
|
+
allowTrailingComma: true,
|
|
292
|
+
disallowComments: false
|
|
293
|
+
});
|
|
294
|
+
if (!root) throw new SyntaxError("Invalid wrangler config");
|
|
295
|
+
return root;
|
|
69
296
|
}
|
|
70
297
|
/**
|
|
71
|
-
*
|
|
298
|
+
* Append an entry to the array or object at `containerPath`: on its own line
|
|
299
|
+
* in the file's indentation when the container spans lines, inline when it
|
|
300
|
+
* is written on one line. An entry with a `key` is a property of an object.
|
|
72
301
|
*/
|
|
73
|
-
function
|
|
74
|
-
|
|
302
|
+
function appendEntry(text, containerPath, entry, layout) {
|
|
303
|
+
const container = findNodeAtLocation(treeOf(text), containerPath);
|
|
304
|
+
if (!container || container.type !== "array" && container.type !== "object") throw new Error(`Cannot append to ${containerPath.join(".")}: not an array or object`);
|
|
305
|
+
const keyPrefix = entry.key !== void 0 ? `${JSON.stringify(entry.key)}: ` : "";
|
|
306
|
+
const children = container.children ?? [];
|
|
307
|
+
const containerEnd = container.offset + container.length;
|
|
308
|
+
const closing = containerEnd - 1;
|
|
309
|
+
const containerIndent = lineIndent(text, container.offset);
|
|
310
|
+
if (children.length === 0) {
|
|
311
|
+
const open = text[container.offset];
|
|
312
|
+
let afterContainer = containerEnd;
|
|
313
|
+
while (text[afterContainer] === " " || text[afterContainer] === " ") afterContainer++;
|
|
314
|
+
if (text[afterContainer] === ",") afterContainer++;
|
|
315
|
+
if (!restOfLineIsTrivia(text, afterContainer)) {
|
|
316
|
+
const inner = open === "[" ? keyPrefix + inlineJson(entry.value) : ` ${keyPrefix}${inlineJson(entry.value)} `;
|
|
317
|
+
return text.slice(0, container.offset) + open + inner + text.slice(closing);
|
|
318
|
+
}
|
|
319
|
+
const childIndent = containerIndent + layout.unit;
|
|
320
|
+
const inner = layout.eol + childIndent + keyPrefix + prettyJson(entry.value, childIndent, layout) + layout.eol + containerIndent;
|
|
321
|
+
return text.slice(0, container.offset) + open + inner + text.slice(closing);
|
|
322
|
+
}
|
|
323
|
+
const last = children[children.length - 1];
|
|
324
|
+
const lastEnd = last.offset + last.length;
|
|
325
|
+
const afterLast = nextSignificant(text, lastEnd);
|
|
326
|
+
const trailingComma = text[afterLast] === ",";
|
|
327
|
+
const separatorEnd = trailingComma ? afterLast + 1 : lastEnd;
|
|
328
|
+
if (!text.slice(container.offset, closing).includes("\n")) {
|
|
329
|
+
const inserted = (trailingComma ? " " : ", ") + keyPrefix + inlineJson(entry.value);
|
|
330
|
+
return text.slice(0, separatorEnd) + inserted + text.slice(separatorEnd);
|
|
331
|
+
}
|
|
332
|
+
const childIndent = startsLine(text, last.offset) ? lineIndent(text, last.offset) : containerIndent + layout.unit;
|
|
333
|
+
const entryText = childIndent + keyPrefix + prettyJson(entry.value, childIndent, layout) + (trailingComma ? "," : "");
|
|
334
|
+
const comma = trailingComma ? "" : ",";
|
|
335
|
+
const end = lineEnd(text, separatorEnd);
|
|
336
|
+
if (closing < end) return text.slice(0, lastEnd) + comma + text.slice(lastEnd, closing).replace(/[ \t]+$/, "") + layout.eol + entryText + layout.eol + containerIndent + text.slice(closing);
|
|
337
|
+
return text.slice(0, lastEnd) + comma + text.slice(lastEnd, end) + layout.eol + entryText + text.slice(end);
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Remove the array element at `elementPath`, with its own lines (and a
|
|
341
|
+
* comment on them) when it has lines of its own, and the comma it leaves.
|
|
342
|
+
*/
|
|
343
|
+
function removeElement(text, elementPath) {
|
|
344
|
+
const element = findNodeAtLocation(treeOf(text), elementPath);
|
|
345
|
+
const array = element?.parent;
|
|
346
|
+
if (!element || !array || array.type !== "array") throw new Error(`Cannot remove ${elementPath.join(".")}: not an array element`);
|
|
347
|
+
const siblings = array.children ?? [];
|
|
348
|
+
const index = siblings.indexOf(element);
|
|
349
|
+
const elementStart = element.offset;
|
|
350
|
+
const elementEnd = element.offset + element.length;
|
|
351
|
+
if (siblings.length === 1) return text.slice(0, array.offset + 1) + text.slice(array.offset + array.length - 1);
|
|
352
|
+
const afterElement = nextSignificant(text, elementEnd);
|
|
353
|
+
const ownComma = text[afterElement] === ",";
|
|
354
|
+
const ownLines = startsLine(text, elementStart);
|
|
355
|
+
let from = ownLines ? text.lastIndexOf("\n", elementStart - 1) + 1 : elementStart;
|
|
356
|
+
let to = ownComma ? afterElement + 1 : elementEnd;
|
|
357
|
+
if (ownLines && restOfLineIsTrivia(text, to)) {
|
|
358
|
+
const newline = text.indexOf("\n", to);
|
|
359
|
+
to = newline === -1 ? text.length : newline + 1;
|
|
360
|
+
} else if (!ownLines) while (to < text.length && (text[to] === " " || text[to] === " ")) to++;
|
|
361
|
+
let commaBefore = -1;
|
|
362
|
+
if (!ownComma && index > 0) {
|
|
363
|
+
const previous = siblings[index - 1];
|
|
364
|
+
const candidate = nextSignificant(text, previous.offset + previous.length);
|
|
365
|
+
if (text[candidate] === ",") commaBefore = candidate;
|
|
366
|
+
if (!ownLines) from = commaBefore !== -1 ? commaBefore : from;
|
|
367
|
+
}
|
|
368
|
+
let result = text.slice(0, from) + text.slice(to);
|
|
369
|
+
if (commaBefore !== -1 && commaBefore < from) result = result.slice(0, commaBefore) + result.slice(commaBefore + 1);
|
|
370
|
+
return result;
|
|
371
|
+
}
|
|
372
|
+
/** The warning for classes whose `deleted_classes` migration only the user may write. */
|
|
373
|
+
function deletedClassesWarning(file, classes, tag) {
|
|
374
|
+
const entry = JSON.stringify({
|
|
375
|
+
tag,
|
|
376
|
+
deleted_classes: classes
|
|
377
|
+
});
|
|
378
|
+
const list = classes.join(", ");
|
|
379
|
+
return `[durable-db] ${file}: ${list} ${classes.length === 1 ? "is" : "are"} no longer a discovered database, but the migrations still declare ${classes.length === 1 ? "it" : "them"}. If ${classes.length === 1 ? "it was" : "they were"} deployed, Cloudflare keeps ${classes.length === 1 ? "its" : "their"} data and refuses a worker that no longer exports ${classes.length === 1 ? "the class" : "the classes"}. To delete ${classes.length === 1 ? "it" : "them"} — and ALL ${classes.length === 1 ? "its" : "their"} data — add this migration to "migrations" yourself:\n ${entry}\nIf ${classes.length === 1 ? "it was" : "they were"} never deployed, remove ${list} from ${classes.length === 1 ? "its" : "their"} new_sqlite_classes entry instead. To keep the data, restore the database.`;
|
|
75
380
|
}
|
|
76
381
|
/**
|
|
77
382
|
* Patch wrangler config with Durable Object bindings
|
|
78
383
|
*
|
|
79
|
-
*
|
|
384
|
+
* Reconciles the config with the discovered databases, editing the file in
|
|
385
|
+
* place so its comments, formatting and trailing newline survive:
|
|
386
|
+
* - adds a binding and a `new_sqlite_classes` migration for each new database;
|
|
387
|
+
* - removes durable-db's own bindings (`<X>_DATABASE_DO` → `<X>DatabaseDO`)
|
|
388
|
+
* whose class is no longer discovered — a binding to a class the worker no
|
|
389
|
+
* longer exports keeps workerd from starting;
|
|
390
|
+
* - writes a `renamed_classes` migration when a database of a mounted source
|
|
391
|
+
* changed its class name unambiguously (a mount change), so its deployed
|
|
392
|
+
* data moves with it — and moves the old database's migrations directory
|
|
393
|
+
* to the new name, since that data carries the old migrations' journal;
|
|
394
|
+
* - refuses such a rename when the migrations cannot follow (both
|
|
395
|
+
* directories exist, or several old ones): neither a rename nor a new class
|
|
396
|
+
* is written, `conflicts` lists it and a warning gives both ways out;
|
|
397
|
+
* - never deletes a class (that deletes its data): a removed database's class
|
|
398
|
+
* gets a warning with the exact `deleted_classes` migration to add by hand.
|
|
399
|
+
* Bindings of other names, and bindings to other workers' classes
|
|
400
|
+
* (`script_name`), are never touched.
|
|
80
401
|
*/
|
|
81
402
|
function patchWranglerConfig(projectRoot, databases) {
|
|
82
403
|
const configPath = findWranglerConfig(projectRoot);
|
|
83
404
|
if (!configPath) {
|
|
84
405
|
console.warn("[db] wrangler.jsonc/json not found");
|
|
85
406
|
logRequiredConfig(databases);
|
|
86
|
-
return
|
|
87
|
-
modified: false,
|
|
88
|
-
configPath: null,
|
|
89
|
-
error: null
|
|
90
|
-
};
|
|
407
|
+
return unchangedPatch(null);
|
|
91
408
|
}
|
|
409
|
+
const file = path$1.basename(configPath);
|
|
410
|
+
const movedMigrations = [];
|
|
92
411
|
try {
|
|
93
412
|
const content = fs.readFileSync(configPath, "utf-8");
|
|
94
413
|
const config = parseWranglerConfig(content);
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
414
|
+
const plan = reconcile(config, databases);
|
|
415
|
+
const layout = layoutOf(content);
|
|
416
|
+
let text = content;
|
|
417
|
+
for (const rename of [...plan.renamedClasses]) {
|
|
418
|
+
const move = plan.migrationsMoves.get(rename.to);
|
|
419
|
+
if (!move) continue;
|
|
420
|
+
try {
|
|
421
|
+
if (fs.existsSync(move.to)) fs.rmdirSync(move.to);
|
|
422
|
+
fs.renameSync(move.from, move.to);
|
|
423
|
+
movedMigrations.push(move);
|
|
424
|
+
} catch (error) {
|
|
425
|
+
plan.renamedClasses.splice(plan.renamedClasses.indexOf(rename), 1);
|
|
426
|
+
plan.conflicts.push({
|
|
427
|
+
...rename,
|
|
428
|
+
reason: `${move.from} could not be moved to ${move.to} (${error.message})`
|
|
429
|
+
});
|
|
430
|
+
}
|
|
110
431
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
432
|
+
for (const index of [...plan.removeBindingIndexes].sort((a, b) => b - a)) text = removeElement(text, [
|
|
433
|
+
"durable_objects",
|
|
434
|
+
"bindings",
|
|
435
|
+
index
|
|
436
|
+
]);
|
|
437
|
+
if (plan.addBindings.length > 0) {
|
|
438
|
+
const durableObjects = config.durable_objects;
|
|
439
|
+
if (durableObjects === void 0) text = appendEntry(text, [], {
|
|
440
|
+
key: "durable_objects",
|
|
441
|
+
value: { bindings: plan.addBindings }
|
|
442
|
+
}, layout);
|
|
443
|
+
else if (durableObjects.bindings === void 0) text = appendEntry(text, ["durable_objects"], {
|
|
444
|
+
key: "bindings",
|
|
445
|
+
value: plan.addBindings
|
|
446
|
+
}, layout);
|
|
447
|
+
else for (const binding of plan.addBindings) text = appendEntry(text, ["durable_objects", "bindings"], { value: binding }, layout);
|
|
114
448
|
}
|
|
115
|
-
const
|
|
116
|
-
const
|
|
117
|
-
if (
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
config.migrations
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
});
|
|
127
|
-
modified = true;
|
|
449
|
+
const migrations = Array.isArray(config.migrations) ? config.migrations : [];
|
|
450
|
+
const migrationTag = plan.newClasses.length > 0 || plan.renamedClasses.length > 0 ? nextTag(migrations) : null;
|
|
451
|
+
if (migrationTag) {
|
|
452
|
+
const migration = {
|
|
453
|
+
tag: migrationTag,
|
|
454
|
+
...plan.newClasses.length > 0 && { new_sqlite_classes: plan.newClasses },
|
|
455
|
+
...plan.renamedClasses.length > 0 && { renamed_classes: plan.renamedClasses }
|
|
456
|
+
};
|
|
457
|
+
text = config.migrations === void 0 ? appendEntry(text, [], {
|
|
458
|
+
key: "migrations",
|
|
459
|
+
value: [migration]
|
|
460
|
+
}, layout) : appendEntry(text, ["migrations"], { value: migration }, layout);
|
|
128
461
|
}
|
|
462
|
+
const modified = text !== content;
|
|
129
463
|
if (modified) {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
if (!fs.existsSync(backupPath)) {
|
|
133
|
-
fs.writeFileSync(backupPath, content, "utf-8");
|
|
134
|
-
debugVite("Original %s contained comments that will be lost during patching. Backup saved to %s", path$1.basename(configPath), path$1.basename(backupPath));
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
const newContent = JSON.stringify(config, null, 2);
|
|
138
|
-
fs.writeFileSync(configPath, newContent, "utf-8");
|
|
139
|
-
debugVite("Updated %s with DO bindings", path$1.basename(configPath));
|
|
464
|
+
fs.writeFileSync(configPath, text, "utf-8");
|
|
465
|
+
debugVite("Updated %s with DO bindings", file);
|
|
140
466
|
}
|
|
467
|
+
for (const rename of plan.renamedClasses) console.log(renameLog(file, projectRoot, rename, plan.migrationsMoves.get(rename.to)));
|
|
468
|
+
const written = migrationTag ? [{ tag: migrationTag }] : [];
|
|
469
|
+
const suggested = [...migrations, ...written];
|
|
470
|
+
const suggestTag = () => {
|
|
471
|
+
const tag = nextTag(suggested);
|
|
472
|
+
suggested.push({ tag });
|
|
473
|
+
return tag;
|
|
474
|
+
};
|
|
475
|
+
if (plan.deletedClasses.length > 0) console.warn(deletedClassesWarning(file, plan.deletedClasses, suggestTag()));
|
|
476
|
+
for (const conflict of plan.conflicts) console.warn(renameConflictWarning(file, projectRoot, conflict, databases, suggestTag()));
|
|
141
477
|
return {
|
|
142
478
|
modified,
|
|
143
479
|
configPath,
|
|
144
|
-
error: null
|
|
480
|
+
error: null,
|
|
481
|
+
addedBindings: plan.addBindings,
|
|
482
|
+
removedBindings: plan.removedBindings,
|
|
483
|
+
newClasses: plan.newClasses,
|
|
484
|
+
migrationTag,
|
|
485
|
+
renamedClasses: plan.renamedClasses,
|
|
486
|
+
movedMigrations,
|
|
487
|
+
conflicts: plan.conflicts,
|
|
488
|
+
deletedClasses: plan.deletedClasses
|
|
145
489
|
};
|
|
146
490
|
} catch (error) {
|
|
147
491
|
debugVite("Failed to patch wrangler config: %O", error);
|
|
148
492
|
logRequiredConfig(databases);
|
|
149
493
|
return {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
error
|
|
494
|
+
...unchangedPatch(configPath, error),
|
|
495
|
+
movedMigrations
|
|
153
496
|
};
|
|
154
497
|
}
|
|
155
498
|
}
|
|
499
|
+
/** A {@link PatchResult} that changed nothing. */
|
|
500
|
+
function unchangedPatch(configPath, error = null) {
|
|
501
|
+
return {
|
|
502
|
+
modified: false,
|
|
503
|
+
configPath,
|
|
504
|
+
error,
|
|
505
|
+
addedBindings: [],
|
|
506
|
+
removedBindings: [],
|
|
507
|
+
newClasses: [],
|
|
508
|
+
migrationTag: null,
|
|
509
|
+
renamedClasses: [],
|
|
510
|
+
movedMigrations: [],
|
|
511
|
+
conflicts: [],
|
|
512
|
+
deletedClasses: []
|
|
513
|
+
};
|
|
514
|
+
}
|
|
156
515
|
/**
|
|
157
|
-
*
|
|
158
|
-
*
|
|
516
|
+
* Whether the config at `configPath` binds any of durable-db's own classes
|
|
517
|
+
* (the bindings {@link patchWranglerConfig} reconciles). An unreadable config
|
|
518
|
+
* binds none.
|
|
159
519
|
*/
|
|
160
|
-
function
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
i++;
|
|
167
|
-
while (i < len) {
|
|
168
|
-
if (content[i] === "\\") {
|
|
169
|
-
i += 2;
|
|
170
|
-
continue;
|
|
171
|
-
}
|
|
172
|
-
if (content[i] === "\"") {
|
|
173
|
-
i++;
|
|
174
|
-
break;
|
|
175
|
-
}
|
|
176
|
-
i++;
|
|
177
|
-
}
|
|
178
|
-
continue;
|
|
179
|
-
}
|
|
180
|
-
if (ch === "/" && i + 1 < len && (content[i + 1] === "/" || content[i + 1] === "*")) return true;
|
|
181
|
-
i++;
|
|
520
|
+
function bindsDurableDbClasses(configPath) {
|
|
521
|
+
if (!configPath) return false;
|
|
522
|
+
try {
|
|
523
|
+
return (parseWranglerConfig(fs.readFileSync(configPath, "utf-8")).durable_objects?.bindings ?? []).some(isDurableDbBinding);
|
|
524
|
+
} catch {
|
|
525
|
+
return false;
|
|
182
526
|
}
|
|
183
|
-
return false;
|
|
184
527
|
}
|
|
185
528
|
/**
|
|
186
529
|
* Log the required wrangler config for manual setup
|
|
@@ -200,21 +543,41 @@ function logRequiredConfig(databases) {
|
|
|
200
543
|
});
|
|
201
544
|
}
|
|
202
545
|
/**
|
|
546
|
+
* What a failed {@link checkWranglerConfig} found, in one sentence: what is
|
|
547
|
+
* missing and what is stale.
|
|
548
|
+
*/
|
|
549
|
+
function describeWranglerCheck(check) {
|
|
550
|
+
const parts = [];
|
|
551
|
+
if (check.missingBindings.length > 0) parts.push(`missing the binding(s) ${check.missingBindings.map((b) => b.name).join(", ")}`);
|
|
552
|
+
if (check.missingSqliteClasses.length > 0) parts.push(`missing a migration declaring ${check.missingSqliteClasses.join(", ")}`);
|
|
553
|
+
if (check.renamedClasses.length > 0) parts.push(`missing the renamed_classes migration for ${check.renamedClasses.map((r) => `${r.from} → ${r.to}`).join(", ")}`);
|
|
554
|
+
if (check.staleBindings.length > 0) parts.push(`binding class(es) the worker no longer exports (${check.staleBindings.map((b) => b.class_name).join(", ")})`);
|
|
555
|
+
const deleted = check.staleClasses.filter((c) => !check.renamedClasses.some((r) => r.from === c) && !check.conflicts.some((r) => r.from === c));
|
|
556
|
+
if (deleted.length > 0) parts.push(`declaring class(es) of database(s) that no longer exist (${deleted.join(", ")})`);
|
|
557
|
+
if (check.conflicts.length > 0) parts.push(`holding renamed database(s) whose migrations cannot follow (${check.conflicts.map((c) => `${c.from} → ${c.to}`).join(", ")})`);
|
|
558
|
+
return parts.join("; ");
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
203
561
|
* Verify (without writing) that the wrangler config contains the Durable
|
|
204
562
|
* Object bindings and sqlite migration entries the discovered databases
|
|
205
|
-
* need
|
|
206
|
-
*
|
|
563
|
+
* need, and no binding or class of a database that is gone. Logs an
|
|
564
|
+
* actionable warning with the exact JSON to add (or remove) when something
|
|
565
|
+
* is off — and, for a rename, the `mv` that moves its migrations with it.
|
|
207
566
|
*
|
|
208
567
|
* This is the default behavior of the Vite plugin — automatic patching
|
|
209
568
|
* is opt-in via the `patchWranglerConfig` plugin option.
|
|
210
569
|
*/
|
|
211
570
|
function checkWranglerConfig(projectRoot, databases) {
|
|
212
|
-
const required = generateRequiredConfig(databases);
|
|
213
571
|
const configPath = findWranglerConfig(projectRoot);
|
|
214
572
|
const result = {
|
|
215
573
|
configPath,
|
|
216
574
|
missingBindings: [],
|
|
217
575
|
missingSqliteClasses: [],
|
|
576
|
+
staleBindings: [],
|
|
577
|
+
staleClasses: [],
|
|
578
|
+
renamedClasses: [],
|
|
579
|
+
migrationsMoves: [],
|
|
580
|
+
conflicts: [],
|
|
218
581
|
ok: true,
|
|
219
582
|
tomlOnly: !configPath && fs.existsSync(path$1.join(projectRoot, "wrangler.toml"))
|
|
220
583
|
};
|
|
@@ -224,49 +587,61 @@ function checkWranglerConfig(projectRoot, databases) {
|
|
|
224
587
|
} catch (error) {
|
|
225
588
|
debugVite("Failed to parse wrangler config for check: %O", error);
|
|
226
589
|
}
|
|
227
|
-
const
|
|
228
|
-
result.missingBindings =
|
|
229
|
-
|
|
230
|
-
result.
|
|
231
|
-
result.
|
|
232
|
-
|
|
590
|
+
const plan = reconcile(config, databases);
|
|
591
|
+
result.missingBindings = plan.addBindings;
|
|
592
|
+
result.missingSqliteClasses = plan.newClasses;
|
|
593
|
+
result.staleBindings = plan.removedBindings;
|
|
594
|
+
result.renamedClasses = plan.renamedClasses;
|
|
595
|
+
result.migrationsMoves = plan.renamedClasses.flatMap((r) => plan.migrationsMoves.get(r.to) ?? []);
|
|
596
|
+
result.conflicts = plan.conflicts;
|
|
597
|
+
result.staleClasses = [
|
|
598
|
+
...plan.renamedClasses.map((r) => r.from),
|
|
599
|
+
...plan.conflicts.map((c) => c.from),
|
|
600
|
+
...plan.deletedClasses
|
|
601
|
+
];
|
|
602
|
+
result.ok = result.missingBindings.length === 0 && result.missingSqliteClasses.length === 0 && result.staleBindings.length === 0 && result.staleClasses.length === 0;
|
|
603
|
+
const existingMigrations = Array.isArray(config.migrations) ? config.migrations : [];
|
|
604
|
+
const migration = plan.newClasses.length > 0 || plan.renamedClasses.length > 0 ? {
|
|
605
|
+
tag: nextTag(existingMigrations),
|
|
606
|
+
...plan.newClasses.length > 0 && { new_sqlite_classes: plan.newClasses },
|
|
607
|
+
...plan.renamedClasses.length > 0 && { renamed_classes: plan.renamedClasses }
|
|
608
|
+
} : null;
|
|
609
|
+
const suggested = [...existingMigrations, ...migration ? [migration] : []];
|
|
610
|
+
const suggestTag = () => {
|
|
611
|
+
const tag = nextTag(suggested);
|
|
612
|
+
suggested.push({ tag });
|
|
613
|
+
return tag;
|
|
614
|
+
};
|
|
615
|
+
const file = configPath ? path$1.basename(configPath) : "wrangler.jsonc";
|
|
616
|
+
if (result.missingBindings.length > 0 || migration) {
|
|
233
617
|
const snippet = JSON.stringify({
|
|
234
618
|
...result.missingBindings.length > 0 && { durable_objects: { bindings: result.missingBindings } },
|
|
235
|
-
...
|
|
236
|
-
tag: "v1",
|
|
237
|
-
new_sqlite_classes: result.missingSqliteClasses
|
|
238
|
-
}] }
|
|
619
|
+
...migration && { migrations: [migration] }
|
|
239
620
|
}, null, 2);
|
|
240
621
|
const hasToml = result.tomlOnly;
|
|
241
622
|
const where = configPath ? path$1.basename(configPath) : hasToml ? "wrangler.toml (not supported — only wrangler.jsonc/json can be verified or patched)" : "wrangler.jsonc";
|
|
242
|
-
|
|
623
|
+
const moves = result.migrationsMoves.map((move) => `mv ${shellWord(relativeDir(projectRoot, move.from))} ${shellWord(relativeDir(projectRoot, move.to))}`);
|
|
624
|
+
console.warn(`[durable-db] ${where} is missing Durable Object config for your database(s). Add ${hasToml ? "the equivalent of " : ""}this${configPath || hasToml ? "" : " to a new wrangler.jsonc"}:\n${snippet}\n` + (plan.renamedClasses.length > 0 ? "renamed_classes hands each new class the old one's deployed data (the same database under a new mount)" + (moves.length > 0 ? `, and that data's __migrations journal names the old migrations — move them with it:\n` + moves.map((move) => ` ${move}`).join("\n") + "\n" : ".\n") : "") + (hasToml ? "" : `Or let the plugin write it for you: durableDb({ patchWranglerConfig: true })`));
|
|
625
|
+
}
|
|
626
|
+
if (result.staleBindings.length > 0 || plan.deletedClasses.length > 0 || plan.conflicts.length > 0) {
|
|
627
|
+
const lines = [];
|
|
628
|
+
if (result.staleBindings.length > 0) lines.push(`remove the Durable Object binding(s) ${result.staleBindings.map((b) => `${b.name} (${b.class_name})`).join(", ")}: the worker no longer exports ${result.staleBindings.length === 1 ? "that class" : "those classes"}, and workerd refuses to start with a binding to it`);
|
|
629
|
+
const item = (warning) => warning.replace(`[durable-db] ${file}: `, "");
|
|
630
|
+
if (plan.deletedClasses.length > 0) lines.push(item(deletedClassesWarning(file, plan.deletedClasses, suggestTag())));
|
|
631
|
+
for (const conflict of plan.conflicts) lines.push(item(renameConflictWarning(file, projectRoot, conflict, databases, suggestTag())));
|
|
632
|
+
console.warn(`[durable-db] ${file} declares Durable Objects of database(s) that no longer exist:\n` + lines.map((line) => `- ${line}`).join("\n") + (plan.conflicts.length > 0 ? "" : `\nOr let the plugin reconcile the bindings for you: durableDb({ patchWranglerConfig: true })`));
|
|
243
633
|
}
|
|
244
634
|
return result;
|
|
245
635
|
}
|
|
246
|
-
/**
|
|
247
|
-
* Generate the required wrangler config as a string
|
|
248
|
-
* Useful for displaying to users or tests
|
|
249
|
-
*/
|
|
250
|
-
function generateRequiredConfig(databases) {
|
|
251
|
-
return {
|
|
252
|
-
durable_objects: { bindings: databases.map((db) => ({
|
|
253
|
-
name: db.bindingName,
|
|
254
|
-
class_name: db.className
|
|
255
|
-
})) },
|
|
256
|
-
migrations: [{
|
|
257
|
-
tag: "v1",
|
|
258
|
-
new_sqlite_classes: databases.map((db) => db.className)
|
|
259
|
-
}]
|
|
260
|
-
};
|
|
261
|
-
}
|
|
262
636
|
//#endregion
|
|
263
637
|
//#region src/vite/modules/generator.ts
|
|
264
638
|
const generate = typeof _generate === "function" ? _generate : _generate.default;
|
|
265
639
|
/**
|
|
266
|
-
* Virtual module (served by the Vite plugin) exporting
|
|
267
|
-
* In dev it suffixes instance keys with the
|
|
268
|
-
*
|
|
269
|
-
*
|
|
640
|
+
* Virtual module (served by the Vite plugin) exporting
|
|
641
|
+
* `applyDevEpoch(key, dbName)`. In dev it suffixes instance keys with the
|
|
642
|
+
* database's dev epoch so `db reset` (which bumps the project epoch, or with
|
|
643
|
+
* `--database` that database's own) yields fresh DO instances; in production
|
|
644
|
+
* builds it is the identity function.
|
|
270
645
|
*/
|
|
271
646
|
const DEV_EPOCH_IMPORT = "virtual:durable-db/__devEpoch";
|
|
272
647
|
const ARKTYPE_LOCAL = "__ddType";
|
|
@@ -406,6 +781,7 @@ function buildMigrationGuardMethod(name, params) {
|
|
|
406
781
|
* When not browsable:
|
|
407
782
|
* export class ClassName extends SqliteDurableObject {
|
|
408
783
|
* migrations = {...};
|
|
784
|
+
* databaseName = "name";
|
|
409
785
|
* async rpc(...) { ... }
|
|
410
786
|
* }
|
|
411
787
|
*/
|
|
@@ -413,7 +789,12 @@ function buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, is
|
|
|
413
789
|
const isBrowsable = db.browsable === true || db.browsable === "development" && isDev;
|
|
414
790
|
const rpcMethod = buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr);
|
|
415
791
|
const migrationsProperty = t.classProperty(t.identifier("migrations"), buildMigrationsObject(db.migrations));
|
|
416
|
-
const
|
|
792
|
+
const databaseNameProperty = t.classProperty(t.identifier("databaseName"), t.stringLiteral(db.name));
|
|
793
|
+
const dataProperties = hasSchema(db) ? [
|
|
794
|
+
migrationsProperty,
|
|
795
|
+
databaseNameProperty,
|
|
796
|
+
buildSchemaProperty(db)
|
|
797
|
+
] : [migrationsProperty, databaseNameProperty];
|
|
417
798
|
const classMethods = [rpcMethod, buildSysMethod()];
|
|
418
799
|
if (db.transport === "websocket") classMethods.push(buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr));
|
|
419
800
|
if (!isBrowsable) {
|
|
@@ -606,12 +987,13 @@ function buildDoShortPath(config) {
|
|
|
606
987
|
]))]))];
|
|
607
988
|
}
|
|
608
989
|
/**
|
|
609
|
-
* Build `applyDevEpoch(<baseKey>)` — instance keys always pass
|
|
610
|
-
* dev-epoch helper so `db reset` can rotate to fresh DO instances
|
|
990
|
+
* Build `applyDevEpoch(<baseKey>, "<dbName>")` — instance keys always pass
|
|
991
|
+
* through the dev-epoch helper so `db reset` can rotate to fresh DO instances
|
|
992
|
+
* in dev; the database name picks its own epoch after `db reset --database`.
|
|
611
993
|
*/
|
|
612
994
|
function buildInstanceKeyExpr(database) {
|
|
613
995
|
const baseKeyExpr = database.instance === "global" ? t.stringLiteral("global") : t.callExpression(t.identifier("getTenantId"), []);
|
|
614
|
-
return t.callExpression(t.identifier("applyDevEpoch"), [baseKeyExpr]);
|
|
996
|
+
return t.callExpression(t.identifier("applyDevEpoch"), [baseKeyExpr, t.stringLiteral(database.name)]);
|
|
615
997
|
}
|
|
616
998
|
function buildStubBodyStatements(config) {
|
|
617
999
|
const { action, database } = config;
|
|
@@ -765,6 +1147,102 @@ function isDefineDatabaseCallNode(node) {
|
|
|
765
1147
|
return t.isCallExpression(node) && t.isIdentifier(node.callee) && node.callee.name === "defineDatabase";
|
|
766
1148
|
}
|
|
767
1149
|
//#endregion
|
|
1150
|
+
//#region src/vite/modules/syncWrangler.ts
|
|
1151
|
+
init_debug();
|
|
1152
|
+
/**
|
|
1153
|
+
* Discover the databases and reconcile wrangler.jsonc/json with them — before
|
|
1154
|
+
* anything reads the config. The Vite plugin runs this in its `config` hook
|
|
1155
|
+
* (with `patchWranglerConfig: true`), ahead of @cloudflare/vite-plugin, which
|
|
1156
|
+
* reads the worker config in its own `config` hook and emits the build's
|
|
1157
|
+
* `wrangler.json` from that copy: patched any later, a build ships the
|
|
1158
|
+
* previous bindings, and a dev server restarts while it starts. CLIs that want
|
|
1159
|
+
* the file settled before Vite starts can call it themselves; a refused rename
|
|
1160
|
+
* is in `conflicts` (the plugin stops on it).
|
|
1161
|
+
*
|
|
1162
|
+
* When a database file does not parse, nothing is written: the patch is
|
|
1163
|
+
* computed from the complete set of databases or not at all (a partial set
|
|
1164
|
+
* would read as databases removed). The plugin reports the parse error when
|
|
1165
|
+
* it loads the file. A missing config file is reported by the patcher.
|
|
1166
|
+
*/
|
|
1167
|
+
function syncWranglerConfig(options) {
|
|
1168
|
+
const { projectRoot, databasesDir = "src/databases", migrationsDir = "migrations" } = options;
|
|
1169
|
+
const { databases, unparsable } = discoverDatabaseInfos(projectRoot, databasesDir, migrationsDir);
|
|
1170
|
+
if (unparsable.length > 0) {
|
|
1171
|
+
debugVite("Not syncing wrangler config: %s did not parse", unparsable.join(", "));
|
|
1172
|
+
return {
|
|
1173
|
+
...unchangedPatch(findWranglerConfig(projectRoot)),
|
|
1174
|
+
databases: databases.map((db) => db.name),
|
|
1175
|
+
unparsable,
|
|
1176
|
+
changes: []
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
return reconcileWranglerConfig(projectRoot, databases, options.log);
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* {@link patchWranglerConfig} for databases already parsed, logging one line
|
|
1183
|
+
* when the file changed: `durable-db updated wrangler.jsonc (…)`. An app
|
|
1184
|
+
* without databases is left alone unless its config still binds durable-db
|
|
1185
|
+
* classes (a database removed: its binding goes).
|
|
1186
|
+
*/
|
|
1187
|
+
function reconcileWranglerConfig(projectRoot, databases, log = (message) => console.log(message)) {
|
|
1188
|
+
const names = databases.map((db) => db.name);
|
|
1189
|
+
if (databases.length === 0) {
|
|
1190
|
+
const configPath = findWranglerConfig(projectRoot);
|
|
1191
|
+
if (!bindsDurableDbClasses(configPath)) return {
|
|
1192
|
+
...unchangedPatch(configPath),
|
|
1193
|
+
databases: names,
|
|
1194
|
+
unparsable: [],
|
|
1195
|
+
changes: []
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
const patch = patchWranglerConfig(projectRoot, databases);
|
|
1199
|
+
const changes = describePatch(patch);
|
|
1200
|
+
if (patch.modified && patch.configPath && log) log(`durable-db updated ${path$1.basename(patch.configPath)}` + (changes.length > 0 ? ` (${changes.join("; ")})` : ""));
|
|
1201
|
+
return {
|
|
1202
|
+
...patch,
|
|
1203
|
+
databases: names,
|
|
1204
|
+
unparsable: [],
|
|
1205
|
+
changes
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* Parse every database file in the sources, each database with its
|
|
1210
|
+
* migrations directory (`<migrationsDir>/<name>`, as the plugin sets it); the
|
|
1211
|
+
* files that fail to parse are listed apart.
|
|
1212
|
+
*/
|
|
1213
|
+
function discoverDatabaseInfos(projectRoot, databasesDir, migrationsDir = "migrations") {
|
|
1214
|
+
const databases = [];
|
|
1215
|
+
const unparsable = [];
|
|
1216
|
+
for (const file of discoverDatabaseFiles({
|
|
1217
|
+
projectRoot,
|
|
1218
|
+
databasesDir
|
|
1219
|
+
})) try {
|
|
1220
|
+
const parsed = parseDatabaseFile(file.absolutePath, readFile(file.absolutePath), { namePrefix: file.prefix });
|
|
1221
|
+
if (parsed.database) {
|
|
1222
|
+
parsed.database.migrationsDir = path$1.resolve(projectRoot, migrationsDir, parsed.database.name);
|
|
1223
|
+
databases.push(parsed.database);
|
|
1224
|
+
}
|
|
1225
|
+
} catch (error) {
|
|
1226
|
+
debugVite("Could not parse %s while syncing wrangler config: %O", file.relativePath, error);
|
|
1227
|
+
unparsable.push(file.relativePath);
|
|
1228
|
+
}
|
|
1229
|
+
return {
|
|
1230
|
+
databases,
|
|
1231
|
+
unparsable
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
/** `Durable Objects: +AUDIT_DATABASE_DO → AuditDatabaseDO`, `migration v2: AuditDatabaseDO`. */
|
|
1235
|
+
function describePatch(patch) {
|
|
1236
|
+
const changes = [];
|
|
1237
|
+
const bindings = [...patch.addedBindings.map((b) => `+${b.name} → ${b.class_name}`), ...patch.removedBindings.map((b) => `-${b.name} → ${b.class_name}`)];
|
|
1238
|
+
if (bindings.length > 0) changes.push(`Durable Objects: ${bindings.join(", ")}`);
|
|
1239
|
+
if (patch.migrationTag) {
|
|
1240
|
+
const classes = [...patch.newClasses, ...patch.renamedClasses.map((r) => `${r.from} → ${r.to}`)];
|
|
1241
|
+
changes.push(`migration ${patch.migrationTag}: ${classes.join(", ")}`);
|
|
1242
|
+
}
|
|
1243
|
+
return changes;
|
|
1244
|
+
}
|
|
1245
|
+
//#endregion
|
|
768
1246
|
//#region src/vite/durableDb.ts
|
|
769
1247
|
init_debug();
|
|
770
1248
|
init_state();
|
|
@@ -780,19 +1258,57 @@ function matchesVirtualId(id, canonicalId) {
|
|
|
780
1258
|
}
|
|
781
1259
|
/**
|
|
782
1260
|
* Generate the __devEpoch virtual module. Action stubs route every DO
|
|
783
|
-
* instance key through `applyDevEpoch()`:
|
|
784
|
-
* - dev: suffixes keys with the
|
|
785
|
-
* `db reset
|
|
1261
|
+
* instance key through `applyDevEpoch(key, dbName)`:
|
|
1262
|
+
* - dev: suffixes keys with the database's epoch (`<key>__dev_<epoch>`) — its
|
|
1263
|
+
* own after `db reset --database <name>`, else the project epoch — so a
|
|
1264
|
+
* `db reset` rotates the reset database(s) to fresh DO instances
|
|
786
1265
|
* - production builds: identity function, zero overhead beyond the call
|
|
787
1266
|
*/
|
|
788
|
-
function generateDevEpochModule(epoch) {
|
|
1267
|
+
function generateDevEpochModule(epoch, databaseEpochs = {}) {
|
|
789
1268
|
return [
|
|
790
1269
|
`export const devEpoch = ${JSON.stringify(epoch)};`,
|
|
791
|
-
`export
|
|
792
|
-
`
|
|
1270
|
+
`export const devEpochs = ${JSON.stringify(epoch ? databaseEpochs : {})};`,
|
|
1271
|
+
`export function applyDevEpoch(key, dbName) {`,
|
|
1272
|
+
` const epoch = (dbName != null && Object.prototype.hasOwnProperty.call(devEpochs, dbName) ? devEpochs[dbName] : null) ?? devEpoch;`,
|
|
1273
|
+
` return epoch ? \`\${key}__dev_\${epoch}\` : key;`,
|
|
793
1274
|
`}`
|
|
794
1275
|
].join("\n");
|
|
795
1276
|
}
|
|
1277
|
+
/**
|
|
1278
|
+
* Cheap pre-check for `transform`: only code that defines a database
|
|
1279
|
+
* (`defineDatabase`, which `destroyDatabase` comes from) or imports an
|
|
1280
|
+
* `action` factory can be rewritten — every other module skips the Babel
|
|
1281
|
+
* parse, so a syntax error in an unrelated file is reported by the compiler
|
|
1282
|
+
* that owns it, not as a durable-db error. A superset, not analysis: the
|
|
1283
|
+
* parser still decides.
|
|
1284
|
+
*
|
|
1285
|
+
* The parser takes an action factory from two places: destructuring a
|
|
1286
|
+
* `defineDatabase()` call (DATABASE_DEFINITION), or an import specifier
|
|
1287
|
+
* named `action` in any import declaration (ACTION_IMPORT). The clause
|
|
1288
|
+
* before the braces may hold anything but the module specifier — a default
|
|
1289
|
+
* binding (`import main, { action }`), `type`, comments, line breaks — so
|
|
1290
|
+
* the gap between `import` and `{` excludes only what cannot occur in it: a
|
|
1291
|
+
* quote (the `from` string, or a side-effect import), `;`, `{` and `}`.
|
|
1292
|
+
*/
|
|
1293
|
+
const DATABASE_DEFINITION = /\b(?:defineDatabase|destroyDatabase)\b/;
|
|
1294
|
+
const ACTION_IMPORT = /\bimport\b[^;'"`{}]*\{[^}]*\baction\b[^}]*\}/;
|
|
1295
|
+
function mayDefineDatabaseCode(code) {
|
|
1296
|
+
return DATABASE_DEFINITION.test(code) || ACTION_IMPORT.test(code);
|
|
1297
|
+
}
|
|
1298
|
+
/** Identifies a set of databases, for {@link PluginState.wranglerReconciledFor}. */
|
|
1299
|
+
function wranglerKey(databaseNames) {
|
|
1300
|
+
return [...databaseNames].sort().join("\n");
|
|
1301
|
+
}
|
|
1302
|
+
/**
|
|
1303
|
+
* A refused rename leaves the database's class undeclared: deployed, its data
|
|
1304
|
+
* would be stranded or meet migrations its journal does not know; in dev the
|
|
1305
|
+
* class would not get SQLite storage. Stop until the user chooses (the
|
|
1306
|
+
* patcher's warning gives both ways out).
|
|
1307
|
+
*/
|
|
1308
|
+
function stopOnRenameConflicts(conflicts) {
|
|
1309
|
+
if (conflicts.length === 0) return;
|
|
1310
|
+
throw new Error(`[durable-db] ${conflicts.map((c) => `${c.from} → ${c.to}`).join(", ")}: a renamed database's migrations cannot move with its data (${conflicts.map((c) => c.reason).join("; ")}). Keep the data or delete it as the warning above says, then restart.`);
|
|
1311
|
+
}
|
|
796
1312
|
var PluginState = class {
|
|
797
1313
|
options;
|
|
798
1314
|
databases = /* @__PURE__ */ new Map();
|
|
@@ -800,6 +1316,13 @@ var PluginState = class {
|
|
|
800
1316
|
databaseFilePaths = /* @__PURE__ */ new Map();
|
|
801
1317
|
initialized = false;
|
|
802
1318
|
initPromise = null;
|
|
1319
|
+
/**
|
|
1320
|
+
* The databases wrangler.jsonc was last reconciled with (sorted names), so
|
|
1321
|
+
* an initialization reconciles only when they changed — the `config` hook
|
|
1322
|
+
* has already settled the file for the databases on disk at startup.
|
|
1323
|
+
* Survives `reset()`.
|
|
1324
|
+
*/
|
|
1325
|
+
wranglerReconciledFor = null;
|
|
803
1326
|
projectRoot = "";
|
|
804
1327
|
config;
|
|
805
1328
|
devServer = null;
|
|
@@ -879,18 +1402,21 @@ var PluginState = class {
|
|
|
879
1402
|
parsed.database.migrationsDir = path$1.resolve(this.projectRoot, this.options.migrationsDir, parsed.database.name);
|
|
880
1403
|
this.databases.set(parsed.database.name, parsed.database);
|
|
881
1404
|
this.registerDatabaseFile(file.absolutePath, parsed.database.name);
|
|
882
|
-
await this.loadMigrations(parsed.database);
|
|
883
1405
|
}
|
|
884
1406
|
}
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
1407
|
+
const databases = Array.from(this.databases.values());
|
|
1408
|
+
debugVite("Found %d database(s)", databases.length);
|
|
1409
|
+
if (this.options.patchWranglerConfig) {
|
|
1410
|
+
const reconciledFor = wranglerKey(databases.map((db) => db.name));
|
|
1411
|
+
if (reconciledFor !== this.wranglerReconciledFor) {
|
|
1412
|
+
stopOnRenameConflicts(reconcileWranglerConfig(this.projectRoot, databases).conflicts);
|
|
1413
|
+
this.wranglerReconciledFor = reconciledFor;
|
|
892
1414
|
}
|
|
1415
|
+
} else if (databases.length > 0) {
|
|
1416
|
+
const check = checkWranglerConfig(this.projectRoot, databases);
|
|
1417
|
+
if (!check.ok && !check.tomlOnly && this.config.command === "build") throw new Error(`[durable-db] ${check.configPath ? path$1.basename(check.configPath) : "wrangler.jsonc"} does not match the discovered database(s): it is ${describeWranglerCheck(check)}. Deploying this build would ship a worker whose Durable Objects do not match it. Make the changes the warning above gives, or opt in to automatic patching with durableDb({ patchWranglerConfig: true }).`);
|
|
893
1418
|
}
|
|
1419
|
+
for (const database of this.databases.values()) await this.loadMigrations(database);
|
|
894
1420
|
this.initialized = true;
|
|
895
1421
|
}
|
|
896
1422
|
async loadMigrations(db) {
|
|
@@ -898,7 +1424,7 @@ var PluginState = class {
|
|
|
898
1424
|
const isDev = this.config.command === "serve";
|
|
899
1425
|
db.migrations = loadMigrationFiles(migrationsDir);
|
|
900
1426
|
if (isDev) try {
|
|
901
|
-
const { loadDevMigrations } = await import("../state-
|
|
1427
|
+
const { loadDevMigrations } = await import("../state-DGYycIoJ.js").then((n) => (n.d(), n.v));
|
|
902
1428
|
const devMigrations = loadDevMigrations(this.projectRoot, db.name);
|
|
903
1429
|
for (const [name, chunks] of devMigrations) db.migrations.set(`_dev_${name}`, chunks);
|
|
904
1430
|
if (devMigrations.size > 0) debugVite("Loaded %d dev migration(s) for %s", devMigrations.size, db.name);
|
|
@@ -967,6 +1493,16 @@ function durableDb(options = {}) {
|
|
|
967
1493
|
return {
|
|
968
1494
|
name: "durable-db",
|
|
969
1495
|
enforce: "pre",
|
|
1496
|
+
config(userConfig) {
|
|
1497
|
+
if (!state.options.patchWranglerConfig) return;
|
|
1498
|
+
const sync = syncWranglerConfig({
|
|
1499
|
+
projectRoot: path$1.resolve(userConfig.root ?? process.cwd()),
|
|
1500
|
+
databasesDir: state.options.databasesDir,
|
|
1501
|
+
migrationsDir: state.options.migrationsDir
|
|
1502
|
+
});
|
|
1503
|
+
stopOnRenameConflicts(sync.conflicts);
|
|
1504
|
+
if (sync.unparsable.length === 0) state.wranglerReconciledFor = wranglerKey(sync.databases);
|
|
1505
|
+
},
|
|
970
1506
|
configResolved(config) {
|
|
971
1507
|
state.config = config;
|
|
972
1508
|
state.projectRoot = config.root;
|
|
@@ -974,6 +1510,12 @@ function durableDb(options = {}) {
|
|
|
974
1510
|
configureServer(server) {
|
|
975
1511
|
state.devServer = server;
|
|
976
1512
|
state.reset();
|
|
1513
|
+
try {
|
|
1514
|
+
const lockToken = writeDevServerLock(state.projectRoot);
|
|
1515
|
+
server.httpServer?.once("close", () => removeDevServerLock(state.projectRoot, lockToken));
|
|
1516
|
+
} catch (error) {
|
|
1517
|
+
debugVite("Could not write the dev-server lock: %O", error);
|
|
1518
|
+
}
|
|
977
1519
|
const absoluteDbDirs = databaseSources(state.options.databasesDir).map((source) => path$1.resolve(state.projectRoot, source.dir));
|
|
978
1520
|
server.watcher.on("change", (file) => {
|
|
979
1521
|
const normalized = path$1.normalize(file);
|
|
@@ -982,7 +1524,9 @@ function durableDb(options = {}) {
|
|
|
982
1524
|
const devPaths = getDevPaths(state.projectRoot);
|
|
983
1525
|
fs.mkdirSync(devPaths.cacheDir, { recursive: true });
|
|
984
1526
|
let reloadTimer = null;
|
|
985
|
-
const
|
|
1527
|
+
const cacheDirName = path$1.basename(devPaths.cacheDir);
|
|
1528
|
+
const onDevStateChange = (_event, filename) => {
|
|
1529
|
+
if (typeof filename === "string" && (path$1.basename(filename) === "dev-server.json" || filename === cacheDirName)) return;
|
|
986
1530
|
if (state.isWithinSelfDevStateWriteWindow()) {
|
|
987
1531
|
debugVite("Ignoring dev cache event caused by the plugin itself");
|
|
988
1532
|
return;
|
|
@@ -1017,6 +1561,7 @@ function durableDb(options = {}) {
|
|
|
1017
1561
|
if (id === VIRTUAL_DEV_EPOCH_MODULE_ID) {
|
|
1018
1562
|
const isDev = state.config.command === "serve";
|
|
1019
1563
|
let epoch = null;
|
|
1564
|
+
let databaseEpochs = {};
|
|
1020
1565
|
if (isDev) {
|
|
1021
1566
|
const devState = loadDevState(state.projectRoot);
|
|
1022
1567
|
if (!fs.existsSync(getDevPaths(state.projectRoot).stateFile)) {
|
|
@@ -1024,8 +1569,9 @@ function durableDb(options = {}) {
|
|
|
1024
1569
|
saveDevState(state.projectRoot, devState);
|
|
1025
1570
|
}
|
|
1026
1571
|
epoch = devState.epoch;
|
|
1572
|
+
databaseEpochs = getDatabaseEpochs(devState);
|
|
1027
1573
|
}
|
|
1028
|
-
return { code: generateDevEpochModule(epoch) };
|
|
1574
|
+
return { code: generateDevEpochModule(epoch, databaseEpochs) };
|
|
1029
1575
|
}
|
|
1030
1576
|
if (id !== VIRTUAL_DO_MODULE_ID) return null;
|
|
1031
1577
|
await state.initialize();
|
|
@@ -1044,6 +1590,7 @@ function durableDb(options = {}) {
|
|
|
1044
1590
|
};
|
|
1045
1591
|
if (id.startsWith("\0") || id.includes("node_modules")) return null;
|
|
1046
1592
|
if (!/\.tsx?$/.test(id)) return null;
|
|
1593
|
+
if (!mayDefineDatabaseCode(code)) return null;
|
|
1047
1594
|
await state.initialize();
|
|
1048
1595
|
const cleanId = path$1.normalize(id.split("?", 1)[0]);
|
|
1049
1596
|
const dbNameForPath = state.getDatabaseNameForPath(cleanId);
|
|
@@ -1096,4 +1643,4 @@ function durableDb(options = {}) {
|
|
|
1096
1643
|
/** @deprecated Renamed to {@link durableDb}. */
|
|
1097
1644
|
const databasePlugin = durableDb;
|
|
1098
1645
|
//#endregion
|
|
1099
|
-
export { databasePlugin, durableDb as default, durableDb };
|
|
1646
|
+
export { databasePlugin, durableDb as default, durableDb, syncWranglerConfig };
|