@digilogiclabs/platform-core 1.1.1 → 1.3.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.
@@ -0,0 +1,1158 @@
1
+ #!/usr/bin/env node
2
+ #!/usr/bin/env node
3
+ "use strict";
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __esm = (fn, res) => function __init() {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ };
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31
+ mod
32
+ ));
33
+
34
+ // src/adapters/postgres/PostgresDatabase.ts
35
+ var PostgresDatabase_exports = {};
36
+ __export(PostgresDatabase_exports, {
37
+ PostgresDatabase: () => PostgresDatabase
38
+ });
39
+ function toPoolConfig(config) {
40
+ const poolConfig = {};
41
+ if (config.connectionString) {
42
+ poolConfig.connectionString = config.connectionString;
43
+ } else {
44
+ poolConfig.host = config.host;
45
+ poolConfig.port = config.port;
46
+ poolConfig.database = config.database;
47
+ poolConfig.user = config.user;
48
+ poolConfig.password = config.password;
49
+ }
50
+ if (config.ssl !== void 0) {
51
+ poolConfig.ssl = config.ssl;
52
+ }
53
+ poolConfig.max = config.max ?? 10;
54
+ poolConfig.idleTimeoutMillis = config.idleTimeoutMillis ?? 3e4;
55
+ poolConfig.connectionTimeoutMillis = config.connectionTimeoutMillis ?? 1e4;
56
+ poolConfig.application_name = config.applicationName ?? "platform-core";
57
+ if (config.statementTimeout) {
58
+ poolConfig.statement_timeout = config.statementTimeout;
59
+ }
60
+ if (config.queryTimeout) {
61
+ poolConfig.query_timeout = config.queryTimeout;
62
+ }
63
+ return poolConfig;
64
+ }
65
+ var PostgresDatabase, TransactionDatabase, PostgresQueryBuilder;
66
+ var init_PostgresDatabase = __esm({
67
+ "src/adapters/postgres/PostgresDatabase.ts"() {
68
+ "use strict";
69
+ PostgresDatabase = class _PostgresDatabase {
70
+ pool;
71
+ config;
72
+ constructor(pool, config = {}) {
73
+ this.pool = pool;
74
+ this.config = config;
75
+ }
76
+ /**
77
+ * Create a PostgresDatabase from configuration
78
+ */
79
+ static async create(config) {
80
+ const { Pool } = await import("pg");
81
+ const poolConfig = toPoolConfig(config);
82
+ const pool = new Pool(poolConfig);
83
+ const client = await pool.connect();
84
+ client.release();
85
+ return new _PostgresDatabase(pool, config);
86
+ }
87
+ /**
88
+ * Create from environment variables
89
+ */
90
+ static async fromEnv() {
91
+ const config = {
92
+ connectionString: process.env.DATABASE_URL,
93
+ host: process.env.POSTGRES_HOST ?? process.env.PGHOST,
94
+ port: parseInt(
95
+ process.env.POSTGRES_PORT ?? process.env.PGPORT ?? "5432",
96
+ 10
97
+ ),
98
+ database: process.env.POSTGRES_DATABASE ?? process.env.PGDATABASE,
99
+ user: process.env.POSTGRES_USER ?? process.env.PGUSER,
100
+ password: process.env.POSTGRES_PASSWORD ?? process.env.PGPASSWORD,
101
+ max: parseInt(process.env.POSTGRES_POOL_MAX ?? "10", 10),
102
+ ssl: process.env.POSTGRES_SSL === "true" ? {
103
+ rejectUnauthorized: process.env.POSTGRES_SSL_REJECT_UNAUTHORIZED !== "false"
104
+ } : void 0,
105
+ applicationName: process.env.POSTGRES_APP_NAME ?? "platform-core"
106
+ };
107
+ return _PostgresDatabase.create(config);
108
+ }
109
+ from(table) {
110
+ return new PostgresQueryBuilder(this.pool, table);
111
+ }
112
+ async raw(sql, params) {
113
+ try {
114
+ const result = await this.pool.query(sql, params);
115
+ return {
116
+ data: result.rows,
117
+ count: result.rowCount ?? void 0
118
+ };
119
+ } catch (error) {
120
+ return {
121
+ data: [],
122
+ error: error instanceof Error ? error : new Error(String(error))
123
+ };
124
+ }
125
+ }
126
+ /**
127
+ * Execute a function within a database transaction.
128
+ * Provides true ACID guarantees - either all operations succeed or all are rolled back.
129
+ */
130
+ async transaction(fn) {
131
+ const client = await this.pool.connect();
132
+ try {
133
+ await client.query("BEGIN");
134
+ const txDatabase = new TransactionDatabase(client);
135
+ const result = await fn(txDatabase);
136
+ await client.query("COMMIT");
137
+ return result;
138
+ } catch (error) {
139
+ await client.query("ROLLBACK");
140
+ throw error;
141
+ } finally {
142
+ client.release();
143
+ }
144
+ }
145
+ async healthCheck() {
146
+ try {
147
+ const result = await this.pool.query("SELECT 1 as health");
148
+ return result.rows.length > 0;
149
+ } catch {
150
+ return false;
151
+ }
152
+ }
153
+ async close() {
154
+ await this.pool.end();
155
+ }
156
+ /**
157
+ * Get pool statistics for monitoring
158
+ */
159
+ getPoolStats() {
160
+ return {
161
+ totalCount: this.pool.totalCount,
162
+ idleCount: this.pool.idleCount,
163
+ waitingCount: this.pool.waitingCount
164
+ };
165
+ }
166
+ };
167
+ TransactionDatabase = class {
168
+ constructor(client) {
169
+ this.client = client;
170
+ }
171
+ from(table) {
172
+ return new PostgresQueryBuilder(this.client, table);
173
+ }
174
+ async raw(sql, params) {
175
+ try {
176
+ const result = await this.client.query(sql, params);
177
+ return {
178
+ data: result.rows,
179
+ count: result.rowCount ?? void 0
180
+ };
181
+ } catch (error) {
182
+ return {
183
+ data: [],
184
+ error: error instanceof Error ? error : new Error(String(error))
185
+ };
186
+ }
187
+ }
188
+ async transaction(fn) {
189
+ const savepointName = `sp_${Date.now()}_${Math.random().toString(36).slice(2)}`;
190
+ try {
191
+ await this.client.query(`SAVEPOINT ${savepointName}`);
192
+ const result = await fn(this);
193
+ await this.client.query(`RELEASE SAVEPOINT ${savepointName}`);
194
+ return result;
195
+ } catch (error) {
196
+ await this.client.query(`ROLLBACK TO SAVEPOINT ${savepointName}`);
197
+ throw error;
198
+ }
199
+ }
200
+ async healthCheck() {
201
+ try {
202
+ await this.client.query("SELECT 1");
203
+ return true;
204
+ } catch {
205
+ return false;
206
+ }
207
+ }
208
+ async close() {
209
+ }
210
+ };
211
+ PostgresQueryBuilder = class {
212
+ client;
213
+ tableName;
214
+ _select = ["*"];
215
+ _where = [];
216
+ _whereIn = [];
217
+ _orderBy = null;
218
+ _limit = null;
219
+ _offset = 0;
220
+ _insertData = null;
221
+ _updateData = null;
222
+ _deleteFlag = false;
223
+ _returning = ["*"];
224
+ constructor(client, tableName) {
225
+ this.client = client;
226
+ this.tableName = this.escapeIdentifier(tableName);
227
+ }
228
+ select(columns) {
229
+ if (columns) {
230
+ this._select = Array.isArray(columns) ? columns : [columns];
231
+ }
232
+ return this;
233
+ }
234
+ insert(data) {
235
+ this._insertData = Array.isArray(data) ? data : [data];
236
+ return this;
237
+ }
238
+ update(data) {
239
+ this._updateData = data;
240
+ return this;
241
+ }
242
+ delete() {
243
+ this._deleteFlag = true;
244
+ return this;
245
+ }
246
+ where(column, operator, value) {
247
+ this._where.push({ column, operator, value });
248
+ return this;
249
+ }
250
+ whereIn(column, values) {
251
+ this._whereIn.push({ column, values });
252
+ return this;
253
+ }
254
+ orderBy(column, direction = "asc") {
255
+ this._orderBy = { column, direction };
256
+ return this;
257
+ }
258
+ limit(count) {
259
+ this._limit = count;
260
+ return this;
261
+ }
262
+ offset(count) {
263
+ this._offset = count;
264
+ return this;
265
+ }
266
+ async single() {
267
+ this._limit = 1;
268
+ const result = await this.execute();
269
+ if (result.error) {
270
+ return { data: null, error: result.error };
271
+ }
272
+ return { data: result.data[0] ?? null };
273
+ }
274
+ async execute() {
275
+ try {
276
+ if (this._insertData) {
277
+ return await this.executeInsert();
278
+ }
279
+ if (this._updateData) {
280
+ return await this.executeUpdate();
281
+ }
282
+ if (this._deleteFlag) {
283
+ return await this.executeDelete();
284
+ }
285
+ return await this.executeSelect();
286
+ } catch (error) {
287
+ return {
288
+ data: [],
289
+ error: error instanceof Error ? error : new Error(String(error))
290
+ };
291
+ }
292
+ }
293
+ async executeSelect() {
294
+ const params = [];
295
+ let paramIndex = 1;
296
+ const selectClause = this._select.map((col) => this.escapeIdentifier(col)).join(", ");
297
+ let sql = `SELECT ${selectClause} FROM ${this.tableName}`;
298
+ const whereClauses = [];
299
+ for (const { column, operator, value } of this._where) {
300
+ whereClauses.push(
301
+ `${this.escapeIdentifier(column)} ${this.mapOperator(operator)} $${paramIndex++}`
302
+ );
303
+ params.push(value);
304
+ }
305
+ for (const { column, values } of this._whereIn) {
306
+ const placeholders = values.map(() => `$${paramIndex++}`).join(", ");
307
+ whereClauses.push(
308
+ `${this.escapeIdentifier(column)} IN (${placeholders})`
309
+ );
310
+ params.push(...values);
311
+ }
312
+ if (whereClauses.length > 0) {
313
+ sql += ` WHERE ${whereClauses.join(" AND ")}`;
314
+ }
315
+ if (this._orderBy) {
316
+ sql += ` ORDER BY ${this.escapeIdentifier(this._orderBy.column)} ${this._orderBy.direction.toUpperCase()}`;
317
+ }
318
+ if (this._limit !== null) {
319
+ sql += ` LIMIT $${paramIndex++}`;
320
+ params.push(this._limit);
321
+ }
322
+ if (this._offset > 0) {
323
+ sql += ` OFFSET $${paramIndex++}`;
324
+ params.push(this._offset);
325
+ }
326
+ const result = await this.client.query(sql, params);
327
+ return {
328
+ data: result.rows,
329
+ count: result.rowCount ?? void 0
330
+ };
331
+ }
332
+ async executeInsert() {
333
+ if (!this._insertData || this._insertData.length === 0) {
334
+ return { data: [] };
335
+ }
336
+ const params = [];
337
+ let paramIndex = 1;
338
+ const columns = /* @__PURE__ */ new Set();
339
+ for (const row of this._insertData) {
340
+ Object.keys(row).forEach((key) => columns.add(key));
341
+ }
342
+ const columnList = Array.from(columns);
343
+ const columnClause = columnList.map((col) => this.escapeIdentifier(col)).join(", ");
344
+ const valueRows = [];
345
+ for (const row of this._insertData) {
346
+ const rowValues = [];
347
+ for (const col of columnList) {
348
+ rowValues.push(`$${paramIndex++}`);
349
+ params.push(row[col] ?? null);
350
+ }
351
+ valueRows.push(`(${rowValues.join(", ")})`);
352
+ }
353
+ const sql = `INSERT INTO ${this.tableName} (${columnClause}) VALUES ${valueRows.join(", ")} RETURNING ${this._returning.join(", ")}`;
354
+ const result = await this.client.query(sql, params);
355
+ return {
356
+ data: result.rows,
357
+ count: result.rowCount ?? void 0
358
+ };
359
+ }
360
+ async executeUpdate() {
361
+ if (!this._updateData) {
362
+ return { data: [] };
363
+ }
364
+ const params = [];
365
+ let paramIndex = 1;
366
+ const setClauses = [];
367
+ for (const [key, value] of Object.entries(this._updateData)) {
368
+ setClauses.push(`${this.escapeIdentifier(key)} = $${paramIndex++}`);
369
+ params.push(value);
370
+ }
371
+ let sql = `UPDATE ${this.tableName} SET ${setClauses.join(", ")}`;
372
+ const whereClauses = [];
373
+ for (const { column, operator, value } of this._where) {
374
+ whereClauses.push(
375
+ `${this.escapeIdentifier(column)} ${this.mapOperator(operator)} $${paramIndex++}`
376
+ );
377
+ params.push(value);
378
+ }
379
+ for (const { column, values } of this._whereIn) {
380
+ const placeholders = values.map(() => `$${paramIndex++}`).join(", ");
381
+ whereClauses.push(
382
+ `${this.escapeIdentifier(column)} IN (${placeholders})`
383
+ );
384
+ params.push(...values);
385
+ }
386
+ if (whereClauses.length > 0) {
387
+ sql += ` WHERE ${whereClauses.join(" AND ")}`;
388
+ }
389
+ sql += ` RETURNING ${this._returning.join(", ")}`;
390
+ const result = await this.client.query(sql, params);
391
+ return {
392
+ data: result.rows,
393
+ count: result.rowCount ?? void 0
394
+ };
395
+ }
396
+ async executeDelete() {
397
+ const params = [];
398
+ let paramIndex = 1;
399
+ let sql = `DELETE FROM ${this.tableName}`;
400
+ const whereClauses = [];
401
+ for (const { column, operator, value } of this._where) {
402
+ whereClauses.push(
403
+ `${this.escapeIdentifier(column)} ${this.mapOperator(operator)} $${paramIndex++}`
404
+ );
405
+ params.push(value);
406
+ }
407
+ for (const { column, values } of this._whereIn) {
408
+ const placeholders = values.map(() => `$${paramIndex++}`).join(", ");
409
+ whereClauses.push(
410
+ `${this.escapeIdentifier(column)} IN (${placeholders})`
411
+ );
412
+ params.push(...values);
413
+ }
414
+ if (whereClauses.length > 0) {
415
+ sql += ` WHERE ${whereClauses.join(" AND ")}`;
416
+ }
417
+ sql += ` RETURNING ${this._returning.join(", ")}`;
418
+ const result = await this.client.query(sql, params);
419
+ return {
420
+ data: result.rows,
421
+ count: result.rowCount ?? void 0
422
+ };
423
+ }
424
+ escapeIdentifier(identifier) {
425
+ if (identifier === "*") return "*";
426
+ if (identifier.includes(".")) {
427
+ return identifier.split(".").map((part) => `"${part.replace(/"/g, '""')}"`).join(".");
428
+ }
429
+ return `"${identifier.replace(/"/g, '""')}"`;
430
+ }
431
+ mapOperator(operator) {
432
+ switch (operator.toLowerCase()) {
433
+ case "=":
434
+ case "==":
435
+ return "=";
436
+ case "!=":
437
+ case "<>":
438
+ return "<>";
439
+ case "<":
440
+ return "<";
441
+ case "<=":
442
+ return "<=";
443
+ case ">":
444
+ return ">";
445
+ case ">=":
446
+ return ">=";
447
+ case "like":
448
+ return "LIKE";
449
+ case "ilike":
450
+ return "ILIKE";
451
+ case "is":
452
+ return "IS";
453
+ case "is not":
454
+ return "IS NOT";
455
+ default:
456
+ return "=";
457
+ }
458
+ }
459
+ };
460
+ }
461
+ });
462
+
463
+ // src/migrations/Migrator.ts
464
+ var DEFAULT_CONFIG = {
465
+ tableName: "_migrations",
466
+ schema: "public",
467
+ lockTimeout: 60,
468
+ validateChecksums: true,
469
+ migrationsDir: void 0
470
+ };
471
+ function generateChecksum(content) {
472
+ let hash = 0;
473
+ for (let i = 0; i < content.length; i++) {
474
+ const char = content.charCodeAt(i);
475
+ hash = (hash << 5) - hash + char;
476
+ hash = hash & hash;
477
+ }
478
+ return Math.abs(hash).toString(16).padStart(8, "0");
479
+ }
480
+ function sortMigrations(migrations) {
481
+ return [...migrations].sort((a, b) => a.version.localeCompare(b.version));
482
+ }
483
+ var Migrator = class {
484
+ db;
485
+ config;
486
+ migrations = [];
487
+ initialized = false;
488
+ locked = false;
489
+ constructor(db, config = {}) {
490
+ this.db = db;
491
+ this.config = { ...DEFAULT_CONFIG, ...config };
492
+ }
493
+ /**
494
+ * Get the fully qualified migration table name
495
+ */
496
+ get tableName() {
497
+ return `"${this.config.schema}"."${this.config.tableName}"`;
498
+ }
499
+ /**
500
+ * Get the lock table name
501
+ */
502
+ get lockTableName() {
503
+ return `"${this.config.schema}"."${this.config.tableName}_lock"`;
504
+ }
505
+ /**
506
+ * Initialize migration tracking tables
507
+ */
508
+ async initialize() {
509
+ if (this.initialized) return;
510
+ await this.db.raw(`CREATE SCHEMA IF NOT EXISTS "${this.config.schema}"`);
511
+ await this.db.raw(`
512
+ CREATE TABLE IF NOT EXISTS ${this.tableName} (
513
+ version VARCHAR(255) PRIMARY KEY,
514
+ name VARCHAR(255) NOT NULL,
515
+ applied_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
516
+ execution_time INTEGER NOT NULL,
517
+ checksum VARCHAR(64)
518
+ )
519
+ `);
520
+ await this.db.raw(`
521
+ CREATE TABLE IF NOT EXISTS ${this.lockTableName} (
522
+ id INTEGER PRIMARY KEY DEFAULT 1,
523
+ locked_at TIMESTAMP WITH TIME ZONE,
524
+ locked_by VARCHAR(255),
525
+ CONSTRAINT single_row CHECK (id = 1)
526
+ )
527
+ `);
528
+ await this.db.raw(`
529
+ INSERT INTO ${this.lockTableName} (id, locked_at, locked_by)
530
+ VALUES (1, NULL, NULL)
531
+ ON CONFLICT (id) DO NOTHING
532
+ `);
533
+ this.initialized = true;
534
+ }
535
+ /**
536
+ * Acquire migration lock
537
+ */
538
+ async lock() {
539
+ await this.initialize();
540
+ const lockId = `${process.pid}-${Date.now()}`;
541
+ const lockTimeout = new Date(Date.now() - this.config.lockTimeout * 1e3);
542
+ const result = await this.db.raw(
543
+ `
544
+ UPDATE ${this.lockTableName}
545
+ SET locked_at = CURRENT_TIMESTAMP, locked_by = $1
546
+ WHERE id = 1 AND (locked_at IS NULL OR locked_at < $2)
547
+ RETURNING locked_at
548
+ `,
549
+ [lockId, lockTimeout]
550
+ );
551
+ if (result.data.length > 0) {
552
+ this.locked = true;
553
+ return true;
554
+ }
555
+ return false;
556
+ }
557
+ /**
558
+ * Release migration lock
559
+ */
560
+ async unlock() {
561
+ if (!this.locked) return;
562
+ await this.db.raw(
563
+ `
564
+ UPDATE ${this.lockTableName}
565
+ SET locked_at = NULL, locked_by = NULL
566
+ WHERE id = 1
567
+ `
568
+ );
569
+ this.locked = false;
570
+ }
571
+ /**
572
+ * Add migrations to the migrator
573
+ */
574
+ addMigrations(migrations) {
575
+ for (const migration of migrations) {
576
+ if (!migration.checksum) {
577
+ const content = typeof migration.up === "string" ? migration.up : migration.up.toString();
578
+ migration.checksum = generateChecksum(content);
579
+ }
580
+ if (!this.migrations.find((m) => m.version === migration.version)) {
581
+ this.migrations.push(migration);
582
+ }
583
+ }
584
+ }
585
+ /**
586
+ * Load migrations from directory
587
+ * Expects files named: {version}_{name}.ts or {version}_{name}.sql
588
+ */
589
+ async loadMigrations(dir) {
590
+ const { readdir, readFile } = await import("fs/promises");
591
+ const { join } = await import("path");
592
+ const files = await readdir(dir);
593
+ const migrationFiles = files.filter(
594
+ (f) => f.match(/^\d+_.*\.(ts|js|sql)$/)
595
+ );
596
+ for (const file of migrationFiles) {
597
+ const filePath = join(dir, file);
598
+ const [version, ...nameParts] = file.replace(/\.(ts|js|sql)$/, "").split("_");
599
+ const name = nameParts.join("_");
600
+ if (file.endsWith(".sql")) {
601
+ const content = await readFile(filePath, "utf-8");
602
+ const [up, down] = this.parseSqlMigration(content);
603
+ this.addMigrations([
604
+ {
605
+ version,
606
+ name,
607
+ up,
608
+ down
609
+ }
610
+ ]);
611
+ } else {
612
+ const module2 = await import(filePath);
613
+ this.addMigrations([
614
+ {
615
+ version,
616
+ name,
617
+ up: module2.up,
618
+ down: module2.down,
619
+ transactional: module2.transactional
620
+ }
621
+ ]);
622
+ }
623
+ }
624
+ }
625
+ /**
626
+ * Parse SQL migration file with -- UP and -- DOWN sections
627
+ */
628
+ parseSqlMigration(content) {
629
+ const upMatch = content.match(/--\s*UP\s*\n([\s\S]*?)(?=--\s*DOWN|$)/i);
630
+ const downMatch = content.match(/--\s*DOWN\s*\n([\s\S]*?)$/i);
631
+ const up = upMatch?.[1]?.trim() ?? content.trim();
632
+ const down = downMatch?.[1]?.trim() ?? "";
633
+ return [up, down];
634
+ }
635
+ /**
636
+ * Get current migration status
637
+ */
638
+ async status() {
639
+ await this.initialize();
640
+ const result = await this.db.raw(
641
+ `SELECT version, name, applied_at, execution_time, checksum
642
+ FROM ${this.tableName}
643
+ ORDER BY version ASC`
644
+ );
645
+ const applied = result.data.map((row) => ({
646
+ version: row.version,
647
+ name: row.name,
648
+ appliedAt: new Date(row.applied_at),
649
+ executionTime: row.execution_time,
650
+ checksum: row.checksum ?? void 0
651
+ }));
652
+ const appliedVersions = new Set(applied.map((m) => m.version));
653
+ const sortedMigrations = sortMigrations(this.migrations);
654
+ const pending = sortedMigrations.filter(
655
+ (m) => !appliedVersions.has(m.version)
656
+ );
657
+ return {
658
+ applied,
659
+ pending,
660
+ currentVersion: applied.length > 0 ? applied[applied.length - 1].version : null,
661
+ latestVersion: sortedMigrations.length > 0 ? sortedMigrations[sortedMigrations.length - 1].version : null
662
+ };
663
+ }
664
+ /**
665
+ * Run all pending migrations (or up to a specific version)
666
+ */
667
+ async up(options = {}) {
668
+ const { dryRun = false, to } = options;
669
+ const results = [];
670
+ if (!dryRun) {
671
+ const acquired = await this.lock();
672
+ if (!acquired) {
673
+ throw new Error(
674
+ "Could not acquire migration lock. Another migration may be in progress."
675
+ );
676
+ }
677
+ }
678
+ try {
679
+ const status = await this.status();
680
+ let pending = status.pending;
681
+ if (to) {
682
+ const targetIndex = pending.findIndex((m) => m.version === to);
683
+ if (targetIndex === -1) {
684
+ throw new Error(
685
+ `Target version ${to} not found in pending migrations`
686
+ );
687
+ }
688
+ pending = pending.slice(0, targetIndex + 1);
689
+ }
690
+ for (const migration of pending) {
691
+ const result = await this.runMigration(migration, "up", dryRun);
692
+ results.push(result);
693
+ if (!result.success) {
694
+ break;
695
+ }
696
+ }
697
+ } finally {
698
+ if (!dryRun) {
699
+ await this.unlock();
700
+ }
701
+ }
702
+ return results;
703
+ }
704
+ /**
705
+ * Rollback migrations
706
+ */
707
+ async down(options = {}) {
708
+ const { dryRun = false, steps = 1 } = options;
709
+ const results = [];
710
+ if (!dryRun) {
711
+ const acquired = await this.lock();
712
+ if (!acquired) {
713
+ throw new Error(
714
+ "Could not acquire migration lock. Another migration may be in progress."
715
+ );
716
+ }
717
+ }
718
+ try {
719
+ const status = await this.status();
720
+ const toRollback = status.applied.slice(-steps).reverse();
721
+ for (const record of toRollback) {
722
+ const migration = this.migrations.find(
723
+ (m) => m.version === record.version
724
+ );
725
+ if (!migration) {
726
+ throw new Error(
727
+ `Migration ${record.version} was applied but is not registered. Cannot rollback.`
728
+ );
729
+ }
730
+ const result = await this.runMigration(migration, "down", dryRun);
731
+ results.push(result);
732
+ if (!result.success) {
733
+ break;
734
+ }
735
+ }
736
+ } finally {
737
+ if (!dryRun) {
738
+ await this.unlock();
739
+ }
740
+ }
741
+ return results;
742
+ }
743
+ /**
744
+ * Rollback all migrations and re-run them
745
+ */
746
+ async reset(options = {}) {
747
+ const status = await this.status();
748
+ const downResults = await this.down({
749
+ dryRun: options.dryRun,
750
+ steps: status.applied.length
751
+ });
752
+ if (downResults.every((r) => r.success)) {
753
+ const upResults = await this.up({ dryRun: options.dryRun });
754
+ return [...downResults, ...upResults];
755
+ }
756
+ return downResults;
757
+ }
758
+ /**
759
+ * Migrate to a specific version
760
+ */
761
+ async goto(version, options = {}) {
762
+ const status = await this.status();
763
+ const currentVersion = status.currentVersion;
764
+ const results = [];
765
+ if (currentVersion === version) {
766
+ return results;
767
+ }
768
+ const isUp = !currentVersion || version > currentVersion;
769
+ if (isUp) {
770
+ return this.up({ ...options, to: version });
771
+ } else {
772
+ const currentIndex = status.applied.findIndex(
773
+ (m) => m.version === currentVersion
774
+ );
775
+ const targetIndex = status.applied.findIndex(
776
+ (m) => m.version === version
777
+ );
778
+ if (targetIndex === -1) {
779
+ throw new Error(
780
+ `Target version ${version} not found in applied migrations`
781
+ );
782
+ }
783
+ const steps = currentIndex - targetIndex;
784
+ return this.down({ ...options, steps });
785
+ }
786
+ }
787
+ /**
788
+ * Run a single migration
789
+ */
790
+ async runMigration(migration, direction, dryRun) {
791
+ const startTime = Date.now();
792
+ const action = direction === "up" ? migration.up : migration.down;
793
+ try {
794
+ if (dryRun) {
795
+ return {
796
+ migration,
797
+ success: true,
798
+ executionTime: 0,
799
+ dryRun: true
800
+ };
801
+ }
802
+ const transactional = migration.transactional !== false;
803
+ const runAction = async (db) => {
804
+ if (typeof action === "string") {
805
+ const result = await db.raw(action);
806
+ if (result.error) {
807
+ throw result.error;
808
+ }
809
+ } else {
810
+ await action(db);
811
+ }
812
+ };
813
+ if (transactional) {
814
+ await this.db.transaction(async (tx) => {
815
+ await runAction(tx);
816
+ });
817
+ } else {
818
+ await runAction(this.db);
819
+ }
820
+ const executionTime = Date.now() - startTime;
821
+ if (direction === "up") {
822
+ await this.db.raw(
823
+ `INSERT INTO ${this.tableName} (version, name, execution_time, checksum)
824
+ VALUES ($1, $2, $3, $4)`,
825
+ [
826
+ migration.version,
827
+ migration.name,
828
+ executionTime,
829
+ migration.checksum
830
+ ]
831
+ );
832
+ } else {
833
+ await this.db.raw(`DELETE FROM ${this.tableName} WHERE version = $1`, [
834
+ migration.version
835
+ ]);
836
+ }
837
+ return {
838
+ migration,
839
+ success: true,
840
+ executionTime,
841
+ dryRun: false
842
+ };
843
+ } catch (error) {
844
+ return {
845
+ migration,
846
+ success: false,
847
+ executionTime: Date.now() - startTime,
848
+ error: error instanceof Error ? error : new Error(String(error)),
849
+ dryRun: false
850
+ };
851
+ }
852
+ }
853
+ /**
854
+ * Create a new migration file
855
+ */
856
+ async create(name) {
857
+ const { writeFile, mkdir } = await import("fs/promises");
858
+ const { join } = await import("path");
859
+ if (!this.config.migrationsDir) {
860
+ throw new Error("migrationsDir must be configured to create migrations");
861
+ }
862
+ await mkdir(this.config.migrationsDir, { recursive: true });
863
+ const now = /* @__PURE__ */ new Date();
864
+ const version = [
865
+ now.getFullYear(),
866
+ String(now.getMonth() + 1).padStart(2, "0"),
867
+ String(now.getDate()).padStart(2, "0"),
868
+ String(now.getHours()).padStart(2, "0"),
869
+ String(now.getMinutes()).padStart(2, "0"),
870
+ String(now.getSeconds()).padStart(2, "0")
871
+ ].join("");
872
+ const safeName = name.replace(/[^a-zA-Z0-9_]/g, "_").toLowerCase();
873
+ const fileName = `${version}_${safeName}.sql`;
874
+ const filePath = join(this.config.migrationsDir, fileName);
875
+ const template = `-- Migration: ${name}
876
+ -- Version: ${version}
877
+ -- Created: ${now.toISOString()}
878
+
879
+ -- UP
880
+ -- Add your forward migration SQL here
881
+
882
+
883
+ -- DOWN
884
+ -- Add your rollback migration SQL here
885
+
886
+ `;
887
+ await writeFile(filePath, template, "utf-8");
888
+ return filePath;
889
+ }
890
+ /**
891
+ * Validate migration integrity
892
+ */
893
+ async validate() {
894
+ const errors = [];
895
+ const status = await this.status();
896
+ if (!this.config.validateChecksums) {
897
+ return { valid: true, errors };
898
+ }
899
+ for (const applied of status.applied) {
900
+ const migration = this.migrations.find(
901
+ (m) => m.version === applied.version
902
+ );
903
+ if (!migration) {
904
+ errors.push(
905
+ `Migration ${applied.version} (${applied.name}) was applied but is not registered`
906
+ );
907
+ continue;
908
+ }
909
+ if (applied.checksum && migration.checksum !== applied.checksum) {
910
+ errors.push(
911
+ `Migration ${applied.version} (${applied.name}) has been modified since it was applied`
912
+ );
913
+ }
914
+ }
915
+ return {
916
+ valid: errors.length === 0,
917
+ errors
918
+ };
919
+ }
920
+ };
921
+
922
+ // src/migrations/cli.ts
923
+ var HELP_TEXT = `
924
+ Database Migration CLI
925
+
926
+ USAGE:
927
+ platform-migrate <command> [options]
928
+
929
+ COMMANDS:
930
+ status Show current migration status
931
+ up Run all pending migrations
932
+ down Rollback the last migration
933
+ reset Rollback all and re-run migrations
934
+ goto <ver> Migrate to a specific version
935
+ create <name> Create a new migration file
936
+ validate Validate migration integrity
937
+
938
+ OPTIONS:
939
+ --dry-run Preview changes without applying
940
+ --steps <n> Number of migrations to rollback (for down command)
941
+ --to <ver> Target version (for up command)
942
+ --dir <path> Migrations directory (default: ./migrations)
943
+ --help, -h Show this help message
944
+
945
+ ENVIRONMENT:
946
+ DATABASE_URL PostgreSQL connection string (required)
947
+ MIGRATIONS_DIR Default migrations directory
948
+ MIGRATIONS_TABLE Migration tracking table name
949
+
950
+ EXAMPLES:
951
+ platform-migrate status
952
+ platform-migrate up
953
+ platform-migrate up --dry-run
954
+ platform-migrate down --steps 3
955
+ platform-migrate create add_users_table
956
+ platform-migrate goto 20240101000000
957
+ `;
958
+ function parseArgs(args) {
959
+ const options = {
960
+ command: "",
961
+ dryRun: false,
962
+ steps: 1,
963
+ migrationsDir: process.env.MIGRATIONS_DIR ?? "./migrations",
964
+ help: false
965
+ };
966
+ for (let i = 0; i < args.length; i++) {
967
+ const arg = args[i];
968
+ if (arg === "--dry-run") {
969
+ options.dryRun = true;
970
+ } else if (arg === "--steps" && args[i + 1]) {
971
+ options.steps = parseInt(args[++i], 10);
972
+ } else if (arg === "--to" && args[i + 1]) {
973
+ options.to = args[++i];
974
+ } else if ((arg === "--dir" || arg === "-d") && args[i + 1]) {
975
+ options.migrationsDir = args[++i];
976
+ } else if (arg === "--help" || arg === "-h") {
977
+ options.help = true;
978
+ } else if (!arg.startsWith("-") && !options.command) {
979
+ options.command = arg;
980
+ } else if (!arg.startsWith("-") && options.command && !options.name) {
981
+ options.name = arg;
982
+ }
983
+ }
984
+ return options;
985
+ }
986
+ function formatResults(results) {
987
+ if (results.length === 0) {
988
+ console.log("No migrations to run.");
989
+ return;
990
+ }
991
+ for (const result of results) {
992
+ const icon = result.success ? "\u2713" : "\u2717";
993
+ const status = result.dryRun ? "[DRY RUN]" : "";
994
+ const time = result.success ? `(${result.executionTime}ms)` : "";
995
+ if (result.success) {
996
+ console.log(
997
+ ` ${icon} ${result.migration.version} - ${result.migration.name} ${time} ${status}`
998
+ );
999
+ } else {
1000
+ console.error(
1001
+ ` ${icon} ${result.migration.version} - ${result.migration.name}`
1002
+ );
1003
+ console.error(` Error: ${result.error?.message}`);
1004
+ }
1005
+ }
1006
+ const successful = results.filter((r) => r.success).length;
1007
+ const failed = results.filter((r) => !r.success).length;
1008
+ console.log(`
1009
+ ${successful} successful, ${failed} failed`);
1010
+ }
1011
+ async function main() {
1012
+ const args = process.argv.slice(2);
1013
+ const options = parseArgs(args);
1014
+ if (options.help || !options.command) {
1015
+ console.log(HELP_TEXT);
1016
+ process.exit(options.help ? 0 : 1);
1017
+ }
1018
+ if (!process.env.DATABASE_URL) {
1019
+ console.error("Error: DATABASE_URL environment variable is required");
1020
+ process.exit(1);
1021
+ }
1022
+ try {
1023
+ const { PostgresDatabase: PostgresDatabase2 } = await Promise.resolve().then(() => (init_PostgresDatabase(), PostgresDatabase_exports));
1024
+ const db = await PostgresDatabase2.fromEnv();
1025
+ const migrator = new Migrator(db, {
1026
+ tableName: process.env.MIGRATIONS_TABLE ?? "_migrations",
1027
+ migrationsDir: options.migrationsDir
1028
+ });
1029
+ try {
1030
+ await migrator.loadMigrations(options.migrationsDir);
1031
+ } catch (e) {
1032
+ if (options.command !== "create") {
1033
+ console.warn(
1034
+ `Warning: Could not load migrations from ${options.migrationsDir}`
1035
+ );
1036
+ }
1037
+ }
1038
+ switch (options.command) {
1039
+ case "status": {
1040
+ const status = await migrator.status();
1041
+ console.log("\n=== Migration Status ===\n");
1042
+ console.log(`Current Version: ${status.currentVersion ?? "None"}`);
1043
+ console.log(`Latest Version: ${status.latestVersion ?? "None"}`);
1044
+ console.log(`
1045
+ Applied (${status.applied.length}):`);
1046
+ for (const m of status.applied) {
1047
+ console.log(
1048
+ ` \u2713 ${m.version} - ${m.name} (${m.appliedAt.toISOString()})`
1049
+ );
1050
+ }
1051
+ console.log(`
1052
+ Pending (${status.pending.length}):`);
1053
+ for (const m of status.pending) {
1054
+ console.log(` \u25CB ${m.version} - ${m.name}`);
1055
+ }
1056
+ break;
1057
+ }
1058
+ case "up": {
1059
+ console.log(
1060
+ options.dryRun ? "\n=== Dry Run: Migrate Up ===\n" : "\n=== Migrating Up ===\n"
1061
+ );
1062
+ const results = await migrator.up({
1063
+ dryRun: options.dryRun,
1064
+ to: options.to
1065
+ });
1066
+ formatResults(results);
1067
+ if (results.some((r) => !r.success)) {
1068
+ process.exit(1);
1069
+ }
1070
+ break;
1071
+ }
1072
+ case "down": {
1073
+ console.log(
1074
+ options.dryRun ? "\n=== Dry Run: Rollback ===\n" : "\n=== Rolling Back ===\n"
1075
+ );
1076
+ const results = await migrator.down({
1077
+ dryRun: options.dryRun,
1078
+ steps: options.steps
1079
+ });
1080
+ formatResults(results);
1081
+ if (results.some((r) => !r.success)) {
1082
+ process.exit(1);
1083
+ }
1084
+ break;
1085
+ }
1086
+ case "reset": {
1087
+ console.log(
1088
+ options.dryRun ? "\n=== Dry Run: Reset ===\n" : "\n=== Resetting Database ===\n"
1089
+ );
1090
+ const results = await migrator.reset({ dryRun: options.dryRun });
1091
+ formatResults(results);
1092
+ if (results.some((r) => !r.success)) {
1093
+ process.exit(1);
1094
+ }
1095
+ break;
1096
+ }
1097
+ case "goto": {
1098
+ if (!options.name) {
1099
+ console.error(
1100
+ "Error: Version required. Usage: platform-migrate goto <version>"
1101
+ );
1102
+ process.exit(1);
1103
+ }
1104
+ console.log(`
1105
+ === Migrating to Version ${options.name} ===
1106
+ `);
1107
+ const results = await migrator.goto(options.name, {
1108
+ dryRun: options.dryRun
1109
+ });
1110
+ formatResults(results);
1111
+ if (results.some((r) => !r.success)) {
1112
+ process.exit(1);
1113
+ }
1114
+ break;
1115
+ }
1116
+ case "create": {
1117
+ if (!options.name) {
1118
+ console.error(
1119
+ "Error: Migration name required. Usage: platform-migrate create <name>"
1120
+ );
1121
+ process.exit(1);
1122
+ }
1123
+ const filePath = await migrator.create(options.name);
1124
+ console.log(`
1125
+ Created migration: ${filePath}
1126
+ `);
1127
+ break;
1128
+ }
1129
+ case "validate": {
1130
+ console.log("\n=== Validating Migrations ===\n");
1131
+ const { valid, errors } = await migrator.validate();
1132
+ if (valid) {
1133
+ console.log("\u2713 All migrations are valid");
1134
+ } else {
1135
+ console.error("\u2717 Validation failed:");
1136
+ for (const error of errors) {
1137
+ console.error(` - ${error}`);
1138
+ }
1139
+ process.exit(1);
1140
+ }
1141
+ break;
1142
+ }
1143
+ default:
1144
+ console.error(`Unknown command: ${options.command}`);
1145
+ console.log(HELP_TEXT);
1146
+ process.exit(1);
1147
+ }
1148
+ await db.close();
1149
+ } catch (error) {
1150
+ console.error("Error:", error instanceof Error ? error.message : error);
1151
+ process.exit(1);
1152
+ }
1153
+ }
1154
+ main().catch((error) => {
1155
+ console.error("Fatal error:", error);
1156
+ process.exit(1);
1157
+ });
1158
+ //# sourceMappingURL=migrate.js.map