@duraxis/cli 0.1.0 → 0.2.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 +13 -0
- package/README.md +52 -10
- package/dist/bin.js +9 -2
- package/dist/config.d.ts +1 -1
- package/dist/index.cjs +3 -494
- package/dist/index.d.ts +1 -0
- package/dist/index.js +121 -12
- package/dist/index.js.map +1 -1
- package/dist/runtime.mjs +15 -0
- package/dist/typescript-loader.d.ts +4 -0
- package/package.json +7 -6
- package/dist/index.cjs.map +0 -1
- package/dist/ts-loader.mjs +0 -43
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @duraxis/cli
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- eb56e40: Add transactional collection alteration/removal, final-schema validation, schema-aware index rebuilding, and protected subsystem metadata. Add standalone ORM schema export and opt-in strict managed validation. Introduce the migration runtime and CLI with snapshots, schema comparison, atomic history, conservative rollback, baseline adoption, and recovery-aware publication. Document deployment sequencing and transaction memory limits.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [eb56e40]
|
|
12
|
+
- @duraxis/core@0.3.0
|
|
13
|
+
- @duraxis/orm@0.3.0
|
|
14
|
+
- @duraxis/migrations@0.2.0
|
|
15
|
+
|
|
3
16
|
## 0.1.0
|
|
4
17
|
|
|
5
18
|
Initial migration tooling.
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @duraxis/cli
|
|
2
2
|
|
|
3
|
-
Standalone Duraxis migration tooling
|
|
3
|
+
Standalone Duraxis migration tooling. Node.js 24.15.0 or newer is required. The CLI builds on
|
|
4
4
|
`@duraxis/migrations` and the ORM's database-independent schema exporter.
|
|
5
5
|
|
|
6
6
|
## Quick start
|
|
@@ -64,7 +64,8 @@ before using `pnpm exec duraxis`.
|
|
|
64
64
|
## Configuration and loading
|
|
65
65
|
|
|
66
66
|
Discovery walks from the working directory upward for `duraxis.config.ts`,
|
|
67
|
-
`duraxis.config.
|
|
67
|
+
`duraxis.config.mts`, `duraxis.config.js`, `duraxis.config.mjs`,
|
|
68
|
+
`duraxis.config.cts`, or `duraxis.config.cjs`. `--config <path>` overrides discovery.
|
|
68
69
|
Migration and snapshot directories resolve relative to the config file. Paths
|
|
69
70
|
inside your database factory are your responsibility; use `import.meta.url` as
|
|
70
71
|
above instead of depending on the command's working directory.
|
|
@@ -80,14 +81,55 @@ that database and storage in a `finally` block. Factories must clean up resource
|
|
|
80
81
|
if they fail before returning. Do not pass an application-owned connection to
|
|
81
82
|
this CLI API; use the programmatic runner for that scenario.
|
|
82
83
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
84
|
+
Duraxis registers synchronous Node.js `registerHooks()` before loading a config,
|
|
85
|
+
entity, or migration, including programmatic `loadConfig()` calls. No manual
|
|
86
|
+
loader registration, experimental Node flags, or extra runtime transpiler is
|
|
87
|
+
required. Native type stripping alone cannot implement legacy decorators.
|
|
88
|
+
|
|
89
|
+
Supported configuration formats are `.ts`, `.mts`, `.js`, `.mjs`, `.cts`, and
|
|
90
|
+
`.cjs`. Discovery checks those extensions in that order. `.ts` and `.mts` source
|
|
91
|
+
modules execute as ESM; `.cts` uses CommonJS. JavaScript keeps Node's ordinary
|
|
92
|
+
package/module semantics. Executable migration artifacts support ESM `.ts`,
|
|
93
|
+
`.mts`, `.js`, and `.mjs`; CommonJS migration artifacts are unsupported because
|
|
94
|
+
their executable form does not share the ESM checksum identity contract.
|
|
95
|
+
|
|
96
|
+
Standard Node resolution runs first. Only missing local relative/file-URL imports
|
|
97
|
+
in module graphs loaded by Duraxis receive source-extension fallbacks:
|
|
98
|
+
`.js` → `.ts`, `.mjs` → `.mts`, `.cjs` → `.cts`. Existing JavaScript wins. Bare
|
|
99
|
+
packages, package exports, built-ins, and dependencies under `node_modules` are
|
|
100
|
+
left to Node. Missing dependencies and execution errors propagate without retrying
|
|
101
|
+
another source module. Direct TypeScript imports, nested and dynamic imports,
|
|
102
|
+
file URLs, spaces, and Unicode filesystem names work through the same path.
|
|
103
|
+
|
|
104
|
+
The production dependency TypeScript 5.9.3 transpiles source with ES2022 output,
|
|
105
|
+
`experimentalDecorators: true`, `emitDecoratorMetadata: true`, and
|
|
106
|
+
`useDefineForClassFields: false`. Reflective metadata consumers must load their
|
|
107
|
+
usual `reflect-metadata` dependency before decorated modules. Entity columns
|
|
108
|
+
should declare their Core `type` explicitly. `tsconfig.json` path aliases,
|
|
109
|
+
custom compiler plugins, `.tsx`/`.jsx`, and TypeScript package sources inside
|
|
110
|
+
`node_modules` are not supported. Use relative imports or published package exports.
|
|
111
|
+
When using a CommonJS config, load decorated entities and Duraxis connections
|
|
112
|
+
from ESM with native dynamic imports. Mixing independent ESM and CommonJS copies
|
|
113
|
+
of ORM decorators/Core constructors is unsupported; the CLI executes as ESM.
|
|
114
|
+
Config files and migrations are trusted executable code; keep module initialization
|
|
115
|
+
free of database writes and external side effects.
|
|
116
|
+
|
|
117
|
+
Programmatic use needs no executable bootstrap:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { loadConfig, disposeTypeScriptLoader } from "@duraxis/cli";
|
|
121
|
+
const { config } = await loadConfig(process.cwd());
|
|
122
|
+
// Use config and its asynchronous entity/migration callbacks here.
|
|
123
|
+
disposeTypeScriptLoader();
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
A library instance registers one hook pair, reuses it for repeated calls, and
|
|
127
|
+
tracks only explicitly loaded local module graphs. Hooks stay active for later
|
|
128
|
+
dynamic imports from those graphs. Call `disposeTypeScriptLoader()` when callbacks
|
|
129
|
+
no longer need them; it deregisters the hooks. Later loads initialize a new pair.
|
|
130
|
+
Graph tracking and Node's module cache remain in effect so cached callbacks keep
|
|
131
|
+
working after reinitialization. This is not a watch-mode/hot-reload facility. The CommonJS entry uses Node 24 require(ESM),
|
|
132
|
+
so both programmatic exports share the same implementation and hook state.
|
|
91
133
|
|
|
92
134
|
Local generation, local diff, offline check, and dry-run never call the database
|
|
93
135
|
factory. Other commands open the configured database. Disk requires exclusive
|
package/dist/bin.js
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import { assertSupportedRuntime } from "./runtime.mjs";
|
|
3
|
+
try {
|
|
4
|
+
assertSupportedRuntime();
|
|
5
|
+
const { runCLI } = await import("./index.js");
|
|
6
|
+
process.exitCode = await runCLI(process.argv.slice(2));
|
|
7
|
+
} catch (error) {
|
|
8
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
9
|
+
process.exitCode = 1;
|
|
10
|
+
}
|
package/dist/config.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ export interface DuraxisConfig extends DuraxisConnectionConfig {
|
|
|
13
13
|
readonly databases?: Readonly<Record<string, DuraxisConnectionConfig>>;
|
|
14
14
|
}
|
|
15
15
|
export declare function defineDuraxisConfig<const T extends DuraxisConfig>(config: T): T;
|
|
16
|
-
export declare function importFile(path: string): Promise<unknown>;
|
|
16
|
+
export declare function importFile(path: string | URL): Promise<unknown>;
|
|
17
17
|
export declare function loadConfig(cwd: string, explicit?: string, database?: string): Promise<{
|
|
18
18
|
config: DuraxisConnectionConfig;
|
|
19
19
|
root: string;
|
package/dist/index.cjs
CHANGED
|
@@ -1,494 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
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
|
|
1
|
+
"use strict";
|
|
2
|
+
require("./runtime.mjs").assertSupportedRuntime();
|
|
3
|
+
module.exports = require("./index.js");
|
package/dist/index.d.ts
CHANGED
|
@@ -2,3 +2,4 @@ export { runCLI } from "./cli.js";
|
|
|
2
2
|
export type { CLIIO } from "./cli.js";
|
|
3
3
|
export { defineDuraxisConfig, loadConfig } from "./config.js";
|
|
4
4
|
export type { DuraxisConfig, DuraxisConnectionConfig } from "./config.js";
|
|
5
|
+
export { disposeTypeScriptLoader } from "./typescript-loader.js";
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,123 @@
|
|
|
1
1
|
import { parseArgs } from "node:util";
|
|
2
2
|
import { access, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
|
|
3
|
-
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
4
4
|
import { exportSchema } from "@duraxis/orm";
|
|
5
5
|
import { MigrationRunner, canonicalJSON, checksum, createSnapshot, diffSchemas, schemaHash, validateArtifacts, validateMigrationId, validateSnapshot } from "@duraxis/migrations";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
6
|
+
import { readFileSync, statSync } from "node:fs";
|
|
7
|
+
import { registerHooks } from "node:module";
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
8
9
|
import ts from "typescript";
|
|
10
|
+
import { randomBytes } from "node:crypto";
|
|
11
|
+
// src/runtime.mjs
|
|
12
|
+
var MINIMUM_NODE_VERSION = "24.15.0";
|
|
13
|
+
/** Reject unsupported runtimes before importing the CLI and its Node.js APIs. */
|
|
14
|
+
function assertSupportedRuntime(version = process.versions.node) {
|
|
15
|
+
const actual = version.split(".").map(Number);
|
|
16
|
+
const minimum = MINIMUM_NODE_VERSION.split(".").map(Number);
|
|
17
|
+
const difference = actual.findIndex((part, index) => part !== minimum[index]);
|
|
18
|
+
if (!(/^\d+\.\d+\.\d+$/.test(version) && (difference === -1 || actual[difference] > minimum[difference]))) throw new Error(`Duraxis requires Node.js ${MINIMUM_NODE_VERSION} or newer.\nCurrent version: ${version}\nPlease upgrade your Node.js installation.`);
|
|
19
|
+
}
|
|
20
|
+
// src/typescript-loader.ts
|
|
21
|
+
var sourceExtensions = {
|
|
22
|
+
".js": ".ts",
|
|
23
|
+
".mjs": ".mts",
|
|
24
|
+
".cjs": ".cts"
|
|
25
|
+
};
|
|
26
|
+
var hooks;
|
|
27
|
+
var modules = /* @__PURE__ */ new Set();
|
|
28
|
+
function localFile(value) {
|
|
29
|
+
if (!value.startsWith("file:")) return;
|
|
30
|
+
const url = new URL(value);
|
|
31
|
+
if (fileURLToPath(url).split(/[\\/]/).includes("node_modules")) return;
|
|
32
|
+
return url;
|
|
33
|
+
}
|
|
34
|
+
function exists(url) {
|
|
35
|
+
try {
|
|
36
|
+
return statSync(url).isFile();
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (["ENOENT", "ENOTDIR"].includes(error.code ?? "")) return false;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function remember(url) {
|
|
43
|
+
if (localFile(url)) modules.add(url);
|
|
44
|
+
}
|
|
45
|
+
/** One hook pair per library instance, limited to explicitly loaded local module graphs. */
|
|
46
|
+
function initializeTypeScriptLoader(entry) {
|
|
47
|
+
assertSupportedRuntime();
|
|
48
|
+
remember(entry.href);
|
|
49
|
+
if (hooks) return;
|
|
50
|
+
hooks = registerHooks({
|
|
51
|
+
resolve(specifier, context, nextResolve) {
|
|
52
|
+
const managed = /^(?:\.{1,2}[\\/]|\/|file:)/.test(specifier) && (modules.has(specifier) || context.parentURL !== void 0 && modules.has(context.parentURL));
|
|
53
|
+
try {
|
|
54
|
+
const resolved = nextResolve(specifier, context);
|
|
55
|
+
if (managed) remember(resolved.url);
|
|
56
|
+
return resolved;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (!managed || !["ERR_MODULE_NOT_FOUND", "MODULE_NOT_FOUND"].includes(error.code ?? "")) throw error;
|
|
59
|
+
const requested = localFile(new URL(specifier, context.parentURL).href);
|
|
60
|
+
if (!requested || exists(requested)) throw error;
|
|
61
|
+
const path = fileURLToPath(requested);
|
|
62
|
+
const extension = extname(path);
|
|
63
|
+
const mapped = sourceExtensions[extension];
|
|
64
|
+
if (!mapped) throw error;
|
|
65
|
+
const candidate = pathToFileURL(path.slice(0, -extension.length) + mapped);
|
|
66
|
+
candidate.search = requested.search;
|
|
67
|
+
candidate.hash = requested.hash;
|
|
68
|
+
if (!exists(candidate)) throw error;
|
|
69
|
+
const resolved = nextResolve(context.conditions.includes("require") ? fileURLToPath(candidate) : candidate.href, context);
|
|
70
|
+
remember(resolved.url);
|
|
71
|
+
return resolved;
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
load(url, context, nextLoad) {
|
|
75
|
+
if (!modules.has(url)) return nextLoad(url, context);
|
|
76
|
+
const file = localFile(url);
|
|
77
|
+
if (!file) return nextLoad(url, context);
|
|
78
|
+
const path = fileURLToPath(file);
|
|
79
|
+
if (!/\.(?:ts|mts|cts)$/.test(path) || /\.d\.(?:ts|mts|cts)$/.test(path)) return nextLoad(url, context);
|
|
80
|
+
const commonjs = path.endsWith(".cts");
|
|
81
|
+
const result = ts.transpileModule(readFileSync(file, "utf8"), {
|
|
82
|
+
fileName: path,
|
|
83
|
+
reportDiagnostics: true,
|
|
84
|
+
compilerOptions: {
|
|
85
|
+
target: ts.ScriptTarget.ES2022,
|
|
86
|
+
module: commonjs ? ts.ModuleKind.NodeNext : ts.ModuleKind.ESNext,
|
|
87
|
+
...commonjs ? { moduleResolution: ts.ModuleResolutionKind.NodeNext } : {},
|
|
88
|
+
experimentalDecorators: true,
|
|
89
|
+
emitDecoratorMetadata: true,
|
|
90
|
+
useDefineForClassFields: false,
|
|
91
|
+
sourceMap: false
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
const errors = (result.diagnostics ?? []).filter((item) => item.category == ts.DiagnosticCategory.Error);
|
|
95
|
+
if (errors.length) throw new Error(ts.formatDiagnosticsWithColorAndContext(errors, {
|
|
96
|
+
getCurrentDirectory: () => process.cwd(),
|
|
97
|
+
getCanonicalFileName: (file) => file,
|
|
98
|
+
getNewLine: () => "\n"
|
|
99
|
+
}));
|
|
100
|
+
return {
|
|
101
|
+
format: commonjs ? "commonjs" : "module",
|
|
102
|
+
source: (commonjs ? "\"use strict\";\nrequire = require(\"node:module\").createRequire(__filename);\n" : "") + result.outputText,
|
|
103
|
+
shortCircuit: true
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/** Call only when no config/entity/migration callbacks need further dynamic imports. Node's module cache is retained. */
|
|
109
|
+
function disposeTypeScriptLoader() {
|
|
110
|
+
hooks?.deregister();
|
|
111
|
+
hooks = void 0;
|
|
112
|
+
}
|
|
9
113
|
// src/config.ts
|
|
10
114
|
function defineDuraxisConfig(config) {
|
|
11
115
|
return config;
|
|
12
116
|
}
|
|
13
117
|
async function importFile(path) {
|
|
14
|
-
|
|
118
|
+
const url = path instanceof URL ? path : pathToFileURL(path);
|
|
119
|
+
initializeTypeScriptLoader(url);
|
|
120
|
+
return import(url.href);
|
|
15
121
|
}
|
|
16
122
|
async function loadConfig(cwd, explicit, database) {
|
|
17
123
|
let path;
|
|
@@ -21,8 +127,11 @@ async function loadConfig(cwd, explicit, database) {
|
|
|
21
127
|
while (true) {
|
|
22
128
|
for (const name of [
|
|
23
129
|
"duraxis.config.ts",
|
|
130
|
+
"duraxis.config.mts",
|
|
24
131
|
"duraxis.config.js",
|
|
25
|
-
"duraxis.config.mjs"
|
|
132
|
+
"duraxis.config.mjs",
|
|
133
|
+
"duraxis.config.cts",
|
|
134
|
+
"duraxis.config.cjs"
|
|
26
135
|
]) {
|
|
27
136
|
const candidate = resolve(directory, name);
|
|
28
137
|
try {
|
|
@@ -73,11 +182,11 @@ async function loadArtifacts(config, root, ownsLock = false, omitLatest = false)
|
|
|
73
182
|
} catch (error) {
|
|
74
183
|
if (error.code != "ENOENT") throw error;
|
|
75
184
|
}
|
|
76
|
-
const files = (await readdir(directory)).filter((file) => /\.(ts|js|mjs)$/.test(file) &&
|
|
185
|
+
const files = (await readdir(directory)).filter((file) => /\.(ts|mts|js|mjs)$/.test(file) && !/\.d\.(?:ts|mts)$/.test(file)).sort();
|
|
77
186
|
const artifacts = [];
|
|
78
187
|
const ids = /* @__PURE__ */ new Set();
|
|
79
188
|
for (const file of files) {
|
|
80
|
-
const id = file.replace(/\.(ts|js|mjs)$/, "");
|
|
189
|
+
const id = file.replace(/\.(ts|mts|js|mjs)$/, "");
|
|
81
190
|
validateMigrationId(id);
|
|
82
191
|
if (ids.has(id)) throw new Error(`Duplicate migration filename: ${id}`);
|
|
83
192
|
ids.add(id);
|
|
@@ -307,11 +416,11 @@ async function runCLI(args, io = {}) {
|
|
|
307
416
|
if (!values.schema) throw new Error("Provide --schema with a JSON array of expected collection definitions");
|
|
308
417
|
await withArtifactLock(directory, async () => {
|
|
309
418
|
const { readdir } = await import("node:fs/promises");
|
|
310
|
-
const files = (await readdir(directory)).filter((file) => /\.(ts|js|mjs)$/.test(file) &&
|
|
419
|
+
const files = (await readdir(directory)).filter((file) => /\.(ts|mts|js|mjs)$/.test(file) && !/\.d\.(?:ts|mts)$/.test(file)).sort();
|
|
311
420
|
const latest = files.at(-1);
|
|
312
421
|
if (!latest) throw new Error("No manual migration found");
|
|
313
|
-
const id = latest.replace(/\.(ts|js|mjs)$/, "");
|
|
314
|
-
const parent = files.at(-2)?.replace(/\.(ts|js|mjs)$/, "") ?? null;
|
|
422
|
+
const id = latest.replace(/\.(ts|mts|js|mjs)$/, "");
|
|
423
|
+
const parent = files.at(-2)?.replace(/\.(ts|mts|js|mjs)$/, "") ?? null;
|
|
315
424
|
if (parent) {
|
|
316
425
|
if ((await readJSON(join(snapshots, `${parent}.json`))).migrationId != parent) throw new Error("Invalid predecessor snapshot");
|
|
317
426
|
}
|
|
@@ -381,7 +490,7 @@ async function runCLI(args, io = {}) {
|
|
|
381
490
|
await withArtifactLock(directory, async () => {
|
|
382
491
|
const local = await loadArtifacts(config, root, true, true);
|
|
383
492
|
const latestFile = local.files.at(-1);
|
|
384
|
-
const latest = latestFile?.replace(/\.(ts|js|mjs)$/, "");
|
|
493
|
+
const latest = latestFile?.replace(/\.(ts|mts|js|mjs)$/, "");
|
|
385
494
|
if (!latest) throw new Error("No local migration to remove");
|
|
386
495
|
await withDatabase(config, async (database) => {
|
|
387
496
|
if ((await new MigrationRunner(database, local.artifacts).status()).applied.some((entry) => entry.id == latest)) throw new Error("Cannot remove an applied migration");
|
|
@@ -464,6 +573,6 @@ async function runCLI(args, io = {}) {
|
|
|
464
573
|
return 1;
|
|
465
574
|
}
|
|
466
575
|
}
|
|
467
|
-
export { defineDuraxisConfig, loadConfig, runCLI };
|
|
576
|
+
export { defineDuraxisConfig, disposeTypeScriptLoader, loadConfig, runCLI };
|
|
468
577
|
|
|
469
578
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"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,OAAO,cAAc,IAAI,CAAC,CAAC;AACpC;AAEA,eAAsB,WACpB,KACA,UACA,UAC0E;CAC1E,IAAI;CAEJ,IAAI,UAAU,OAAO,QAAQ,KAAK,QAAQ;MACrC;EACH,IAAI,YAAY,QAAQ,GAAG;EAE3B,OAAO,MAAM;GACX,KAAK,MAAM,QAAQ;IAAC;IAAqB;IAAqB;GAAoB,GAAG;IACnF,MAAM,YAAY,QAAQ,WAAW,IAAI;IAEzC,IAAI;KACF,MAAM,OAAO,SAAS;KAEtB,OAAO;KAEP;IACF,SAAS,OAAO;KACd,IAAK,MAAgC,QAAQ,UAAU,MAAM;IAC/D;GACF;GAEA,IAAI,QAAQ,QAAQ,SAAS,KAAK,WAAW;GAE7C,YAAY,QAAQ,SAAS;EAC/B;CACF;CAEA,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,wDAAwD;CAInF,MAAM,QAAO,MAFS,WAAW,IAAI,EAAA,CAEjB;CAEpB,MAAM,SAAS,WAAW,MAAM,YAAY,YAAY;CAExD,IACE,CAAC,UACD,OAAO,OAAO,kBAAkB,cAC/B,CAAC,MAAM,QAAQ,OAAO,QAAQ,KAAK,OAAO,OAAO,YAAY,cAC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WAAW,kBAAkB;IACtC,MAAM,SAAS,MAAM,OAAO,OAAO;IAEnC,MACE,QACA,uCAAuC,OAAO,YAAY,UAAU,gBAAgB,OAAO,QAAQ,KAAK,UAAU,KAAK,MAAM,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE,cAAc,OAAO,QAAQ,KAAK,OAAO,KAAK,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE,wBAAwB,OAAO,QAAQ,OAAO,YAAY,OAAO,QAAQ,OAAO,SAC/R;GACF,OAAO,IAAI,WAAW,gBAAgB;IACpC,MAAM,OAAO,MAAM,OAAO,MAAM;IAEhC,MAAM,MAAM,QAAQ,IAAI,CAAC;GAC3B,OAAO,IAAI,WAAW,iBAAiB;IACrC,MAAM,OAAO,OAAO;IAEpB,MAAM,OAAO,YACX,MAAM,UAAU,GAAG,EAAE,CAAC,EAAE,SAAS,eAAe,CAAC,GACjD,MAAM,SAAS,CACjB;IAEA,IAAI,KAAK,WAAW,QAClB,MAAM,IAAI,MAAM,kCAAkC,QAAQ,IAAI,GAAG;IAEnE,MACE,EAAE,OAAO,KAAK,GACd,sEACF;GACF;EACF,CAAC;EAED,OAAO;CACT,SAAS,OAAO;EACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAErE,SAAS,aAAa,KAAK,UAAU,EAAE,OAAO,QAAQ,CAAC,IAAI,OAAO;EAElE,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/runtime.mjs","../src/typescript-loader.ts","../src/config.ts","../src/artifacts.ts","../src/cli.ts"],"sourcesContent":["export const MINIMUM_NODE_VERSION = \"24.15.0\";\n\n/** Reject unsupported runtimes before importing the CLI and its Node.js APIs. */\nexport function assertSupportedRuntime(version = process.versions.node) {\n const actual = version.split(\".\").map(Number);\n const minimum = MINIMUM_NODE_VERSION.split(\".\").map(Number);\n const difference = actual.findIndex((part, index) => part !== minimum[index]);\n const supported =\n /^\\d+\\.\\d+\\.\\d+$/.test(version) &&\n (difference === -1 || actual[difference] > minimum[difference]);\n if (!supported)\n throw new Error(\n `Duraxis requires Node.js ${MINIMUM_NODE_VERSION} or newer.\\nCurrent version: ${version}\\nPlease upgrade your Node.js installation.`,\n );\n}\n","import { readFileSync, statSync } from \"node:fs\";\nimport { registerHooks, type ModuleHooks } from \"node:module\";\nimport { extname } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport ts from \"typescript\";\nimport { assertSupportedRuntime } from \"./runtime.mjs\";\n\nconst sourceExtensions: Readonly<Record<string, string>> = {\n \".js\": \".ts\",\n \".mjs\": \".mts\",\n \".cjs\": \".cts\",\n};\nlet hooks: ModuleHooks | undefined;\nconst modules = new Set<string>();\n\nfunction localFile(value: string): URL | undefined {\n if (!value.startsWith(\"file:\")) return;\n const url = new URL(value);\n const path = fileURLToPath(url);\n if (path.split(/[\\\\/]/).includes(\"node_modules\")) return;\n return url;\n}\nfunction exists(url: URL): boolean {\n try {\n return statSync(url).isFile();\n } catch (error) {\n if ([\"ENOENT\", \"ENOTDIR\"].includes((error as NodeJS.ErrnoException).code ?? \"\")) return false;\n throw error;\n }\n}\nfunction remember(url: string): void {\n if (localFile(url)) modules.add(url);\n}\n\n/** One hook pair per library instance, limited to explicitly loaded local module graphs. */\nexport function initializeTypeScriptLoader(entry: URL): void {\n assertSupportedRuntime();\n remember(entry.href);\n if (hooks) return;\n hooks = registerHooks({\n resolve(specifier, context, nextResolve) {\n const relative = /^(?:\\.{1,2}[\\\\/]|\\/|file:)/.test(specifier);\n const managed =\n relative &&\n (modules.has(specifier) ||\n (context.parentURL !== undefined && modules.has(context.parentURL)));\n try {\n const resolved = nextResolve(specifier, context);\n if (managed) remember(resolved.url);\n return resolved;\n } catch (error) {\n if (\n !managed ||\n ![\"ERR_MODULE_NOT_FOUND\", \"MODULE_NOT_FOUND\"].includes(\n (error as NodeJS.ErrnoException).code ?? \"\",\n )\n )\n throw error;\n const requested = localFile(new URL(specifier, context.parentURL).href);\n if (!requested || exists(requested)) throw error;\n const path = fileURLToPath(requested);\n const extension = extname(path);\n const mapped = sourceExtensions[extension];\n if (!mapped) throw error;\n const candidate = pathToFileURL(path.slice(0, -extension.length) + mapped);\n candidate.search = requested.search;\n candidate.hash = requested.hash;\n if (!exists(candidate)) throw error;\n const resolved = nextResolve(\n context.conditions.includes(\"require\") ? fileURLToPath(candidate) : candidate.href,\n context,\n );\n remember(resolved.url);\n return resolved;\n }\n },\n load(url, context, nextLoad) {\n if (!modules.has(url)) return nextLoad(url, context);\n const file = localFile(url);\n if (!file) return nextLoad(url, context);\n const path = fileURLToPath(file);\n if (!/\\.(?:ts|mts|cts)$/.test(path) || /\\.d\\.(?:ts|mts|cts)$/.test(path))\n return nextLoad(url, context);\n const commonjs = path.endsWith(\".cts\");\n const result = ts.transpileModule(readFileSync(file, \"utf8\"), {\n fileName: path,\n reportDiagnostics: true,\n compilerOptions: {\n target: ts.ScriptTarget.ES2022,\n module: commonjs ? ts.ModuleKind.NodeNext : ts.ModuleKind.ESNext,\n ...(commonjs ? { moduleResolution: ts.ModuleResolutionKind.NodeNext } : {}),\n experimentalDecorators: true,\n emitDecoratorMetadata: true,\n useDefineForClassFields: false,\n sourceMap: false,\n },\n });\n const errors = (result.diagnostics ?? []).filter(\n (item) => item.category == ts.DiagnosticCategory.Error,\n );\n if (errors.length)\n throw new Error(\n ts.formatDiagnosticsWithColorAndContext(errors, {\n getCurrentDirectory: () => process.cwd(),\n getCanonicalFileName: (file) => file,\n getNewLine: () => \"\\n\",\n }),\n );\n // Imported CommonJS source otherwise receives the ESM translator's synthetic\n // require, which bypasses customization hooks. Use Node's hook-aware require.\n return {\n format: commonjs ? \"commonjs\" : \"module\",\n source:\n (commonjs\n ? '\"use strict\";\\nrequire = require(\"node:module\").createRequire(__filename);\\n'\n : \"\") + result.outputText,\n shortCircuit: true,\n };\n },\n });\n}\n\n/** Call only when no config/entity/migration callbacks need further dynamic imports. Node's module cache is retained. */\nexport function disposeTypeScriptLoader(): void {\n hooks?.deregister();\n hooks = undefined;\n // Retain graph identity alongside Node's module cache so cached callbacks can\n // resolve further imports after a later initialization.\n}\n","import { access, readFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { initializeTypeScriptLoader } from \"./typescript-loader.js\";\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 | URL): Promise<unknown> {\n const url = path instanceof URL ? path : pathToFileURL(path);\n initializeTypeScriptLoader(url);\n return import(url.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 [\n \"duraxis.config.ts\",\n \"duraxis.config.mts\",\n \"duraxis.config.js\",\n \"duraxis.config.mjs\",\n \"duraxis.config.cts\",\n \"duraxis.config.cjs\",\n ]) {\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|mts|js|mjs)$/.test(file) && !/\\.d\\.(?:ts|mts)$/.test(file))\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|mts|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|mts|js|mjs)$/.test(file) && !/\\.d\\.(?:ts|mts)$/.test(file))\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|mts|js|mjs)$/, \"\");\n\n const parent = files.at(-2)?.replace(/\\.(ts|mts|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|mts|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":";;;;;;;;;;;AAAA,IAAa,uBAAuB;;AAGpC,SAAgB,uBAAuB,UAAU,QAAQ,SAAS,MAAM;CACtE,MAAM,SAAS,QAAQ,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC5C,MAAM,UAAU,qBAAqB,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC1D,MAAM,aAAa,OAAO,WAAW,MAAM,UAAU,SAAS,QAAQ,MAAM;CAI5E,IAAI,EAFF,kBAAkB,KAAK,OAAO,MAC7B,eAAe,MAAM,OAAO,cAAc,QAAQ,eAEnD,MAAM,IAAI,MACR,4BAA4B,qBAAqB,+BAA+B,QAAQ,4CAC1F;AACJ;;ACPA,IAAM,mBAAqD;CACzD,OAAO;CACP,QAAQ;CACR,QAAQ;AACV;AACA,IAAI;AACJ,IAAM,0BAAU,IAAI,IAAY;AAEhC,SAAS,UAAU,OAAgC;CACjD,IAAI,CAAC,MAAM,WAAW,OAAO,GAAG;CAChC,MAAM,MAAM,IAAI,IAAI,KAAK;CAEzB,IADa,cAAc,GACvB,CAAA,CAAK,MAAM,OAAO,CAAC,CAAC,SAAS,cAAc,GAAG;CAClD,OAAO;AACT;AACA,SAAS,OAAO,KAAmB;CACjC,IAAI;EACF,OAAO,SAAS,GAAG,CAAC,CAAC,OAAO;CAC9B,SAAS,OAAO;EACd,IAAI,CAAC,UAAU,SAAS,CAAC,CAAC,SAAU,MAAgC,QAAQ,EAAE,GAAG,OAAO;EACxF,MAAM;CACR;AACF;AACA,SAAS,SAAS,KAAmB;CACnC,IAAI,UAAU,GAAG,GAAG,QAAQ,IAAI,GAAG;AACrC;;AAGA,SAAgB,2BAA2B,OAAkB;CAC3D,uBAAuB;CACvB,SAAS,MAAM,IAAI;CACnB,IAAI,OAAO;CACX,QAAQ,cAAc;EACp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AAC,IAAI,OAAO;EAElE,OAAO;CACT;AACF"}
|
package/dist/runtime.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const MINIMUM_NODE_VERSION = "24.15.0";
|
|
2
|
+
|
|
3
|
+
/** Reject unsupported runtimes before importing the CLI and its Node.js APIs. */
|
|
4
|
+
export function assertSupportedRuntime(version = process.versions.node) {
|
|
5
|
+
const actual = version.split(".").map(Number);
|
|
6
|
+
const minimum = MINIMUM_NODE_VERSION.split(".").map(Number);
|
|
7
|
+
const difference = actual.findIndex((part, index) => part !== minimum[index]);
|
|
8
|
+
const supported =
|
|
9
|
+
/^\d+\.\d+\.\d+$/.test(version) &&
|
|
10
|
+
(difference === -1 || actual[difference] > minimum[difference]);
|
|
11
|
+
if (!supported)
|
|
12
|
+
throw new Error(
|
|
13
|
+
`Duraxis requires Node.js ${MINIMUM_NODE_VERSION} or newer.\nCurrent version: ${version}\nPlease upgrade your Node.js installation.`,
|
|
14
|
+
);
|
|
15
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** One hook pair per library instance, limited to explicitly loaded local module graphs. */
|
|
2
|
+
export declare function initializeTypeScriptLoader(entry: URL): void;
|
|
3
|
+
/** Call only when no config/entity/migration callbacks need further dynamic imports. Node's module cache is retained. */
|
|
4
|
+
export declare function disposeTypeScriptLoader(): void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@duraxis/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Standalone migration CLI for Duraxis.",
|
|
5
5
|
"license": "ISC",
|
|
6
6
|
"author": "João Paulo Dias <joaopdias.dev@gmail.com>",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"url": "https://github.com/Joaopdiasventura/Duraxis/issues"
|
|
22
22
|
},
|
|
23
23
|
"engines": {
|
|
24
|
-
"node": ">=
|
|
24
|
+
"node": ">=24.15.0"
|
|
25
25
|
},
|
|
26
26
|
"publishConfig": {
|
|
27
27
|
"access": "public",
|
|
@@ -46,14 +46,15 @@
|
|
|
46
46
|
],
|
|
47
47
|
"sideEffects": false,
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@duraxis/core": "0.
|
|
50
|
-
"@duraxis/migrations": "0.
|
|
51
|
-
"@duraxis/orm": "0.
|
|
49
|
+
"@duraxis/core": "0.3.0",
|
|
50
|
+
"@duraxis/migrations": "0.2.0",
|
|
51
|
+
"@duraxis/orm": "0.3.0",
|
|
52
52
|
"typescript": "5.9.3"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@duraxis/storage-memory": "0.1.3",
|
|
56
|
-
"@duraxis/storage-disk": "0.1.3"
|
|
56
|
+
"@duraxis/storage-disk": "0.1.3",
|
|
57
|
+
"reflect-metadata": "^0.2.2"
|
|
57
58
|
},
|
|
58
59
|
"bin": {
|
|
59
60
|
"duraxis": "./dist/bin.js"
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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,CAA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AC,CAAC,KAAK,IAAI,EAAE,wBAAwB,OAAO,QAAQ,OAAO,YAAY,OAAO,QAAQ,OAAO,SAC/R;GACF,OAAO,IAAI,WAAW,gBAAgB;IACpC,MAAM,OAAO,MAAM,OAAO,MAAM;IAEhC,MAAM,MAAM,QAAQ,IAAI,CAAC;GAC3B,OAAO,IAAI,WAAW,iBAAiB;IACrC,MAAM,OAAO,OAAO;IAEpB,MAAM,QAAA,GAAOF,oBAAAA,YAAAA,CACX,MAAM,UAAU,GAAG,EAAE,CAAC,EAAE,SAAS,eAAe,CAAC,GACjD,MAAM,SAAS,CACjB;IAEA,IAAI,KAAK,WAAW,QAClB,MAAM,IAAI,MAAM,kCAAkC,QAAQ,IAAI,GAAG;IAEnE,MACE,EAAE,OAAO,KAAK,GACd,sEACF;GACF;EACF,CAAC;EAED,OAAO;CACT,SAAS,OAAO;EACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAErE,SAAS,aAAa,KAAK,UAAU,EAAE,OAAO,QAAQ,CAAC,IAAI,OAAO;EAElE,OAAO;CACT;AACF"}
|
package/dist/ts-loader.mjs
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import ts from "typescript";
|
|
2
|
-
import { readFile } from "node:fs/promises";
|
|
3
|
-
export async function resolve(specifier, context, nextResolve) {
|
|
4
|
-
try {
|
|
5
|
-
return await nextResolve(specifier, context);
|
|
6
|
-
} catch (error) {
|
|
7
|
-
if (
|
|
8
|
-
error.code == "ERR_MODULE_NOT_FOUND" &&
|
|
9
|
-
/^(\.|\/)/.test(specifier) &&
|
|
10
|
-
specifier.endsWith(".js")
|
|
11
|
-
)
|
|
12
|
-
return nextResolve(specifier.slice(0, -3) + ".ts", context);
|
|
13
|
-
throw error;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
export async function load(url, context, nextLoad) {
|
|
17
|
-
if (!url.endsWith(".ts") || url.endsWith(".d.ts")) return nextLoad(url, context);
|
|
18
|
-
const source = await readFile(new URL(url), "utf8");
|
|
19
|
-
const result = ts.transpileModule(source, {
|
|
20
|
-
fileName: new URL(url).pathname,
|
|
21
|
-
reportDiagnostics: true,
|
|
22
|
-
compilerOptions: {
|
|
23
|
-
target: ts.ScriptTarget.ES2022,
|
|
24
|
-
module: ts.ModuleKind.ESNext,
|
|
25
|
-
experimentalDecorators: true,
|
|
26
|
-
emitDecoratorMetadata: true,
|
|
27
|
-
useDefineForClassFields: false,
|
|
28
|
-
sourceMap: false,
|
|
29
|
-
},
|
|
30
|
-
});
|
|
31
|
-
const errors = (result.diagnostics ?? []).filter(
|
|
32
|
-
(item) => item.category == ts.DiagnosticCategory.Error,
|
|
33
|
-
);
|
|
34
|
-
if (errors.length)
|
|
35
|
-
throw new Error(
|
|
36
|
-
ts.formatDiagnosticsWithColorAndContext(errors, {
|
|
37
|
-
getCurrentDirectory: () => process.cwd(),
|
|
38
|
-
getCanonicalFileName: (file) => file,
|
|
39
|
-
getNewLine: () => "\n",
|
|
40
|
-
}),
|
|
41
|
-
);
|
|
42
|
-
return { format: "module", source: result.outputText, shortCircuit: true };
|
|
43
|
-
}
|