@duraxis/cli 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 +244 -2
- package/dist/artifacts.d.ts +17 -0
- package/dist/bin.js +3 -0
- package/dist/cli.d.ts +6 -0
- package/dist/config.d.ts +22 -0
- package/dist/index.cjs +494 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +469 -0
- package/dist/index.js.map +1 -0
- package/dist/ts-loader.mjs +43 -0
- package/package.json +65 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
// \0rolldown/runtime.js
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
13
|
+
get: ((k) => from[k]).bind(null, key),
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
|
+
value: mod,
|
|
21
|
+
enumerable: true
|
|
22
|
+
}) : target, mod));
|
|
23
|
+
let node_util = require("node:util");
|
|
24
|
+
let node_fs_promises = require("node:fs/promises");
|
|
25
|
+
let node_path = require("node:path");
|
|
26
|
+
let _duraxis_orm = require("@duraxis/orm");
|
|
27
|
+
let _duraxis_migrations = require("@duraxis/migrations");
|
|
28
|
+
let node_url = require("node:url");
|
|
29
|
+
let node_crypto = require("node:crypto");
|
|
30
|
+
let typescript = require("typescript");
|
|
31
|
+
typescript = __toESM(typescript, 1);
|
|
32
|
+
// src/config.ts
|
|
33
|
+
function defineDuraxisConfig(config) {
|
|
34
|
+
return config;
|
|
35
|
+
}
|
|
36
|
+
async function importFile(path) {
|
|
37
|
+
return import((0, node_url.pathToFileURL)(path).href);
|
|
38
|
+
}
|
|
39
|
+
async function loadConfig(cwd, explicit, database) {
|
|
40
|
+
let path;
|
|
41
|
+
if (explicit) path = (0, node_path.resolve)(cwd, explicit);
|
|
42
|
+
else {
|
|
43
|
+
let directory = (0, node_path.resolve)(cwd);
|
|
44
|
+
while (true) {
|
|
45
|
+
for (const name of [
|
|
46
|
+
"duraxis.config.ts",
|
|
47
|
+
"duraxis.config.js",
|
|
48
|
+
"duraxis.config.mjs"
|
|
49
|
+
]) {
|
|
50
|
+
const candidate = (0, node_path.resolve)(directory, name);
|
|
51
|
+
try {
|
|
52
|
+
await (0, node_fs_promises.access)(candidate);
|
|
53
|
+
path = candidate;
|
|
54
|
+
break;
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error.code != "ENOENT") throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (path || (0, node_path.dirname)(directory) == directory) break;
|
|
60
|
+
directory = (0, node_path.dirname)(directory);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!path) throw new Error("No duraxis.config.ts or JavaScript configuration found");
|
|
64
|
+
const base = (await importFile(path)).default;
|
|
65
|
+
const config = database ? base?.databases?.[database] : base;
|
|
66
|
+
if (!config || typeof config.createDatabase != "function" || !Array.isArray(config.entities) && typeof config.entities != "function" || typeof config.migrations?.directory != "string" || typeof config.migrations.snapshots != "string" || config.migrations.format !== void 0 && !["ts", "js"].includes(config.migrations.format)) throw new Error("Invalid Duraxis configuration or unknown named database");
|
|
67
|
+
return {
|
|
68
|
+
config,
|
|
69
|
+
root: (0, node_path.dirname)(path),
|
|
70
|
+
path
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
async function readJSON(path) {
|
|
74
|
+
return JSON.parse(await (0, node_fs_promises.readFile)(path, "utf8"));
|
|
75
|
+
}
|
|
76
|
+
// src/artifacts.ts
|
|
77
|
+
function artifactChecksum(source) {
|
|
78
|
+
const options = { compilerOptions: {
|
|
79
|
+
target: typescript.default.ScriptTarget.ES2022,
|
|
80
|
+
module: typescript.default.ModuleKind.ESNext,
|
|
81
|
+
removeComments: true,
|
|
82
|
+
newLine: typescript.default.NewLineKind.LineFeed,
|
|
83
|
+
experimentalDecorators: true,
|
|
84
|
+
emitDecoratorMetadata: true,
|
|
85
|
+
useDefineForClassFields: false
|
|
86
|
+
} };
|
|
87
|
+
const first = typescript.default.transpileModule(source, options).outputText;
|
|
88
|
+
return (0, _duraxis_migrations.checksum)(typescript.default.transpileModule(first, options).outputText);
|
|
89
|
+
}
|
|
90
|
+
async function loadArtifacts(config, root, ownsLock = false, omitLatest = false) {
|
|
91
|
+
const directory = (0, node_path.resolve)(root, config.migrations.directory);
|
|
92
|
+
const snapshots = (0, node_path.resolve)(root, config.migrations.snapshots);
|
|
93
|
+
if (!ownsLock) try {
|
|
94
|
+
await (0, node_fs_promises.access)((0, node_path.join)(directory, ".duraxis-artifacts.lock"));
|
|
95
|
+
throw new Error("Artifact update in progress or stale guard; inspect artifacts before removing the guard");
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error.code != "ENOENT") throw error;
|
|
98
|
+
}
|
|
99
|
+
const files = (await (0, node_fs_promises.readdir)(directory)).filter((file) => /\.(ts|js|mjs)$/.test(file) && !file.endsWith(".d.ts")).sort();
|
|
100
|
+
const artifacts = [];
|
|
101
|
+
const ids = /* @__PURE__ */ new Set();
|
|
102
|
+
for (const file of files) {
|
|
103
|
+
const id = file.replace(/\.(ts|js|mjs)$/, "");
|
|
104
|
+
(0, _duraxis_migrations.validateMigrationId)(id);
|
|
105
|
+
if (ids.has(id)) throw new Error(`Duplicate migration filename: ${id}`);
|
|
106
|
+
ids.add(id);
|
|
107
|
+
if (omitLatest && file == files.at(-1)) continue;
|
|
108
|
+
const source = await (0, node_fs_promises.readFile)((0, node_path.join)(directory, file), "utf8");
|
|
109
|
+
const module = await importFile((0, node_path.join)(directory, file));
|
|
110
|
+
if (module.default?.id != id) throw new Error(`Migration ID does not match filename: ${file}`);
|
|
111
|
+
const snapshot = await readJSON((0, node_path.join)(snapshots, `${id}.json`));
|
|
112
|
+
(0, _duraxis_migrations.validateSnapshot)(snapshot);
|
|
113
|
+
artifacts.push({
|
|
114
|
+
migration: module.default,
|
|
115
|
+
checksum: artifactChecksum(source),
|
|
116
|
+
snapshot
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
const expected = new Set([...ids].map((id) => `${id}.json`));
|
|
120
|
+
for (const file of await (0, node_fs_promises.readdir)(snapshots)) if (file.endsWith(".json") && file != "baseline.json" && !expected.has(file)) throw new Error(`Orphaned snapshot: ${file}`);
|
|
121
|
+
const initial = await readJSON((0, node_path.join)(snapshots, "baseline.json"));
|
|
122
|
+
(0, _duraxis_migrations.validateSnapshot)(initial);
|
|
123
|
+
if (initial.migrationId !== null || initial.parentMigrationId !== null || initial.collections.length) throw new Error("Invalid empty baseline snapshot");
|
|
124
|
+
(0, _duraxis_migrations.validateArtifacts)(artifacts);
|
|
125
|
+
return {
|
|
126
|
+
artifacts,
|
|
127
|
+
files,
|
|
128
|
+
snapshots,
|
|
129
|
+
directory
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function migrationId(name, previous) {
|
|
133
|
+
if (name.includes("..") || /[\\/]/.test(name)) throw new Error("Migration names cannot contain paths");
|
|
134
|
+
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
135
|
+
if (!slug || slug.length > 64) throw new Error("Invalid migration name");
|
|
136
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "");
|
|
137
|
+
const previousStamp = previous?.slice(0, 17);
|
|
138
|
+
return `${previousStamp && previousStamp >= stamp ? (BigInt(previousStamp) + 1n).toString().padStart(17, "0") : stamp}_${slug}`;
|
|
139
|
+
}
|
|
140
|
+
function literal(value) {
|
|
141
|
+
return JSON.stringify(value, null, 2).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
142
|
+
}
|
|
143
|
+
function renderMigration(id, plan) {
|
|
144
|
+
if (!plan) return `import { defineMigration } from "@duraxis/migrations";\n\nexport default defineMigration({\n id: ${JSON.stringify(id)},\n async up(context) {\n throw new Error("Unfinished migration: implement up and provide its expected snapshot");\n },\n});\n`;
|
|
145
|
+
const inverse = (0, _duraxis_migrations.diffSchemas)(plan.after, plan.before);
|
|
146
|
+
const reversible = !plan.operations.some((operation) => operation.kind == "collection" && operation.after == null) && inverse.operations.every((operation) => operation.risk != "requires-data-transformation");
|
|
147
|
+
return `import { defineMigration, applySchemaPlan } from "@duraxis/migrations";\n\nexport default defineMigration({\n id: ${JSON.stringify(id)},\n async up(context) {\n await applySchemaPlan(context, ${literal(plan)});\n },\n${reversible ? ` async down(context) {\n${inverse.operations.filter((operation) => operation.kind == "collection" && operation.after == null).map((operation) => ` for await (const row of context.scan(${JSON.stringify(operation.collection)})) throw new Error("Cannot drop a populated collection during generated rollback");\n`).join("")} await applySchemaPlan(context, ${literal(inverse)});\n },\n` : " // Irreversible automatically: write an explicit data-safe down() if needed.\n"} });\n`;
|
|
148
|
+
}
|
|
149
|
+
async function withArtifactLock(directory, callback) {
|
|
150
|
+
await (0, node_fs_promises.mkdir)(directory, { recursive: true });
|
|
151
|
+
const lock = (0, node_path.join)(directory, ".duraxis-artifacts.lock");
|
|
152
|
+
await (0, node_fs_promises.writeFile)(lock, (0, _duraxis_migrations.canonicalJSON)({
|
|
153
|
+
pid: process.pid,
|
|
154
|
+
purpose: "artifact update; inspect files before removing a stale guard"
|
|
155
|
+
}), { flag: "wx" });
|
|
156
|
+
try {
|
|
157
|
+
return await callback();
|
|
158
|
+
} finally {
|
|
159
|
+
await (0, node_fs_promises.unlink)(lock);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async function writePair(migrationPath, source, snapshotPath, snapshot) {
|
|
163
|
+
await (0, node_fs_promises.mkdir)((0, node_path.resolve)(snapshotPath, ".."), { recursive: true });
|
|
164
|
+
await (0, node_fs_promises.writeFile)(migrationPath, source, { flag: "wx" });
|
|
165
|
+
try {
|
|
166
|
+
await (0, node_fs_promises.writeFile)(snapshotPath, JSON.stringify(snapshot, null, 2) + "\n", { flag: "wx" });
|
|
167
|
+
} catch (error) {
|
|
168
|
+
await (0, node_fs_promises.unlink)(migrationPath);
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
async function removePair(migrationPath, snapshotPath) {
|
|
173
|
+
const suffix = `.removing-${(0, node_crypto.randomBytes)(6).toString("hex")}`;
|
|
174
|
+
await (0, node_fs_promises.rename)(migrationPath, migrationPath + suffix);
|
|
175
|
+
try {
|
|
176
|
+
await (0, node_fs_promises.rename)(snapshotPath, snapshotPath + suffix);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
await (0, node_fs_promises.rename)(migrationPath + suffix, migrationPath);
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
await (0, node_fs_promises.unlink)(migrationPath + suffix);
|
|
182
|
+
await (0, node_fs_promises.unlink)(snapshotPath + suffix);
|
|
183
|
+
}
|
|
184
|
+
// src/cli.ts
|
|
185
|
+
var help = `duraxis <command> [options]
|
|
186
|
+
init
|
|
187
|
+
migration:create <name>
|
|
188
|
+
migration:generate <name> [--allow-destructive]
|
|
189
|
+
migration:snapshot --schema <collections.json>
|
|
190
|
+
migration:remove --yes
|
|
191
|
+
migration:baseline <name> --yes
|
|
192
|
+
migrate:up [--steps N | --to ID] [--dry-run] [--allow-destructive]
|
|
193
|
+
migrate:down [--steps N | --to ID] --yes
|
|
194
|
+
migrate:status
|
|
195
|
+
migrate:diff [--persisted]
|
|
196
|
+
migrate:check [--offline]
|
|
197
|
+
Options: --config PATH --database NAME --json
|
|
198
|
+
Rollback --to retains the target version. Dry-run is a static preview only.`;
|
|
199
|
+
async function withDatabase(config, callback) {
|
|
200
|
+
const database = await config.createDatabase();
|
|
201
|
+
try {
|
|
202
|
+
return await callback(database);
|
|
203
|
+
} finally {
|
|
204
|
+
await database.close({ closeStorage: true });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function summary(plan) {
|
|
208
|
+
return plan.operations.length ? plan.operations.map((operation) => `${operation.before == null ? "+" : operation.after == null ? "-" : "~"} ${operation.kind} ${operation.collection}/${operation.name} (${operation.risk})`).join("\n") : "No schema differences.";
|
|
209
|
+
}
|
|
210
|
+
async function init(cwd) {
|
|
211
|
+
const configPath = (0, node_path.resolve)(cwd, "duraxis.config.ts");
|
|
212
|
+
const base = (0, node_path.resolve)(cwd, "duraxis/snapshots/baseline.json");
|
|
213
|
+
for (const path of [configPath, base]) try {
|
|
214
|
+
await (0, node_fs_promises.access)(path);
|
|
215
|
+
throw new Error(`Refusing to overwrite ${path}`);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
if (error.code != "ENOENT") throw error;
|
|
218
|
+
}
|
|
219
|
+
await (0, node_fs_promises.mkdir)((0, node_path.resolve)(cwd, "duraxis/migrations"), { recursive: true });
|
|
220
|
+
await (0, node_fs_promises.mkdir)((0, node_path.resolve)(cwd, "duraxis/snapshots"), { recursive: true });
|
|
221
|
+
await (0, node_fs_promises.writeFile)(configPath, `import { defineDuraxisConfig } from "@duraxis/cli";
|
|
222
|
+
|
|
223
|
+
export default defineDuraxisConfig({
|
|
224
|
+
entities: [], // Import your decorated entity classes here.
|
|
225
|
+
migrations: { directory: "./duraxis/migrations", snapshots: "./duraxis/snapshots", format: "ts" },
|
|
226
|
+
async createDatabase() {
|
|
227
|
+
// Return a DuraxisDatabase configured with your storage driver.
|
|
228
|
+
// The CLI closes this database and its storage after every command.
|
|
229
|
+
throw new Error("Configure createDatabase() before accessing a database");
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
`, { flag: "wx" });
|
|
233
|
+
try {
|
|
234
|
+
await (0, node_fs_promises.writeFile)(base, JSON.stringify((0, _duraxis_migrations.createSnapshot)(null, null, []), null, 2) + "\n", { flag: "wx" });
|
|
235
|
+
} catch (error) {
|
|
236
|
+
await (0, node_fs_promises.unlink)(configPath);
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
async function runCLI(args, io = {}) {
|
|
241
|
+
const cwd = io.cwd ?? process.cwd();
|
|
242
|
+
const out = io.out ?? console.log;
|
|
243
|
+
const errorOut = io.error ?? console.error;
|
|
244
|
+
let jsonErrors = false;
|
|
245
|
+
try {
|
|
246
|
+
const { values, positionals } = (0, node_util.parseArgs)({
|
|
247
|
+
args: [...args],
|
|
248
|
+
allowPositionals: true,
|
|
249
|
+
strict: true,
|
|
250
|
+
options: {
|
|
251
|
+
config: { type: "string" },
|
|
252
|
+
database: { type: "string" },
|
|
253
|
+
json: { type: "boolean" },
|
|
254
|
+
steps: { type: "string" },
|
|
255
|
+
to: { type: "string" },
|
|
256
|
+
"dry-run": { type: "boolean" },
|
|
257
|
+
"allow-destructive": { type: "boolean" },
|
|
258
|
+
yes: { type: "boolean" },
|
|
259
|
+
offline: { type: "boolean" },
|
|
260
|
+
persisted: { type: "boolean" },
|
|
261
|
+
schema: { type: "string" },
|
|
262
|
+
help: { type: "boolean" }
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
jsonErrors = values.json ?? false;
|
|
266
|
+
const command = positionals[0];
|
|
267
|
+
const name = positionals[1];
|
|
268
|
+
if (!command || values.help) {
|
|
269
|
+
out(help);
|
|
270
|
+
return 0;
|
|
271
|
+
}
|
|
272
|
+
if (![
|
|
273
|
+
"init",
|
|
274
|
+
"migration:create",
|
|
275
|
+
"migration:generate",
|
|
276
|
+
"migration:snapshot",
|
|
277
|
+
"migration:remove",
|
|
278
|
+
"migration:baseline",
|
|
279
|
+
"migrate:up",
|
|
280
|
+
"migrate:down",
|
|
281
|
+
"migrate:status",
|
|
282
|
+
"migrate:diff",
|
|
283
|
+
"migrate:check"
|
|
284
|
+
].includes(command)) throw new Error(`Unknown command: ${command}`);
|
|
285
|
+
if (positionals.length > 2 || name && ![
|
|
286
|
+
"migration:create",
|
|
287
|
+
"migration:generate",
|
|
288
|
+
"migration:baseline"
|
|
289
|
+
].includes(command)) throw new Error("Unexpected positional arguments");
|
|
290
|
+
const allowed = {
|
|
291
|
+
init: [],
|
|
292
|
+
"migration:create": [],
|
|
293
|
+
"migration:generate": ["allow-destructive"],
|
|
294
|
+
"migration:snapshot": ["schema"],
|
|
295
|
+
"migration:remove": ["yes"],
|
|
296
|
+
"migration:baseline": ["yes"],
|
|
297
|
+
"migrate:up": [
|
|
298
|
+
"steps",
|
|
299
|
+
"to",
|
|
300
|
+
"dry-run",
|
|
301
|
+
"allow-destructive"
|
|
302
|
+
],
|
|
303
|
+
"migrate:down": [
|
|
304
|
+
"steps",
|
|
305
|
+
"to",
|
|
306
|
+
"yes"
|
|
307
|
+
],
|
|
308
|
+
"migrate:status": [],
|
|
309
|
+
"migrate:diff": ["persisted"],
|
|
310
|
+
"migrate:check": ["offline"]
|
|
311
|
+
};
|
|
312
|
+
for (const option of Object.keys(values)) if (![
|
|
313
|
+
"config",
|
|
314
|
+
"database",
|
|
315
|
+
"json",
|
|
316
|
+
"help",
|
|
317
|
+
...allowed[command]
|
|
318
|
+
].includes(option)) throw new Error(`Option --${option} is not supported by ${command}`);
|
|
319
|
+
if (command == "init") {
|
|
320
|
+
await init(cwd);
|
|
321
|
+
out("Initialized duraxis.config.ts and migration directories. Configure entities and createDatabase().");
|
|
322
|
+
return 0;
|
|
323
|
+
}
|
|
324
|
+
const { config, root } = await loadConfig(cwd, values.config, values.database);
|
|
325
|
+
const directory = (0, node_path.resolve)(root, config.migrations.directory);
|
|
326
|
+
const snapshots = (0, node_path.resolve)(root, config.migrations.snapshots);
|
|
327
|
+
const print = (value, text) => out(values.json ? JSON.stringify(value, null, 2) : text);
|
|
328
|
+
const entities = async () => (0, _duraxis_orm.exportSchema)(typeof config.entities == "function" ? await config.entities() : config.entities);
|
|
329
|
+
if (command == "migration:snapshot") {
|
|
330
|
+
if (!values.schema) throw new Error("Provide --schema with a JSON array of expected collection definitions");
|
|
331
|
+
await withArtifactLock(directory, async () => {
|
|
332
|
+
const { readdir } = await import("node:fs/promises");
|
|
333
|
+
const files = (await readdir(directory)).filter((file) => /\.(ts|js|mjs)$/.test(file) && !file.endsWith(".d.ts")).sort();
|
|
334
|
+
const latest = files.at(-1);
|
|
335
|
+
if (!latest) throw new Error("No manual migration found");
|
|
336
|
+
const id = latest.replace(/\.(ts|js|mjs)$/, "");
|
|
337
|
+
const parent = files.at(-2)?.replace(/\.(ts|js|mjs)$/, "") ?? null;
|
|
338
|
+
if (parent) {
|
|
339
|
+
if ((await readJSON((0, node_path.join)(snapshots, `${parent}.json`))).migrationId != parent) throw new Error("Invalid predecessor snapshot");
|
|
340
|
+
}
|
|
341
|
+
const definitions = await readJSON((0, node_path.resolve)(cwd, values.schema));
|
|
342
|
+
await (0, node_fs_promises.writeFile)((0, node_path.join)(snapshots, `${id}.json`), JSON.stringify((0, _duraxis_migrations.createSnapshot)(id, parent, definitions), null, 2) + "\n", { flag: "wx" });
|
|
343
|
+
});
|
|
344
|
+
out("Saved intended manual snapshot. migrate:up verifies the actual result atomically.");
|
|
345
|
+
return 0;
|
|
346
|
+
}
|
|
347
|
+
if ([
|
|
348
|
+
"migration:create",
|
|
349
|
+
"migration:generate",
|
|
350
|
+
"migration:baseline"
|
|
351
|
+
].includes(command)) {
|
|
352
|
+
if (!name) throw new Error("A migration name is required");
|
|
353
|
+
if (command == "migration:baseline" && !values.yes) throw new Error("Baseline adoption requires --yes");
|
|
354
|
+
await withArtifactLock(directory, async () => {
|
|
355
|
+
const local = await loadArtifacts(config, root, true);
|
|
356
|
+
const previous = local.artifacts.at(-1);
|
|
357
|
+
const id = migrationId(name, previous?.migration.id);
|
|
358
|
+
const migrationPath = (0, node_path.join)(directory, `${id}.${config.migrations.format ?? "ts"}`);
|
|
359
|
+
if (command == "migration:create") {
|
|
360
|
+
await (0, node_fs_promises.writeFile)(migrationPath, renderMigration(id), { flag: "wx" });
|
|
361
|
+
print({
|
|
362
|
+
id,
|
|
363
|
+
unfinished: true
|
|
364
|
+
}, `Created ${id}. Implement up(), then use migration:snapshot --schema <collections.json>.`);
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const desired = await entities();
|
|
368
|
+
const before = previous?.snapshot.collections ?? [];
|
|
369
|
+
const plan = (0, _duraxis_migrations.diffSchemas)(before, desired);
|
|
370
|
+
if (command == "migration:baseline" && local.artifacts.length) {
|
|
371
|
+
if (local.artifacts.length != 1) throw new Error("Baseline requires exactly one initial artifact");
|
|
372
|
+
const initial = local.artifacts[0];
|
|
373
|
+
const creation = (0, _duraxis_migrations.diffSchemas)([], desired);
|
|
374
|
+
if (initial.snapshot.schemaHash != (0, _duraxis_migrations.schemaHash)(desired) || initial.checksum != artifactChecksum(renderMigration(initial.migration.id, creation))) throw new Error("Existing baseline must be an unmodified generated initial-schema migration matching entities");
|
|
375
|
+
await withDatabase(config, (database) => new _duraxis_migrations.MigrationRunner(database, local.artifacts).baseline());
|
|
376
|
+
out(`Registered existing baseline ${initial.migration.id}`);
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
if (!plan.operations.length) {
|
|
380
|
+
print({ operations: [] }, "No schema differences.");
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
if (plan.operations.some((operation) => operation.risk == "requires-data-transformation")) throw new Error("Automatic generation requires a manual data transformation. Use migration:create and provide a snapshot.");
|
|
384
|
+
if (plan.operations.some((operation) => operation.risk == "destructive") && !values["allow-destructive"]) throw new Error("Destructive generation requires --allow-destructive");
|
|
385
|
+
const snapshot = (0, _duraxis_migrations.createSnapshot)(id, previous?.migration.id ?? null, desired);
|
|
386
|
+
if (command == "migration:baseline") await withDatabase(config, async (database) => {
|
|
387
|
+
const actual = await database.getCollectionDefinitions();
|
|
388
|
+
const names = new Set(desired.map((schema) => schema.name));
|
|
389
|
+
if ((0, _duraxis_migrations.schemaHash)(actual.filter((schema) => names.has(schema.name))) != snapshot.schemaHash) throw new Error("Persisted managed schema is incompatible with baseline");
|
|
390
|
+
await writePair(migrationPath, renderMigration(id, plan), (0, node_path.join)(snapshots, `${id}.json`), snapshot);
|
|
391
|
+
const loaded = await loadArtifacts(config, root, true);
|
|
392
|
+
await new _duraxis_migrations.MigrationRunner(database, loaded.artifacts).baseline();
|
|
393
|
+
});
|
|
394
|
+
else await writePair(migrationPath, renderMigration(id, plan), (0, node_path.join)(snapshots, `${id}.json`), snapshot);
|
|
395
|
+
print({
|
|
396
|
+
id,
|
|
397
|
+
operations: plan.operations
|
|
398
|
+
}, `Created ${id}\n${summary(plan)}`);
|
|
399
|
+
});
|
|
400
|
+
return 0;
|
|
401
|
+
}
|
|
402
|
+
if (command == "migration:remove") {
|
|
403
|
+
if (!values.yes) throw new Error("Removing the latest unpublished local migration requires --yes");
|
|
404
|
+
await withArtifactLock(directory, async () => {
|
|
405
|
+
const local = await loadArtifacts(config, root, true, true);
|
|
406
|
+
const latestFile = local.files.at(-1);
|
|
407
|
+
const latest = latestFile?.replace(/\.(ts|js|mjs)$/, "");
|
|
408
|
+
if (!latest) throw new Error("No local migration to remove");
|
|
409
|
+
await withDatabase(config, async (database) => {
|
|
410
|
+
if ((await new _duraxis_migrations.MigrationRunner(database, local.artifacts).status()).applied.some((entry) => entry.id == latest)) throw new Error("Cannot remove an applied migration");
|
|
411
|
+
const snapshotPath = (0, node_path.join)(snapshots, `${latest}.json`);
|
|
412
|
+
try {
|
|
413
|
+
await (0, node_fs_promises.access)(snapshotPath);
|
|
414
|
+
} catch (error) {
|
|
415
|
+
if (error.code != "ENOENT") throw error;
|
|
416
|
+
await (0, node_fs_promises.unlink)((0, node_path.join)(directory, latestFile));
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
await removePair((0, node_path.join)(directory, latestFile), snapshotPath);
|
|
420
|
+
});
|
|
421
|
+
out(`Removed ${latest}. This checks only the configured database; never remove shared or released migrations.`);
|
|
422
|
+
});
|
|
423
|
+
return 0;
|
|
424
|
+
}
|
|
425
|
+
const local = await loadArtifacts(config, root);
|
|
426
|
+
if (command == "migrate:diff" && !values.persisted) {
|
|
427
|
+
const plan = (0, _duraxis_migrations.diffSchemas)(local.artifacts.at(-1)?.snapshot.collections ?? [], await entities());
|
|
428
|
+
print(plan, summary(plan));
|
|
429
|
+
return 0;
|
|
430
|
+
}
|
|
431
|
+
if (command == "migrate:check" && values.offline) {
|
|
432
|
+
(0, _duraxis_migrations.validateArtifacts)(local.artifacts);
|
|
433
|
+
const plan = (0, _duraxis_migrations.diffSchemas)(local.artifacts.at(-1)?.snapshot.collections ?? [], await entities());
|
|
434
|
+
if (plan.operations.length) throw new Error(`Unrepresented entity changes:\n${summary(plan)}`);
|
|
435
|
+
print({
|
|
436
|
+
valid: true,
|
|
437
|
+
mode: "offline"
|
|
438
|
+
}, "Local files, snapshots, and entity schema are valid. Database history was not checked.");
|
|
439
|
+
return 0;
|
|
440
|
+
}
|
|
441
|
+
if (command == "migrate:up" && values["dry-run"]) {
|
|
442
|
+
const steps = values.steps === void 0 ? void 0 : Number(values.steps);
|
|
443
|
+
if (steps !== void 0 && (!Number.isSafeInteger(steps) || steps < 0)) throw new Error("Invalid steps");
|
|
444
|
+
if (values.to && (!local.artifacts.some((artifact) => artifact.migration.id == values.to) || steps !== void 0)) throw new Error("Invalid target or conflicting --steps");
|
|
445
|
+
const candidates = local.artifacts.filter((artifact) => !values.to || artifact.migration.id <= values.to).slice(0, steps ?? Infinity).map((artifact) => artifact.migration.id);
|
|
446
|
+
print({
|
|
447
|
+
dryRun: true,
|
|
448
|
+
appliedStateChecked: false,
|
|
449
|
+
candidates
|
|
450
|
+
}, `Static preview only; database was not opened and applied state was not checked. Migration callbacks were not executed.\n${candidates.join("\n")}`);
|
|
451
|
+
return 0;
|
|
452
|
+
}
|
|
453
|
+
await withDatabase(config, async (database) => {
|
|
454
|
+
const runner = new _duraxis_migrations.MigrationRunner(database, local.artifacts);
|
|
455
|
+
const options = {
|
|
456
|
+
...values.steps === void 0 ? {} : { steps: Number(values.steps) },
|
|
457
|
+
...values.to ? { to: values.to } : {},
|
|
458
|
+
allowDestructive: values["allow-destructive"] ?? false
|
|
459
|
+
};
|
|
460
|
+
if (command == "migrate:up") {
|
|
461
|
+
const applied = await runner.up(options);
|
|
462
|
+
print({ applied }, `Applied ${applied.length} migration(s).\n${applied.join("\n")}`);
|
|
463
|
+
} else if (command == "migrate:down") {
|
|
464
|
+
if (!values.yes) throw new Error("Rollback requires --yes; review backups and down() first");
|
|
465
|
+
const reverted = await runner.down({
|
|
466
|
+
...options,
|
|
467
|
+
allowDestructive: true
|
|
468
|
+
});
|
|
469
|
+
print({ reverted }, `Reverted ${reverted.length} migration(s).`);
|
|
470
|
+
} else if (command == "migrate:status") {
|
|
471
|
+
const status = await runner.status();
|
|
472
|
+
print(status, `Duraxis migration status\nDatabase: ${values.database ?? "default"}\n\nApplied:\n${status.applied.map((entry) => ` ${entry.id}`).join("\n")}\nPending:\n${status.pending.map((id) => ` ${id}`).join("\n")}\nSchema drift: none\n${status.applied.length} applied, ${status.pending.length} pending`);
|
|
473
|
+
} else if (command == "migrate:diff") {
|
|
474
|
+
const plan = await runner.drift();
|
|
475
|
+
print(plan, summary(plan));
|
|
476
|
+
} else if (command == "migrate:check") {
|
|
477
|
+
await runner.status();
|
|
478
|
+
const plan = (0, _duraxis_migrations.diffSchemas)(local.artifacts.at(-1)?.snapshot.collections ?? [], await entities());
|
|
479
|
+
if (plan.operations.length) throw new Error(`Unrepresented entity changes:\n${summary(plan)}`);
|
|
480
|
+
print({ valid: true }, "Migration files, snapshots, history, schema, and entities are valid.");
|
|
481
|
+
}
|
|
482
|
+
});
|
|
483
|
+
return 0;
|
|
484
|
+
} catch (error) {
|
|
485
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
486
|
+
errorOut(jsonErrors ? JSON.stringify({ error: message }) : message);
|
|
487
|
+
return 1;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
exports.defineDuraxisConfig = defineDuraxisConfig;
|
|
491
|
+
exports.loadConfig = loadConfig;
|
|
492
|
+
exports.runCLI = runCLI;
|
|
493
|
+
|
|
494
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["pathToFileURL","resolve","access","dirname","readFile","ts","checksum","resolve","access","join","readdir","readFile","diffSchemas","mkdir","writeFile","canonicalJSON","unlink","randomBytes","rename","resolve","access","mkdir","writeFile","createSnapshot","unlink","parseArgs","exportSchema","join","diffSchemas","schemaHash","MigrationRunner"],"sources":["../src/config.ts","../src/artifacts.ts","../src/cli.ts"],"sourcesContent":["import { access, readFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { DuraxisDatabase } from \"@duraxis/core\";\nimport type { EntityClass } from \"@duraxis/orm\";\n\nexport interface DuraxisConnectionConfig {\n readonly entities:\n readonly EntityClass[] | (() => readonly EntityClass[] | Promise<readonly EntityClass[]>);\n readonly migrations: {\n readonly directory: string;\n readonly snapshots: string;\n readonly format?: \"ts\" | \"js\";\n };\n readonly createDatabase: () => DuraxisDatabase | Promise<DuraxisDatabase>;\n}\n\nexport interface DuraxisConfig extends DuraxisConnectionConfig {\n readonly databases?: Readonly<Record<string, DuraxisConnectionConfig>>;\n}\n\nexport function defineDuraxisConfig<const T extends DuraxisConfig>(config: T): T {\n return config;\n}\n\nexport async function importFile(path: string): Promise<unknown> {\n return import(pathToFileURL(path).href);\n}\n\nexport async function loadConfig(\n cwd: string,\n explicit?: string,\n database?: string,\n): Promise<{ config: DuraxisConnectionConfig; root: string; path: string }> {\n let path: string | undefined;\n\n if (explicit) path = resolve(cwd, explicit);\n else {\n let directory = resolve(cwd);\n\n while (true) {\n for (const name of [\"duraxis.config.ts\", \"duraxis.config.js\", \"duraxis.config.mjs\"]) {\n const candidate = resolve(directory, name);\n\n try {\n await access(candidate);\n\n path = candidate;\n\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n }\n }\n\n if (path || dirname(directory) == directory) break;\n\n directory = dirname(directory);\n }\n }\n\n if (!path) throw new Error(\"No duraxis.config.ts or JavaScript configuration found\");\n\n const module = (await importFile(path)) as { default?: DuraxisConfig };\n\n const base = module.default;\n\n const config = database ? base?.databases?.[database] : base;\n\n if (\n !config ||\n typeof config.createDatabase != \"function\" ||\n (!Array.isArray(config.entities) && typeof config.entities != \"function\") ||\n typeof config.migrations?.directory != \"string\" ||\n typeof config.migrations.snapshots != \"string\" ||\n (config.migrations.format !== undefined && ![\"ts\", \"js\"].includes(config.migrations.format))\n )\n throw new Error(\"Invalid Duraxis configuration or unknown named database\");\n\n return { config, root: dirname(path), path };\n}\n\nexport async function readJSON<T>(path: string): Promise<T> {\n return JSON.parse(await readFile(path, \"utf8\")) as T;\n}\n","import { randomBytes } from \"node:crypto\";\nimport { access, mkdir, readdir, readFile, writeFile, unlink, rename } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport ts from \"typescript\";\nimport {\n checksum,\n canonicalJSON,\n createSnapshot,\n validateSnapshot,\n validateMigrationId,\n validateArtifacts,\n type DuraxisMigration,\n type MigrationArtifact,\n type SchemaSnapshot,\n type SchemaPlan,\n diffSchemas,\n} from \"@duraxis/migrations\";\nimport type { CollectionDefinition } from \"@duraxis/core\";\nimport { importFile, readJSON, type DuraxisConnectionConfig } from \"./config.js\";\n\nexport function artifactChecksum(source: string): string {\n const options: ts.TranspileOptions = {\n compilerOptions: {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.ESNext,\n removeComments: true,\n newLine: ts.NewLineKind.LineFeed,\n experimentalDecorators: true,\n emitDecoratorMetadata: true,\n useDefineForClassFields: false,\n },\n };\n\n const first = ts.transpileModule(source, options).outputText;\n\n return checksum(ts.transpileModule(first, options).outputText);\n}\n\nexport interface LocalArtifacts {\n readonly artifacts: readonly MigrationArtifact[];\n readonly files: readonly string[];\n readonly snapshots: string;\n readonly directory: string;\n}\n\nexport async function loadArtifacts(\n config: DuraxisConnectionConfig,\n root: string,\n ownsLock = false,\n omitLatest = false,\n): Promise<LocalArtifacts> {\n const directory = resolve(root, config.migrations.directory);\n const snapshots = resolve(root, config.migrations.snapshots);\n\n if (!ownsLock)\n try {\n await access(join(directory, \".duraxis-artifacts.lock\"));\n throw new Error(\n \"Artifact update in progress or stale guard; inspect artifacts before removing the guard\",\n );\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n }\n\n const files = (await readdir(directory))\n .filter((file) => /\\.(ts|js|mjs)$/.test(file) && !file.endsWith(\".d.ts\"))\n .sort();\n\n const artifacts: MigrationArtifact[] = [];\n\n const ids = new Set<string>();\n\n for (const file of files) {\n const id = file.replace(/\\.(ts|js|mjs)$/, \"\");\n\n validateMigrationId(id);\n\n if (ids.has(id)) throw new Error(`Duplicate migration filename: ${id}`);\n\n ids.add(id);\n\n if (omitLatest && file == files.at(-1)) continue;\n\n const source = await readFile(join(directory, file), \"utf8\");\n const module = (await importFile(join(directory, file))) as { default: DuraxisMigration };\n\n if (module.default?.id != id) throw new Error(`Migration ID does not match filename: ${file}`);\n\n const snapshot = await readJSON<SchemaSnapshot>(join(snapshots, `${id}.json`));\n\n validateSnapshot(snapshot);\n\n artifacts.push({ migration: module.default, checksum: artifactChecksum(source), snapshot });\n }\n\n const expected = new Set([...ids].map((id) => `${id}.json`));\n\n for (const file of await readdir(snapshots))\n if (file.endsWith(\".json\") && file != \"baseline.json\" && !expected.has(file))\n throw new Error(`Orphaned snapshot: ${file}`);\n\n const initial = await readJSON<SchemaSnapshot>(join(snapshots, \"baseline.json\"));\n\n validateSnapshot(initial);\n\n if (\n initial.migrationId !== null ||\n initial.parentMigrationId !== null ||\n initial.collections.length\n )\n throw new Error(\"Invalid empty baseline snapshot\");\n\n validateArtifacts(artifacts);\n\n return { artifacts, files, snapshots, directory };\n}\nexport function migrationId(name: string, previous?: string): string {\n if (name.includes(\"..\") || /[\\\\/]/.test(name))\n throw new Error(\"Migration names cannot contain paths\");\n\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\n if (!slug || slug.length > 64) throw new Error(\"Invalid migration name\");\n\n const stamp = new Date().toISOString().replace(/\\D/g, \"\");\n\n const previousStamp = previous?.slice(0, 17);\n\n const prefix =\n previousStamp && previousStamp >= stamp\n ? (BigInt(previousStamp) + 1n).toString().padStart(17, \"0\")\n : stamp;\n\n return `${prefix}_${slug}`;\n}\n\nfunction literal(value: unknown): string {\n return JSON.stringify(value, null, 2)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nexport function renderMigration(id: string, plan?: SchemaPlan): string {\n if (!plan)\n return `import { defineMigration } from \"@duraxis/migrations\";\\n\\nexport default defineMigration({\\n id: ${JSON.stringify(id)},\\n async up(context) {\\n throw new Error(\"Unfinished migration: implement up and provide its expected snapshot\");\\n },\\n});\\n`;\n\n const inverse = diffSchemas(plan.after, plan.before);\n\n const reversible =\n !plan.operations.some(\n (operation) => operation.kind == \"collection\" && operation.after == null,\n ) && inverse.operations.every((operation) => operation.risk != \"requires-data-transformation\");\n\n return `import { defineMigration, applySchemaPlan } from \"@duraxis/migrations\";\\n\\nexport default defineMigration({\\n id: ${JSON.stringify(id)},\\n async up(context) {\\n await applySchemaPlan(context, ${literal(plan)});\\n },\\n${\n reversible\n ? ` async down(context) {\\n${inverse.operations\n .filter((operation) => operation.kind == \"collection\" && operation.after == null)\n .map(\n (operation) =>\n ` for await (const row of context.scan(${JSON.stringify(operation.collection)})) throw new Error(\"Cannot drop a populated collection during generated rollback\");\\n`,\n )\n .join(\"\")} await applySchemaPlan(context, ${literal(inverse)});\\n },\\n`\n : \" // Irreversible automatically: write an explicit data-safe down() if needed.\\n\"\n } });\\n`;\n}\n\nexport async function withArtifactLock<T>(\n directory: string,\n callback: () => Promise<T>,\n): Promise<T> {\n await mkdir(directory, { recursive: true });\n\n const lock = join(directory, \".duraxis-artifacts.lock\");\n\n await writeFile(\n lock,\n canonicalJSON({\n pid: process.pid,\n purpose: \"artifact update; inspect files before removing a stale guard\",\n }),\n { flag: \"wx\" },\n );\n\n try {\n return await callback();\n } finally {\n await unlink(lock);\n }\n}\n\nexport async function writePair(\n migrationPath: string,\n source: string,\n snapshotPath: string,\n snapshot: SchemaSnapshot,\n): Promise<void> {\n await mkdir(resolve(snapshotPath, \"..\"), { recursive: true });\n await writeFile(migrationPath, source, { flag: \"wx\" });\n\n try {\n await writeFile(snapshotPath, JSON.stringify(snapshot, null, 2) + \"\\n\", { flag: \"wx\" });\n } catch (error) {\n await unlink(migrationPath);\n throw error;\n }\n}\n\nexport async function removePair(migrationPath: string, snapshotPath: string): Promise<void> {\n const suffix = `.removing-${randomBytes(6).toString(\"hex\")}`;\n await rename(migrationPath, migrationPath + suffix);\n\n try {\n await rename(snapshotPath, snapshotPath + suffix);\n } catch (error) {\n await rename(migrationPath + suffix, migrationPath);\n throw error;\n }\n\n await unlink(migrationPath + suffix);\n await unlink(snapshotPath + suffix);\n}\n\nexport function snapshotFor(\n id: string,\n parent: string | null,\n schema: readonly CollectionDefinition[],\n): SchemaSnapshot {\n return createSnapshot(id, parent, schema);\n}\n","import { parseArgs } from \"node:util\";\nimport { access, mkdir, writeFile, unlink } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { exportSchema } from \"@duraxis/orm\";\nimport {\n MigrationRunner,\n validateArtifacts,\n createSnapshot,\n diffSchemas,\n schemaHash,\n type SchemaSnapshot,\n type SchemaPlan,\n} from \"@duraxis/migrations\";\nimport type { CollectionDefinition, DuraxisDatabase } from \"@duraxis/core\";\nimport { loadConfig, readJSON, type DuraxisConnectionConfig } from \"./config.js\";\nimport {\n artifactChecksum,\n loadArtifacts,\n migrationId,\n renderMigration,\n withArtifactLock,\n writePair,\n removePair,\n} from \"./artifacts.js\";\n\nexport interface CLIIO {\n readonly cwd?: string;\n readonly out?: (message: string) => void;\n readonly error?: (message: string) => void;\n}\n\nconst help = `duraxis <command> [options]\n init\n migration:create <name>\n migration:generate <name> [--allow-destructive]\n migration:snapshot --schema <collections.json>\n migration:remove --yes\n migration:baseline <name> --yes\n migrate:up [--steps N | --to ID] [--dry-run] [--allow-destructive]\n migrate:down [--steps N | --to ID] --yes\n migrate:status\n migrate:diff [--persisted]\n migrate:check [--offline]\nOptions: --config PATH --database NAME --json\nRollback --to retains the target version. Dry-run is a static preview only.`;\n\nasync function withDatabase<T>(\n config: DuraxisConnectionConfig,\n callback: (database: DuraxisDatabase) => Promise<T>,\n): Promise<T> {\n const database = await config.createDatabase();\n\n try {\n return await callback(database);\n } finally {\n await database.close({ closeStorage: true });\n }\n}\n\nfunction summary(plan: SchemaPlan): string {\n return plan.operations.length\n ? plan.operations\n .map(\n (operation) =>\n `${operation.before == null ? \"+\" : operation.after == null ? \"-\" : \"~\"} ${operation.kind} ${operation.collection}/${operation.name} (${operation.risk})`,\n )\n .join(\"\\n\")\n : \"No schema differences.\";\n}\n\nasync function init(cwd: string): Promise<void> {\n const configPath = resolve(cwd, \"duraxis.config.ts\");\n const base = resolve(cwd, \"duraxis/snapshots/baseline.json\");\n\n for (const path of [configPath, base])\n try {\n await access(path);\n throw new Error(`Refusing to overwrite ${path}`);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n }\n\n await mkdir(resolve(cwd, \"duraxis/migrations\"), { recursive: true });\n await mkdir(resolve(cwd, \"duraxis/snapshots\"), { recursive: true });\n\n await writeFile(\n configPath,\n `import { defineDuraxisConfig } from \"@duraxis/cli\";\n\nexport default defineDuraxisConfig({\n entities: [], // Import your decorated entity classes here.\n migrations: { directory: \"./duraxis/migrations\", snapshots: \"./duraxis/snapshots\", format: \"ts\" },\n async createDatabase() {\n // Return a DuraxisDatabase configured with your storage driver.\n // The CLI closes this database and its storage after every command.\n throw new Error(\"Configure createDatabase() before accessing a database\");\n },\n});\n`,\n { flag: \"wx\" },\n );\n\n try {\n await writeFile(base, JSON.stringify(createSnapshot(null, null, []), null, 2) + \"\\n\", {\n flag: \"wx\",\n });\n } catch (error) {\n await unlink(configPath);\n throw error;\n }\n}\n\nexport async function runCLI(args: readonly string[], io: CLIIO = {}): Promise<number> {\n const cwd = io.cwd ?? process.cwd();\n const out = io.out ?? console.log;\n\n const errorOut = io.error ?? console.error;\n\n let jsonErrors = false;\n\n try {\n const { values, positionals } = parseArgs({\n args: [...args],\n allowPositionals: true,\n strict: true,\n options: {\n config: { type: \"string\" },\n database: { type: \"string\" },\n json: { type: \"boolean\" },\n steps: { type: \"string\" },\n to: { type: \"string\" },\n \"dry-run\": { type: \"boolean\" },\n \"allow-destructive\": { type: \"boolean\" },\n yes: { type: \"boolean\" },\n offline: { type: \"boolean\" },\n persisted: { type: \"boolean\" },\n schema: { type: \"string\" },\n help: { type: \"boolean\" },\n },\n });\n\n jsonErrors = values.json ?? false;\n\n const command = positionals[0];\n const name = positionals[1];\n\n if (!command || values.help) {\n out(help);\n return 0;\n }\n\n const commands = [\n \"init\",\n \"migration:create\",\n \"migration:generate\",\n \"migration:snapshot\",\n \"migration:remove\",\n \"migration:baseline\",\n \"migrate:up\",\n \"migrate:down\",\n \"migrate:status\",\n \"migrate:diff\",\n \"migrate:check\",\n ];\n\n if (!commands.includes(command)) throw new Error(`Unknown command: ${command}`);\n\n if (\n positionals.length > 2 ||\n (name && ![\"migration:create\", \"migration:generate\", \"migration:baseline\"].includes(command))\n )\n throw new Error(\"Unexpected positional arguments\");\n\n const allowed: Record<string, readonly string[]> = {\n init: [],\n \"migration:create\": [],\n \"migration:generate\": [\"allow-destructive\"],\n \"migration:snapshot\": [\"schema\"],\n \"migration:remove\": [\"yes\"],\n \"migration:baseline\": [\"yes\"],\n \"migrate:up\": [\"steps\", \"to\", \"dry-run\", \"allow-destructive\"],\n \"migrate:down\": [\"steps\", \"to\", \"yes\"],\n \"migrate:status\": [],\n \"migrate:diff\": [\"persisted\"],\n \"migrate:check\": [\"offline\"],\n };\n\n for (const option of Object.keys(values))\n if (![\"config\", \"database\", \"json\", \"help\", ...allowed[command]].includes(option))\n throw new Error(`Option --${option} is not supported by ${command}`);\n\n if (command == \"init\") {\n await init(cwd);\n out(\n \"Initialized duraxis.config.ts and migration directories. Configure entities and createDatabase().\",\n );\n return 0;\n }\n\n const { config, root } = await loadConfig(cwd, values.config, values.database);\n\n const directory = resolve(root, config.migrations.directory);\n const snapshots = resolve(root, config.migrations.snapshots);\n\n const print = (value: unknown, text: string) =>\n out(values.json ? JSON.stringify(value, null, 2) : text);\n\n const entities = async () =>\n exportSchema(\n typeof config.entities == \"function\" ? await config.entities() : config.entities,\n );\n\n if (command == \"migration:snapshot\") {\n if (!values.schema)\n throw new Error(\"Provide --schema with a JSON array of expected collection definitions\");\n\n await withArtifactLock(directory, async () => {\n const { readdir } = await import(\"node:fs/promises\");\n\n const files = (await readdir(directory))\n .filter((file) => /\\.(ts|js|mjs)$/.test(file) && !file.endsWith(\".d.ts\"))\n .sort();\n\n const latest = files.at(-1);\n\n if (!latest) throw new Error(\"No manual migration found\");\n\n const id = latest.replace(/\\.(ts|js|mjs)$/, \"\");\n\n const parent = files.at(-2)?.replace(/\\.(ts|js|mjs)$/, \"\") ?? null;\n\n if (parent) {\n const previous = await readJSON<SchemaSnapshot>(join(snapshots, `${parent}.json`));\n if (previous.migrationId != parent) throw new Error(\"Invalid predecessor snapshot\");\n }\n\n const definitions = await readJSON<readonly CollectionDefinition[]>(\n resolve(cwd, values.schema!),\n );\n\n await writeFile(\n join(snapshots, `${id}.json`),\n JSON.stringify(createSnapshot(id, parent, definitions), null, 2) + \"\\n\",\n { flag: \"wx\" },\n );\n });\n\n out(\"Saved intended manual snapshot. migrate:up verifies the actual result atomically.\");\n\n return 0;\n }\n\n if ([\"migration:create\", \"migration:generate\", \"migration:baseline\"].includes(command)) {\n if (!name) throw new Error(\"A migration name is required\");\n\n if (command == \"migration:baseline\" && !values.yes)\n throw new Error(\"Baseline adoption requires --yes\");\n\n await withArtifactLock(directory, async () => {\n const local = await loadArtifacts(config, root, true);\n const previous = local.artifacts.at(-1);\n\n const id = migrationId(name, previous?.migration.id);\n const migrationPath = join(directory, `${id}.${config.migrations.format ?? \"ts\"}`);\n\n if (command == \"migration:create\") {\n await writeFile(migrationPath, renderMigration(id), { flag: \"wx\" });\n print(\n { id, unfinished: true },\n `Created ${id}. Implement up(), then use migration:snapshot --schema <collections.json>.`,\n );\n return;\n }\n\n const desired = await entities();\n\n const before = previous?.snapshot.collections ?? [];\n const plan = diffSchemas(before, desired);\n\n if (command == \"migration:baseline\" && local.artifacts.length) {\n if (local.artifacts.length != 1)\n throw new Error(\"Baseline requires exactly one initial artifact\");\n\n const initial = local.artifacts[0]!;\n const creation = diffSchemas([], desired);\n\n if (\n initial.snapshot.schemaHash != schemaHash(desired) ||\n initial.checksum != artifactChecksum(renderMigration(initial.migration.id, creation))\n )\n throw new Error(\n \"Existing baseline must be an unmodified generated initial-schema migration matching entities\",\n );\n await withDatabase(config, (database) =>\n new MigrationRunner(database, local.artifacts).baseline(),\n );\n\n out(`Registered existing baseline ${initial.migration.id}`);\n return;\n }\n\n if (!plan.operations.length) {\n print({ operations: [] }, \"No schema differences.\");\n return;\n }\n\n if (plan.operations.some((operation) => operation.risk == \"requires-data-transformation\"))\n throw new Error(\n \"Automatic generation requires a manual data transformation. Use migration:create and provide a snapshot.\",\n );\n\n if (\n plan.operations.some((operation) => operation.risk == \"destructive\") &&\n !values[\"allow-destructive\"]\n )\n throw new Error(\"Destructive generation requires --allow-destructive\");\n\n const snapshot = createSnapshot(id, previous?.migration.id ?? null, desired);\n\n if (command == \"migration:baseline\") {\n await withDatabase(config, async (database) => {\n const actual = await database.getCollectionDefinitions();\n const names = new Set(desired.map((schema) => schema.name));\n\n if (\n schemaHash(actual.filter((schema) => names.has(schema.name))) != snapshot.schemaHash\n )\n throw new Error(\"Persisted managed schema is incompatible with baseline\");\n\n await writePair(\n migrationPath,\n renderMigration(id, plan),\n join(snapshots, `${id}.json`),\n snapshot,\n );\n\n const loaded = await loadArtifacts(config, root, true);\n\n await new MigrationRunner(database, loaded.artifacts).baseline();\n });\n } else\n await writePair(\n migrationPath,\n renderMigration(id, plan),\n join(snapshots, `${id}.json`),\n snapshot,\n );\n\n print({ id, operations: plan.operations }, `Created ${id}\\n${summary(plan)}`);\n });\n\n return 0;\n }\n\n if (command == \"migration:remove\") {\n if (!values.yes)\n throw new Error(\"Removing the latest unpublished local migration requires --yes\");\n\n await withArtifactLock(directory, async () => {\n const local = await loadArtifacts(config, root, true, true);\n\n const latestFile = local.files.at(-1);\n\n const latest = latestFile?.replace(/\\.(ts|js|mjs)$/, \"\");\n\n if (!latest) throw new Error(\"No local migration to remove\");\n\n await withDatabase(config, async (database) => {\n const status = await new MigrationRunner(database, local.artifacts).status();\n\n if (status.applied.some((entry) => entry.id == latest))\n throw new Error(\"Cannot remove an applied migration\");\n\n const snapshotPath = join(snapshots, `${latest}.json`);\n\n try {\n await access(snapshotPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code != \"ENOENT\") throw error;\n\n await unlink(join(directory, latestFile!));\n\n return;\n }\n\n await removePair(join(directory, latestFile!), snapshotPath);\n });\n\n out(\n `Removed ${latest}. This checks only the configured database; never remove shared or released migrations.`,\n );\n });\n\n return 0;\n }\n\n const local = await loadArtifacts(config, root);\n\n if (command == \"migrate:diff\" && !values.persisted) {\n const plan = diffSchemas(\n local.artifacts.at(-1)?.snapshot.collections ?? [],\n await entities(),\n );\n\n print(plan, summary(plan));\n\n return 0;\n }\n\n if (command == \"migrate:check\" && values.offline) {\n validateArtifacts(local.artifacts);\n\n const plan = diffSchemas(\n local.artifacts.at(-1)?.snapshot.collections ?? [],\n await entities(),\n );\n\n if (plan.operations.length)\n throw new Error(`Unrepresented entity changes:\\n${summary(plan)}`);\n\n print(\n { valid: true, mode: \"offline\" },\n \"Local files, snapshots, and entity schema are valid. Database history was not checked.\",\n );\n\n return 0;\n }\n\n if (command == \"migrate:up\" && values[\"dry-run\"]) {\n const steps = values.steps === undefined ? undefined : Number(values.steps);\n\n if (steps !== undefined && (!Number.isSafeInteger(steps) || steps < 0))\n throw new Error(\"Invalid steps\");\n\n if (\n values.to &&\n (!local.artifacts.some((artifact) => artifact.migration.id == values.to) ||\n steps !== undefined)\n )\n throw new Error(\"Invalid target or conflicting --steps\");\n\n const candidates = local.artifacts\n .filter((artifact) => !values.to || artifact.migration.id <= values.to)\n .slice(0, steps ?? Infinity)\n .map((artifact) => artifact.migration.id);\n\n print(\n { dryRun: true, appliedStateChecked: false, candidates },\n `Static preview only; database was not opened and applied state was not checked. Migration callbacks were not executed.\\n${candidates.join(\"\\n\")}`,\n );\n\n return 0;\n }\n\n await withDatabase(config, async (database) => {\n const runner = new MigrationRunner(database, local.artifacts);\n\n const options = {\n ...(values.steps === undefined ? {} : { steps: Number(values.steps) }),\n ...(values.to ? { to: values.to } : {}),\n allowDestructive: values[\"allow-destructive\"] ?? false,\n };\n\n if (command == \"migrate:up\") {\n const applied = await runner.up(options);\n\n print({ applied }, `Applied ${applied.length} migration(s).\\n${applied.join(\"\\n\")}`);\n } else if (command == \"migrate:down\") {\n if (!values.yes)\n throw new Error(\"Rollback requires --yes; review backups and down() first\");\n\n const reverted = await runner.down({ ...options, allowDestructive: true });\n\n print({ reverted }, `Reverted ${reverted.length} migration(s).`);\n } else if (command == \"migrate:status\") {\n const status = await runner.status();\n\n print(\n status,\n `Duraxis migration status\\nDatabase: ${values.database ?? \"default\"}\\n\\nApplied:\\n${status.applied.map((entry) => ` ${entry.id}`).join(\"\\n\")}\\nPending:\\n${status.pending.map((id) => ` ${id}`).join(\"\\n\")}\\nSchema drift: none\\n${status.applied.length} applied, ${status.pending.length} pending`,\n );\n } else if (command == \"migrate:diff\") {\n const plan = await runner.drift();\n\n print(plan, summary(plan));\n } else if (command == \"migrate:check\") {\n await runner.status();\n\n const plan = diffSchemas(\n local.artifacts.at(-1)?.snapshot.collections ?? [],\n await entities(),\n );\n\n if (plan.operations.length)\n throw new Error(`Unrepresented entity changes:\\n${summary(plan)}`);\n\n print(\n { valid: true },\n \"Migration files, snapshots, history, schema, and entities are valid.\",\n );\n }\n });\n\n return 0;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n errorOut(jsonErrors ? JSON.stringify({ error: message }) : message);\n\n return 1;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,oBAAmD,QAAc;CAC/E,OAAO;AACT;AAEA,eAAsB,WAAW,MAAgC;CAC/D,OAAO,QAAA,GAAOA,SAAAA,cAAAA,CAAc,IAAI,CAAC,CAAC;AACpC;AAEA,eAAsB,WACpB,KACA,UACA,UAC0E;CAC1E,IAAI;CAEJ,IAAI,UAAU,QAAA,GAAOC,UAAAA,QAAAA,CAAQ,KAAK,QAAQ;MACrC;EACH,IAAI,aAAA,GAAYA,UAAAA,QAAAA,CAAQ,GAAG;EAE3B,OAAO,MAAM;GACX,KAAK,MAAM,QAAQ;IAAC;IAAqB;IAAqB;GAAoB,GAAG;IACnF,MAAM,aAAA,GAAYA,UAAAA,QAAAA,CAAQ,WAAW,IAAI;IAEzC,IAAI;KACF,OAAA,GAAMC,iBAAAA,OAAAA,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