@duraxis/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # @duraxis/cli
2
+
3
+ ## 0.1.0
4
+
5
+ Initial migration tooling.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 João Paulo Dias
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,245 @@
1
- # Temporary Holding Version
1
+ # @duraxis/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Standalone Duraxis migration tooling for Node.js 22.12+. The CLI builds on
4
+ `@duraxis/migrations` and the ORM's database-independent schema exporter.
5
+
6
+ ## Quick start
7
+
8
+ ```bash
9
+ pnpm add @duraxis/core @duraxis/orm @duraxis/migrations @duraxis/storage-disk
10
+ pnpm add -D @duraxis/cli
11
+ pnpm exec duraxis init
12
+ ```
13
+
14
+ Edit the generated config to import your decorated entities and open your storage:
15
+
16
+ ```ts
17
+ import { fileURLToPath } from "node:url";
18
+ import { defineDuraxisConfig } from "@duraxis/cli";
19
+ import { DuraxisDatabase } from "@duraxis/core";
20
+ import { AsyncDiskStorageDriver } from "@duraxis/storage-disk";
21
+ import { User } from "./src/entities/user.entity.js";
22
+
23
+ export default defineDuraxisConfig({
24
+ entities: [User],
25
+ migrations: {
26
+ directory: "./duraxis/migrations",
27
+ snapshots: "./duraxis/snapshots",
28
+ format: "ts",
29
+ },
30
+ async createDatabase() {
31
+ const storage = await AsyncDiskStorageDriver.open({
32
+ directory: fileURLToPath(new URL("./data/duraxis", import.meta.url)),
33
+ });
34
+ return new DuraxisDatabase({ storage });
35
+ },
36
+ });
37
+ ```
38
+
39
+ ```bash
40
+ pnpm exec duraxis migration:generate initial-schema
41
+ pnpm exec duraxis migrate:up
42
+ # Modify entity definitions to add an optional status column.
43
+ pnpm exec duraxis migration:generate add-user-status
44
+ pnpm exec duraxis migrate:diff
45
+ pnpm exec duraxis migrate:up
46
+ pnpm exec duraxis migrate:status
47
+ pnpm exec duraxis migrate:check
48
+ pnpm exec duraxis migrate:down --yes
49
+ ```
50
+
51
+ Generated rollback rejects populated fields or collections it would remove. For
52
+ production, review generated files, constraints, data transformations, and backups
53
+ before applying or reverting. Never edit a shared or applied migration.
54
+
55
+ Without a local installation, use the scoped package name explicitly:
56
+
57
+ ```bash
58
+ npx --package @duraxis/cli duraxis --help
59
+ ```
60
+
61
+ An unscoped `npx duraxis` does not identify this package. Install the dev dependency
62
+ before using `pnpm exec duraxis`.
63
+
64
+ ## Configuration and loading
65
+
66
+ Discovery walks from the working directory upward for `duraxis.config.ts`,
67
+ `duraxis.config.js`, or `duraxis.config.mjs`. `--config <path>` overrides discovery.
68
+ Migration and snapshot directories resolve relative to the config file. Paths
69
+ inside your database factory are your responsibility; use `import.meta.url` as
70
+ above instead of depending on the command's working directory.
71
+
72
+ `entities` accepts a class array or an async factory returning classes, allowing
73
+ project-specific entity discovery. `migrations.format` is `ts` (default) or `js`.
74
+ A `databases` object can hold named connection configs with the same three fields
75
+ (`entities`, `migrations`, `createDatabase`). Select one with `--database <name>`;
76
+ the top-level connection is the default.
77
+
78
+ The factory returns an owned Core database, not a NestJS connection. The CLI closes
79
+ that database and storage in a `finally` block. Factories must clean up resources
80
+ if they fail before returning. Do not pass an application-owned connection to
81
+ this CLI API; use the programmatic runner for that scenario.
82
+
83
+ The packaged loader compiles `.ts` modules using pinned TypeScript 5.9.3, ES2022
84
+ ESM, legacy decorators, and decorator metadata. It resolves relative `.js`
85
+ imports to `.ts` when JavaScript is absent. Native Node type stripping alone is
86
+ not used. Explicit `.ts` extensions also work. Entity columns should declare their
87
+ Core `type` explicitly. Config files and migrations are trusted executable code:
88
+ keep their module initialization free of database writes and external side effects.
89
+ TypeScript path aliases, CommonJS migration files, and custom compiler plugins
90
+ are not supported. Use relative ESM imports and normal package imports.
91
+
92
+ Local generation, local diff, offline check, and dry-run never call the database
93
+ factory. Other commands open the configured database. Disk requires exclusive
94
+ directory ownership: stop the application or use deployment sequencing that
95
+ releases that directory before invoking the CLI.
96
+
97
+ ## Commands
98
+
99
+ Every command supports `--config`, `--database`, and `--json`. Unknown options and
100
+ options inappropriate for a command are errors. Errors exit with code 1; success
101
+ exits 0. `--json` emits machine-readable success results for inspection commands
102
+ and JSON errors on stderr. No command requires an interactive prompt.
103
+
104
+ | Command | Behavior and options |
105
+ | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
106
+ | `init` | Creates a config, migration/snapshot directories, and an empty `baseline.json`; refuses existing files. Does not modify application source. |
107
+ | `migration:create <name>` | Creates a throwing manual template. Complete it and provide an expected snapshot before use. |
108
+ | `migration:snapshot --schema <file>` | Saves an intended snapshot for the latest manual migration from a JSON array of Core collection definitions. Never overwrites a snapshot. Application verifies the result atomically. |
109
+ | `migration:generate <name>` | Compares the latest local snapshot with exported entities and generates a self-contained migration/snapshot pair. No file on no-change. `--allow-destructive` authorizes generating removals. |
110
+ | `migration:remove --yes` | Removes the latest unpublished local migration and its snapshot after proving it is unapplied to this configured database. Also accepts an unfinished latest template. |
111
+ | `migration:baseline <name> --yes` | Adopts an existing matching managed catalog without reapplying creation. Creates initial artifacts, or validates and registers a single unmodified generated initial artifact. |
112
+ | `migrate:up` | Applies pending versions in ascending order, one transaction each. `--steps N` or `--to ID` (inclusive); `--allow-destructive` for schema removal. |
113
+ | `migrate:up --dry-run` | Static local artifact preview; does not open the target database or execute callbacks. Applied/pending status is explicitly unknown. Supports `--steps` or `--to`. |
114
+ | `migrate:down --yes` | Reverts the latest version; `--steps N` or `--to ID`. `--to` **retains** the target and reverts later versions. Requires usable `down()` implementations. |
115
+ | `migrate:status` | Displays applied/pending versions and validates checksums, history, snapshots, and managed catalog drift. Integrity failures exit nonzero. |
116
+ | `migrate:diff` | Compares the latest local snapshot with current entities. `--persisted` instead compares the applied expected snapshot with persisted managed catalog in one transaction, while checking history integrity. |
117
+ | `migrate:check` | Checks local artifacts, snapshots, chain, applied checksums, managed drift, and unrepresented entity changes. `--offline` excludes database/history checks. |
118
+
119
+ `steps` and `to` are mutually exclusive. Names are sanitized to lowercase
120
+ underscore-separated names; paths and traversal components are rejected. IDs use
121
+ UTC milliseconds and advance beyond the latest local timestamp on collisions.
122
+ Exclusive filesystem creation prevents overwrites. Concurrent development branches
123
+ can produce divergent parents: rebase and regenerate unpublished branches before
124
+ release. There is no automatic history merge.
125
+
126
+ ## Automatic and manual migrations
127
+
128
+ Generation uses snapshots, not an arbitrary development database. Entity metadata
129
+ is desired schema; snapshots are versioned expected schema; migration files are
130
+ executable changes; the persisted catalog and internal history are actual state.
131
+ Generated files embed definitions and never import current entities. Plans stage
132
+ the final catalog graph atomically, supporting circular foreign keys.
133
+
134
+ Type changes and newly required fields on existing collections require explicit
135
+ manual transformations, so generation rejects them. It does not infer renames.
136
+ Use `migration:create` and write `context.schema.renameField`, backfills, or other
137
+ transformations. For example:
138
+
139
+ ```ts
140
+ import { defineMigration } from "@duraxis/migrations";
141
+ export default defineMigration({
142
+ id: "20261127110000000_add_status", // Use the generated filename's ID.
143
+ async up(context) {
144
+ context.schema.addField("users", "status", { type: "string", required: true });
145
+ await context.transform("users", (document) => ({ ...document, status: "active" }));
146
+ },
147
+ // Omit down when values cannot be safely restored.
148
+ });
149
+ ```
150
+
151
+ Prepare a complete JSON array of intended managed collection definitions, then run:
152
+
153
+ ```bash
154
+ pnpm exec duraxis migration:snapshot --schema expected-schema.json
155
+ pnpm exec duraxis migrate:up
156
+ ```
157
+
158
+ The supplied snapshot is an intention, not proof that a manual callback is correct.
159
+ The runner verifies the actual resulting catalog hash before publication; Core
160
+ then validates existing documents, constraints, and indexes. A throwing template
161
+ or mismatched schema cannot acquire an applied history entry.
162
+
163
+ Generated removal of a field rejects existing values, even with
164
+ `--allow-destructive`; write an explicit `removeField` with `delete-values` to
165
+ acknowledge data loss. Generated collection drops have no automatic rollback.
166
+ Generated inverses for field/collection creation reject populated data. Unique
167
+ index creation validates duplicates; constraint failures roll back the version.
168
+
169
+ ## Snapshots and immutable identity
170
+
171
+ Commit all migration files and snapshots, including the empty baseline. Every
172
+ migration must have one snapshot with matching ID, parent, and hash. Duplicate
173
+ TS/JS copies, missing applied files, orphan snapshots, incompatible formats,
174
+ checksum mismatches, and divergent chains are rejected. Production should contain
175
+ one executable format per migration, not both `.ts` and `.js` copies.
176
+
177
+ Artifact checksums normalize executable code with pinned TypeScript 5.9.3 (two
178
+ passes, ES2022 ESM, comments removed, legacy decorators, metadata enabled,
179
+ `useDefineForClassFields: false`). Compiled migrations must preserve this target
180
+ and ESM module form. Comments/types/formatting do not change identity; executable
181
+ edits do. External helper content is not transitively hashed: keep historical
182
+ migrations self-contained and pin unavoidable dependencies. Do not bundle,
183
+ minify, or downlevel production migrations. Snapshots and IDs accompany compiled
184
+ files unchanged. The packed consumer test verifies this deployment path.
185
+
186
+ ## Existing databases and recovery
187
+
188
+ Baseline compares only entity-owned collections, permits unrelated collections,
189
+ and registers the initial generated schema in the same transaction that verifies
190
+ its persisted definitions. The same initial migration creates the schema on a new
191
+ empty database. Baseline refuses incompatible catalogs or existing history. If
192
+ registration fails after files were written, retain those files; rerun the
193
+ baseline command to validate the single generated initial artifact and register
194
+ it, provided persisted history is still empty. If history is already recorded,
195
+ inspect `migrate:status` instead.
196
+
197
+ History lives in protected transactional Core metadata, never a local JSON history
198
+ file. CAS publication coordinates runners across processes. Conflicts reload
199
+ history; identical committed versions are accepted and arbitrary callbacks are
200
+ never automatically replayed. Unknown publication outcomes are reconciled against
201
+ persisted receipts and Core recovery; inconclusive outcomes stop safely. Do not
202
+ assume an unknown outcome rolled back. Restore storage availability and inspect
203
+ status before further action. Checkpoints do not invalidate persisted receipts.
204
+
205
+ Generation/removal uses an exclusive `.duraxis-artifacts.lock` guard. Ordinary
206
+ pair-write failures remove the newly created migration. Removal renames both files
207
+ before deleting either. A process crash may leave the guard, a partial pair, or
208
+ `.removing-*` tombstones. Stop other writers, inspect/recover the intended pair
209
+ from version control or tombstones, verify the snapshot chain, then remove the
210
+ stale guard and run `migrate:check`. Filesystem pair updates are not a power-loss
211
+ atomic database transaction. Never remove guards automatically based on age.
212
+
213
+ Checking one configured database cannot prove a migration was never applied in
214
+ another environment. Never remove shared or released migrations. Checksums have
215
+ no default bypass flag. Rollback runs explicit transactional code against current
216
+ data; it never restores an old manifest or discards unrelated later writes.
217
+
218
+ ## Deployment and CI
219
+
220
+ ```bash
221
+ pnpm exec duraxis migrate:check --offline
222
+ pnpm exec duraxis migrate:up
223
+ pnpm exec duraxis migrate:check
224
+ # Start the application only after successful validation.
225
+ ```
226
+
227
+ Ship the CLI in the migration job's image even when application dev dependencies
228
+ are omitted. For disk, release exclusive storage ownership before the job. For
229
+ S3, use the existing driver's conditional publication and namespace configuration;
230
+ ordinary application writers are not locked out by migrations. Quiesce writers
231
+ for incompatible changes. Use one deployment job, backups, and representative
232
+ pre-production data. Do not depend on process-local locks across replicas.
233
+
234
+ For NestJS, run migrations before application initialization with
235
+ `schema: { mode: "validate" }`, or `validate-managed` to reject extra indexes in
236
+ managed collections. No mandatory CLI dependency or automatic startup migration
237
+ is added to NestJS. Existing named connections, `forRootAsync`, entity auto-loading,
238
+ and transaction ownership are unchanged. Stop incompatible older replicas before
239
+ schema changes; use staged compatible releases for rolling deployments.
240
+
241
+ All transformed writes and affected-schema validation writes are staged in memory
242
+ until one atomic commit. Streaming reads do not provide bounded transaction size.
243
+ There is no online DDL, resumable batching, distributed maintenance lock, or
244
+ implicit partial migration commit. See [`@duraxis/migrations`](../migrations/README.md)
245
+ for the programmatic API, recovery guarantees, and Core compatibility details.
@@ -0,0 +1,17 @@
1
+ import { type MigrationArtifact, type SchemaSnapshot, type SchemaPlan } from "@duraxis/migrations";
2
+ import type { CollectionDefinition } from "@duraxis/core";
3
+ import { type DuraxisConnectionConfig } from "./config.js";
4
+ export declare function artifactChecksum(source: string): string;
5
+ export interface LocalArtifacts {
6
+ readonly artifacts: readonly MigrationArtifact[];
7
+ readonly files: readonly string[];
8
+ readonly snapshots: string;
9
+ readonly directory: string;
10
+ }
11
+ export declare function loadArtifacts(config: DuraxisConnectionConfig, root: string, ownsLock?: boolean, omitLatest?: boolean): Promise<LocalArtifacts>;
12
+ export declare function migrationId(name: string, previous?: string): string;
13
+ export declare function renderMigration(id: string, plan?: SchemaPlan): string;
14
+ export declare function withArtifactLock<T>(directory: string, callback: () => Promise<T>): Promise<T>;
15
+ export declare function writePair(migrationPath: string, source: string, snapshotPath: string, snapshot: SchemaSnapshot): Promise<void>;
16
+ export declare function removePair(migrationPath: string, snapshotPath: string): Promise<void>;
17
+ export declare function snapshotFor(id: string, parent: string | null, schema: readonly CollectionDefinition[]): SchemaSnapshot;
package/dist/bin.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { runCLI } from "./index.js";
3
+ process.exitCode = await runCLI(process.argv.slice(2));
package/dist/cli.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export interface CLIIO {
2
+ readonly cwd?: string;
3
+ readonly out?: (message: string) => void;
4
+ readonly error?: (message: string) => void;
5
+ }
6
+ export declare function runCLI(args: readonly string[], io?: CLIIO): Promise<number>;
@@ -0,0 +1,22 @@
1
+ import type { DuraxisDatabase } from "@duraxis/core";
2
+ import type { EntityClass } from "@duraxis/orm";
3
+ export interface DuraxisConnectionConfig {
4
+ readonly entities: readonly EntityClass[] | (() => readonly EntityClass[] | Promise<readonly EntityClass[]>);
5
+ readonly migrations: {
6
+ readonly directory: string;
7
+ readonly snapshots: string;
8
+ readonly format?: "ts" | "js";
9
+ };
10
+ readonly createDatabase: () => DuraxisDatabase | Promise<DuraxisDatabase>;
11
+ }
12
+ export interface DuraxisConfig extends DuraxisConnectionConfig {
13
+ readonly databases?: Readonly<Record<string, DuraxisConnectionConfig>>;
14
+ }
15
+ export declare function defineDuraxisConfig<const T extends DuraxisConfig>(config: T): T;
16
+ export declare function importFile(path: string): Promise<unknown>;
17
+ export declare function loadConfig(cwd: string, explicit?: string, database?: string): Promise<{
18
+ config: DuraxisConnectionConfig;
19
+ root: string;
20
+ path: string;
21
+ }>;
22
+ export declare function readJSON<T>(path: string): Promise<T>;