symmetria-kit 1.0.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/dist/cli.js ADDED
@@ -0,0 +1,1656 @@
1
+ #!/usr/bin/env node
2
+ import { f as canonicalJSON, g as migrationSnapshot } from "./ddl-BpRIXfCw.js";
3
+ import { n as diffSchemas } from "./diff-ConfLt63.js";
4
+ import { _ as formatLintFindings, a as verifyMigrations, c as detectDrift, d as lintMigrationSQL, f as generateMigration, g as recoverMigrationFiles, h as squashMigrations, l as formatDriftFindings, n as schemaGraph, o as migrator, p as loadMigrationState, r as pullSchema, t as renderMermaid, v as lintMigration } from "./src-C2mBlLSB.js";
5
+ import { _ as supportsColor, a as matchesEntry, b as wrapLines, c as ask, d as withScreen, f as withSpinner, g as panel, h as heading, i as inspectTabs, l as choose, m as formatError, n as inspectEntries, o as matchesTableName, p as fitLine, r as inspectTableSQL, s as matchingTables, t as highlightSQL, u as view, v as terminalWidth, y as theme } from "./schema-browser-data-BVymL_xf.js";
6
+ import * as nodeModule from "node:module";
7
+ import { access, lstat, mkdir, open, readFile, readdir, rm, writeFile } from "node:fs/promises";
8
+ import { basename, dirname, extname, relative, resolve } from "node:path";
9
+ import { postgres } from "symmetria/driver";
10
+ import { pathToFileURL } from "node:url";
11
+ import stringWidth from "string-width";
12
+ import { emitKeypressEvents } from "node:readline";
13
+ import { parseArgs, stripVTControlCharacters } from "node:util";
14
+ //#region src/cli/context.ts
15
+ /** Everything a command needs: terminal mode, output, the project configuration and a database driver. */
16
+ const createContext = (values, output, rerun) => {
17
+ const pretty = !!process.stdout.isTTY && process.env.TERM !== "dumb";
18
+ const interactive = !!process.stdin.isTTY && pretty && !values["no-interactive"] && !values.json && !values.sql;
19
+ const color = supportsColor() && !values["no-color"] && !values.json && !values.sql;
20
+ const { style } = theme(color);
21
+ return {
22
+ values,
23
+ output,
24
+ pretty,
25
+ interactive,
26
+ color,
27
+ style,
28
+ progress: (label, operation) => withSpinner(label, operation, {
29
+ enabled: pretty && !values.json && !values.sql,
30
+ color,
31
+ animation: !values["no-animation"]
32
+ }),
33
+ select: (question, choices) => choose(question, choices, { color }),
34
+ emit: (rendering) => {
35
+ output(values.json ? JSON.stringify(rendering.json, rendering.replacer, rendering.indent) : pretty && rendering.pretty ? rendering.pretty() : rendering.plain());
36
+ },
37
+ rerun
38
+ };
39
+ };
40
+ const TIMEOUT_FLAGS = [
41
+ ["advisoryLockTimeoutMs", "advisory-lock-timeout"],
42
+ ["lockTimeoutMs", "lock-timeout"],
43
+ ["statementTimeoutMs", "statement-timeout"]
44
+ ];
45
+ const RESOLVE_EXTENSIONS = [
46
+ ".ts",
47
+ ".mts",
48
+ ".js",
49
+ ".mjs",
50
+ "/index.ts",
51
+ "/index.js"
52
+ ];
53
+ const RELATIVE_SPECIFIER = /^(\.\.?\/|\/|file:)/;
54
+ const KNOWN_EXTENSION = /\.[cm]?[jt]sx?$|\.json$/;
55
+ let hooksRegistered = false;
56
+ /**
57
+ * Node resolves `./src/schema` only with an extension, so the config and the
58
+ * modules it imports get extension fallbacks. Bun resolves them natively and
59
+ * has no registerHooks.
60
+ */
61
+ const registerExtensionHooks = () => {
62
+ const registerHooks = nodeModule.registerHooks;
63
+ if (hooksRegistered || typeof registerHooks !== "function") return;
64
+ hooksRegistered = true;
65
+ registerHooks({ resolve(specifier, context, nextResolve) {
66
+ try {
67
+ return nextResolve(specifier, context);
68
+ } catch (error) {
69
+ const code = error?.code;
70
+ if (code !== "ERR_MODULE_NOT_FOUND" && code !== "ERR_UNSUPPORTED_DIR_IMPORT" || !RELATIVE_SPECIFIER.test(specifier) || KNOWN_EXTENSION.test(specifier)) throw error;
71
+ for (const extension of RESOLVE_EXTENSIONS) try {
72
+ return nextResolve(`${specifier}${extension}`, context);
73
+ } catch {}
74
+ throw error;
75
+ }
76
+ } });
77
+ };
78
+ const loadProject = async (context) => {
79
+ const { values } = context;
80
+ const configPath = resolve(values.config ?? "symmetria.config.ts");
81
+ const present = await access(configPath).then(() => true, (error) => {
82
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT" && !values.config) return false;
83
+ throw error;
84
+ });
85
+ let config = {};
86
+ if (present) {
87
+ registerExtensionHooks();
88
+ const module = await context.progress("Loading schema", () => import(pathToFileURL(configPath).href));
89
+ if (!module.default || typeof module.default !== "object") throw new Error("symmetria: config must default-export a migration configuration");
90
+ config = module.default;
91
+ }
92
+ const directory = values.dir ? resolve(values.dir) : resolve(present ? dirname(configPath) : process.cwd(), config.directory ?? "migrations");
93
+ const databaseUrl = values["database-url"] ?? config.databaseUrl ?? process.env.DATABASE_URL;
94
+ const timeouts = Object.fromEntries(TIMEOUT_FLAGS.flatMap(([key, flag]) => {
95
+ const value = values[flag] === void 0 ? config[key] : Number(values[flag]);
96
+ if (value === void 0) return [];
97
+ if (!Number.isSafeInteger(value) || value < 0 || value > 2147483647) throw new Error(`symmetria: invalid --${flag}`);
98
+ return [[key, value]];
99
+ }));
100
+ const verificationDatabaseUrl = values["verify-url"] ?? config.verificationDatabaseUrl;
101
+ return {
102
+ configPath,
103
+ present,
104
+ config,
105
+ directory,
106
+ databaseUrl,
107
+ runnerOptions: {
108
+ directory,
109
+ ...config.metadataSchema ? { metadataSchema: config.metadataSchema } : {},
110
+ ...config.metadataTable ? { metadataTable: config.metadataTable } : {},
111
+ ...verificationDatabaseUrl ? { verificationDatabaseUrl } : {},
112
+ ...timeouts,
113
+ ...config.onEvent ? { onEvent: config.onEvent } : {}
114
+ },
115
+ snapshot: () => {
116
+ const source = config.schema;
117
+ return source ? "$snapshot" in source ? source.$snapshot() : source : void 0;
118
+ }
119
+ };
120
+ };
121
+ /**
122
+ * Opens a driver for the configured database, turns SIGINT/SIGTERM into a
123
+ * cancellation signal with the conventional exit codes, and always closes it.
124
+ */
125
+ const withDatabase = async (project, operation) => {
126
+ if (!project.databaseUrl) throw new Error("symmetria: configure databaseUrl or DATABASE_URL");
127
+ const driver = postgres(project.databaseUrl);
128
+ try {
129
+ return await withCancellation((signal) => operation(driver, signal));
130
+ } finally {
131
+ await driver.close();
132
+ }
133
+ };
134
+ const withCancellation = async (operation) => {
135
+ const cancellation = new AbortController();
136
+ const interrupt = () => {
137
+ process.exitCode = 130;
138
+ cancellation.abort(/* @__PURE__ */ new Error("symmetria: interrupted"));
139
+ };
140
+ const terminate = () => {
141
+ process.exitCode = 143;
142
+ cancellation.abort(/* @__PURE__ */ new Error("symmetria: terminated"));
143
+ };
144
+ process.once("SIGINT", interrupt);
145
+ process.once("SIGTERM", terminate);
146
+ try {
147
+ return await operation(cancellation.signal);
148
+ } finally {
149
+ process.removeListener("SIGINT", interrupt);
150
+ process.removeListener("SIGTERM", terminate);
151
+ }
152
+ };
153
+ //#endregion
154
+ //#region src/cli/ui/format.ts
155
+ const equal = (left, right) => canonicalJSON(left ?? null) === canonicalJSON(right ?? null);
156
+ const columnLabel = (column) => [
157
+ column.sqlType,
158
+ column.notNull ? "" : "nullable",
159
+ column.identity ? "identity" : "",
160
+ column.unique ? "unique" : "",
161
+ column.default === void 0 ? "" : `default ${column.default}`,
162
+ column.references ? `→ ${column.references.table}.${column.references.column} ON DELETE ${column.references.onDelete}` : ""
163
+ ].filter(Boolean).join(" · ");
164
+ const formatDiff = (plan, color = false, renames = {}) => {
165
+ const { style } = theme(color);
166
+ if (!plan.up.length) return color ? `\n ${style("✓", "success")} No schema changes. ${style("Everything is in sync.", "muted")}\n` : "No schema changes.";
167
+ const output = color ? [heading("Schema changes", "code → snapshot", color)] : [];
168
+ const previous = new Map(plan.before.tables.map((table) => [table.name, table]));
169
+ const next = new Map(plan.after.tables.map((table) => [table.name, table]));
170
+ const marker = (sign, text) => style(` ${sign} ${text}`, sign === "+" ? "success" : sign === "-" ? "danger" : "warning");
171
+ let changed = 0;
172
+ for (const name of [...new Set([...previous.keys()].map((name) => renames.tables?.[name] ?? name).concat([...next.keys()]))].sort()) {
173
+ const originalName = Object.entries(renames.tables ?? {}).find(([, target]) => target === name)?.[0] ?? name;
174
+ const before = previous.get(originalName);
175
+ const after = next.get(name);
176
+ if (equal(before, after)) continue;
177
+ changed++;
178
+ output.push(style(` ${before ? after ? "~" : "-" : "+"} ${originalName === name ? name : `${originalName} → ${name}`}`, "accent"));
179
+ const renamedColumns = renames.columns?.[name] ?? {};
180
+ const columns = /* @__PURE__ */ new Set([...before?.columns.map((column) => renamedColumns[column.name] ?? column.name) ?? [], ...after?.columns.map((column) => column.name) ?? []]);
181
+ for (const columnName of columns) {
182
+ const originalColumnName = Object.entries(renamedColumns).find(([, target]) => target === columnName)?.[0] ?? columnName;
183
+ const old = before?.columns.find((column) => column.name === originalColumnName);
184
+ const current = after?.columns.find((column) => column.name === columnName);
185
+ if (equal(old, current)) continue;
186
+ output.push(marker(old ? current ? "~" : "-" : "+", `${(originalColumnName === columnName ? columnName : `${originalColumnName} → ${columnName}`).padEnd(20)} ${old && current && columnLabel(old) !== columnLabel(current) ? `${columnLabel(old)} → ${columnLabel(current)}` : columnLabel(current ?? old)}`));
187
+ }
188
+ if (!equal(before?.primaryKey ?? [], after?.primaryKey ?? [])) output.push(marker(before?.primaryKey.length ? after?.primaryKey.length ? "~" : "-" : "+", `primary key (${(before?.primaryKey ?? []).join(", ")}) → (${(after?.primaryKey ?? []).join(", ")})`));
189
+ for (const kind of ["indexes", "checks"]) {
190
+ const names = /* @__PURE__ */ new Set([...before?.[kind]?.map((entry) => entry.sqlName) ?? [], ...after?.[kind]?.map((entry) => entry.sqlName) ?? []]);
191
+ for (const name of names) {
192
+ const old = before?.[kind]?.find((entry) => entry.sqlName === name);
193
+ const current = after?.[kind]?.find((entry) => entry.sqlName === name);
194
+ if (equal(old, current)) continue;
195
+ const entry = current ?? old;
196
+ const description = "expression" in entry ? `CHECK (${entry.expression})` : `${entry.unique ? "UNIQUE " : ""}${entry.method} (${entry.keys.join(", ")})${entry.include.length ? ` INCLUDE (${entry.include.join(", ")})` : ""}${entry.where ? ` WHERE ${entry.where}` : ""}`;
197
+ output.push(marker(old ? current ? "~" : "-" : "+", `${name} ${description}`));
198
+ }
199
+ }
200
+ output.push("");
201
+ }
202
+ for (const name of new Set([...plan.before.enumerations, ...plan.after.enumerations].map((entry) => entry.name))) {
203
+ const before = plan.before.enumerations.find((entry) => entry.name === name);
204
+ const after = plan.after.enumerations.find((entry) => entry.name === name);
205
+ if (!equal(before, after)) output.push(marker(before ? after ? "~" : "-" : "+", `enum ${name}: ${(before?.values ?? []).join(" | ")} → ${(after?.values ?? []).join(" | ")}`));
206
+ }
207
+ output.push(` ${style(`${changed} tables changed`, "violet")} ${style("·", "muted")} ${style(`${plan.up.filter((statement) => !statement.startsWith("--")).length} SQL statements`, "accent")}`);
208
+ if (color) output.push(` ${style("+ added", "success")} ${style("~ modified", "warning")} ${style("− removed", "danger")}\n`);
209
+ return output.join("\n");
210
+ };
211
+ const formatSchema = (snapshot, name, relationsOnly = false, color = false) => {
212
+ const { style } = theme(color);
213
+ const tables = name ? snapshot.tables.filter((table) => table.name === name || table.sqlName === name) : snapshot.tables;
214
+ if (name && !tables.length) throw new Error(`symmetria: unknown table "${name}"`);
215
+ if (relationsOnly) return tables.flatMap((table) => table.relations.map((relation) => ` ${style(`${table.name}.${relation.name}`, "accent")} ${style(relation.kind === "one" || relation.kind === "condition" && !relation.many ? "──" : "──<", "violet")} ${style(relation.target, "success")}${relation.kind === "through" ? style(` through ${relation.junction}`, "muted") : relation.kind === "condition" ? style(" by condition", "muted") : ""}`)).join("\n") || "No relations.";
216
+ return tables.map((table) => [
217
+ color ? heading(table.name, `${table.columns.length} columns${table.name === table.sqlName ? "" : ` · ${table.sqlName}`}`, color) : ` ${table.name}${table.name === table.sqlName ? "" : ` (${table.sqlName})`}`,
218
+ ...table.columns.map((column, position) => ` ${style(position === table.columns.length - 1 ? "└─" : "├─", "border")} ${style(column.name.padEnd(20), column.primaryKey ? "strong" : "accent")} ${[
219
+ style(column.sqlType, "violet"),
220
+ column.primaryKey ? style("primary key", "warning") : "",
221
+ column.unique ? style("unique", "success") : "",
222
+ column.notNull ? "" : style("nullable", "muted"),
223
+ column.references ? style(`→ ${column.references.table}.${column.references.column}`, "accent") : "",
224
+ column.default ? style(`default ${column.default.kind === "sql" ? column.default.sql : JSON.stringify(column.default.value, (_name, value) => typeof value === "bigint" ? String(value) : value)}`, "muted") : ""
225
+ ].filter(Boolean).join(style(" · ", "border"))}`),
226
+ ...table.relations.length ? [
227
+ "",
228
+ ` ${style("Relations", "violet")}`,
229
+ ...table.relations.map((relation) => ` ${style(relation.name.padEnd(20), "accent")} ${style(relation.kind === "through" ? "many" : relation.kind === "condition" ? relation.many ? "many" : "one" : relation.kind, "muted")} ${style(relation.target, "success")}${relation.kind === "through" ? style(` through ${relation.junction}`, "muted") : relation.kind === "condition" ? style(" by condition", "muted") : ""}`)
230
+ ] : [],
231
+ ...table.indexes?.length ? [
232
+ "",
233
+ ` ${style("Indexes", "violet")}`,
234
+ ...table.indexes.map((index) => ` ${style(index.sqlName, "accent")} ${style(`${index.unique ? "UNIQUE " : ""}${index.method}`, "success")} (${index.keys.join(", ")})`)
235
+ ] : [],
236
+ ...table.checks?.length ? [
237
+ "",
238
+ ` ${style("Checks", "violet")}`,
239
+ ...table.checks.map((check) => ` ${style(check.sqlName, "accent")} ${style(check.expression, "muted")}`)
240
+ ] : []
241
+ ].join("\n")).join("\n\n") || "No tables.";
242
+ };
243
+ const formatStatus = (statuses, color = false) => {
244
+ const { style } = theme(color);
245
+ if (!statuses.length) return `${heading("Migration history", "", color)} ${style("○ No migrations yet.", "muted")}\n`;
246
+ const applied = statuses.filter((entry) => entry.status === "applied").length;
247
+ const pending = statuses.filter((entry) => entry.status === "pending").length;
248
+ const incomplete = statuses.length - applied - pending;
249
+ return [
250
+ heading("Migration history", `${statuses.length} total`, color),
251
+ ...statuses.map((entry) => ` ${style(entry.status === "applied" ? "✓" : "○", entry.status === "applied" ? "success" : "warning")} ${style(entry.id.padEnd(36), "strong")} ${style(entry.status, entry.status === "applied" ? "success" : "warning")}${entry.status === "incomplete" ? ` · ${entry.direction} · ${entry.statement} confirmed statements · repair required` : entry.appliedAt ? style(` · ${entry.appliedAt.toISOString()}`, "muted") : ""}`),
252
+ "",
253
+ ` ${style(`${applied} applied`, "success")} ${style("·", "muted")} ${style(`${pending} pending`, pending ? "warning" : "muted")}${incomplete ? ` · ${style(`${incomplete} incomplete`, "warning")}` : ""}\n`
254
+ ].join("\n");
255
+ };
256
+ const formatDashboard = (details, color = false, frame = -10) => {
257
+ const { style, brand } = theme(color);
258
+ const tables = details.snapshot?.tables;
259
+ const count = (value, label, tone) => `${style(String(value), tone)} ${style(label, "muted")}`;
260
+ const separator = style(" · ", "border");
261
+ const address = `${style("●", details.connection === "connected" ? "connected" : details.connection === "unavailable" ? "danger" : "muted")} ${details.address}`;
262
+ if (process.stdout.rows && process.stdout.rows < 16) return ` ${brand(frame)}\n ${address}`;
263
+ const width = terminalWidth();
264
+ if (width >= 72) {
265
+ const cardWidth = Math.floor((width - 4) / 3);
266
+ const card = (title, value, subtitle, tone) => {
267
+ const fill = (line) => {
268
+ const content = fitLine(line, cardWidth - 4);
269
+ return `${style("│", "border")} ${content}${" ".repeat(cardWidth - 4 - stringWidth(content))} ${style("│", "border")}`;
270
+ };
271
+ return [
272
+ `${style("╭─ ", "border")}${style(title, tone)}${style(` ${"─".repeat(cardWidth - title.length - 5)}╮`, "border")}`,
273
+ fill(value),
274
+ fill(subtitle),
275
+ style(`╰${"─".repeat(cardWidth - 2)}╯`, "border")
276
+ ];
277
+ };
278
+ const cards = [
279
+ card("SCHEMA", `${style(String(tables?.length ?? "—"), "strong")} ${style("tables", "accent")}`, tables ? `${tables.reduce((total, table) => total + table.relations.length, 0)} relations${cardWidth >= 28 ? ` · ${tables.reduce((total, table) => total + (table.indexes?.length ?? 0), 0)} indexes` : ""}` : "Configure a schema", "accent"),
280
+ card("MIGRATIONS", details.connection === "unavailable" ? style("! Unavailable", "danger") : `${style(String(details.connection === "connected" ? details.applied ?? 0 : details.local ?? 0), "strong")} ${style(details.connection === "connected" ? "applied" : "local", "violet")}`, style(details.connection === "connected" ? details.pending ? `${details.pending} pending` : "✓ Up to date" : details.connection === "offline" ? "Database offline" : "Check connection", details.pending ? "warning" : "muted"), "violet"),
281
+ card("CHANGES", details.changes === 0 ? style("✓ In sync", "success") : `${style(String(details.changes ?? "—"), "strong")} ${style("statements", "pink")}`, style("code → snapshot", "muted"), "pink")
282
+ ];
283
+ return [
284
+ ` ${brand(frame)} ${style("/ PostgreSQL toolkit", "muted")}`,
285
+ ` ${fitLine(address, width)}`,
286
+ "",
287
+ ...cards[0].map((_line, index) => ` ${cards.map((card) => card[index]).join(" ")}`),
288
+ ...details.connection === "unavailable" ? [` ${style(fitLine(details.migrations, width), "danger")}`] : [],
289
+ ` ${style(fitLine(details.config, width), "muted")}`
290
+ ].join("\n");
291
+ }
292
+ return panel([
293
+ `${brand(frame)} ${style("/ PostgreSQL toolkit", "muted")}`,
294
+ address,
295
+ "",
296
+ `${style("Schema ", "muted")}${tables ? [
297
+ count(tables.length, "tables", "accent"),
298
+ count(tables.reduce((total, table) => total + table.relations.length, 0), "relations", "violet"),
299
+ count(tables.reduce((total, table) => total + (table.indexes?.length ?? 0), 0), "indexes", "pink")
300
+ ].join(separator) : "not configured"}`,
301
+ `${style("Migrations ", "muted")}${style(details.migrations, details.connection === "unavailable" ? "danger" : details.pending ? "warning" : details.connection === "connected" ? "success" : "muted")}`,
302
+ `${style("Changes ", "muted")}${style(details.changes === void 0 ? "schema not configured" : details.changes ? `${details.changes} SQL statements since last snapshot` : "✓ In sync with the latest snapshot", details.changes ? "warning" : details.changes === 0 ? "success" : "muted")}`,
303
+ style(details.config, "muted")
304
+ ], color);
305
+ };
306
+ const formatCreated = (directory, files, color = false) => {
307
+ const { style } = theme(color);
308
+ return [
309
+ `\n ${style("✓", "success")} ${style("Created", "strong")} ${style(directory, "accent")}`,
310
+ "",
311
+ ...files.map((file, position) => ` ${style(position === files.length - 1 ? "└─" : "├─", "border")} ${style(file, "violet")}`),
312
+ ""
313
+ ].join("\n");
314
+ };
315
+ /** The review list after `pull`: one line per approximation, with the SQL that removes it when there is one. */
316
+ const formatPullWarnings = (warnings, color = false) => {
317
+ const { style } = theme(color);
318
+ if (!warnings.length) return ` ${style("✓", "success")} ${style("Nothing needs review; the schema matches the database.", "muted")}`;
319
+ return [
320
+ ` ${style("!", "warning")} ${style(`${warnings.length} ${warnings.length === 1 ? "item needs" : "items need"} review`, "strong")}`,
321
+ "",
322
+ ...warnings.flatMap((warning) => [` ${style("•", "border")} ${style(`[${warning.code}]`, "muted")} ${warning.message}`, ...warning.fix ? [` ${style("fix:", "accent")} ${warning.fix}`] : []]),
323
+ ""
324
+ ].join("\n");
325
+ };
326
+ const formatExecution = (migrationIdentifiers, action, durationMs, color = false) => {
327
+ const { style } = theme(color);
328
+ if (!migrationIdentifiers.length) return `\n ${style("✓", "success")} ${action === "Applied" ? "Database is up to date." : "No applied migrations."}\n`;
329
+ return [
330
+ heading(action === "Applied" ? "Migrations applied" : "Migrations reverted", `${durationMs} ms`, color),
331
+ ...migrationIdentifiers.map((identifier) => ` ${style("✓", "success")} ${style(identifier, "strong")}`),
332
+ "",
333
+ ` ${style(`${action} ${migrationIdentifiers.length} migrations`, "success")} ${style(`in ${durationMs} ms`, "muted")}${action === "Applied" ? " · Database is up to date." : ""}\n`
334
+ ].join("\n");
335
+ };
336
+ const formatHelp = (help, color = false) => {
337
+ const { style, brand } = theme(color);
338
+ return `\n ${brand()} ${style("/ PostgreSQL toolkit", "muted")}\n\n` + help.replace(/^symmetria <command>/, ` ${style("Usage", "violet")} symmetria ${style("<command>", "accent")}`).split("\n").map((line) => line.replace(/^( )(--[\w-]+|[a-z]+)(.*?)( {2,})(.+)$/, (_match, indent, command, argument, spacing, description) => `${indent}${style(command, "accent")}${style(argument, "violet")}${spacing}${style(description, "muted")}`)).join("\n");
339
+ };
340
+ //#endregion
341
+ //#region src/cli/screens/schema-browser.ts
342
+ /**
343
+ * Interactive schema browser: navigates tables, columns, relations, indexes and generated DDL.
344
+ */
345
+ /** Runs inside the caller's alternate screen, both standalone and in the dashboard. */
346
+ const inspectSchema = (snapshot, options) => {
347
+ const initial = options.table ? snapshot.tables.find((table) => table.name === options.table || table.sqlName === options.table) : snapshot.tables[0];
348
+ if (options.table && !initial) throw new Error(`symmetria: unknown table "${options.table}"`);
349
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("symmetria: schema browser requires a terminal");
350
+ return new Promise((resolve, reject) => {
351
+ const { style, brand } = theme(options.color);
352
+ const position = {
353
+ table: initial,
354
+ tab: options.tab ?? "Columns",
355
+ row: 0,
356
+ search: "",
357
+ focus: options.table ? "details" : "tables"
358
+ };
359
+ const history = [];
360
+ const sqlCache = /* @__PURE__ */ new Map();
361
+ let searchStart;
362
+ let finished = false;
363
+ let previousLines = [];
364
+ let pageSize = 1;
365
+ let tablePageSize = 1;
366
+ let rowCount = 0;
367
+ const wasRaw = process.stdin.isRaw;
368
+ const tables = () => matchingTables(snapshot, position.search);
369
+ const entries = () => position.table ? inspectEntries(position.table, position.tab).filter((entry) => !position.search || matchesTableName(position.table, position.search) || matchesEntry(entry, position.search)) : [];
370
+ const align = (text, width) => {
371
+ const clipped = fitLine(text, width);
372
+ return clipped + " ".repeat(Math.max(0, width - stringWidth(clipped)));
373
+ };
374
+ const frame = (title, body, width, focused) => {
375
+ const tone = focused ? "violet" : "border";
376
+ const top = `─ ${title} `;
377
+ return [
378
+ style(`╭${fitLine(top, width - 2)}${"─".repeat(Math.max(0, width - 2 - stringWidth(top)))}╮`, tone),
379
+ ...body.map((line) => `${style("│", tone)} ${align(line, width - 4)} ${style("│", tone)}`),
380
+ style(`╰${"─".repeat(width - 2)}╯`, tone)
381
+ ];
382
+ };
383
+ const rowStyle = (line, selected, focused, width) => selected ? style(align(stripVTControlCharacters(line), width), focused ? "selected" : "accent") : align(line, width);
384
+ const normalize = () => {
385
+ const visible = tables();
386
+ if (!position.table || !visible.includes(position.table)) {
387
+ position.table = visible[0];
388
+ position.row = 0;
389
+ }
390
+ };
391
+ const render = () => {
392
+ normalize();
393
+ const width = Math.max(1, Math.min(process.stdout.columns || 88, 160) - 4);
394
+ const height = process.stdout.rows || 24;
395
+ if (width < 28 || height < 12) return [
396
+ fitLine(" symmetria / inspect", width),
397
+ fitLine(" Enlarge terminal to browse", width),
398
+ fitLine(" Esc to return", width)
399
+ ];
400
+ const visible = tables();
401
+ const selectedTableIndex = Math.max(0, visible.indexOf(position.table));
402
+ const split = width >= 72;
403
+ const sidebarWidth = split ? Math.min(28, Math.max(19, Math.floor(width * .23))) : width;
404
+ const detailWidth = split ? width - sidebarWidth - 2 : width;
405
+ const innerWidth = detailWidth - 4;
406
+ const innerHeight = height - 7;
407
+ tablePageSize = innerHeight;
408
+ const tableOffset = Math.max(0, Math.min(selectedTableIndex - innerHeight + 1, visible.length - innerHeight));
409
+ const sidebar = visible.slice(tableOffset, tableOffset + innerHeight).map((table) => {
410
+ const selected = table === position.table;
411
+ return rowStyle(`${selected ? "›" : " "} ${table.name}`, selected, position.focus === "tables", sidebarWidth - 4);
412
+ });
413
+ if (!sidebar.length) sidebar.push(style("No matching tables", "muted"));
414
+ while (sidebar.length < innerHeight) sidebar.push("");
415
+ const selectedEntries = entries();
416
+ const labels = innerWidth >= 66 ? inspectTabs : [
417
+ "Cols",
418
+ "Rels",
419
+ "Idx",
420
+ "Checks",
421
+ "SQL"
422
+ ];
423
+ const tabs = inspectTabs.map((tab, index) => {
424
+ const count = position.table && tab !== "SQL" ? ` ${inspectEntries(position.table, tab).length}` : "";
425
+ const label = `${labels[index]}${count}`;
426
+ return style(position.tab === tab ? `[${label}]` : label, position.tab === tab ? "pink" : "muted");
427
+ }).join(" ");
428
+ const detail = [stringWidth(tabs) <= innerWidth ? tabs : `${style(`‹ ${position.tab} ›`, "pink")} ${style(`${inspectTabs.indexOf(position.tab) + 1}/5 · ← → tabs`, "muted")}`, style("─".repeat(innerWidth), "border")];
429
+ let pageLabel = "";
430
+ if (position.tab === "SQL" && position.table) {
431
+ if (!sqlCache.has(position.table)) sqlCache.set(position.table, highlightSQL(inspectTableSQL(snapshot, position.table), options.color));
432
+ const sqlLines = wrapLines(sqlCache.get(position.table), innerWidth - 5);
433
+ pageSize = innerHeight - detail.length;
434
+ rowCount = sqlLines.length;
435
+ position.row = Math.max(0, Math.min(position.row, rowCount - pageSize));
436
+ detail.push(...sqlLines.slice(position.row, position.row + pageSize).map((line, index) => `${style(String(position.row + index + 1).padStart(3), "muted")} ${line}`));
437
+ pageLabel = `SQL ${position.row + 1}–${Math.min(rowCount, position.row + pageSize)}/${rowCount}`;
438
+ } else {
439
+ const nameWidth = Math.min(Math.max(10, ...selectedEntries.map((entry) => stringWidth(entry.name))), Math.floor(innerWidth * .43));
440
+ const typeWidth = Math.min(Math.max(7, ...selectedEntries.map((entry) => stringWidth(entry.kind))), Math.floor(innerWidth * .25));
441
+ const entryLine = (name, kind, flags) => `${align(name, nameWidth)} ${align(kind, typeWidth)} ${flags}`;
442
+ const detailBudget = Math.min(4, Math.max(2, Math.floor(innerHeight / 4)));
443
+ pageSize = Math.max(1, innerHeight - detail.length - 1 - detailBudget - 1);
444
+ rowCount = selectedEntries.length;
445
+ position.row = Math.max(0, Math.min(position.row, rowCount - 1));
446
+ const offset = Math.max(0, Math.min(position.row - pageSize + 1, rowCount - pageSize));
447
+ detail.push(style(` ${entryLine("NAME", "TYPE", "FLAGS")}`, "muted"));
448
+ const rows = selectedEntries.slice(offset, offset + pageSize).map((entry, index) => {
449
+ const selected = position.row === offset + index;
450
+ return rowStyle(`${selected ? "›" : " "} ${entryLine(style(entry.name, "accent"), style(entry.kind, "violet"), entry.badges.map((badge) => style(badge, "pink")).join(" · "))}`, selected, position.focus === "details", innerWidth);
451
+ });
452
+ if (!rows.length) rows.push(style(position.search ? "No matches in this tab" : `No ${position.tab.toLowerCase()}`, "muted"));
453
+ while (rows.length < pageSize) rows.push("");
454
+ detail.push(...rows, style("─".repeat(innerWidth), "border"));
455
+ const selected = selectedEntries[position.row];
456
+ const description = selected ? wrapLines(style(selected.description, "muted"), innerWidth).slice(0, detailBudget) : [style(position.table ? "← → switch tabs · / search" : "No tables to inspect", "muted")];
457
+ detail.push(...description);
458
+ pageLabel = rowCount ? `${position.tab} ${position.row + 1}/${rowCount}` : position.tab;
459
+ }
460
+ while (detail.length < innerHeight) detail.push("");
461
+ const sidebarPanel = frame(`Tables · ${visible.length}/${snapshot.tables.length}`, sidebar, sidebarWidth, position.focus === "tables");
462
+ const detailPanel = frame(position.table?.name ?? "Schema", detail.slice(0, innerHeight), detailWidth, position.focus === "details");
463
+ const panels = split ? sidebarPanel.map((line, index) => `${line} ${detailPanel[index]}`) : position.focus === "tables" ? sidebarPanel : detailPanel;
464
+ const breadcrumb = `${history.length ? `${history.at(-1).table?.name} → ` : ""}${position.table?.name ?? "schema"}`;
465
+ const search = searchStart ? `${style("/", "pink")} ${position.search}${style("▏", "pink")} ${style("enter apply · esc cancel", "muted")}` : position.search ? `${style("/", "pink")} ${position.search} ${style("esc clear", "muted")}` : style("/ search tables and fields", "muted");
466
+ const hint = width >= 90 ? "↑↓ select · Tab pane · ←→ tabs · Enter follow · / search · ⌫ back · Esc exit" : width >= 64 ? "↑↓ select · Tab pane · ←→ tabs · Enter follow · / find · Esc back" : "Tab pane · ←→ tabs · / find · Esc back";
467
+ return [
468
+ ` ${fitLine(`${brand()} ${style(`/ inspect / ${breadcrumb}`, "muted")}`, width)}`,
469
+ ` ${fitLine(search, width)}`,
470
+ ...panels.map((line) => ` ${line}`),
471
+ ` ${fitLine(`${style(position.focus === "tables" ? "TABLES" : "DETAILS", "violet")} ${style(pageLabel, "muted")}${history.length ? style(" · ⌫ previous table", "pink") : ""}`, width)}`,
472
+ ` ${style(fitLine(hint, width), "muted")}`
473
+ ];
474
+ };
475
+ const draw = () => {
476
+ try {
477
+ const lines = render();
478
+ const changes = lines.flatMap((line, index) => line === previousLines[index] ? [] : [`\u001b[${index + 1};1H\u001b[2K${line}`]);
479
+ for (let index = lines.length; index < previousLines.length; index++) changes.push(`\u001b[${index + 1};1H\u001b[2K`);
480
+ process.stdout.write(changes.join(""));
481
+ previousLines = lines;
482
+ } catch (error) {
483
+ finish(error);
484
+ }
485
+ };
486
+ const resize = () => {
487
+ previousLines = [];
488
+ process.stdout.write("\x1B[H\x1B[2J");
489
+ draw();
490
+ };
491
+ const finish = (error) => {
492
+ if (finished) return;
493
+ finished = true;
494
+ process.stdin.off("keypress", keypress);
495
+ process.stdin.off("end", end);
496
+ process.stdout.off("resize", resize);
497
+ process.stdin.setRawMode(wasRaw);
498
+ process.stdin.pause();
499
+ process.stdout.write("\x1B[?25h");
500
+ if (error) reject(error);
501
+ else resolve();
502
+ };
503
+ const end = () => finish();
504
+ const keypress = (input, key) => {
505
+ if (key.ctrl && ["c", "d"].includes(key.name ?? "")) return finish();
506
+ if (searchStart) {
507
+ if (key.name === "escape") {
508
+ Object.assign(position, searchStart);
509
+ searchStart = void 0;
510
+ } else if (key.name === "return") searchStart = void 0;
511
+ else if (key.name === "backspace") {
512
+ position.search = [...position.search].slice(0, -1).join("");
513
+ position.row = 0;
514
+ } else if (key.ctrl && key.name === "u") {
515
+ position.search = "";
516
+ position.row = 0;
517
+ } else if (!key.ctrl && !key.meta && input && !/[\p{C}]/u.test(input)) {
518
+ position.search += input;
519
+ position.row = 0;
520
+ }
521
+ draw();
522
+ return;
523
+ }
524
+ if (input === "/") {
525
+ searchStart = { ...position };
526
+ draw();
527
+ return;
528
+ }
529
+ if (key.name === "escape") {
530
+ if (position.search) {
531
+ position.search = "";
532
+ position.row = 0;
533
+ draw();
534
+ return;
535
+ }
536
+ return finish();
537
+ }
538
+ if (key.name === "tab") position.focus = position.focus === "tables" ? "details" : "tables";
539
+ else if (key.name === "backspace") {
540
+ const previous = history.pop();
541
+ if (previous) Object.assign(position, previous);
542
+ else position.focus = "tables";
543
+ } else if (key.name === "left" || key.name === "right" || /^[1-5]$/.test(input)) {
544
+ const index = inspectTabs.indexOf(position.tab);
545
+ position.tab = inspectTabs[/^[1-5]$/.test(input) ? Number(input) - 1 : (index + (key.name === "left" ? -1 : 1) + inspectTabs.length) % inspectTabs.length];
546
+ position.row = 0;
547
+ position.focus = "details";
548
+ } else if (key.name === "return") {
549
+ if (position.focus === "tables") position.focus = "details";
550
+ else {
551
+ const target = entries()[position.row]?.target;
552
+ const table = target && snapshot.tables.find((table) => table.name === target.table || table.sqlName === target.table);
553
+ if (table) {
554
+ history.push({ ...position });
555
+ Object.assign(position, {
556
+ table,
557
+ tab: "Columns",
558
+ search: "",
559
+ row: Math.max(0, table.columns.findIndex((column) => column.name === target.column || column.sqlName === target.column))
560
+ });
561
+ }
562
+ }
563
+ } else if ([
564
+ "up",
565
+ "down",
566
+ "pageup",
567
+ "pagedown",
568
+ "home",
569
+ "end"
570
+ ].includes(key.name ?? "")) {
571
+ const visible = tables();
572
+ const maximum = position.focus === "tables" ? visible.length - 1 : position.tab === "SQL" ? rowCount - pageSize : rowCount - 1;
573
+ const current = position.focus === "tables" ? visible.indexOf(position.table) : position.row;
574
+ const step = position.focus === "tables" ? tablePageSize : pageSize;
575
+ const amount = key.name === "up" ? -1 : key.name === "down" ? 1 : key.name === "pageup" ? -step : step;
576
+ const next = Math.max(0, Math.min(maximum, key.name === "home" ? 0 : key.name === "end" ? maximum : current + amount));
577
+ if (position.focus === "tables") {
578
+ position.table = visible[next];
579
+ position.row = 0;
580
+ } else position.row = next;
581
+ } else return;
582
+ draw();
583
+ };
584
+ emitKeypressEvents(process.stdin);
585
+ process.stdin.setRawMode(true);
586
+ process.stdin.resume();
587
+ process.stdin.on("keypress", keypress);
588
+ process.stdin.once("end", end);
589
+ process.stdout.on("resize", resize);
590
+ process.stdout.write("\x1B[?25l");
591
+ resize();
592
+ });
593
+ };
594
+ //#endregion
595
+ //#region src/cli/screens/dashboard.ts
596
+ /**
597
+ * Interactive dashboard: header with chain, connectivity and schema state, plus a menu for generate,
598
+ * migrate, inspect, status and rollback.
599
+ */
600
+ const ACTIONS = [
601
+ [
602
+ "View schema changes",
603
+ "diff",
604
+ "Compare your schema with the latest local snapshot."
605
+ ],
606
+ [
607
+ "Generate migration",
608
+ "generate",
609
+ "Turn schema changes into a versioned SQL migration."
610
+ ],
611
+ [
612
+ "Apply migrations",
613
+ "migrate",
614
+ "Run pending migrations against PostgreSQL."
615
+ ],
616
+ [
617
+ "Inspect schema",
618
+ "inspect",
619
+ "Explore tables, columns, relationships and constraints."
620
+ ],
621
+ [
622
+ "Migration history",
623
+ "status",
624
+ "See applied and pending migrations at a glance."
625
+ ],
626
+ [
627
+ "Rollback latest migration",
628
+ "rollback",
629
+ "Execute down.sql for the latest applied migration."
630
+ ],
631
+ [
632
+ "Exit",
633
+ "",
634
+ "Back to your terminal."
635
+ ]
636
+ ];
637
+ const clear = () => process.stdout.write("\x1B[H\x1B[2J");
638
+ /** What the dashboard header shows: local chain, database connectivity and schema changes. */
639
+ const overview = async (context, project) => {
640
+ const { migrations, snapshot: before } = await loadMigrationState(project.directory);
641
+ const snapshot = project.snapshot();
642
+ const summary = {
643
+ migrations: `${migrations.length} local · database not configured`,
644
+ address: "Offline · set DATABASE_URL to connect",
645
+ connection: "offline",
646
+ pending: 0,
647
+ applied: 0
648
+ };
649
+ if (project.databaseUrl) {
650
+ const url = new URL(project.databaseUrl);
651
+ summary.address = `PostgreSQL · ${url.hostname}:${url.port || "5432"}${url.pathname}`;
652
+ const driver = postgres(project.databaseUrl);
653
+ try {
654
+ const statuses = await context.progress("Checking PostgreSQL", () => migrator({
655
+ driver,
656
+ ...project.runnerOptions
657
+ }).status());
658
+ summary.applied = statuses.filter((entry) => entry.status === "applied").length;
659
+ summary.pending = statuses.filter((entry) => entry.status === "pending").length;
660
+ summary.connection = "connected";
661
+ summary.migrations = `${summary.applied} applied · ${summary.pending} pending`;
662
+ const incomplete = statuses.length - summary.applied - summary.pending;
663
+ if (incomplete) summary.migrations += ` · ${incomplete} incomplete (repair required)`;
664
+ } catch (error) {
665
+ summary.connection = "unavailable";
666
+ summary.migrations = `Unavailable: ${error instanceof Error ? error.message : String(error)}`;
667
+ } finally {
668
+ await driver.close();
669
+ }
670
+ }
671
+ return {
672
+ ...summary,
673
+ snapshot,
674
+ local: migrations.length,
675
+ changes: snapshot ? diffSchemas(before, snapshot).up.filter((statement) => !statement.startsWith("--")).length : void 0,
676
+ config: project.present ? relative(process.cwd(), project.configPath) || project.configPath : "No config · symmetria init to get started"
677
+ };
678
+ };
679
+ /** `dashboard` (the bare `symmetria` command): a menu that runs the other commands in place. */
680
+ const dashboard = async (context, project) => {
681
+ const { values, color } = context;
682
+ if (!context.interactive) throw new Error("symmetria: dashboard requires an interactive terminal");
683
+ const forwarded = [
684
+ ...values.config ? ["--config", values.config] : [],
685
+ ...values.dir ? ["--dir", values.dir] : [],
686
+ ...values["database-url"] ? ["--database-url", values["database-url"]] : [],
687
+ ...values["no-color"] ? ["--no-color"] : [],
688
+ ...values["no-animation"] ? ["--no-animation"] : []
689
+ ];
690
+ return withScreen(async () => {
691
+ while (true) {
692
+ const state = await overview(context, project);
693
+ const selected = await choose("Choose an action", ACTIONS.map(([label]) => label), {
694
+ color,
695
+ animation: !values["no-animation"],
696
+ header: (frame) => formatDashboard(state, color, frame),
697
+ descriptions: ACTIONS.map(([, , description]) => description)
698
+ });
699
+ const action = selected === void 0 ? "" : ACTIONS[selected][1];
700
+ if (!action) return;
701
+ clear();
702
+ if (action === "inspect" && state.snapshot) {
703
+ try {
704
+ await inspectSchema(state.snapshot, { color });
705
+ } catch (error) {
706
+ await view("inspect", formatError(error instanceof Error ? error.message : String(error), color), color);
707
+ }
708
+ clear();
709
+ continue;
710
+ }
711
+ const messages = [];
712
+ try {
713
+ await context.rerun([action, ...forwarded], (message) => {
714
+ messages.push(message);
715
+ });
716
+ } catch (error) {
717
+ messages.push(formatError(error instanceof Error ? error.message : String(error), color));
718
+ }
719
+ await view(action, messages.join("\n"), color);
720
+ clear();
721
+ }
722
+ });
723
+ };
724
+ //#endregion
725
+ //#region src/cli/commands/database.ts
726
+ /**
727
+ * Database-backed CLI commands: verify, drift, repair, adopt, status, migrate and rollback.
728
+ * Each one opens a connection through the shared context and prints or emits JSON.
729
+ */
730
+ /** `verify`: replay the chain in disposable databases on the verification server. */
731
+ const verify = async (context, project) => {
732
+ const url = project.runnerOptions.verificationDatabaseUrl;
733
+ if (!url) throw new Error("symmetria: verify requires --verify-url or verificationDatabaseUrl: an administrative PostgreSQL URL with CREATEDB permission, separate from the application database");
734
+ const result = await withCancellation((signal) => verifyMigrations({
735
+ ...project.runnerOptions,
736
+ ...project.config.verify,
737
+ url,
738
+ signal
739
+ }));
740
+ context.emit({
741
+ json: result,
742
+ plain: () => `Verified ${result.migrations.length} migrations: installation, upgrade, rollback and reapplication.`
743
+ });
744
+ };
745
+ /** `drift`: compare the live catalog with the latest snapshot or the declared schema. */
746
+ const drift = async (context, project) => withDatabase(project, async (driver) => {
747
+ const { migrations, snapshot } = await loadMigrationState(project.directory);
748
+ const expected = (migrations.length ? snapshot : void 0) ?? project.snapshot();
749
+ if (!expected) throw new Error("symmetria: drift needs a migration chain or a schema in the config");
750
+ const { metadataSchema, metadataTable } = project.config;
751
+ const findings = await context.progress("Inspecting the database", () => detectDrift({
752
+ execute: driver.execute,
753
+ snapshot: expected,
754
+ ...metadataSchema ? { metadataSchema } : {},
755
+ ...metadataTable ? { metadataTable } : {}
756
+ }));
757
+ context.emit({
758
+ json: findings,
759
+ indent: 2,
760
+ plain: () => formatDriftFindings(findings)
761
+ });
762
+ if (context.values.strict && findings.length) process.exitCode = 1;
763
+ });
764
+ /** `migrate`, `rollback`, `status`, `adopt` and `repair` share one migrator bound to the database. */
765
+ const withRunner = (project, operation) => withDatabase(project, (driver, signal) => operation(migrator({
766
+ ...project.runnerOptions,
767
+ driver,
768
+ signal
769
+ })));
770
+ const plan = async (context, runner, direction) => {
771
+ const { values } = context;
772
+ const steps = await runner.plan({
773
+ ...values.to ? { to: values.to } : {},
774
+ ...values.steps ? { steps: Number(values.steps) } : {},
775
+ direction
776
+ });
777
+ context.emit({
778
+ json: steps,
779
+ indent: 2,
780
+ plain: () => steps.map((step) => `-- group ${step.group}: ${step.transaction} · ${step.id}\n${step.statements.map((sql) => `${sql};`).join("\n\n")}`).join("\n\n")
781
+ });
782
+ };
783
+ const repair = (context, project, id) => withRunner(project, async (runner) => {
784
+ const action = context.values.action;
785
+ await runner.repair({
786
+ id,
787
+ action
788
+ });
789
+ context.emit({
790
+ json: {
791
+ repaired: id,
792
+ action
793
+ },
794
+ plain: () => `Repaired ${id}: ${action}`
795
+ });
796
+ });
797
+ const adopt = (context, project) => withRunner(project, async (runner) => {
798
+ const { values } = context;
799
+ const adopted = await context.progress("Recording the local chain", () => runner.adopt(values.to ? { to: values.to } : {}));
800
+ context.emit({
801
+ json: { adopted },
802
+ plain: () => adopted.length ? adopted.map((id) => `Adopted ${id}`).join("\n") : "Nothing to adopt."
803
+ });
804
+ });
805
+ const status = (context, project) => withRunner(project, async (runner) => {
806
+ const statuses = await context.progress("Reading migration history", () => runner.status());
807
+ if (statuses.some((entry) => entry.status === "incomplete")) process.exitCode = 1;
808
+ context.emit({
809
+ json: statuses,
810
+ pretty: () => formatStatus(statuses, context.color),
811
+ plain: () => statuses.length ? statuses.map((entry) => `${entry.status.padEnd(7)} ${entry.id}${entry.status === "incomplete" ? ` · ${entry.direction} · ${entry.statement} confirmed statements · repair required` : ""}`).join("\n") : "No migrations."
812
+ });
813
+ });
814
+ const migrate = (context, project) => withRunner(project, async (runner) => {
815
+ const { values } = context;
816
+ if (values.plan) return plan(context, runner, "up");
817
+ const started = performance.now();
818
+ const applied = await context.progress("Applying migrations", () => runner.migrate(values.to ? { to: values.to } : {}));
819
+ const durationMs = Math.round(performance.now() - started);
820
+ context.emit({
821
+ json: {
822
+ applied,
823
+ durationMs
824
+ },
825
+ pretty: () => formatExecution(applied, "Applied", durationMs, context.color),
826
+ plain: () => applied.length ? applied.map((id) => `Applied ${id}`).join("\n") : "Database is up to date."
827
+ });
828
+ });
829
+ const rollback = (context, project) => withRunner(project, async (runner) => {
830
+ const { values } = context;
831
+ if (values.plan) return plan(context, runner, "down");
832
+ const started = performance.now();
833
+ const reverted = await context.progress("Rolling back migrations", () => runner.rollback(values.steps === void 0 ? {} : { steps: Number(values.steps) }));
834
+ const durationMs = Math.round(performance.now() - started);
835
+ context.emit({
836
+ json: {
837
+ reverted,
838
+ durationMs
839
+ },
840
+ pretty: () => formatExecution(reverted, "Reverted", durationMs, context.color),
841
+ plain: () => reverted.length ? reverted.map((id) => `Reverted ${id}`).join("\n") : "No applied migrations."
842
+ });
843
+ });
844
+ //#endregion
845
+ //#region src/cli/commands/files.ts
846
+ /** `recover`: finish or roll back a publication left behind by a crashed generator. */
847
+ const recover = async (context, project) => {
848
+ await recoverMigrationFiles(project.directory);
849
+ context.emit({
850
+ json: { recovered: true },
851
+ plain: () => "Migration files recovered."
852
+ });
853
+ };
854
+ /** `squash <name>`: replace the local chain with one baseline migration. */
855
+ const squash = async (context, project, name) => {
856
+ const squashed = await context.progress("Squashing migrations", () => squashMigrations({
857
+ directory: project.directory,
858
+ name
859
+ }));
860
+ context.emit({
861
+ json: squashed ? { id: squashed.id } : { id: null },
862
+ plain: () => squashed ? `Squashed into ${squashed.id}. Run "symmetria adopt" on databases that applied the old chain.` : "Nothing to squash."
863
+ });
864
+ };
865
+ //#endregion
866
+ //#region src/cli/commands/graph.ts
867
+ /**
868
+ * `graph [file]`: a Mermaid entity-relationship diagram of the declared schema,
869
+ * or of the latest migration snapshot when the config declares no schema.
870
+ * Printed to stdout, or written to a file (`.md` files get a ```mermaid fence).
871
+ */
872
+ const graph = async (context, project, name) => {
873
+ const { values, color } = context;
874
+ const snapshot = project.snapshot() ?? await loadMigrationState(project.directory).then(({ migrations, snapshot }) => migrations.length ? snapshot : void 0);
875
+ if (!snapshot) throw new Error("symmetria: graph needs a schema in the config or a migration chain");
876
+ const model = schemaGraph(snapshot);
877
+ const summary = `${model.tables.length} ${model.tables.length === 1 ? "table" : "tables"}, ${model.edges.length} ${model.edges.length === 1 ? "relation" : "relations"}`;
878
+ if (!name) {
879
+ context.emit({
880
+ json: model,
881
+ indent: 2,
882
+ plain: () => renderMermaid(model, { compact: !!values.compact }).trimEnd()
883
+ });
884
+ return;
885
+ }
886
+ const path = resolve(name);
887
+ const diagram = renderMermaid(model, {
888
+ fenced: extname(path).toLowerCase() === ".md",
889
+ compact: !!values.compact
890
+ });
891
+ await mkdir(dirname(path), { recursive: true });
892
+ try {
893
+ await writeFile(path, diagram, { flag: values.force ? "w" : "wx" });
894
+ } catch (error) {
895
+ if (error && typeof error === "object" && "code" in error && error.code === "EEXIST") throw new Error(`symmetria: ${path} exists; use --force to overwrite it`);
896
+ throw error;
897
+ }
898
+ context.emit({
899
+ json: {
900
+ path,
901
+ tables: model.tables.length,
902
+ relations: model.edges.length
903
+ },
904
+ indent: 2,
905
+ pretty: () => `${formatCreated(dirname(path), [basename(path)], color)} ${context.style(summary, "muted")}`,
906
+ plain: () => `Created\n ${path}\n ${summary}`
907
+ });
908
+ };
909
+ //#endregion
910
+ //#region src/cli/scaffold.ts
911
+ /**
912
+ * `symmetria-kit init`: writes the starter schema, migrations directory and config files for a new project.
913
+ */
914
+ const files = {
915
+ "src/database/tables/users.ts": `import { table, uuid, text } from "symmetria";\n\nexport const users = table({\n id: uuid.v4.brand("UserId"),\n email: text.unique,\n name: text,\n});\n`,
916
+ "src/database/schema.ts": `import { schema } from "symmetria";\nimport { users } from "./tables/users.ts";\n\nexport const appSchema = schema({ users });\n`,
917
+ "src/database/index.ts": `import { createDatabase } from "symmetria";\nimport { postgres } from "symmetria/driver";\nimport { appSchema } from "./schema.ts";\n\nconst url = process.env.DATABASE_URL;\n\nif (!url) {\n throw new Error("Set DATABASE_URL before connecting");\n}\n\nexport const db = createDatabase({\n schema: appSchema,\n driver: postgres({ url }),\n});\n`,
918
+ "symmetria.config.ts": `import { defineMigrationConfig } from "symmetria-kit";\nimport { appSchema } from "./src/database/schema";\n\nexport default defineMigrationConfig({\n schema: appSchema,\n directory: "./migrations",\n databaseUrl: process.env.DATABASE_URL,\n});\n`,
919
+ ".env.example": "DATABASE_URL=postgres://postgres:postgres@localhost:5432/app\n"
920
+ };
921
+ const initializeProject = async (directory) => {
922
+ for (const name of ["symmetria.config.ts", "migrations.config.ts"]) if (await lstat(resolve(directory, name)).catch((error) => {
923
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return;
924
+ throw error;
925
+ })) return [];
926
+ if ((await readdir(resolve(directory, "migrations"), { withFileTypes: true }).catch((error) => {
927
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return [];
928
+ throw error;
929
+ })).some((entry) => entry.isDirectory() && /^\d{6}_/.test(entry.name))) return [];
930
+ const created = [];
931
+ try {
932
+ for (const [name, contents] of Object.entries(files)) {
933
+ const path = resolve(directory, name);
934
+ await mkdir(dirname(path), { recursive: true });
935
+ const file = await open(path, "wx").catch((error) => {
936
+ if (error && typeof error === "object" && "code" in error && error.code === "EEXIST") return;
937
+ throw error;
938
+ });
939
+ if (!file) continue;
940
+ created.push(name);
941
+ try {
942
+ await file.writeFile(contents);
943
+ } finally {
944
+ await file.close();
945
+ }
946
+ }
947
+ return created;
948
+ } catch (error) {
949
+ await Promise.all(created.map((name) => rm(resolve(directory, name))));
950
+ throw new Error("symmetria: init could not create the project files (existing files are preserved)", { cause: error });
951
+ }
952
+ };
953
+ //#endregion
954
+ //#region src/cli/commands/init.ts
955
+ const quoteArgument = (value) => /^[\w./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
956
+ /** `init [directory]`: scaffold schema modules, a connection and migration config. */
957
+ const init = async (context, name) => {
958
+ const { style, color } = context;
959
+ const directory = resolve(name ?? ".");
960
+ const files = await context.progress("Creating your project", () => initializeProject(directory));
961
+ if (!files.length) {
962
+ context.emit({
963
+ json: {
964
+ directory,
965
+ files
966
+ },
967
+ plain: () => "Existing project files preserved; nothing to create."
968
+ });
969
+ return;
970
+ }
971
+ const invocation = "bunx --package symmetria-kit symmetria";
972
+ const changeDirectory = directory === process.cwd() ? "" : ` cd ${quoteArgument(relative(process.cwd(), directory))}\n`;
973
+ const next = `${style("Next", "violet")}\n${changeDirectory} Set DATABASE_URL (see .env.example)\n ${style(`${invocation} generate initial`, "accent")}\n ${style(`${invocation} migrate`, "accent")}`;
974
+ context.emit({
975
+ json: {
976
+ directory,
977
+ files
978
+ },
979
+ pretty: () => `${formatCreated(directory, files, color)}\n${next}`,
980
+ plain: () => `Created\n${files.map((file) => ` ${file}`).join("\n")}\n\n${next}`
981
+ });
982
+ };
983
+ //#endregion
984
+ //#region src/cli/screens/profiler.ts
985
+ /**
986
+ * Live profiler screen: polls a running profiler endpoint and renders request and query timings.
987
+ */
988
+ const profileScreen = async (address, token, color) => withScreen(() => new Promise((resolve, reject) => {
989
+ const { style, brand } = theme(color);
990
+ let requests = [];
991
+ let selectedRequest = 0;
992
+ let selectedQuery = 0;
993
+ let mode = "requests";
994
+ let offset = 0;
995
+ let error = "";
996
+ let plan = "";
997
+ let closed = false;
998
+ let pending = false;
999
+ let activeRequest;
1000
+ const wasRaw = process.stdin.isRaw;
1001
+ const milliseconds = (value) => `${value.toFixed(3)} ms`;
1002
+ const query = () => activeRequest?.queries[selectedQuery];
1003
+ const draw = () => {
1004
+ const height = Math.max(1, (process.stdout.rows || 24) - 7);
1005
+ const selected = query();
1006
+ const lines = [];
1007
+ if (mode === "requests") {
1008
+ lines.push(style("Request SQL Build Total", "muted"));
1009
+ const start = Math.max(0, selectedRequest - height + 2);
1010
+ for (const [position, request] of requests.slice(start, start + height - 1).entries()) {
1011
+ const duplicates = request.queries.length - new Set(request.queries.map((entry) => entry.sql)).size;
1012
+ lines.push(style(`${start + position === selectedRequest ? "›" : " "} ${request.label.padEnd(42)} ${String(request.queries.length).padStart(3)} ${request.buildMs.toFixed(2).padStart(7)} ${request.durationMs.toFixed(2).padStart(7)}${duplicates ? ` ↻ ${duplicates}` : ""}${request.error ? " ERROR" : ""}`, start + position === selectedRequest ? "selected" : "text"));
1013
+ }
1014
+ if (!requests.length) lines.push("Waiting for queries… Send a request to your application.");
1015
+ } else if (mode === "queries") {
1016
+ lines.push(style(`${activeRequest.label} · build ${milliseconds(activeRequest.buildMs)} · total ${milliseconds(activeRequest.durationMs)}`, "pink"));
1017
+ lines.push(style("Query Compile Database Decode Rows", "muted"));
1018
+ const start = Math.max(0, selectedQuery - height + 3);
1019
+ for (const [position, entry] of activeRequest.queries.slice(start, start + height - 2).entries()) lines.push(style(`${start + position === selectedQuery ? "›" : " "} ${entry.kind.padEnd(9)} #${String(entry.id).padEnd(10)} ${entry.compileMs.toFixed(3).padStart(9)} ${entry.databaseMs.toFixed(3).padStart(14)} ${entry.decodeMs.toFixed(3).padStart(12)} ${String(entry.rows).padStart(7)}${entry.error ? " ERROR" : ""}`, start + position === selectedQuery ? "selected" : "text"));
1020
+ } else {
1021
+ const content = mode === "plan" ? plan : `${selected.sql}\n\nParameters\n${JSON.stringify(selected.parameters, null, 2)}${selected.error ? `\n\n${selected.error}` : ""}`;
1022
+ const wrapped = wrapLines(content);
1023
+ offset = Math.min(offset, Math.max(0, wrapped.length - height));
1024
+ lines.push(...wrapped.slice(offset, offset + height));
1025
+ }
1026
+ process.stdout.write(`\u001b[H\u001b[2J ${brand()} ${style("/ live profiler", "muted")}\n ${style(fitLine(error || address), error ? "danger" : "muted")}\n\n${lines.map((line) => ` ${fitLine(line)}`).join("\n")}\u001b[${Math.max(1, (process.stdout.rows || 24) - 1)};1H ${style(fitLine("↑ ↓ navigate · enter open · esc back · e explain · a analyze · q quit"), "muted")}`);
1027
+ };
1028
+ const refresh = async () => {
1029
+ if (pending || closed) return;
1030
+ pending = true;
1031
+ try {
1032
+ const response = await fetch(new URL("/requests", address), {
1033
+ headers: { "x-symmetria-token": token },
1034
+ signal: AbortSignal.timeout(3e3)
1035
+ });
1036
+ if (!response.ok) throw new Error(response.status === 403 ? "Profiler rejected the token; pass --profile-token or set SYMMETRIA_PROFILE_TOKEN to the value used by profiler.serve()" : `Profiler returned HTTP ${response.status}`);
1037
+ const updated = await response.json();
1038
+ if (!Array.isArray(updated)) throw new Error("Invalid profiler response");
1039
+ const selectedId = requests[selectedRequest]?.id;
1040
+ requests = updated.toSorted((left, right) => right.id - left.id);
1041
+ selectedRequest = Math.max(0, requests.findIndex((entry) => entry.id === selectedId));
1042
+ error = "";
1043
+ } catch (cause) {
1044
+ error = cause instanceof Error ? cause.message : String(cause);
1045
+ } finally {
1046
+ pending = false;
1047
+ if (!closed) draw();
1048
+ else resolve();
1049
+ }
1050
+ };
1051
+ const explain = async (analyze) => {
1052
+ const selected = query();
1053
+ if (!selected || pending) return;
1054
+ pending = true;
1055
+ error = analyze ? "Running EXPLAIN ANALYZE…" : "Estimating query plan…";
1056
+ draw();
1057
+ try {
1058
+ const response = await fetch(new URL(`/explain?id=${selected.id}&analyze=${analyze}`, address), {
1059
+ method: "POST",
1060
+ headers: { "x-symmetria-token": token },
1061
+ signal: AbortSignal.timeout(3e4)
1062
+ });
1063
+ const result = await response.json();
1064
+ if (!response.ok) throw new Error(result && typeof result === "object" && "error" in result ? String(result.error) : `HTTP ${response.status}`);
1065
+ plan = JSON.stringify(result, null, 2);
1066
+ mode = "plan";
1067
+ offset = 0;
1068
+ error = "";
1069
+ } catch (cause) {
1070
+ error = cause instanceof Error ? cause.message : String(cause);
1071
+ } finally {
1072
+ pending = false;
1073
+ if (!closed) draw();
1074
+ else resolve();
1075
+ }
1076
+ };
1077
+ const finish = () => {
1078
+ if (closed) return;
1079
+ closed = true;
1080
+ clearInterval(timer);
1081
+ process.stdin.off("keypress", keypress);
1082
+ process.stdin.off("end", finish);
1083
+ process.stdout.off("resize", draw);
1084
+ process.stdin.setRawMode(wasRaw);
1085
+ process.stdin.pause();
1086
+ if (!pending) resolve();
1087
+ };
1088
+ const keypress = (input, key) => {
1089
+ if (input === "q" || key.ctrl && key.name === "c") {
1090
+ finish();
1091
+ return;
1092
+ }
1093
+ if (key.name === "escape" || key.name === "left") {
1094
+ if (mode === "requests") {
1095
+ finish();
1096
+ return;
1097
+ }
1098
+ mode = mode === "queries" ? "requests" : "queries";
1099
+ offset = 0;
1100
+ } else if (key.name === "return") {
1101
+ if (mode === "requests" && requests[selectedRequest]) {
1102
+ activeRequest = requests[selectedRequest];
1103
+ selectedQuery = 0;
1104
+ mode = "queries";
1105
+ } else if (mode === "queries" && query()) {
1106
+ mode = "sql";
1107
+ offset = 0;
1108
+ }
1109
+ } else if (input === "e" || input === "a") {
1110
+ if (mode !== "requests") explain(input === "a");
1111
+ } else if ([
1112
+ "up",
1113
+ "down",
1114
+ "pageup",
1115
+ "pagedown"
1116
+ ].includes(key.name ?? "")) {
1117
+ const direction = key.name === "up" || key.name === "pageup" ? -1 : 1;
1118
+ const step = key.name?.startsWith("page") ? 10 : 1;
1119
+ if (mode === "requests") selectedRequest = Math.max(0, Math.min(requests.length - 1, selectedRequest + direction * step));
1120
+ else if (mode === "queries") selectedQuery = Math.max(0, Math.min(activeRequest.queries.length - 1, selectedQuery + direction * step));
1121
+ else offset = Math.max(0, offset + direction * step);
1122
+ }
1123
+ draw();
1124
+ };
1125
+ emitKeypressEvents(process.stdin);
1126
+ process.stdin.setRawMode(true);
1127
+ process.stdin.resume();
1128
+ process.stdin.on("keypress", keypress);
1129
+ process.stdin.once("end", finish);
1130
+ process.stdout.on("resize", draw);
1131
+ process.stdout.write("\x1B[?25l");
1132
+ const timer = setInterval(() => {
1133
+ refresh();
1134
+ }, 500);
1135
+ draw();
1136
+ refresh().catch(reject);
1137
+ }));
1138
+ //#endregion
1139
+ //#region src/cli/commands/profile.ts
1140
+ /** `profile`: the live profiler screen, or its JSON feed when not interactive. */
1141
+ const profile = async (context) => {
1142
+ const { values, interactive, color, output } = context;
1143
+ const address = values["profile-url"] ?? "http://127.0.0.1:7331";
1144
+ const token = values["profile-token"] ?? process.env.SYMMETRIA_PROFILE_TOKEN;
1145
+ if (!token) throw new Error("symmetria: profile requires --profile-token or SYMMETRIA_PROFILE_TOKEN, the token configured for or returned by profiler.serve()");
1146
+ if (interactive) return profileScreen(address, token, color);
1147
+ const response = await fetch(new URL("/requests", address), { headers: { "x-symmetria-token": token } });
1148
+ if (!response.ok) throw new Error(`symmetria: profiler returned HTTP ${response.status}`);
1149
+ output(JSON.stringify(await response.json(), null, 2));
1150
+ };
1151
+ //#endregion
1152
+ //#region src/cli/commands/pull.ts
1153
+ /**
1154
+ * `pull [file]`: introspect the configured database and write a schema module.
1155
+ * The connection comes from --database-url, the config (when it loads) or DATABASE_URL.
1156
+ */
1157
+ const pull = async (context, name) => {
1158
+ const { values, color } = context;
1159
+ const path = resolve(name ?? "schema.ts");
1160
+ const explicit = values["database-url"] ?? process.env.DATABASE_URL;
1161
+ const project = await loadProject(context).catch((error) => {
1162
+ if (!explicit) throw error;
1163
+ });
1164
+ const databaseUrl = values["database-url"] ?? project?.databaseUrl ?? explicit;
1165
+ const { metadataSchema, metadataTable } = project?.config ?? {};
1166
+ const result = await withDatabase({ databaseUrl }, (driver) => context.progress("Reading the database", () => pullSchema({
1167
+ execute: driver.execute,
1168
+ ...metadataSchema ? { metadataSchema } : {},
1169
+ ...metadataTable ? { metadataTable } : {}
1170
+ })));
1171
+ await mkdir(dirname(path), { recursive: true });
1172
+ try {
1173
+ await writeFile(path, result.source, { flag: values.force ? "w" : "wx" });
1174
+ } catch (error) {
1175
+ if (error && typeof error === "object" && "code" in error && error.code === "EEXIST") throw new Error(`symmetria: ${path} exists; use --force to overwrite it`);
1176
+ throw error;
1177
+ }
1178
+ const summary = `${result.tables.length} ${result.tables.length === 1 ? "table" : "tables"} from schema "${result.schemaName}"`;
1179
+ context.emit({
1180
+ json: {
1181
+ path,
1182
+ schema: result.schemaName,
1183
+ tables: result.tables,
1184
+ enumerations: result.enumerations,
1185
+ warnings: result.warnings
1186
+ },
1187
+ indent: 2,
1188
+ pretty: () => `${formatCreated(dirname(path), [basename(path)], color)} ${context.style(summary, "muted")}\n\n${formatPullWarnings(result.warnings, color)}`,
1189
+ plain: () => [
1190
+ "Created",
1191
+ ` ${path}`,
1192
+ ` ${summary}`,
1193
+ "",
1194
+ ...result.warnings.length ? [`Review (${result.warnings.length})`, ...result.warnings.flatMap((warning) => [` [${warning.code}] ${warning.message}`, ...warning.fix ? [` fix: ${warning.fix}`] : []])] : ["Nothing needs review; the schema matches the database."]
1195
+ ].join("\n")
1196
+ });
1197
+ };
1198
+ //#endregion
1199
+ //#region src/cli/screens/rename-prompt.ts
1200
+ /** Suggestions are decisions, never guessed renames; persisted SQL records the result. */
1201
+ const resolveRenames = async (before, after, select, options = {}) => {
1202
+ const tables = { ...options.renames?.tables };
1203
+ const columns = Object.fromEntries(Object.entries(options.renames?.columns ?? {}).map(([name, entries]) => [name, { ...entries }]));
1204
+ const shape = (table) => JSON.stringify(table.columns.map((column) => [
1205
+ column.name,
1206
+ column.sqlType,
1207
+ column.notNull
1208
+ ]));
1209
+ for (const old of before.tables.filter((table) => !tables[table.name] && !after.tables.some((next) => next.name === table.name))) {
1210
+ const candidates = after.tables.filter((next) => !Object.values(tables).includes(next.name) && !before.tables.some((table) => table.name === next.name) && shape(old) === shape(next));
1211
+ if (!candidates.length) continue;
1212
+ const choice = await select(`Table ${old.name} disappeared. How should this change be represented?`, [...candidates.map((candidate) => `Rename ${old.name} → ${candidate.name}`), "Drop and add tables"]);
1213
+ if (choice === void 0) throw new Error("symmetria: migration generation cancelled");
1214
+ if (choice < candidates.length) tables[old.name] = candidates[choice].name;
1215
+ }
1216
+ for (const oldTable of before.tables) {
1217
+ const table = after.tables.find((next) => next.name === (tables[oldTable.name] ?? oldTable.name));
1218
+ if (!table) continue;
1219
+ const hints = columns[table.name] ?? {};
1220
+ for (const old of oldTable.columns.filter((column) => !hints[column.name] && !table.columns.some((next) => next.name === column.name))) {
1221
+ const candidates = table.columns.filter((next) => !Object.values(hints).includes(next.name) && !oldTable.columns.some((column) => column.name === next.name) && next.sqlType === old.sqlType && next.notNull === old.notNull);
1222
+ if (!candidates.length) continue;
1223
+ const choice = await select(`${table.name}.${old.name} disappeared. How should this change be represented?`, [...candidates.map((candidate) => `Rename ${old.name} → ${candidate.name}`), "Drop column and add new columns"]);
1224
+ if (choice === void 0) throw new Error("symmetria: migration generation cancelled");
1225
+ if (choice < candidates.length) hints[old.name] = candidates[choice].name;
1226
+ }
1227
+ if (Object.keys(hints).length) columns[table.name] = hints;
1228
+ }
1229
+ return {
1230
+ ...options,
1231
+ renames: {
1232
+ tables,
1233
+ columns
1234
+ }
1235
+ };
1236
+ };
1237
+ //#endregion
1238
+ //#region src/cli/commands/schema.ts
1239
+ /**
1240
+ * Schema-only CLI commands that need no database: inspect, lint, diff and generate.
1241
+ */
1242
+ /** The declared schema, required unless the command can run without one. */
1243
+ const declaredSchema = (project, required) => {
1244
+ const snapshot = project.snapshot();
1245
+ if (required && !snapshot) throw new Error("symmetria: configure schema in symmetria.config.ts before inspecting or generating a migration");
1246
+ return snapshot;
1247
+ };
1248
+ const readDiffOptions = async (context) => {
1249
+ const { values } = context;
1250
+ const options = values.diff ? JSON.parse(await readFile(resolve(values.diff), "utf8")) : {};
1251
+ return values.online ? {
1252
+ ...options,
1253
+ online: true
1254
+ } : options;
1255
+ };
1256
+ /** `inspect [table]`: the schema browser, or a listing of tables, columns and relations. */
1257
+ const inspect$1 = async (context, project, name) => {
1258
+ const { values, color } = context;
1259
+ const snapshot = declaredSchema(project, true);
1260
+ const tables = name ? snapshot.tables.filter((table) => table.name === name || table.sqlName === name) : snapshot.tables;
1261
+ if (name && !tables.length) throw new Error(`symmetria: unknown table "${name}"`);
1262
+ if (context.interactive) return withScreen(() => inspectSchema(snapshot, {
1263
+ color,
1264
+ ...name ? { table: name } : {},
1265
+ tab: values.relations ? "Relations" : "Columns"
1266
+ }));
1267
+ context.emit({
1268
+ json: values.relations ? tables.map((table) => ({
1269
+ name: table.name,
1270
+ relations: table.relations
1271
+ })) : { tables },
1272
+ replacer: (_name, value) => typeof value === "bigint" ? value.toString() : value,
1273
+ indent: 2,
1274
+ plain: () => formatSchema(snapshot, name, values.relations, color)
1275
+ });
1276
+ };
1277
+ /** `lint`: review saved up.sql files and the ungenerated schema diff. */
1278
+ const lint = async (context, project) => {
1279
+ const { values } = context;
1280
+ const diffOptions = await readDiffOptions(context);
1281
+ const snapshot = declaredSchema(project, false);
1282
+ const { snapshot: before, migrations } = await loadMigrationState(project.directory);
1283
+ const after = snapshot ? migrationSnapshot(snapshot) : before;
1284
+ const plan = diffSchemas(before, after, diffOptions);
1285
+ let selected = migrations;
1286
+ if (values.pending) {
1287
+ if (!project.databaseUrl) throw new Error("symmetria: --pending requires databaseUrl");
1288
+ const driver = postgres(project.databaseUrl);
1289
+ try {
1290
+ const statuses = await migrator({
1291
+ driver,
1292
+ ...project.runnerOptions
1293
+ }).status();
1294
+ if (statuses.some((entry) => entry.status === "incomplete")) throw new Error("symmetria: repair incomplete migrations before linting the pending chain");
1295
+ selected = migrations.filter((migration) => statuses.some((status) => status.id === migration.id && status.status === "pending"));
1296
+ } finally {
1297
+ await driver.close();
1298
+ }
1299
+ }
1300
+ const findings = [...selected.flatMap((migration) => lintMigrationSQL(migration.up, migration.id)), ...lintMigration(plan, diffOptions.renames)];
1301
+ context.emit({
1302
+ json: findings,
1303
+ indent: 2,
1304
+ plain: () => formatLintFindings(findings)
1305
+ });
1306
+ if (findings.some((finding) => values.strict || finding.level !== "caution")) process.exitCode = 1;
1307
+ };
1308
+ /** `diff`: compare the declared schema with the latest local snapshot. */
1309
+ const diff = async (context, project) => {
1310
+ const { values, color, output } = context;
1311
+ const diffOptions = await readDiffOptions(context);
1312
+ const snapshot = declaredSchema(project, true);
1313
+ const { snapshot: before } = await loadMigrationState(project.directory);
1314
+ const plan = diffSchemas(before, migrationSnapshot(snapshot), diffOptions);
1315
+ if (values.sql) {
1316
+ output(plan.up.map((statement) => `${statement};`).join("\n\n"));
1317
+ return;
1318
+ }
1319
+ context.emit({
1320
+ json: plan,
1321
+ indent: 2,
1322
+ plain: () => formatDiff(plan, color, diffOptions.renames)
1323
+ });
1324
+ };
1325
+ /** `generate [name]`: write up.sql, down.sql and the versioned snapshot. */
1326
+ const generate = async (context, project, requestedName) => {
1327
+ const { values, color, pretty, interactive, output } = context;
1328
+ let diffOptions = await readDiffOptions(context);
1329
+ const snapshot = declaredSchema(project, !values.empty);
1330
+ const { snapshot: before } = await loadMigrationState(project.directory);
1331
+ const after = snapshot && !values.empty ? migrationSnapshot(snapshot) : before;
1332
+ if (interactive && !values.empty) diffOptions = await resolveRenames(before, after, context.select, diffOptions);
1333
+ const plan = diffSchemas(before, after, diffOptions);
1334
+ const name = requestedName ?? await ask("Migration name:", color);
1335
+ if (!name) throw new Error("symmetria: generate requires a migration name");
1336
+ if (pretty && !values.json && !values.empty) output(formatDiff(plan, color, diffOptions.renames));
1337
+ const migration = await context.progress("Writing migration", () => generateMigration({
1338
+ ...diffOptions,
1339
+ directory: project.directory,
1340
+ name,
1341
+ ...snapshot ? { snapshot } : {},
1342
+ ...values.empty ? { empty: true } : {},
1343
+ ...values["allow-destructive"] ? { allowDestructive: true } : {},
1344
+ ...values.transaction ? { transaction: values.transaction } : {},
1345
+ ...values.online ? { online: true } : {}
1346
+ }));
1347
+ const directory = project.directory;
1348
+ context.emit({
1349
+ json: migration ? {
1350
+ id: migration.id,
1351
+ directory: resolve(directory, migration.id),
1352
+ metadataDirectory: resolve(directory, "meta"),
1353
+ up: migration.up,
1354
+ down: migration.down
1355
+ } : {
1356
+ id: null,
1357
+ changed: false
1358
+ },
1359
+ pretty: () => migration ? formatCreated(directory, [
1360
+ `${migration.id}/up.sql`,
1361
+ `${migration.id}/down.sql`,
1362
+ "meta/snapshot.json",
1363
+ "meta/migration.json"
1364
+ ], color) : "No schema changes.",
1365
+ plain: () => migration ? `Generated ${migration.id}` : "No schema changes."
1366
+ });
1367
+ };
1368
+ //#endregion
1369
+ //#region src/cli/commands/index.ts
1370
+ /**
1371
+ * Dispatches a parsed command line to the command implementation in ./schema, ./database,
1372
+ * ./files, ./graph, ./init, ./pull or ./profile.
1373
+ */
1374
+ /** Runs one command; every command except `profile`, `init` and `pull` works on the loaded project. */
1375
+ const runCommand = async (command, name, context) => {
1376
+ switch (command) {
1377
+ case "profile": return profile(context);
1378
+ case "init": return init(context, name);
1379
+ case "pull": return pull(context, name);
1380
+ }
1381
+ const project = await loadProject(context);
1382
+ switch (command) {
1383
+ case "recover": return recover(context, project);
1384
+ case "squash": return squash(context, project, name);
1385
+ case "dashboard": return dashboard(context, project);
1386
+ case "inspect": return inspect$1(context, project, name);
1387
+ case "graph": return graph(context, project, name);
1388
+ case "lint": return lint(context, project);
1389
+ case "diff": return diff(context, project);
1390
+ case "generate": return generate(context, project, name);
1391
+ case "verify": return verify(context, project);
1392
+ case "drift": return drift(context, project);
1393
+ case "repair": return repair(context, project, name);
1394
+ case "adopt": return adopt(context, project);
1395
+ case "status": return status(context, project);
1396
+ case "migrate": return migrate(context, project);
1397
+ case "rollback": return rollback(context, project);
1398
+ }
1399
+ };
1400
+ //#endregion
1401
+ //#region src/cli/options.ts
1402
+ /** Command-line surface: help text, flag parsing and the rules that tie flags to commands. */
1403
+ const help = `symmetria <command>
1404
+
1405
+ init [directory] Create modular tables, connection and migration config
1406
+ pull [file] Write a schema module for an existing database (default: schema.ts)
1407
+ diff Compare schema code with the latest migration snapshot
1408
+ lint Review saved up.sql files and ungenerated schema changes
1409
+ inspect [table] Inspect tables, columns, relations, indexes and checks
1410
+ graph [file] Print or write a Mermaid entity-relationship diagram
1411
+ profile Observe live application requests and SQL timings
1412
+ generate <name> Generate up.sql, down.sql and a versioned snapshot
1413
+ migrate Apply pending migrations atomically
1414
+ status Show applied and pending migrations
1415
+ rollback Revert the latest migration
1416
+ squash <name> Replace the migration chain with one baseline migration
1417
+ adopt Record the local chain as applied after a squash or baseline
1418
+ drift Compare the live database with the latest migration snapshot
1419
+ verify Exercise installation, upgrade and rollback in disposable databases
1420
+ repair <id> Resolve an incomplete migration after verifying its schema
1421
+ recover Recover files left by a crashed generation process
1422
+ (no command) Open the interactive dashboard in a terminal
1423
+
1424
+ --config <file> Config module (default: symmetria.config.ts)
1425
+ --dir <directory> Override the migrations directory
1426
+ --database-url <url> Override config/database environment URL
1427
+ --profile-url <url> Profiler endpoint (default: http://127.0.0.1:7331)
1428
+ --profile-token <t> Profiler token (default: SYMMETRIA_PROFILE_TOKEN)
1429
+ --diff <file.json> Explicit rename hints and USING conversions for generate
1430
+ --empty Generate an empty, editable SQL migration
1431
+ --allow-destructive Explicitly permit destructive generation
1432
+ --transaction <mode> batch (default), each, or none
1433
+ --pending Lint only migrations pending in the configured database
1434
+ --online Generate concurrent indexes and phased validation (transaction none)
1435
+ --plan Show SQL and transaction groups without executing migrations
1436
+ --action <action> repair: retry or complete, after manual data reconciliation
1437
+ --verify-url <url> Administrative PostgreSQL URL for disposable verification databases
1438
+ --advisory-lock-timeout <ms> Migration lock wait (default: 10000)
1439
+ --lock-timeout <ms> DDL lock wait (default: 5000; 0 disables)
1440
+ --statement-timeout <ms> Statement duration (default: 600000; 0 disables)
1441
+ --to <migration-id> Apply up to a migration
1442
+ --steps <number> Number of migrations to rollback (default: 1)
1443
+ --strict Exit with code 1 when lint or drift report findings
1444
+ --force Overwrite the file written by pull or graph
1445
+ --compact graph: entities and relations without column lists
1446
+ --sql Print executable SQL for diff
1447
+ --json Machine-readable output
1448
+ --relations Show the relation graph with inspect
1449
+ --no-color Disable terminal colors
1450
+ --no-animation Disable logo and loading animations
1451
+ --no-interactive Disable dashboard, schema browser and rename questions
1452
+ --help Show this help
1453
+ `;
1454
+ const COMMANDS = [
1455
+ "generate",
1456
+ "migrate",
1457
+ "status",
1458
+ "rollback",
1459
+ "init",
1460
+ "pull",
1461
+ "graph",
1462
+ "diff",
1463
+ "lint",
1464
+ "squash",
1465
+ "adopt",
1466
+ "drift",
1467
+ "inspect",
1468
+ "dashboard",
1469
+ "profile",
1470
+ "verify",
1471
+ "repair",
1472
+ "recover"
1473
+ ];
1474
+ const parseCommandLine = (argumentsList) => parseArgs({
1475
+ args: argumentsList,
1476
+ allowPositionals: true,
1477
+ strict: true,
1478
+ options: {
1479
+ config: { type: "string" },
1480
+ dir: { type: "string" },
1481
+ "database-url": { type: "string" },
1482
+ "profile-url": { type: "string" },
1483
+ "profile-token": { type: "string" },
1484
+ diff: { type: "string" },
1485
+ strict: { type: "boolean" },
1486
+ force: { type: "boolean" },
1487
+ compact: { type: "boolean" },
1488
+ empty: { type: "boolean" },
1489
+ "allow-destructive": { type: "boolean" },
1490
+ transaction: { type: "string" },
1491
+ pending: { type: "boolean" },
1492
+ online: { type: "boolean" },
1493
+ plan: { type: "boolean" },
1494
+ action: { type: "string" },
1495
+ "verify-url": { type: "string" },
1496
+ "advisory-lock-timeout": { type: "string" },
1497
+ "lock-timeout": { type: "string" },
1498
+ "statement-timeout": { type: "string" },
1499
+ to: { type: "string" },
1500
+ steps: { type: "string" },
1501
+ help: {
1502
+ type: "boolean",
1503
+ short: "h"
1504
+ },
1505
+ sql: { type: "boolean" },
1506
+ json: { type: "boolean" },
1507
+ relations: { type: "boolean" },
1508
+ "no-color": { type: "boolean" },
1509
+ "no-animation": { type: "boolean" },
1510
+ "no-interactive": { type: "boolean" }
1511
+ }
1512
+ });
1513
+ /** Commands that take a second positional argument (a name or an ID). */
1514
+ const NAMED = [
1515
+ "generate",
1516
+ "inspect",
1517
+ "init",
1518
+ "pull",
1519
+ "graph",
1520
+ "squash",
1521
+ "repair"
1522
+ ];
1523
+ /** Flags that belong to specific commands, with the exact refusal wording. */
1524
+ const SCOPED_FLAGS = [
1525
+ {
1526
+ flags: [
1527
+ "allow-destructive",
1528
+ "transaction",
1529
+ "online"
1530
+ ],
1531
+ commands: ["generate"],
1532
+ message: "symmetria: --allow-destructive, --transaction and --online are generate options"
1533
+ },
1534
+ {
1535
+ flags: ["pending"],
1536
+ commands: ["lint"],
1537
+ message: "symmetria: --pending is a lint option"
1538
+ },
1539
+ {
1540
+ flags: ["plan"],
1541
+ commands: ["migrate", "rollback"],
1542
+ message: "symmetria: --plan is a migrate/rollback option"
1543
+ },
1544
+ {
1545
+ flags: ["action"],
1546
+ commands: ["repair"],
1547
+ message: "symmetria: --action is a repair option"
1548
+ },
1549
+ {
1550
+ flags: ["strict"],
1551
+ commands: ["lint", "drift"],
1552
+ message: "symmetria: --strict is a lint/drift option"
1553
+ },
1554
+ {
1555
+ flags: ["diff"],
1556
+ commands: [
1557
+ "generate",
1558
+ "diff",
1559
+ "lint"
1560
+ ],
1561
+ message: "symmetria: --diff is for generate/diff/lint; --empty is for generate"
1562
+ },
1563
+ {
1564
+ flags: ["empty"],
1565
+ commands: ["generate"],
1566
+ message: "symmetria: --diff is for generate/diff/lint; --empty is for generate"
1567
+ },
1568
+ {
1569
+ flags: ["sql"],
1570
+ commands: ["diff"],
1571
+ message: "symmetria: --sql is a diff option"
1572
+ },
1573
+ {
1574
+ flags: ["relations"],
1575
+ commands: ["inspect"],
1576
+ message: "symmetria: --relations is an inspect option"
1577
+ },
1578
+ {
1579
+ flags: ["to"],
1580
+ commands: ["migrate", "adopt"],
1581
+ message: "symmetria: --to is a migrate/adopt option"
1582
+ },
1583
+ {
1584
+ flags: ["steps"],
1585
+ commands: ["rollback"],
1586
+ message: "symmetria: --steps is a rollback option"
1587
+ },
1588
+ {
1589
+ flags: ["force"],
1590
+ commands: ["pull", "graph"],
1591
+ message: "symmetria: --force is a pull/graph option"
1592
+ },
1593
+ {
1594
+ flags: ["compact"],
1595
+ commands: ["graph"],
1596
+ message: "symmetria: --compact is a graph option"
1597
+ }
1598
+ ];
1599
+ /** Resolves the command and its name, then rejects flags and arguments that do not fit it. */
1600
+ const resolveCommand = ({ values, positionals }, interactive) => {
1601
+ const command = positionals[0] ?? "dashboard";
1602
+ const name = positionals[1];
1603
+ if (!COMMANDS.includes(command)) throw new Error(`symmetria: unknown command "${command}"`);
1604
+ if (positionals.length > (NAMED.includes(command) ? 2 : 1)) throw new Error("symmetria: unexpected positional arguments");
1605
+ if (command === "generate" && !name && !interactive) throw new Error("symmetria: generate requires a migration name");
1606
+ if (command === "squash" && !name) throw new Error("symmetria: squash requires a migration name");
1607
+ for (const rule of SCOPED_FLAGS) if (!rule.commands.includes(command) && rule.flags.some((flag) => values[flag])) throw new Error(rule.message);
1608
+ if (values.transaction && ![
1609
+ "batch",
1610
+ "each",
1611
+ "none"
1612
+ ].includes(values.transaction)) throw new Error("symmetria: --transaction must be batch, each, or none");
1613
+ if (command === "repair" && (!name || !["retry", "complete"].includes(values.action ?? ""))) throw new Error("symmetria: repair requires an ID and --action retry|complete");
1614
+ if (values.sql && values.json) throw new Error("symmetria: choose either --sql or --json");
1615
+ return {
1616
+ command,
1617
+ name
1618
+ };
1619
+ };
1620
+ //#endregion
1621
+ //#region src/cli/index.ts
1622
+ /**
1623
+ * `symmetria` command line. Parsing and flag rules live in ./options,
1624
+ * the shared environment in ./context and each command in ./commands.
1625
+ */
1626
+ const runMigrationCLI = async (argumentsList, output = (message) => console.log(message)) => {
1627
+ const parsed = parseCommandLine(argumentsList);
1628
+ const context = createContext(parsed.values, output, runMigrationCLI);
1629
+ if (parsed.values.help || !parsed.positionals.length && !context.interactive) {
1630
+ output(context.pretty && !parsed.values.json && !parsed.values.sql ? formatHelp(help, context.color) : help);
1631
+ return;
1632
+ }
1633
+ const { command, name } = resolveCommand(parsed, context.interactive);
1634
+ await runCommand(command, name, context);
1635
+ };
1636
+ if (import.meta.main) try {
1637
+ try {
1638
+ process.loadEnvFile?.();
1639
+ } catch (error) {
1640
+ if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
1641
+ }
1642
+ await runMigrationCLI(process.argv.slice(2));
1643
+ } catch (error) {
1644
+ let cause = error;
1645
+ const messages = [];
1646
+ while (cause instanceof Error) {
1647
+ messages.push(cause.message);
1648
+ cause = cause.cause;
1649
+ }
1650
+ console.error(formatError(messages.length ? messages.join("\n") : String(error), supportsColor() && !process.argv.includes("--no-color") && !process.argv.includes("--json") && !process.argv.includes("--sql")));
1651
+ process.exitCode = 1;
1652
+ }
1653
+ //#endregion
1654
+ export {};
1655
+
1656
+ //# sourceMappingURL=cli.js.map