@event-driven-io/pongo 0.16.4-alpha.1 → 0.16.4

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.cjs CHANGED
@@ -1,28 +1,450 @@
1
1
  #!/usr/bin/env node
2
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkPUUNCOTHcjs = require('./chunk-PUUNCOTH.cjs');var _commander = require('commander');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var w=o=>{if(o.length===0)return o;let e=o.charAt(0).toUpperCase()+o.slice(1);return e.endsWith("s")&&(e=e.slice(0,-1)),e},l=(o=["users"])=>{let e=o.map(n=>`export type ${w(n)} = { name: string; description: string; date: Date }`).join(`
3
- `),i=o.map(n=>` ${n}: pongoSchema.collection<${w(n)}>('${n}'),`).join(`
4
- `);return`import { pongoSchema } from '@event-driven-io/pongo';
2
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
5
3
 
6
- ${e}
4
+
5
+
6
+
7
+
8
+ var _chunkHZVM5GBHcjs = require('./chunk-HZVM5GBH.cjs');
9
+
10
+ // src/cli.ts
11
+ var _commander = require('commander');
12
+
13
+ // src/commandLine/configFile.ts
14
+
15
+ var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
16
+ var formatTypeName = (input) => {
17
+ if (input.length === 0) {
18
+ return input;
19
+ }
20
+ let formatted = input.charAt(0).toUpperCase() + input.slice(1);
21
+ if (formatted.endsWith("s")) {
22
+ formatted = formatted.slice(0, -1);
23
+ }
24
+ return formatted;
25
+ };
26
+ var sampleConfig = (collectionNames = ["users"]) => {
27
+ const types = collectionNames.map(
28
+ (name) => `export type ${formatTypeName(name)} = { name: string; description: string; date: Date }`
29
+ ).join("\n");
30
+ const collections = collectionNames.map(
31
+ (name) => ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`
32
+ ).join("\n");
33
+ return `import { pongoSchema } from '@event-driven-io/pongo';
34
+
35
+ ${types}
7
36
 
8
37
  export default {
9
38
  schema: pongoSchema.client({
10
39
  database: pongoSchema.db({
11
- ${i}
40
+ ${collections}
12
41
  }),
13
42
  }),
14
- };`},I=`Error: Config should contain default export, e.g.
43
+ };`;
44
+ };
45
+ var missingDefaultExport = `Error: Config should contain default export, e.g.
46
+
47
+ ${sampleConfig()}`;
48
+ var missingSchema = `Error: Config should contain schema property, e.g.
49
+
50
+ ${sampleConfig()}`;
51
+ var missingDbs = `Error: Config should have at least a single database defined, e.g.
52
+
53
+ ${sampleConfig()}`;
54
+ var missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.
55
+
56
+ ${sampleConfig()}`;
57
+ var missingCollections = `Error: Database should have defined at least one collection, e.g.
58
+
59
+ ${sampleConfig()}`;
60
+ var loadConfigFile = async (configPath) => {
61
+ const configUrl = new URL(configPath, `file://${process.cwd()}/`);
62
+ try {
63
+ const imported = await Promise.resolve().then(() => _interopRequireWildcard(require(configUrl.href)));
64
+ const parsed = parseDefaultDbSchema(imported);
65
+ if (typeof parsed === "string") {
66
+ console.error(parsed);
67
+ process.exit(1);
68
+ }
69
+ return parsed;
70
+ } catch (e) {
71
+ console.error(`Error: Couldn't load file: ${configUrl.href}`);
72
+ process.exit(1);
73
+ }
74
+ };
75
+ var generateConfigFile = (configPath, collectionNames) => {
76
+ try {
77
+ _fs2.default.writeFileSync(configPath, sampleConfig(collectionNames), "utf8");
78
+ console.log(`Configuration file stored at: ${configPath}`);
79
+ } catch (error) {
80
+ console.error(`Error: Couldn't store config file: ${configPath}!`);
81
+ console.error(error);
82
+ process.exit(1);
83
+ }
84
+ };
85
+ var parseDefaultDbSchema = (imported) => {
86
+ if (!imported.default) {
87
+ return missingDefaultExport;
88
+ }
89
+ if (!imported.default.schema) {
90
+ return missingSchema;
91
+ }
92
+ if (!imported.default.schema.dbs) {
93
+ return missingDbs;
94
+ }
95
+ const dbs = _chunkHZVM5GBHcjs.objectEntries.call(void 0, imported.default.schema.dbs).map((db) => db[1]);
96
+ const defaultDb = dbs.find((db) => db.name === void 0);
97
+ if (!defaultDb) {
98
+ return missingDefaultDb;
99
+ }
100
+ if (!defaultDb.collections) {
101
+ return missingCollections;
102
+ }
103
+ const collections = _chunkHZVM5GBHcjs.objectEntries.call(void 0, defaultDb.collections).map((col) => col[1]);
104
+ if (collections.length === 0) {
105
+ return missingCollections;
106
+ }
107
+ return _chunkHZVM5GBHcjs.toDbSchemaMetadata.call(void 0, defaultDb);
108
+ };
109
+ var configCommand = new (0, _commander.Command)("config").description(
110
+ "Manage Pongo configuration"
111
+ );
112
+ configCommand.command("sample").description("Generate or print sample configuration").option(
113
+ "-col, --collection <name>",
114
+ "Specify the collection name",
115
+ (value, previous) => {
116
+ return previous.concat([value]);
117
+ },
118
+ []
119
+ ).option(
120
+ "-f, --file <path>",
121
+ "Path to configuration file with collection list"
122
+ ).option("-g, --generate", "Generate sample config file").option("-p, --print", "Print sample config file").action((options) => {
123
+ const collectionNames = options.collection.length > 0 ? options.collection : ["users"];
124
+ if (!("print" in options) && !("generate" in options)) {
125
+ console.error(
126
+ "Error: Please provide either:\n--print param to print sample config or\n--generate to generate sample config file"
127
+ );
128
+ process.exit(1);
129
+ }
130
+ if ("print" in options) {
131
+ console.log(`${sampleConfig(collectionNames)}`);
132
+ } else if ("generate" in options) {
133
+ if (!options.file) {
134
+ console.error(
135
+ "Error: You need to provide a config file through a --file"
136
+ );
137
+ process.exit(1);
138
+ }
139
+ generateConfigFile(options.file, collectionNames);
140
+ }
141
+ });
142
+
143
+ // src/commandLine/migrate.ts
144
+
145
+
146
+
147
+
148
+
149
+ var _dumbo = require('@event-driven-io/dumbo');
150
+
151
+ var migrateCommand = new (0, _commander.Command)("migrate").description(
152
+ "Manage database migrations"
153
+ );
154
+ migrateCommand.command("run").description("Run database migrations").option(
155
+ "-cs, --connection-string <string>",
156
+ "Connection string for the database"
157
+ ).option(
158
+ "-col, --collection <name>",
159
+ "Specify the collection name",
160
+ (value, previous) => {
161
+ return previous.concat([value]);
162
+ },
163
+ []
164
+ ).option("-f, --config <path>", "Path to configuration file with Pongo config").option("-dr, --dryRun", "Perform dry run without commiting changes", false).action(async (options) => {
165
+ const { collection, dryRun } = options;
166
+ const connectionString = _nullishCoalesce(options.connectionString, () => ( process.env.DB_CONNECTION_STRING));
167
+ let collectionNames;
168
+ if (!connectionString) {
169
+ console.error(
170
+ 'Error: Connection string is required. Provide it either as a "--connection-string" parameter or through the DB_CONNECTION_STRING environment variable.\nFor instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres'
171
+ );
172
+ process.exit(1);
173
+ }
174
+ if (options.config) {
175
+ const config = await loadConfigFile(options.config);
176
+ collectionNames = config.collections.map((c) => c.name);
177
+ } else if (collection) {
178
+ collectionNames = collection;
179
+ } else {
180
+ console.error(
181
+ 'Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'
182
+ );
183
+ process.exit(1);
184
+ }
185
+ const pool = _dumbo.dumbo.call(void 0, { connectionString });
186
+ const migrations = collectionNames.flatMap(
187
+ (collectionsName) => _chunkHZVM5GBHcjs.pongoCollectionSchemaComponent.call(void 0, collectionsName).migrations({
188
+ connector: "PostgreSQL:pg"
189
+ // TODO: Provide connector here
190
+ })
191
+ );
192
+ await _dumbo.runPostgreSQLMigrations.call(void 0, pool, migrations, {
193
+ dryRun
194
+ });
195
+ });
196
+ migrateCommand.command("sql").description("Generate SQL for database migration").option(
197
+ "-col, --collection <name>",
198
+ "Specify the collection name",
199
+ (value, previous) => {
200
+ return previous.concat([value]);
201
+ },
202
+ []
203
+ ).option("-f, --config <path>", "Path to configuration file with Pongo config").option("--print", "Print the SQL to the console (default)", true).action(async (options) => {
204
+ const { collection } = options;
205
+ let collectionNames;
206
+ if (options.config) {
207
+ const config = await loadConfigFile(options.config);
208
+ collectionNames = config.collections.map((c) => c.name);
209
+ } else if (collection) {
210
+ collectionNames = collection;
211
+ } else {
212
+ console.error(
213
+ 'Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'
214
+ );
215
+ process.exit(1);
216
+ }
217
+ const coreMigrations = _dumbo.migrationTableSchemaComponent.migrations({
218
+ connector: "PostgreSQL:pg"
219
+ });
220
+ const migrations = [
221
+ ...coreMigrations,
222
+ ...collectionNames.flatMap(
223
+ (collectionName) => _chunkHZVM5GBHcjs.pongoCollectionSchemaComponent.call(void 0, collectionName).migrations({
224
+ connector: "PostgreSQL:pg"
225
+ // TODO: Provide connector here
226
+ })
227
+ )
228
+ ];
229
+ console.log("Printing SQL:");
230
+ console.log(_dumbo.combineMigrations.call(void 0, ...migrations));
231
+ });
232
+
233
+ // src/commandLine/shell.ts
234
+
235
+
236
+
237
+
238
+
239
+
240
+
15
241
 
16
- ${l()}`,_=`Error: Config should contain schema property, e.g.
242
+ var _clitable3 = require('cli-table3'); var _clitable32 = _interopRequireDefault(_clitable3);
17
243
 
18
- ${l()}`,$=`Error: Config should have at least a single database defined, e.g.
244
+ var _repl = require('repl'); var _repl2 = _interopRequireDefault(_repl);
245
+ var pongo;
246
+ var calculateColumnWidths = (results, columnNames) => {
247
+ const columnWidths = columnNames.map((col) => {
248
+ const maxWidth = Math.max(
249
+ col.length,
250
+ ...results.map(
251
+ (result) => (
252
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
253
+ result[col] ? String(result[col]).length : 0
254
+ )
255
+ )
256
+ );
257
+ return maxWidth + 2;
258
+ });
259
+ return columnWidths;
260
+ };
261
+ var shouldDisplayResultsAsTable = false;
262
+ var printResultsAsTable = (print) => shouldDisplayResultsAsTable = print === void 0 || print === true;
263
+ var printOutput = (obj) => Array.isArray(obj) && shouldDisplayResultsAsTable ? displayResultsAsTable(obj) : _dumbo.prettyJson.call(void 0, obj);
264
+ var displayResultsAsTable = (results) => {
265
+ if (results.length === 0) {
266
+ return _dumbo.color.yellow("No documents found.");
267
+ }
268
+ const columnNames = results.flatMap(
269
+ (result) => (
270
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
271
+ typeof result === "object" ? Object.keys(result) : typeof result
272
+ )
273
+ ).filter((value, index, array) => array.indexOf(value) === index);
274
+ const columnWidths = calculateColumnWidths(results, columnNames);
275
+ const table = new (0, _clitable32.default)({
276
+ head: columnNames.map((col) => _dumbo.color.cyan(col)),
277
+ colWidths: columnWidths
278
+ });
279
+ results.forEach((result) => {
280
+ table.push(
281
+ columnNames.map(
282
+ (col) => (
283
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
284
+ result[col] !== void 0 ? (
285
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
286
+ Array.isArray(result[col]) ? (
287
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
288
+ displayResultsAsTable(result[col])
289
+ ) : (
290
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
291
+ _dumbo.prettyJson.call(void 0, result[col])
292
+ )
293
+ ) : typeof result === "object" ? "" : result != void 0 && result != void 0 ? _dumbo.prettyJson.call(void 0, result) : ""
294
+ )
295
+ )
296
+ );
297
+ });
298
+ return table.toString();
299
+ };
300
+ var setLogLevel = (logLevel) => {
301
+ process.env.DUMBO_LOG_LEVEL = logLevel;
302
+ };
303
+ var setLogStyle = (logLevel) => {
304
+ process.env.DUMBO_LOG_STYLE = logLevel;
305
+ };
306
+ var prettifyLogs = (logLevel) => {
307
+ if (logLevel !== void 0) setLogLevel(logLevel);
308
+ setLogStyle(_dumbo.LogStyle.PRETTY);
309
+ };
310
+ var startRepl = async (options) => {
311
+ setLogLevel(_nullishCoalesce(process.env.DUMBO_LOG_LEVEL, () => ( options.logging.logLevel)));
312
+ setLogStyle(_nullishCoalesce(process.env.DUMBO_LOG_STYLE, () => ( options.logging.logStyle)));
313
+ console.log(_dumbo.color.green("Starting Pongo Shell (version: 0.16.4)"));
314
+ if (options.logging.printOptions) {
315
+ console.log(_dumbo.color.green("With Options:"));
316
+ console.log(_dumbo.prettyJson.call(void 0, options));
317
+ }
318
+ const connectionString = _nullishCoalesce(_nullishCoalesce(options.connectionString, () => ( process.env.DB_CONNECTION_STRING)), () => ( "postgresql://postgres:postgres@localhost:5432/postgres"));
319
+ if (!(_nullishCoalesce(options.connectionString, () => ( process.env.DB_CONNECTION_STRING)))) {
320
+ console.log(
321
+ _dumbo.color.yellow(
322
+ `No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'`
323
+ )
324
+ );
325
+ }
326
+ const connectionCheck = await _dumbo.checkConnection.call(void 0, connectionString);
327
+ if (!connectionCheck.successful) {
328
+ if (connectionCheck.errorType === "ConnectionRefused") {
329
+ console.error(
330
+ _dumbo.color.red(
331
+ `Connection was refused. Check if the PostgreSQL server is running and accessible.`
332
+ )
333
+ );
334
+ } else if (connectionCheck.errorType === "Authentication") {
335
+ console.error(
336
+ _dumbo.color.red(
337
+ `Authentication failed. Check the username and password in the connection string.`
338
+ )
339
+ );
340
+ } else {
341
+ console.error(_dumbo.color.red("Error connecting to PostgreSQL server"));
342
+ }
343
+ console.log(_dumbo.color.red("Exiting Pongo Shell..."));
344
+ process.exit();
345
+ }
346
+ console.log(_dumbo.color.green(`Successfully connected`));
347
+ console.log(_dumbo.color.green("Use db.<collection>.<method>() to query."));
348
+ const shell = _repl2.default.start({
349
+ prompt: _dumbo.color.green("pongo> "),
350
+ useGlobal: true,
351
+ breakEvalOnSigint: true,
352
+ writer: printOutput
353
+ });
354
+ let db;
355
+ if (options.schema.collections.length > 0) {
356
+ const collectionsSchema = {};
357
+ for (const collectionName of options.schema.collections) {
358
+ collectionsSchema[collectionName] = _chunkHZVM5GBHcjs.pongoSchema.collection(collectionName);
359
+ }
360
+ const schema = _chunkHZVM5GBHcjs.pongoSchema.client({
361
+ database: _chunkHZVM5GBHcjs.pongoSchema.db(options.schema.database, collectionsSchema)
362
+ });
363
+ const typedClient = _chunkHZVM5GBHcjs.pongoClient.call(void 0, connectionString, {
364
+ schema: {
365
+ definition: schema,
366
+ autoMigration: options.schema.autoMigration
367
+ }
368
+ });
369
+ db = typedClient.database;
370
+ for (const collectionName of options.schema.collections) {
371
+ shell.context[collectionName] = typedClient.database[collectionName];
372
+ }
373
+ pongo = typedClient;
374
+ } else {
375
+ pongo = _chunkHZVM5GBHcjs.pongoClient.call(void 0, connectionString, {
376
+ schema: { autoMigration: options.schema.autoMigration }
377
+ });
378
+ db = pongo.db(options.schema.database);
379
+ }
380
+ shell.context.pongo = pongo;
381
+ shell.context.db = db;
382
+ shell.context.SQL = _dumbo.SQL;
383
+ shell.context.setLogLevel = setLogLevel;
384
+ shell.context.setLogStyle = setLogStyle;
385
+ shell.context.prettifyLogs = prettifyLogs;
386
+ shell.context.printResultsAsTable = printResultsAsTable;
387
+ shell.context.LogStyle = _dumbo.LogStyle;
388
+ shell.context.LogLevel = _dumbo.LogLevel;
389
+ shell.on("exit", async () => {
390
+ await teardown();
391
+ process.exit();
392
+ });
393
+ shell.on("SIGINT", async () => {
394
+ await teardown();
395
+ process.exit();
396
+ });
397
+ };
398
+ var teardown = async () => {
399
+ console.log(_dumbo.color.yellow("Exiting Pongo Shell..."));
400
+ await pongo.close();
401
+ };
402
+ process.on("uncaughtException", teardown);
403
+ process.on("SIGINT", teardown);
404
+ var shellCommand = new (0, _commander.Command)("shell").description("Start an interactive Pongo shell").option(
405
+ "-cs, --connectionString <string>",
406
+ "Connection string for the database"
407
+ ).option("-db, --database <string>", "Database name to connect", "postgres").option(
408
+ "-col, --collection <name>",
409
+ "Specify the collection name",
410
+ (value, previous) => {
411
+ return previous.concat([value]);
412
+ },
413
+ []
414
+ ).option(
415
+ "-no-migrations, --disable-auto-migrations",
416
+ "Disable automatic migrations"
417
+ ).option("-o, --print-options", "Print shell options").option(
418
+ "-ll, --log-level <logLevel>",
419
+ "Log level: DISABLED, INFO, LOG, WARN, ERROR",
420
+ "DISABLED"
421
+ ).option("-ls, --log-style", "Log style: RAW, PRETTY", "RAW").option("-p, --pretty-log", "Turn on logging with prettified output").action(async (options) => {
422
+ const { collection, database } = options;
423
+ const connectionString = options.connectionString;
424
+ await startRepl({
425
+ logging: {
426
+ printOptions: options.printOptions === true,
427
+ logStyle: options.prettyLog ? _dumbo.LogStyle.PRETTY : _nullishCoalesce(options.logStyle, () => ( _dumbo.LogStyle.RAW)),
428
+ logLevel: options.logLevel ? options.logLevel : options.prettyLog ? _dumbo.LogLevel.INFO : _dumbo.LogLevel.DISABLED
429
+ },
430
+ schema: {
431
+ collections: collection,
432
+ database,
433
+ autoMigration: options.disableAutoMigrations ? "None" : "CreateOrUpdate"
434
+ },
435
+ connectionString
436
+ });
437
+ });
19
438
 
20
- ${l()}`,G=`Error: Config should have a default database defined (without name or or with default database name), e.g.
439
+ // src/cli.ts
440
+ var program = new (0, _commander.Command)();
441
+ program.name("pongo").description("CLI tool for Pongo");
442
+ program.addCommand(configCommand);
443
+ program.addCommand(migrateCommand);
444
+ program.addCommand(shellCommand);
445
+ program.parse(process.argv);
446
+ var cli_default = program;
21
447
 
22
- ${l()}`,D=`Error: Database should have defined at least one collection, e.g.
23
448
 
24
- ${l()}`,L=async o=>{let e=new URL(o,`file://${process.cwd()}/`);try{let i=await Promise.resolve().then(() => _interopRequireWildcard(require(e.href))),n=B(i);return typeof n=="string"&&(console.error(n),process.exit(1)),n}catch (e2){console.error(`Error: Couldn't load file: ${e.href}`),process.exit(1)}},W=(o,e)=>{try{_fs2.default.writeFileSync(o,l(e),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(i){console.error(`Error: Couldn't store config file: ${o}!`),console.error(i),process.exit(1)}},B=o=>{if(!o.default)return I;if(!o.default.schema)return _;if(!o.default.schema.dbs)return $;let i=_chunkPUUNCOTHcjs.t.call(void 0, o.default.schema.dbs).map(t=>t[1]).find(t=>t.name===void 0);return i?!i.collections||_chunkPUUNCOTHcjs.t.call(void 0, i.collections).map(t=>t[1]).length===0?D:_chunkPUUNCOTHcjs.F.call(void 0, i):G},v=new (0, _commander.Command)("config").description("Manage Pongo configuration");v.command("sample").description("Generate or print sample configuration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(o=>{let e=o.collection.length>0?o.collection:["users"];!("print"in o)&&!("generate"in o)&&(console.error(`Error: Please provide either:
25
- --print param to print sample config or
26
- --generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${l(e)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),W(o.file,e))});var _dumbo = require('@event-driven-io/dumbo');var d=new (0, _commander.Command)("migrate").description("Manage database migrations");d.command("run").description("Run database migrations").option("-cs, --connection-string <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:e,dryRun:i}=o,n=_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)),t;n||(console.error(`Error: Connection string is required. Provide it either as a "--connection-string" parameter or through the DB_CONNECTION_STRING environment variable.
27
- For instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres`),process.exit(1)),o.config?t=(await L(o.config)).collections.map(c=>c.name):e?t=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let r=_dumbo.dumbo.call(void 0, {connectionString:n}),s=t.flatMap(g=>_chunkPUUNCOTHcjs.h.call(void 0, g).migrations({connector:"PostgreSQL:pg"}));await _dumbo.runPostgreSQLMigrations.call(void 0, r,s,{dryRun:i})});d.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("--print","Print the SQL to the console (default)",!0).action(async o=>{let{collection:e}=o,i;o.config?i=(await L(o.config)).collections.map(s=>s.name):e?i=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let t=[..._dumbo.migrationTableSchemaComponent.migrations({connector:"PostgreSQL:pg"}),...i.flatMap(r=>_chunkPUUNCOTHcjs.h.call(void 0, r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(_dumbo.combineMigrations.call(void 0, ...t))});var _clitable3 = require('cli-table3'); var _clitable32 = _interopRequireDefault(_clitable3);var _repl = require('repl'); var _repl2 = _interopRequireDefault(_repl);var m,H=(o,e)=>e.map(n=>Math.max(n.length,...o.map(r=>r[n]?String(r[n]).length:0))+2),M=!1,K=o=>M=o===void 0||o===!0,X=o=>Array.isArray(o)&&M?N(o):_dumbo.prettyJson.call(void 0, o),N=o=>{if(o.length===0)return _dumbo.color.yellow("No documents found.");let e=o.flatMap(t=>typeof t=="object"?Object.keys(t):typeof t).filter((t,r,s)=>s.indexOf(t)===r),i=H(o,e),n=new (0, _clitable32.default)({head:e.map(t=>_dumbo.color.cyan(t)),colWidths:i});return o.forEach(t=>{n.push(e.map(r=>t[r]!==void 0?Array.isArray(t[r])?N(t[r]):_dumbo.prettyJson.call(void 0, t[r]):typeof t=="object"?"":t!=null&&t!=null?_dumbo.prettyJson.call(void 0, t):""))}),n.toString()},P=o=>{process.env.DUMBO_LOG_LEVEL=o},O=o=>{process.env.DUMBO_LOG_STYLE=o},Z=o=>{o!==void 0&&P(o),O(_dumbo.LogStyle.PRETTY)},oo=async o=>{P(_nullishCoalesce(process.env.DUMBO_LOG_LEVEL, () => (o.logging.logLevel))),O(_nullishCoalesce(process.env.DUMBO_LOG_STYLE, () => (o.logging.logStyle))),console.log(_dumbo.color.green("Starting Pongo Shell (version: 0.16.4-alpha.1)")),o.logging.printOptions&&(console.log(_dumbo.color.green("With Options:")),console.log(_dumbo.prettyJson.call(void 0, o)));let e=_nullishCoalesce(_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)), () => ("postgresql://postgres:postgres@localhost:5432/postgres"));(_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)))||console.log(_dumbo.color.yellow("No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'"));let i=await _dumbo.checkConnection.call(void 0, e);i.successful||(i.errorType==="ConnectionRefused"?console.error(_dumbo.color.red("Connection was refused. Check if the PostgreSQL server is running and accessible.")):i.errorType==="Authentication"?console.error(_dumbo.color.red("Authentication failed. Check the username and password in the connection string.")):console.error(_dumbo.color.red("Error connecting to PostgreSQL server")),console.log(_dumbo.color.red("Exiting Pongo Shell...")),process.exit()),console.log(_dumbo.color.green("Successfully connected")),console.log(_dumbo.color.green("Use db.<collection>.<method>() to query."));let n=_repl2.default.start({prompt:_dumbo.color.green("pongo> "),useGlobal:!0,breakEvalOnSigint:!0,writer:X}),t;if(o.schema.collections.length>0){let r={};for(let c of o.schema.collections)r[c]=_chunkPUUNCOTHcjs.C.collection(c);let s=_chunkPUUNCOTHcjs.C.client({database:_chunkPUUNCOTHcjs.C.db(o.schema.database,r)}),g=_chunkPUUNCOTHcjs.H.call(void 0, e,{schema:{definition:s,autoMigration:o.schema.autoMigration}});t=g.database;for(let c of o.schema.collections)n.context[c]=g.database[c];m=g}else m=_chunkPUUNCOTHcjs.H.call(void 0, e,{schema:{autoMigration:o.schema.autoMigration}}),t=m.db(o.schema.database);n.context.pongo=m,n.context.db=t,n.context.SQL=_dumbo.SQL,n.context.setLogLevel=P,n.context.setLogStyle=O,n.context.prettifyLogs=Z,n.context.printResultsAsTable=K,n.context.LogStyle=_dumbo.LogStyle,n.context.LogLevel=_dumbo.LogLevel,n.on("exit",async()=>{await S(),process.exit()}),n.on("SIGINT",async()=>{await S(),process.exit()})},S=async()=>{console.log(_dumbo.color.yellow("Exiting Pongo Shell...")),await m.close()};process.on("uncaughtException",S);process.on("SIGINT",S);var R=new (0, _commander.Command)("shell").description("Start an interactive Pongo shell").option("-cs, --connectionString <string>","Connection string for the database").option("-db, --database <string>","Database name to connect","postgres").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-no-migrations, --disable-auto-migrations","Disable automatic migrations").option("-o, --print-options","Print shell options").option("-ll, --log-level <logLevel>","Log level: DISABLED, INFO, LOG, WARN, ERROR","DISABLED").option("-ls, --log-style","Log style: RAW, PRETTY","RAW").option("-p, --pretty-log","Turn on logging with prettified output").action(async o=>{let{collection:e,database:i}=o,n=o.connectionString;await oo({logging:{printOptions:o.printOptions===!0,logStyle:o.prettyLog?_dumbo.LogStyle.PRETTY:_nullishCoalesce(o.logStyle, () => (_dumbo.LogStyle.RAW)),logLevel:o.logLevel?o.logLevel:o.prettyLog?_dumbo.LogLevel.INFO:_dumbo.LogLevel.DISABLED},schema:{collections:e,database:i,autoMigration:o.disableAutoMigrations?"None":"CreateOrUpdate"},connectionString:n})});var p=new _commander.Command;p.name("pongo").description("CLI tool for Pongo");p.addCommand(v);p.addCommand(d);p.addCommand(R);p.parse(process.argv);var Po=p;exports.default = Po;
449
+ exports.default = cli_default;
28
450
  //# sourceMappingURL=cli.cjs.map
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts"],"names":["formatTypeName","input","formatted","sampleConfig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AA;ACpHA,wFAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","sourcesContent":[null,"#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand, shellCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(shellCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `export type ${formatTypeName(name)} = { name: string; description: string; date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n","import {\n combineMigrations,\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n config?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connection-string <string>',\n 'Connection string for the database',\n )\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connection-string\" parameter or through the DB_CONNECTION_STRING environment variable.' +\n '\\nFor instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres',\n );\n process.exit(1);\n }\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action(async (options: MigrateSqlOptions) => {\n const { collection } = options;\n\n let collectionNames: string[];\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collectionNames.flatMap((collectionName) =>\n pongoCollectionSchemaComponent(collectionName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n"]}
1
+ {"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell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EAAA;AACA,EAAA;AAEM;AAEN,EAAA;AACA,EAAA;AACgB,EAAA;AAEP,IAAA;AACT,EAAA;AACC,EAAA;AAEF;AACC,EAAA;AACA,EAAA;AAEM;AAEN,EAAA;AACA,EAAA;AACA,EAAA;AAEM;AAGE,EAAA;AACF,EAAA;AAEA,EAAA;AACK,IAAA;AACP,MAAA;AACU,MAAA;AAGA,MAAA;AAKZ,IAAA;AACQ,IAAA;AACN,MAAA;AACA,MAAA;AACA,MAAA;AAGF,IAAA;AACA,IAAA;AACD,EAAA;AACF;AJ+Hc;AACA;AClbD;AAEH;AAEL;AACA;AACA;AAEM;AAEP;ADgbU;AACA;AACA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","sourcesContent":[null,"#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand, shellCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(shellCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `export type ${formatTypeName(name)} = { name: string; description: string; date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n","import {\n combineMigrations,\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n config?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connection-string <string>',\n 'Connection string for the database',\n )\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connection-string\" parameter or through the DB_CONNECTION_STRING environment variable.' +\n '\\nFor instance: --connection-string postgresql://postgres:postgres@localhost:5432/postgres',\n );\n process.exit(1);\n }\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action(async (options: MigrateSqlOptions) => {\n const { collection } = options;\n\n let collectionNames: string[];\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collectionNames.flatMap((collectionName) =>\n pongoCollectionSchemaComponent(collectionName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n","import {\n checkConnection,\n color,\n LogLevel,\n LogStyle,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoSchema,\n type PongoClient,\n type PongoCollectionSchema,\n type PongoDb,\n} from '../core';\n\nlet pongo: PongoClient;\n\nconst calculateColumnWidths = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n results: any[],\n columnNames: string[],\n): number[] => {\n const columnWidths = columnNames.map((col) => {\n const maxWidth = Math.max(\n col.length, // Header size\n ...results.map((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] ? String(result[col]).length : 0,\n ),\n );\n return maxWidth + 2; // Add padding\n });\n return columnWidths;\n};\n\nlet shouldDisplayResultsAsTable = false;\n\nconst printResultsAsTable = (print?: boolean) =>\n (shouldDisplayResultsAsTable = print === undefined || print === true);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst printOutput = (obj: any): string =>\n Array.isArray(obj) && shouldDisplayResultsAsTable\n ? displayResultsAsTable(obj)\n : prettyJson(obj);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst displayResultsAsTable = (results: any[]): string => {\n if (results.length === 0) {\n return color.yellow('No documents found.');\n }\n\n const columnNames = results\n\n .flatMap((result) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n typeof result === 'object' ? Object.keys(result) : typeof result,\n )\n .filter((value, index, array) => array.indexOf(value) === index);\n\n const columnWidths = calculateColumnWidths(results, columnNames);\n\n const table = new Table({\n head: columnNames.map((col) => color.cyan(col)),\n colWidths: columnWidths,\n });\n\n results.forEach((result) => {\n table.push(\n columnNames.map((col) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n result[col] !== undefined\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n Array.isArray(result[col])\n ? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n displayResultsAsTable(result[col])\n : // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n prettyJson(result[col])\n : typeof result === 'object'\n ? ''\n : result != undefined && result != undefined\n ? prettyJson(result)\n : '',\n ),\n );\n });\n\n return table.toString();\n};\n\nconst setLogLevel = (logLevel: string) => {\n process.env.DUMBO_LOG_LEVEL = logLevel;\n};\n\nconst setLogStyle = (logLevel: string) => {\n process.env.DUMBO_LOG_STYLE = logLevel;\n};\n\nconst prettifyLogs = (logLevel?: string) => {\n if (logLevel !== undefined) setLogLevel(logLevel);\n setLogStyle(LogStyle.PRETTY);\n};\n\nconst startRepl = async (options: {\n logging: {\n printOptions: boolean;\n logLevel: LogLevel;\n logStyle: LogStyle;\n };\n schema: {\n database: string;\n collections: string[];\n autoMigration: MigrationStyle;\n };\n connectionString: string | undefined;\n}) => {\n // TODO: This will change when we have proper tracing and logging config\n // For now, that's enough\n setLogLevel(process.env.DUMBO_LOG_LEVEL ?? options.logging.logLevel);\n setLogStyle(process.env.DUMBO_LOG_STYLE ?? options.logging.logStyle);\n\n console.log(color.green('Starting Pongo Shell (version: 0.16.4)'));\n\n if (options.logging.printOptions) {\n console.log(color.green('With Options:'));\n console.log(prettyJson(options));\n }\n\n const connectionString =\n options.connectionString ??\n process.env.DB_CONNECTION_STRING ??\n 'postgresql://postgres:postgres@localhost:5432/postgres';\n\n if (!(options.connectionString ?? process.env.DB_CONNECTION_STRING)) {\n console.log(\n color.yellow(\n `No connection string provided, using: 'postgresql://postgres:postgres@localhost:5432/postgres'`,\n ),\n );\n }\n\n const connectionCheck = await checkConnection(connectionString);\n\n if (!connectionCheck.successful) {\n if (connectionCheck.errorType === 'ConnectionRefused') {\n console.error(\n color.red(\n `Connection was refused. Check if the PostgreSQL server is running and accessible.`,\n ),\n );\n } else if (connectionCheck.errorType === 'Authentication') {\n console.error(\n color.red(\n `Authentication failed. Check the username and password in the connection string.`,\n ),\n );\n } else {\n console.error(color.red('Error connecting to PostgreSQL server'));\n }\n console.log(color.red('Exiting Pongo Shell...'));\n process.exit();\n }\n\n console.log(color.green(`Successfully connected`));\n console.log(color.green('Use db.<collection>.<method>() to query.'));\n\n const shell = repl.start({\n prompt: color.green('pongo> '),\n useGlobal: true,\n breakEvalOnSigint: true,\n writer: printOutput,\n });\n\n let db: PongoDb;\n\n if (options.schema.collections.length > 0) {\n const collectionsSchema: Record<string, PongoCollectionSchema> = {};\n\n for (const collectionName of options.schema.collections) {\n collectionsSchema[collectionName] =\n pongoSchema.collection(collectionName);\n }\n\n const schema = pongoSchema.client({\n database: pongoSchema.db(options.schema.database, collectionsSchema),\n });\n\n const typedClient = pongoClient(connectionString, {\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n });\n\n db = typedClient.database;\n\n for (const collectionName of options.schema.collections) {\n shell.context[collectionName] = typedClient.database[collectionName];\n }\n\n pongo = typedClient;\n } else {\n pongo = pongoClient(connectionString, {\n schema: { autoMigration: options.schema.autoMigration },\n });\n\n db = pongo.db(options.schema.database);\n }\n\n shell.context.pongo = pongo;\n shell.context.db = db;\n\n // helpers\n shell.context.SQL = SQL;\n shell.context.setLogLevel = setLogLevel;\n shell.context.setLogStyle = setLogStyle;\n shell.context.prettifyLogs = prettifyLogs;\n shell.context.printResultsAsTable = printResultsAsTable;\n shell.context.LogStyle = LogStyle;\n shell.context.LogLevel = LogLevel;\n\n // Intercept REPL output to display results as a table if they are arrays\n shell.on('exit', async () => {\n await teardown();\n process.exit();\n });\n\n shell.on('SIGINT', async () => {\n await teardown();\n process.exit();\n });\n};\n\nconst teardown = async () => {\n console.log(color.yellow('Exiting Pongo Shell...'));\n await pongo.close();\n};\n\nprocess.on('uncaughtException', teardown);\nprocess.on('SIGINT', teardown);\n\ninterface ShellOptions {\n database: string;\n collection: string[];\n connectionString?: string;\n disableAutoMigrations: boolean;\n logStyle?: string;\n logLevel?: string;\n prettyLog?: boolean;\n printOptions?: boolean;\n}\n\nconst shellCommand = new Command('shell')\n .description('Start an interactive Pongo shell')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option('-db, --database <string>', 'Database name to connect', 'postgres')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-no-migrations, --disable-auto-migrations',\n 'Disable automatic migrations',\n )\n .option('-o, --print-options', 'Print shell options')\n .option(\n '-ll, --log-level <logLevel>',\n 'Log level: DISABLED, INFO, LOG, WARN, ERROR',\n 'DISABLED',\n )\n .option('-ls, --log-style', 'Log style: RAW, PRETTY', 'RAW')\n .option('-p, --pretty-log', 'Turn on logging with prettified output')\n .action(async (options: ShellOptions) => {\n const { collection, database } = options;\n const connectionString = options.connectionString;\n\n await startRepl({\n logging: {\n printOptions: options.printOptions === true,\n logStyle: options.prettyLog\n ? LogStyle.PRETTY\n : ((options.logStyle as LogStyle | undefined) ?? LogStyle.RAW),\n logLevel: options.logLevel\n ? (options.logLevel as LogLevel)\n : options.prettyLog\n ? LogLevel.INFO\n : LogLevel.DISABLED,\n },\n schema: {\n collections: collection,\n database,\n autoMigration: options.disableAutoMigrations\n ? 'None'\n : 'CreateOrUpdate',\n },\n connectionString,\n });\n });\n\nexport { shellCommand };\n"]}