@duraxis/migrations 0.0.0-stage → 0.1.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/CHANGELOG.md +5 -0
- package/LICENSE +15 -0
- package/README.md +192 -2
- package/dist/context.d.ts +30 -0
- package/dist/diff.d.ts +20 -0
- package/dist/index.cjs +470 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +456 -0
- package/dist/index.js.map +1 -0
- package/dist/runner.d.ts +49 -0
- package/dist/schema.d.ts +15 -0
- package/package.json +59 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let node_crypto = require("node:crypto");
|
|
3
|
+
let _duraxis_core = require("@duraxis/core");
|
|
4
|
+
// src/schema.ts
|
|
5
|
+
function canonicalJSON(value) {
|
|
6
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(",")}]`;
|
|
7
|
+
if (value && typeof value == "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalJSON(v)}`).join(",")}}`;
|
|
8
|
+
const json = JSON.stringify(value);
|
|
9
|
+
if (json === void 0) throw new Error("Non-JSON schema value");
|
|
10
|
+
return json;
|
|
11
|
+
}
|
|
12
|
+
function checksum(value) {
|
|
13
|
+
return `sha256:${(0, node_crypto.createHash)("sha256").update(value).digest("hex")}`;
|
|
14
|
+
}
|
|
15
|
+
function canonicalSchema(collections) {
|
|
16
|
+
const names = /* @__PURE__ */ new Set();
|
|
17
|
+
return collections.map((definition) => {
|
|
18
|
+
if (names.has(definition.name)) throw new Error(`Duplicate collection: ${definition.name}`);
|
|
19
|
+
names.add(definition.name);
|
|
20
|
+
const schema = (0, _duraxis_core.normalizeCollection)(definition);
|
|
21
|
+
return {
|
|
22
|
+
...schema,
|
|
23
|
+
indexes: [...schema.indexes].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
|
|
24
|
+
...schema.foreignKeys ? { foreignKeys: [...schema.foreignKeys].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0) } : {}
|
|
25
|
+
};
|
|
26
|
+
}).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
27
|
+
}
|
|
28
|
+
function schemaHash(collections) {
|
|
29
|
+
return checksum(canonicalJSON(canonicalSchema(collections)));
|
|
30
|
+
}
|
|
31
|
+
function createSnapshot(migrationId, parentMigrationId, collections) {
|
|
32
|
+
const normalized = canonicalSchema(collections);
|
|
33
|
+
return {
|
|
34
|
+
formatVersion: 1,
|
|
35
|
+
migrationId,
|
|
36
|
+
parentMigrationId,
|
|
37
|
+
schemaHash: schemaHash(normalized),
|
|
38
|
+
collections: normalized
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function validateSnapshot(snapshot) {
|
|
42
|
+
if (!snapshot || snapshot.formatVersion !== 1 || !Array.isArray(snapshot.collections) || snapshot.schemaHash !== schemaHash(snapshot.collections)) throw new Error("Invalid or incompatible schema snapshot");
|
|
43
|
+
const catalog = new Map(snapshot.collections.map((schema) => [schema.name, schema]));
|
|
44
|
+
for (const schema of snapshot.collections) for (const key of schema.foreignKeys ?? []) if (!catalog.has(key.references.collection)) throw new Error("Snapshot foreign key references an unmanaged collection");
|
|
45
|
+
if (snapshot.migrationId === null && snapshot.parentMigrationId !== null) throw new Error("Invalid baseline parent");
|
|
46
|
+
if (snapshot.migrationId !== null) validateMigrationId(snapshot.migrationId);
|
|
47
|
+
if (snapshot.parentMigrationId !== null) validateMigrationId(snapshot.parentMigrationId);
|
|
48
|
+
}
|
|
49
|
+
function validateMigrationId(id) {
|
|
50
|
+
if (typeof id != "string" || !/^\d{17}_[a-z0-9]+(?:_[a-z0-9]+)*$/.test(id)) throw new Error(`Invalid migration ID: ${id}`);
|
|
51
|
+
}
|
|
52
|
+
// src/context.ts
|
|
53
|
+
var SchemaEditor = class {
|
|
54
|
+
#tx;
|
|
55
|
+
constructor(tx) {
|
|
56
|
+
this.#tx = tx;
|
|
57
|
+
}
|
|
58
|
+
inspect() {
|
|
59
|
+
return this.#tx.getCollectionDefinitions();
|
|
60
|
+
}
|
|
61
|
+
definition(name) {
|
|
62
|
+
const result = this.inspect().find((schema) => schema.name == name);
|
|
63
|
+
if (!result) throw new Error(`Unknown collection: ${name}`);
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
createCollection(definition) {
|
|
67
|
+
this.#tx.defineCollection(definition);
|
|
68
|
+
}
|
|
69
|
+
createCollections(definitions) {
|
|
70
|
+
this.#tx.defineCollections(definitions);
|
|
71
|
+
}
|
|
72
|
+
alterCollection(name, definition) {
|
|
73
|
+
this.#tx.alterCollection(name, definition);
|
|
74
|
+
}
|
|
75
|
+
dropCollection(name) {
|
|
76
|
+
this.#tx.dropCollection(name);
|
|
77
|
+
}
|
|
78
|
+
addField(collection, name, definition) {
|
|
79
|
+
const schema = this.definition(collection);
|
|
80
|
+
if (Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Field already exists: ${name}`);
|
|
81
|
+
this.alterCollection(collection, {
|
|
82
|
+
...schema,
|
|
83
|
+
fields: {
|
|
84
|
+
...schema.fields,
|
|
85
|
+
[name]: definition
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
alterField(collection, name, definition) {
|
|
90
|
+
const schema = this.definition(collection);
|
|
91
|
+
if (!Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Unknown field: ${name}`);
|
|
92
|
+
this.alterCollection(collection, {
|
|
93
|
+
...schema,
|
|
94
|
+
fields: {
|
|
95
|
+
...schema.fields,
|
|
96
|
+
[name]: definition
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
async removeField(collection, name, options) {
|
|
101
|
+
const schema = this.definition(collection);
|
|
102
|
+
const fields = { ...schema.fields };
|
|
103
|
+
if (!Object.hasOwn(fields, name)) throw new Error(`Unknown field: ${name}`);
|
|
104
|
+
if (schema.indexes.some((index) => (0, _duraxis_core.indexFields)(index).some((part) => part.field == name)) || schema.foreignKeys?.some((key) => key.field == name)) throw new Error("Remove dependent indexes and foreign keys first");
|
|
105
|
+
delete fields[name];
|
|
106
|
+
if (options.strategy == "reject-if-populated") {
|
|
107
|
+
for await (const row of this.#tx.scanCollection(collection)) if (Object.hasOwn(row.document, name)) throw new Error(`Field is populated: ${collection}/${name}`);
|
|
108
|
+
} else if (options.strategy != "delete-values") throw new Error("Explicit field removal strategy required");
|
|
109
|
+
this.alterCollection(collection, {
|
|
110
|
+
...schema,
|
|
111
|
+
fields
|
|
112
|
+
});
|
|
113
|
+
if (options.strategy == "delete-values") for await (const row of this.#tx.scanCollection(collection)) {
|
|
114
|
+
const document = { ...row.document };
|
|
115
|
+
delete document[name];
|
|
116
|
+
this.#tx.putDocument(collection, row.id, document);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async renameField(collection, from, to) {
|
|
120
|
+
const schema = this.definition(collection);
|
|
121
|
+
const fields = { ...schema.fields };
|
|
122
|
+
if (!Object.hasOwn(fields, from) || Object.hasOwn(fields, to)) throw new Error("Invalid field rename");
|
|
123
|
+
for await (const row of this.#tx.scanCollection(collection)) if (Object.hasOwn(row.document, to)) throw new Error(`Rename would overwrite ${to}`);
|
|
124
|
+
fields[to] = fields[from];
|
|
125
|
+
delete fields[from];
|
|
126
|
+
this.alterCollection(collection, {
|
|
127
|
+
...schema,
|
|
128
|
+
fields,
|
|
129
|
+
indexes: schema.indexes.map((index) => ({
|
|
130
|
+
name: index.name,
|
|
131
|
+
unique: index.unique,
|
|
132
|
+
fields: (0, _duraxis_core.indexFields)(index).map((part) => ({
|
|
133
|
+
...part,
|
|
134
|
+
field: part.field == from ? to : part.field
|
|
135
|
+
}))
|
|
136
|
+
})),
|
|
137
|
+
foreignKeys: schema.foreignKeys?.map((key) => ({
|
|
138
|
+
...key,
|
|
139
|
+
field: key.field == from ? to : key.field
|
|
140
|
+
}))
|
|
141
|
+
});
|
|
142
|
+
for await (const row of this.#tx.scanCollection(collection)) {
|
|
143
|
+
const document = { ...row.document };
|
|
144
|
+
if (Object.hasOwn(document, from)) {
|
|
145
|
+
document[to] = document[from];
|
|
146
|
+
delete document[from];
|
|
147
|
+
}
|
|
148
|
+
this.#tx.putDocument(collection, row.id, document);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
addIndex(collection, index) {
|
|
152
|
+
this.#tx.addIndex(collection, index);
|
|
153
|
+
}
|
|
154
|
+
removeIndex(collection, name) {
|
|
155
|
+
this.#tx.removeIndex(collection, name);
|
|
156
|
+
}
|
|
157
|
+
addForeignKey(collection, definition) {
|
|
158
|
+
const schema = this.definition(collection);
|
|
159
|
+
if (schema.foreignKeys?.some((key) => key.name == definition.name)) throw new Error("Foreign key already exists");
|
|
160
|
+
this.alterCollection(collection, {
|
|
161
|
+
...schema,
|
|
162
|
+
foreignKeys: [...schema.foreignKeys ?? [], definition]
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
removeForeignKey(collection, name) {
|
|
166
|
+
const schema = this.definition(collection);
|
|
167
|
+
if (!schema.foreignKeys?.some((key) => key.name == name)) throw new Error("Unknown foreign key");
|
|
168
|
+
this.alterCollection(collection, {
|
|
169
|
+
...schema,
|
|
170
|
+
foreignKeys: schema.foreignKeys.filter((key) => key.name != name)
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
function createMigrationContext(tx) {
|
|
175
|
+
return Object.freeze({
|
|
176
|
+
schema: new SchemaEditor(tx),
|
|
177
|
+
get: tx.getDocument.bind(tx),
|
|
178
|
+
scan: tx.scanCollection.bind(tx),
|
|
179
|
+
put: tx.putDocument.bind(tx),
|
|
180
|
+
delete: tx.deleteDocument.bind(tx),
|
|
181
|
+
async transform(collection, transform) {
|
|
182
|
+
for await (const row of tx.scanCollection(collection)) tx.putDocument(collection, row.id, await transform(row.document, row.id));
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
// src/diff.ts
|
|
187
|
+
function fieldRisk(before, after) {
|
|
188
|
+
if (!after) return "destructive";
|
|
189
|
+
if (!before) return after.required ? "requires-data-transformation" : "safe";
|
|
190
|
+
if (before.type != after.type || !before.required && after.required) return "requires-data-transformation";
|
|
191
|
+
if (before.nullable && !after.nullable) return "requires-validation";
|
|
192
|
+
return "safe";
|
|
193
|
+
}
|
|
194
|
+
function diffSchemas(before, after) {
|
|
195
|
+
const previous = canonicalSchema(before);
|
|
196
|
+
const next = canonicalSchema(after);
|
|
197
|
+
const left = new Map(previous.map((schema) => [schema.name, schema]));
|
|
198
|
+
const right = new Map(next.map((schema) => [schema.name, schema]));
|
|
199
|
+
const operations = [];
|
|
200
|
+
for (const name of [.../* @__PURE__ */ new Set([...left.keys(), ...right.keys()])].sort()) {
|
|
201
|
+
const a = left.get(name);
|
|
202
|
+
const b = right.get(name);
|
|
203
|
+
if (!a || !b) {
|
|
204
|
+
operations.push({
|
|
205
|
+
kind: "collection",
|
|
206
|
+
collection: name,
|
|
207
|
+
name,
|
|
208
|
+
before: a ?? null,
|
|
209
|
+
after: b ?? null,
|
|
210
|
+
risk: b ? "requires-validation" : "destructive"
|
|
211
|
+
});
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (a.fields == null != (b.fields == null)) operations.push({
|
|
215
|
+
kind: "collection",
|
|
216
|
+
collection: name,
|
|
217
|
+
name,
|
|
218
|
+
before: a,
|
|
219
|
+
after: b,
|
|
220
|
+
risk: "requires-validation"
|
|
221
|
+
});
|
|
222
|
+
const fields = /* @__PURE__ */ new Set([...Object.keys(a.fields ?? {}), ...Object.keys(b.fields ?? {})]);
|
|
223
|
+
for (const field of [...fields].sort()) {
|
|
224
|
+
const from = a.fields?.[field] ?? null;
|
|
225
|
+
const to = b.fields?.[field] ?? null;
|
|
226
|
+
if (canonicalJSON(from) != canonicalJSON(to)) operations.push({
|
|
227
|
+
kind: "field",
|
|
228
|
+
collection: name,
|
|
229
|
+
name: field,
|
|
230
|
+
before: from,
|
|
231
|
+
after: to,
|
|
232
|
+
risk: fieldRisk(from, to)
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
if (a.allowAdditionalFields != b.allowAdditionalFields) operations.push({
|
|
236
|
+
kind: "additional-fields",
|
|
237
|
+
collection: name,
|
|
238
|
+
name,
|
|
239
|
+
before: a.allowAdditionalFields ?? true,
|
|
240
|
+
after: b.allowAdditionalFields ?? true,
|
|
241
|
+
risk: b.allowAdditionalFields ? "safe" : "requires-validation"
|
|
242
|
+
});
|
|
243
|
+
for (const index of [...new Set([...a.indexes, ...b.indexes].map((index) => index.name))].sort()) {
|
|
244
|
+
const from = a.indexes.find((item) => item.name == index) ?? null;
|
|
245
|
+
const to = b.indexes.find((item) => item.name == index) ?? null;
|
|
246
|
+
if (canonicalJSON(from) != canonicalJSON(to)) operations.push({
|
|
247
|
+
kind: "index",
|
|
248
|
+
collection: name,
|
|
249
|
+
name: index,
|
|
250
|
+
before: from,
|
|
251
|
+
after: to,
|
|
252
|
+
risk: to?.unique ? "requires-validation" : "safe"
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
for (const key of [...new Set([...a.foreignKeys ?? [], ...b.foreignKeys ?? []].map((key) => key.name))].sort()) {
|
|
256
|
+
const from = a.foreignKeys?.find((item) => item.name == key) ?? null;
|
|
257
|
+
const to = b.foreignKeys?.find((item) => item.name == key) ?? null;
|
|
258
|
+
if (canonicalJSON(from) != canonicalJSON(to)) operations.push({
|
|
259
|
+
kind: "foreign-key",
|
|
260
|
+
collection: name,
|
|
261
|
+
name: key,
|
|
262
|
+
before: from,
|
|
263
|
+
after: to,
|
|
264
|
+
risk: to ? "requires-validation" : "safe"
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
before: previous,
|
|
270
|
+
after: next,
|
|
271
|
+
operations
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
async function applySchemaPlan(context, plan) {
|
|
275
|
+
const names = new Set([...plan.before, ...plan.after].map((schema) => schema.name));
|
|
276
|
+
if (schemaHash(context.schema.inspect().filter((schema) => names.has(schema.name))) != schemaHash(plan.before)) throw new Error("Schema plan predecessor mismatch");
|
|
277
|
+
for (const operation of plan.operations) {
|
|
278
|
+
if (operation.risk == "requires-data-transformation") throw new Error(`Manual data transformation required: ${operation.collection}/${operation.name}`);
|
|
279
|
+
if (operation.kind == "field" && !operation.after) {
|
|
280
|
+
for await (const row of context.scan(operation.collection)) if (Object.hasOwn(row.document, operation.name)) throw new Error(`Cannot remove populated field: ${operation.collection}/${operation.name}; write an explicit transformation`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const old = new Set(plan.before.map((schema) => schema.name));
|
|
284
|
+
const next = new Set(plan.after.map((schema) => schema.name));
|
|
285
|
+
for (const schema of plan.before) if (!next.has(schema.name)) context.schema.dropCollection(schema.name);
|
|
286
|
+
for (const schema of plan.after) if (old.has(schema.name)) context.schema.alterCollection(schema.name, schema);
|
|
287
|
+
else context.schema.createCollection(schema);
|
|
288
|
+
}
|
|
289
|
+
// src/runner.ts
|
|
290
|
+
function defineMigration(migration) {
|
|
291
|
+
validateMigrationId(migration.id);
|
|
292
|
+
if (typeof migration.up != "function" || migration.down !== void 0 && typeof migration.down != "function") throw new Error("Invalid migration callbacks");
|
|
293
|
+
return Object.freeze(migration);
|
|
294
|
+
}
|
|
295
|
+
var namespace = "migrations";
|
|
296
|
+
var digest = /^sha256:[a-f0-9]{64}$/;
|
|
297
|
+
async function readHistory(tx) {
|
|
298
|
+
const bytes = await tx.getMetadata(namespace);
|
|
299
|
+
if (bytes == null) return {
|
|
300
|
+
formatVersion: 1,
|
|
301
|
+
revision: "",
|
|
302
|
+
entries: []
|
|
303
|
+
};
|
|
304
|
+
const history = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
305
|
+
if (history.formatVersion !== 1 || !Array.isArray(history.entries) || typeof history.revision != "string") throw new Error("Invalid migration history");
|
|
306
|
+
history.entries.forEach((entry, index) => {
|
|
307
|
+
validateMigrationId(entry.id);
|
|
308
|
+
if (entry.sequence != index + 1 || !digest.test(entry.checksum) || !digest.test(entry.schemaHash) || typeof entry.operationId != "string" || !Number.isFinite(Date.parse(entry.appliedAt)) || index && history.entries[index - 1].id >= entry.id) throw new Error("Invalid migration history ordering or metadata");
|
|
309
|
+
});
|
|
310
|
+
return history;
|
|
311
|
+
}
|
|
312
|
+
function writeHistory(tx, history) {
|
|
313
|
+
tx.putMetadata(namespace, new TextEncoder().encode(canonicalJSON(history)));
|
|
314
|
+
}
|
|
315
|
+
function validateArtifacts(artifacts) {
|
|
316
|
+
let parent = null;
|
|
317
|
+
for (const artifact of artifacts) {
|
|
318
|
+
defineMigration(artifact.migration);
|
|
319
|
+
validateSnapshot(artifact.snapshot);
|
|
320
|
+
if (!digest.test(artifact.checksum)) throw new Error("Invalid artifact checksum");
|
|
321
|
+
if (artifact.snapshot.migrationId != artifact.migration.id || artifact.snapshot.parentMigrationId != parent || parent && parent >= artifact.migration.id) throw new Error("Duplicate, unordered, or divergent migration chain");
|
|
322
|
+
parent = artifact.migration.id;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
var MigrationRunner = class {
|
|
326
|
+
database;
|
|
327
|
+
artifacts;
|
|
328
|
+
managedNames;
|
|
329
|
+
constructor(database, artifacts) {
|
|
330
|
+
this.database = database;
|
|
331
|
+
this.artifacts = artifacts;
|
|
332
|
+
validateArtifacts(artifacts);
|
|
333
|
+
this.managedNames = new Set(artifacts.flatMap((artifact) => artifact.snapshot.collections.map((schema) => schema.name)));
|
|
334
|
+
}
|
|
335
|
+
async validate(tx, checkSchema = true) {
|
|
336
|
+
const history = await readHistory(tx);
|
|
337
|
+
history.entries.forEach((entry, index) => {
|
|
338
|
+
const artifact = this.artifacts[index];
|
|
339
|
+
if (!artifact || artifact.migration.id != entry.id) throw new Error(`Missing migration or divergent history: ${entry.id}`);
|
|
340
|
+
if (artifact.checksum != entry.checksum) throw new Error(`Applied migration checksum mismatch: ${entry.id}`);
|
|
341
|
+
if (artifact.snapshot.schemaHash != entry.schemaHash) throw new Error(`Applied snapshot mismatch: ${entry.id}`);
|
|
342
|
+
});
|
|
343
|
+
const expected = history.entries.at(-1)?.schemaHash ?? schemaHash([]);
|
|
344
|
+
if (checkSchema && schemaHash(tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name))) != expected) throw new Error("Database schema drift detected");
|
|
345
|
+
return history;
|
|
346
|
+
}
|
|
347
|
+
async status() {
|
|
348
|
+
return this.database.transaction(async (tx) => {
|
|
349
|
+
const history = await this.validate(tx);
|
|
350
|
+
return {
|
|
351
|
+
applied: history.entries,
|
|
352
|
+
pending: this.artifacts.slice(history.entries.length).map((artifact) => artifact.migration.id)
|
|
353
|
+
};
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
async drift() {
|
|
357
|
+
return this.database.transaction(async (tx) => {
|
|
358
|
+
const history = await this.validate(tx, false);
|
|
359
|
+
return diffSchemas(this.artifacts[history.entries.length - 1]?.snapshot.collections ?? [], tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)));
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
validateOptions(options) {
|
|
363
|
+
if (options.steps !== void 0 && (!Number.isSafeInteger(options.steps) || options.steps < 0)) throw new Error("Invalid migration steps");
|
|
364
|
+
if (options.to && !this.artifacts.some((artifact) => artifact.migration.id == options.to)) throw new Error(`Unknown migration target: ${options.to}`);
|
|
365
|
+
if (options.to && options.steps !== void 0) throw new Error("Use either --steps or --to");
|
|
366
|
+
}
|
|
367
|
+
async up(options = {}) {
|
|
368
|
+
this.validateOptions(options);
|
|
369
|
+
const status = await this.status();
|
|
370
|
+
const selected = this.artifacts.slice(status.applied.length).filter((artifact) => !options.to || artifact.migration.id <= options.to).slice(0, options.steps ?? Infinity);
|
|
371
|
+
const completed = [];
|
|
372
|
+
for (const artifact of selected) {
|
|
373
|
+
await this.execute(artifact, "up", options);
|
|
374
|
+
completed.push(artifact.migration.id);
|
|
375
|
+
}
|
|
376
|
+
return completed;
|
|
377
|
+
}
|
|
378
|
+
async down(options = {}) {
|
|
379
|
+
this.validateOptions(options);
|
|
380
|
+
if (!options.allowDestructive) throw new Error("Rollback requires explicit destructive authorization");
|
|
381
|
+
const status = await this.status();
|
|
382
|
+
if (options.to && !status.applied.some((entry) => entry.id == options.to)) throw new Error("Rollback target is not applied");
|
|
383
|
+
const selected = this.artifacts.slice(0, status.applied.length).reverse().filter((artifact) => !options.to || artifact.migration.id > options.to).slice(0, options.steps ?? (options.to ? Infinity : 1));
|
|
384
|
+
for (const artifact of selected) if (!artifact.migration.down) throw new Error(`Irreversible migration: ${artifact.migration.id}`);
|
|
385
|
+
const completed = [];
|
|
386
|
+
for (const artifact of selected) {
|
|
387
|
+
await this.execute(artifact, "down", options);
|
|
388
|
+
completed.push(artifact.migration.id);
|
|
389
|
+
}
|
|
390
|
+
return completed;
|
|
391
|
+
}
|
|
392
|
+
async baseline() {
|
|
393
|
+
if (this.artifacts.length != 1) throw new Error("Baseline requires exactly one initial artifact");
|
|
394
|
+
const artifact = this.artifacts[0];
|
|
395
|
+
const operationId = (0, node_crypto.randomUUID)();
|
|
396
|
+
try {
|
|
397
|
+
await this.database.transaction(async (tx) => {
|
|
398
|
+
if ((await readHistory(tx)).entries.length) throw new Error("Database already has migration history");
|
|
399
|
+
this.assertSchema(tx, artifact.snapshot);
|
|
400
|
+
writeHistory(tx, {
|
|
401
|
+
formatVersion: 1,
|
|
402
|
+
revision: operationId,
|
|
403
|
+
entries: [this.entry(artifact, 1, operationId)]
|
|
404
|
+
});
|
|
405
|
+
});
|
|
406
|
+
} catch (error) {
|
|
407
|
+
await this.reconcile(error, operationId, "up", artifact);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
entry(artifact, sequence, operationId) {
|
|
411
|
+
return {
|
|
412
|
+
id: artifact.migration.id,
|
|
413
|
+
checksum: artifact.checksum,
|
|
414
|
+
schemaHash: artifact.snapshot.schemaHash,
|
|
415
|
+
appliedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
416
|
+
sequence,
|
|
417
|
+
operationId
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
assertSchema(tx, snapshot) {
|
|
421
|
+
if (schemaHash(tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name))) != (snapshot?.schemaHash ?? schemaHash([]))) throw new Error("Migration result does not match expected snapshot");
|
|
422
|
+
}
|
|
423
|
+
async execute(artifact, direction, options) {
|
|
424
|
+
const operationId = (0, node_crypto.randomUUID)();
|
|
425
|
+
try {
|
|
426
|
+
await this.database.transaction(async (tx) => {
|
|
427
|
+
const history = await this.validate(tx);
|
|
428
|
+
const index = this.artifacts.indexOf(artifact);
|
|
429
|
+
if (direction == "up" && history.entries[index]?.id == artifact.migration.id) return;
|
|
430
|
+
if ((direction == "up" ? history.entries.length : history.entries.length - 1) != index) throw new Error("Migration predecessor changed");
|
|
431
|
+
const before = tx.getCollectionDefinitions();
|
|
432
|
+
await (direction == "up" ? artifact.migration.up : artifact.migration.down)(createMigrationContext(tx));
|
|
433
|
+
const after = new Map(tx.getCollectionDefinitions().map((schema) => [schema.name, schema]));
|
|
434
|
+
if (!options.allowDestructive && before.some((schema) => !after.has(schema.name) || Object.keys(schema.fields ?? {}).some((name) => !Object.hasOwn(after.get(schema.name)?.fields ?? {}, name)))) throw new Error("Destructive schema change requires explicit authorization");
|
|
435
|
+
if (schemaHash(before.filter((schema) => !this.managedNames.has(schema.name))) != schemaHash([...after.values()].filter((schema) => !this.managedNames.has(schema.name)))) throw new Error("Migration changed collections outside its snapshots");
|
|
436
|
+
this.assertSchema(tx, direction == "up" ? artifact.snapshot : this.artifacts[index - 1]?.snapshot);
|
|
437
|
+
writeHistory(tx, {
|
|
438
|
+
formatVersion: 1,
|
|
439
|
+
revision: operationId,
|
|
440
|
+
entries: direction == "up" ? [...history.entries, this.entry(artifact, index + 1, operationId)] : history.entries.slice(0, -1)
|
|
441
|
+
});
|
|
442
|
+
});
|
|
443
|
+
} catch (error) {
|
|
444
|
+
await this.reconcile(error, operationId, direction, artifact);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
async reconcile(error, operationId, direction, artifact) {
|
|
448
|
+
if (!(error instanceof _duraxis_core.TransactionConflictError) && !(error instanceof _duraxis_core.CommitOutcomeUnknownError)) throw error;
|
|
449
|
+
const history = await this.database.transaction((tx) => this.validate(tx));
|
|
450
|
+
if (history.revision == operationId || direction == "up" && history.entries.some((entry) => entry.id == artifact.migration.id && entry.checksum == artifact.checksum)) return;
|
|
451
|
+
if (error instanceof _duraxis_core.CommitOutcomeUnknownError && await this.database.getCommitStatus(error.transactionId) == "committed") return;
|
|
452
|
+
throw error;
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
exports.MigrationRunner = MigrationRunner;
|
|
456
|
+
exports.SchemaEditor = SchemaEditor;
|
|
457
|
+
exports.applySchemaPlan = applySchemaPlan;
|
|
458
|
+
exports.canonicalJSON = canonicalJSON;
|
|
459
|
+
exports.canonicalSchema = canonicalSchema;
|
|
460
|
+
exports.checksum = checksum;
|
|
461
|
+
exports.createMigrationContext = createMigrationContext;
|
|
462
|
+
exports.createSnapshot = createSnapshot;
|
|
463
|
+
exports.defineMigration = defineMigration;
|
|
464
|
+
exports.diffSchemas = diffSchemas;
|
|
465
|
+
exports.schemaHash = schemaHash;
|
|
466
|
+
exports.validateArtifacts = validateArtifacts;
|
|
467
|
+
exports.validateMigrationId = validateMigrationId;
|
|
468
|
+
exports.validateSnapshot = validateSnapshot;
|
|
469
|
+
|
|
470
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["createHash","normalizeCollection","indexFields","randomUUID","TransactionConflictError","CommitOutcomeUnknownError"],"sources":["../src/schema.ts","../src/context.ts","../src/diff.ts","../src/runner.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { normalizeCollection, type CollectionDefinition } from \"@duraxis/core\";\n\nexport function canonicalJSON(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(\",\")}]`;\n\n if (value && typeof value == \"object\")\n return `{${Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJSON(v)}`)\n .join(\",\")}}`;\n\n const json = JSON.stringify(value);\n\n if (json === undefined) throw new Error(\"Non-JSON schema value\");\n\n return json;\n}\n\nexport function checksum(value: string): string {\n return `sha256:${createHash(\"sha256\").update(value).digest(\"hex\")}`;\n}\n\nexport function canonicalSchema(\n collections: readonly CollectionDefinition[],\n): readonly CollectionDefinition[] {\n const names = new Set<string>();\n\n return collections\n .map((definition) => {\n if (names.has(definition.name)) throw new Error(`Duplicate collection: ${definition.name}`);\n\n names.add(definition.name);\n\n const schema = normalizeCollection(definition);\n\n return {\n ...schema,\n indexes: [...schema.indexes].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n ),\n ...(schema.foreignKeys\n ? {\n foreignKeys: [...schema.foreignKeys].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n ),\n }\n : {}),\n };\n })\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\nexport function schemaHash(collections: readonly CollectionDefinition[]): string {\n return checksum(canonicalJSON(canonicalSchema(collections)));\n}\n\nexport interface SchemaSnapshot {\n readonly formatVersion: 1;\n readonly migrationId: string | null;\n readonly parentMigrationId: string | null;\n readonly schemaHash: string;\n readonly collections: readonly CollectionDefinition[];\n}\n\nexport function createSnapshot(\n migrationId: string | null,\n parentMigrationId: string | null,\n collections: readonly CollectionDefinition[],\n): SchemaSnapshot {\n const normalized = canonicalSchema(collections);\n\n return {\n formatVersion: 1,\n migrationId,\n parentMigrationId,\n schemaHash: schemaHash(normalized),\n collections: normalized,\n };\n}\n\nexport function validateSnapshot(snapshot: SchemaSnapshot): void {\n if (\n !snapshot ||\n snapshot.formatVersion !== 1 ||\n !Array.isArray(snapshot.collections) ||\n snapshot.schemaHash !== schemaHash(snapshot.collections)\n )\n throw new Error(\"Invalid or incompatible schema snapshot\");\n\n const catalog = new Map(snapshot.collections.map((schema) => [schema.name, schema]));\n\n for (const schema of snapshot.collections)\n for (const key of schema.foreignKeys ?? [])\n if (!catalog.has(key.references.collection))\n throw new Error(\"Snapshot foreign key references an unmanaged collection\");\n\n if (snapshot.migrationId === null && snapshot.parentMigrationId !== null)\n throw new Error(\"Invalid baseline parent\");\n\n if (snapshot.migrationId !== null) validateMigrationId(snapshot.migrationId);\n if (snapshot.parentMigrationId !== null) validateMigrationId(snapshot.parentMigrationId);\n}\n\nexport function validateMigrationId(id: string): void {\n if (typeof id != \"string\" || !/^\\d{17}_[a-z0-9]+(?:_[a-z0-9]+)*$/.test(id))\n throw new Error(`Invalid migration ID: ${id}`);\n}\n","import {\n type CollectionDefinition,\n type DocumentRecord,\n type FieldDefinition,\n type ForeignKeyDefinition,\n type SecondaryIndexDefinition,\n type Transaction,\n indexFields,\n} from \"@duraxis/core\";\n\nexport class SchemaEditor {\n readonly #tx: Transaction;\n\n public constructor(tx: Transaction) {\n this.#tx = tx;\n }\n\n public inspect(): readonly CollectionDefinition[] {\n return this.#tx.getCollectionDefinitions();\n }\n\n public definition(name: string): CollectionDefinition {\n const result = this.inspect().find((schema) => schema.name == name);\n if (!result) throw new Error(`Unknown collection: ${name}`);\n return result;\n }\n\n public createCollection(definition: CollectionDefinition): void {\n this.#tx.defineCollection(definition);\n }\n\n public createCollections(definitions: readonly CollectionDefinition[]): void {\n this.#tx.defineCollections(definitions);\n }\n\n public alterCollection(name: string, definition: CollectionDefinition): void {\n this.#tx.alterCollection(name, definition);\n }\n\n public dropCollection(name: string): void {\n this.#tx.dropCollection(name);\n }\n\n public addField(collection: string, name: string, definition: FieldDefinition): void {\n const schema = this.definition(collection);\n\n if (Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Field already exists: ${name}`);\n\n this.alterCollection(collection, {\n ...schema,\n fields: { ...schema.fields, [name]: definition },\n });\n }\n\n public alterField(collection: string, name: string, definition: FieldDefinition): void {\n const schema = this.definition(collection);\n\n if (!Object.hasOwn(schema.fields ?? {}, name)) throw new Error(`Unknown field: ${name}`);\n\n this.alterCollection(collection, {\n ...schema,\n fields: { ...schema.fields, [name]: definition },\n });\n }\n\n public async removeField(\n collection: string,\n name: string,\n options: { strategy: \"reject-if-populated\" | \"delete-values\" },\n ): Promise<void> {\n const schema = this.definition(collection);\n const fields = { ...schema.fields };\n\n if (!Object.hasOwn(fields, name)) throw new Error(`Unknown field: ${name}`);\n\n if (\n schema.indexes.some((index) => indexFields(index).some((part) => part.field == name)) ||\n schema.foreignKeys?.some((key) => key.field == name)\n )\n throw new Error(\"Remove dependent indexes and foreign keys first\");\n\n delete fields[name];\n\n if (options.strategy == \"reject-if-populated\") {\n for await (const row of this.#tx.scanCollection(collection))\n if (Object.hasOwn(row.document, name))\n throw new Error(`Field is populated: ${collection}/${name}`);\n } else if (options.strategy != \"delete-values\")\n throw new Error(\"Explicit field removal strategy required\");\n\n this.alterCollection(collection, { ...schema, fields });\n\n if (options.strategy == \"delete-values\")\n for await (const row of this.#tx.scanCollection(collection)) {\n const document = { ...row.document };\n\n delete document[name];\n this.#tx.putDocument(collection, row.id, document);\n }\n }\n\n public async renameField(collection: string, from: string, to: string): Promise<void> {\n const schema = this.definition(collection);\n\n const fields = { ...schema.fields };\n\n if (!Object.hasOwn(fields, from) || Object.hasOwn(fields, to))\n throw new Error(\"Invalid field rename\");\n\n for await (const row of this.#tx.scanCollection(collection))\n if (Object.hasOwn(row.document, to)) throw new Error(`Rename would overwrite ${to}`);\n\n fields[to] = fields[from]!;\n\n delete fields[from];\n\n this.alterCollection(collection, {\n ...schema,\n fields,\n indexes: schema.indexes.map((index) => ({\n name: index.name,\n unique: index.unique,\n fields: indexFields(index).map((part) => ({\n ...part,\n field: part.field == from ? to : part.field,\n })),\n })),\n foreignKeys: schema.foreignKeys?.map((key) => ({\n ...key,\n field: key.field == from ? to : key.field,\n })),\n });\n\n for await (const row of this.#tx.scanCollection(collection)) {\n const document = { ...row.document };\n\n if (Object.hasOwn(document, from)) {\n document[to] = document[from];\n delete document[from];\n }\n\n this.#tx.putDocument(collection, row.id, document);\n }\n }\n\n public addIndex(collection: string, index: SecondaryIndexDefinition): void {\n this.#tx.addIndex(collection, index);\n }\n\n public removeIndex(collection: string, name: string): void {\n this.#tx.removeIndex(collection, name);\n }\n\n public addForeignKey(collection: string, definition: ForeignKeyDefinition): void {\n const schema = this.definition(collection);\n if (schema.foreignKeys?.some((key) => key.name == definition.name))\n throw new Error(\"Foreign key already exists\");\n this.alterCollection(collection, {\n ...schema,\n foreignKeys: [...(schema.foreignKeys ?? []), definition],\n });\n }\n\n public removeForeignKey(collection: string, name: string): void {\n const schema = this.definition(collection);\n\n if (!schema.foreignKeys?.some((key) => key.name == name))\n throw new Error(\"Unknown foreign key\");\n\n this.alterCollection(collection, {\n ...schema,\n foreignKeys: schema.foreignKeys.filter((key) => key.name != name),\n });\n }\n}\n\nexport interface MigrationContext {\n readonly schema: SchemaEditor;\n readonly get: Transaction[\"getDocument\"];\n readonly scan: Transaction[\"scanCollection\"];\n readonly put: Transaction[\"putDocument\"];\n readonly delete: Transaction[\"deleteDocument\"];\n transform(\n collection: string,\n transform: (document: DocumentRecord, id: string) => DocumentRecord | Promise<DocumentRecord>,\n ): Promise<void>;\n}\n\nexport function createMigrationContext(tx: Transaction): MigrationContext {\n return Object.freeze({\n schema: new SchemaEditor(tx),\n get: tx.getDocument.bind(tx),\n scan: tx.scanCollection.bind(tx),\n put: tx.putDocument.bind(tx),\n delete: tx.deleteDocument.bind(tx),\n async transform(\n collection: string,\n transform: (document: DocumentRecord, id: string) => DocumentRecord | Promise<DocumentRecord>,\n ) {\n for await (const row of tx.scanCollection(collection))\n tx.putDocument(collection, row.id, await transform(row.document, row.id));\n },\n });\n}\n","import type {\n CollectionDefinition,\n FieldDefinition,\n ForeignKeyDefinition,\n SecondaryIndexDefinition,\n} from \"@duraxis/core\";\nimport type { MigrationContext } from \"./context.js\";\nimport { canonicalJSON, canonicalSchema, schemaHash } from \"./schema.js\";\n\nexport type MigrationRisk =\n \"safe\" | \"requires-validation\" | \"requires-data-transformation\" | \"destructive\";\n\ninterface Change<K extends string, T> {\n readonly kind: K;\n readonly collection: string;\n readonly name: string;\n readonly before: T | null;\n readonly after: T | null;\n readonly risk: MigrationRisk;\n}\n\nexport type MigrationOperation =\n | Change<\"collection\", CollectionDefinition>\n | Change<\"field\", FieldDefinition>\n | Change<\"index\", SecondaryIndexDefinition>\n | Change<\"foreign-key\", ForeignKeyDefinition>\n | Change<\"additional-fields\", boolean>;\n\nexport interface SchemaPlan {\n readonly before: readonly CollectionDefinition[];\n readonly after: readonly CollectionDefinition[];\n readonly operations: readonly MigrationOperation[];\n}\n\nfunction fieldRisk(before: FieldDefinition | null, after: FieldDefinition | null): MigrationRisk {\n if (!after) return \"destructive\";\n\n if (!before) return after.required ? \"requires-data-transformation\" : \"safe\";\n\n if (before.type != after.type || (!before.required && after.required))\n return \"requires-data-transformation\";\n\n if (before.nullable && !after.nullable) return \"requires-validation\";\n\n return \"safe\";\n}\n\nexport function diffSchemas(\n before: readonly CollectionDefinition[],\n after: readonly CollectionDefinition[],\n): SchemaPlan {\n const previous = canonicalSchema(before);\n const next = canonicalSchema(after);\n\n const left = new Map(previous.map((schema) => [schema.name, schema]));\n const right = new Map(next.map((schema) => [schema.name, schema]));\n\n const operations: MigrationOperation[] = [];\n\n for (const name of [...new Set([...left.keys(), ...right.keys()])].sort()) {\n const a = left.get(name);\n const b = right.get(name);\n\n if (!a || !b) {\n operations.push({\n kind: \"collection\",\n collection: name,\n name,\n before: a ?? null,\n after: b ?? null,\n risk: b ? \"requires-validation\" : \"destructive\",\n });\n\n continue;\n }\n\n if ((a.fields == null) != (b.fields == null))\n operations.push({\n kind: \"collection\",\n collection: name,\n name,\n before: a,\n after: b,\n risk: \"requires-validation\",\n });\n\n const fields = new Set([...Object.keys(a.fields ?? {}), ...Object.keys(b.fields ?? {})]);\n\n for (const field of [...fields].sort()) {\n const from = a.fields?.[field] ?? null;\n const to = b.fields?.[field] ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"field\",\n collection: name,\n name: field,\n before: from,\n after: to,\n risk: fieldRisk(from, to),\n });\n }\n\n if (a.allowAdditionalFields != b.allowAdditionalFields)\n operations.push({\n kind: \"additional-fields\",\n collection: name,\n name,\n before: a.allowAdditionalFields ?? true,\n after: b.allowAdditionalFields ?? true,\n risk: b.allowAdditionalFields ? \"safe\" : \"requires-validation\",\n });\n\n for (const index of [\n ...new Set([...a.indexes, ...b.indexes].map((index) => index.name)),\n ].sort()) {\n const from = a.indexes.find((item) => item.name == index) ?? null;\n const to = b.indexes.find((item) => item.name == index) ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"index\",\n collection: name,\n name: index,\n before: from,\n after: to,\n risk: to?.unique ? \"requires-validation\" : \"safe\",\n });\n }\n\n for (const key of [\n ...new Set([...(a.foreignKeys ?? []), ...(b.foreignKeys ?? [])].map((key) => key.name)),\n ].sort()) {\n const from = a.foreignKeys?.find((item) => item.name == key) ?? null;\n const to = b.foreignKeys?.find((item) => item.name == key) ?? null;\n\n if (canonicalJSON(from) != canonicalJSON(to))\n operations.push({\n kind: \"foreign-key\",\n collection: name,\n name: key,\n before: from,\n after: to,\n risk: to ? \"requires-validation\" : \"safe\",\n });\n }\n }\n\n return { before: previous, after: next, operations };\n}\n\nexport async function applySchemaPlan(context: MigrationContext, plan: SchemaPlan): Promise<void> {\n const names = new Set([...plan.before, ...plan.after].map((schema) => schema.name));\n\n if (\n schemaHash(context.schema.inspect().filter((schema) => names.has(schema.name))) !=\n schemaHash(plan.before)\n )\n throw new Error(\"Schema plan predecessor mismatch\");\n\n for (const operation of plan.operations) {\n if (operation.risk == \"requires-data-transformation\")\n throw new Error(\n `Manual data transformation required: ${operation.collection}/${operation.name}`,\n );\n\n if (operation.kind == \"field\" && !operation.after)\n for await (const row of context.scan(operation.collection))\n if (Object.hasOwn(row.document, operation.name))\n throw new Error(\n `Cannot remove populated field: ${operation.collection}/${operation.name}; write an explicit transformation`,\n );\n }\n\n const old = new Set(plan.before.map((schema) => schema.name));\n const next = new Set(plan.after.map((schema) => schema.name));\n\n for (const schema of plan.before)\n if (!next.has(schema.name)) context.schema.dropCollection(schema.name);\n\n for (const schema of plan.after)\n if (old.has(schema.name)) context.schema.alterCollection(schema.name, schema);\n else context.schema.createCollection(schema);\n}\n","import { diffSchemas, type SchemaPlan } from \"./diff.js\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n CommitOutcomeUnknownError,\n TransactionConflictError,\n type DuraxisDatabase,\n type Transaction,\n} from \"@duraxis/core\";\nimport { createMigrationContext, type MigrationContext } from \"./context.js\";\nimport {\n canonicalJSON,\n schemaHash,\n validateMigrationId,\n validateSnapshot,\n type SchemaSnapshot,\n} from \"./schema.js\";\n\nexport interface DuraxisMigration {\n readonly id: string;\n up(context: MigrationContext): Promise<void> | void;\n down?(context: MigrationContext): Promise<void> | void;\n}\n\nexport function defineMigration<const T extends DuraxisMigration>(migration: T): T {\n validateMigrationId(migration.id);\n\n if (\n typeof migration.up != \"function\" ||\n (migration.down !== undefined && typeof migration.down != \"function\")\n )\n throw new Error(\"Invalid migration callbacks\");\n\n return Object.freeze(migration);\n}\n\nexport interface MigrationArtifact {\n readonly migration: DuraxisMigration;\n readonly checksum: string;\n readonly snapshot: SchemaSnapshot;\n}\n\nexport interface MigrationHistoryEntry {\n readonly id: string;\n readonly checksum: string;\n readonly appliedAt: string;\n readonly sequence: number;\n readonly schemaHash: string;\n readonly operationId: string;\n}\n\ninterface History {\n readonly formatVersion: 1;\n readonly revision: string;\n readonly entries: readonly MigrationHistoryEntry[];\n}\n\nconst namespace = \"migrations\";\nconst digest = /^sha256:[a-f0-9]{64}$/;\n\nasync function readHistory(tx: Transaction): Promise<History> {\n const bytes = await tx.getMetadata(namespace);\n\n if (bytes == null) return { formatVersion: 1, revision: \"\", entries: [] };\n const history: History = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\n if (\n history.formatVersion !== 1 ||\n !Array.isArray(history.entries) ||\n typeof history.revision != \"string\"\n )\n throw new Error(\"Invalid migration history\");\n\n history.entries.forEach((entry, index) => {\n validateMigrationId(entry.id);\n\n if (\n entry.sequence != index + 1 ||\n !digest.test(entry.checksum) ||\n !digest.test(entry.schemaHash) ||\n typeof entry.operationId != \"string\" ||\n !Number.isFinite(Date.parse(entry.appliedAt)) ||\n (index && history.entries[index - 1]!.id >= entry.id)\n )\n throw new Error(\"Invalid migration history ordering or metadata\");\n });\n\n return history;\n}\n\nfunction writeHistory(tx: Transaction, history: History): void {\n tx.putMetadata(namespace, new TextEncoder().encode(canonicalJSON(history)));\n}\n\nexport function validateArtifacts(artifacts: readonly MigrationArtifact[]): void {\n let parent: string | null = null;\n\n for (const artifact of artifacts) {\n defineMigration(artifact.migration);\n validateSnapshot(artifact.snapshot);\n\n if (!digest.test(artifact.checksum)) throw new Error(\"Invalid artifact checksum\");\n\n if (\n artifact.snapshot.migrationId != artifact.migration.id ||\n artifact.snapshot.parentMigrationId != parent ||\n (parent && parent >= artifact.migration.id)\n )\n throw new Error(\"Duplicate, unordered, or divergent migration chain\");\n\n parent = artifact.migration.id;\n }\n}\n\nexport interface RunOptions {\n readonly steps?: number;\n readonly to?: string;\n readonly allowDestructive?: boolean;\n}\n\nexport class MigrationRunner {\n private readonly managedNames: ReadonlySet<string>;\n\n public constructor(\n private readonly database: DuraxisDatabase,\n private readonly artifacts: readonly MigrationArtifact[],\n ) {\n validateArtifacts(artifacts);\n\n this.managedNames = new Set(\n artifacts.flatMap((artifact) => artifact.snapshot.collections.map((schema) => schema.name)),\n );\n }\n\n private async validate(tx: Transaction, checkSchema = true): Promise<History> {\n const history = await readHistory(tx);\n\n history.entries.forEach((entry, index) => {\n const artifact = this.artifacts[index];\n\n if (!artifact || artifact.migration.id != entry.id)\n throw new Error(`Missing migration or divergent history: ${entry.id}`);\n\n if (artifact.checksum != entry.checksum)\n throw new Error(`Applied migration checksum mismatch: ${entry.id}`);\n\n if (artifact.snapshot.schemaHash != entry.schemaHash)\n throw new Error(`Applied snapshot mismatch: ${entry.id}`);\n });\n\n const expected = history.entries.at(-1)?.schemaHash ?? schemaHash([]);\n\n if (\n checkSchema &&\n schemaHash(\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n ) != expected\n )\n throw new Error(\"Database schema drift detected\");\n\n return history;\n }\n\n public async status(): Promise<{\n applied: readonly MigrationHistoryEntry[];\n pending: readonly string[];\n }> {\n return this.database.transaction(async (tx) => {\n const history = await this.validate(tx);\n\n return {\n applied: history.entries,\n pending: this.artifacts\n .slice(history.entries.length)\n .map((artifact) => artifact.migration.id),\n };\n });\n }\n\n public async drift(): Promise<SchemaPlan> {\n return this.database.transaction(async (tx) => {\n const history = await this.validate(tx, false);\n\n return diffSchemas(\n this.artifacts[history.entries.length - 1]?.snapshot.collections ?? [],\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n );\n });\n }\n\n private validateOptions(options: RunOptions): void {\n if (options.steps !== undefined && (!Number.isSafeInteger(options.steps) || options.steps < 0))\n throw new Error(\"Invalid migration steps\");\n\n if (options.to && !this.artifacts.some((artifact) => artifact.migration.id == options.to))\n throw new Error(`Unknown migration target: ${options.to}`);\n\n if (options.to && options.steps !== undefined) throw new Error(\"Use either --steps or --to\");\n }\n\n public async up(options: RunOptions = {}): Promise<readonly string[]> {\n this.validateOptions(options);\n\n const status = await this.status();\n const selected = this.artifacts\n .slice(status.applied.length)\n .filter((artifact) => !options.to || artifact.migration.id <= options.to)\n .slice(0, options.steps ?? Infinity);\n\n const completed: string[] = [];\n\n for (const artifact of selected) {\n await this.execute(artifact, \"up\", options);\n completed.push(artifact.migration.id);\n }\n\n return completed;\n }\n\n public async down(options: RunOptions = {}): Promise<readonly string[]> {\n this.validateOptions(options);\n\n if (!options.allowDestructive)\n throw new Error(\"Rollback requires explicit destructive authorization\");\n\n const status = await this.status();\n\n if (options.to && !status.applied.some((entry) => entry.id == options.to))\n throw new Error(\"Rollback target is not applied\");\n\n const selected = this.artifacts\n .slice(0, status.applied.length)\n .reverse()\n .filter((artifact) => !options.to || artifact.migration.id > options.to)\n .slice(0, options.steps ?? (options.to ? Infinity : 1));\n\n for (const artifact of selected)\n if (!artifact.migration.down)\n throw new Error(`Irreversible migration: ${artifact.migration.id}`);\n\n const completed: string[] = [];\n\n for (const artifact of selected) {\n await this.execute(artifact, \"down\", options);\n completed.push(artifact.migration.id);\n }\n\n return completed;\n }\n\n public async baseline(): Promise<void> {\n if (this.artifacts.length != 1)\n throw new Error(\"Baseline requires exactly one initial artifact\");\n\n const artifact = this.artifacts[0]!;\n const operationId = randomUUID();\n\n try {\n await this.database.transaction(async (tx) => {\n const history = await readHistory(tx);\n if (history.entries.length) throw new Error(\"Database already has migration history\");\n\n this.assertSchema(tx, artifact.snapshot);\n\n writeHistory(tx, {\n formatVersion: 1,\n revision: operationId,\n entries: [this.entry(artifact, 1, operationId)],\n });\n });\n } catch (error) {\n await this.reconcile(error, operationId, \"up\", artifact);\n }\n }\n\n private entry(\n artifact: MigrationArtifact,\n sequence: number,\n operationId: string,\n ): MigrationHistoryEntry {\n return {\n id: artifact.migration.id,\n checksum: artifact.checksum,\n schemaHash: artifact.snapshot.schemaHash,\n appliedAt: new Date().toISOString(),\n sequence,\n operationId,\n };\n }\n\n private assertSchema(tx: Transaction, snapshot?: SchemaSnapshot): void {\n if (\n schemaHash(\n tx.getCollectionDefinitions().filter((schema) => this.managedNames.has(schema.name)),\n ) != (snapshot?.schemaHash ?? schemaHash([]))\n )\n throw new Error(\"Migration result does not match expected snapshot\");\n }\n\n private async execute(\n artifact: MigrationArtifact,\n direction: \"up\" | \"down\",\n options: RunOptions,\n ): Promise<void> {\n const operationId = randomUUID();\n try {\n await this.database.transaction(async (tx) => {\n const history = await this.validate(tx);\n const index = this.artifacts.indexOf(artifact);\n\n if (direction == \"up\" && history.entries[index]?.id == artifact.migration.id) return;\n if ((direction == \"up\" ? history.entries.length : history.entries.length - 1) != index)\n throw new Error(\"Migration predecessor changed\");\n\n const before = tx.getCollectionDefinitions();\n\n await (direction == \"up\" ? artifact.migration.up : artifact.migration.down!)(\n createMigrationContext(tx),\n );\n\n const after = new Map(tx.getCollectionDefinitions().map((schema) => [schema.name, schema]));\n\n if (\n !options.allowDestructive &&\n before.some(\n (schema) =>\n !after.has(schema.name) ||\n Object.keys(schema.fields ?? {}).some(\n (name) => !Object.hasOwn(after.get(schema.name)?.fields ?? {}, name),\n ),\n )\n )\n throw new Error(\"Destructive schema change requires explicit authorization\");\n\n if (\n schemaHash(before.filter((schema) => !this.managedNames.has(schema.name))) !=\n schemaHash([...after.values()].filter((schema) => !this.managedNames.has(schema.name)))\n )\n throw new Error(\"Migration changed collections outside its snapshots\");\n\n this.assertSchema(\n tx,\n direction == \"up\" ? artifact.snapshot : this.artifacts[index - 1]?.snapshot,\n );\n\n writeHistory(tx, {\n formatVersion: 1,\n revision: operationId,\n entries:\n direction == \"up\"\n ? [...history.entries, this.entry(artifact, index + 1, operationId)]\n : history.entries.slice(0, -1),\n });\n });\n } catch (error) {\n await this.reconcile(error, operationId, direction, artifact);\n }\n }\n\n private async reconcile(\n error: unknown,\n operationId: string,\n direction: \"up\" | \"down\",\n artifact: MigrationArtifact,\n ): Promise<void> {\n if (\n !(error instanceof TransactionConflictError) &&\n !(error instanceof CommitOutcomeUnknownError)\n )\n throw error;\n\n const history = await this.database.transaction((tx) => this.validate(tx));\n\n if (\n history.revision == operationId ||\n (direction == \"up\" &&\n history.entries.some(\n (entry) => entry.id == artifact.migration.id && entry.checksum == artifact.checksum,\n ))\n )\n return;\n\n if (\n error instanceof CommitOutcomeUnknownError &&\n (await this.database.getCommitStatus(error.transactionId)) == \"committed\"\n )\n return;\n\n throw error;\n }\n}\n"],"mappings":";;;;AAGA,SAAgB,cAAc,OAAwB;CACpD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,aAAa,CAAC,CAAC,KAAK,GAAG,EAAE;CAExE,IAAI,SAAS,OAAO,SAAS,UAC3B,OAAO,IAAI,OAAO,QAAQ,KAAK,CAAC,CAC7B,QAAQ,GAAG,OAAO,MAAM,KAAA,CAAS,CAAC,CAClC,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAChD,KAAK,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,cAAc,CAAC,GAAG,CAAC,CAC3D,KAAK,GAAG,EAAE;CAEf,MAAM,OAAO,KAAK,UAAU,KAAK;CAEjC,IAAI,SAAS,KAAA,GAAW,MAAM,IAAI,MAAM,uBAAuB;CAE/D,OAAO;AACT;AAEA,SAAgB,SAAS,OAAuB;CAC9C,OAAO,WAAA,GAAUA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAClE;AAEA,SAAgB,gBACd,aACiC;CACjC,MAAM,wBAAQ,IAAI,IAAY;CAE9B,OAAO,YACJ,KAAK,eAAe;EACnB,IAAI,MAAM,IAAI,WAAW,IAAI,GAAG,MAAM,IAAI,MAAM,yBAAyB,WAAW,MAAM;EAE1F,MAAM,IAAI,WAAW,IAAI;EAEzB,MAAM,UAAA,GAASC,cAAAA,oBAAAA,CAAoB,UAAU;EAE7C,OAAO;GACL,GAAG;GACH,SAAS,CAAC,GAAG,OAAO,OAAO,CA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