@event-driven-io/pongo 0.17.0-beta.37 → 0.17.0-beta.39

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.
Files changed (43) hide show
  1. package/dist/cli.cjs +2 -2
  2. package/dist/cli.cjs.map +1 -1
  3. package/dist/cli.js +2 -2
  4. package/dist/cli.js.map +1 -1
  5. package/dist/cloudflare.cjs +2 -2
  6. package/dist/cloudflare.d.cts +2 -2
  7. package/dist/cloudflare.d.ts +2 -2
  8. package/dist/cloudflare.js +2 -2
  9. package/dist/{core-DwoTLYbR.cjs → core-BYk4wCpe.cjs} +4 -4
  10. package/dist/{core-DwoTLYbR.cjs.map → core-BYk4wCpe.cjs.map} +1 -1
  11. package/dist/{core-CwxxuUAn.cjs → core-BdTIuXiI.cjs} +60 -47
  12. package/dist/core-BdTIuXiI.cjs.map +1 -0
  13. package/dist/{core-D_iZiiYe.js → core-Dtn-d-91.js} +60 -47
  14. package/dist/core-Dtn-d-91.js.map +1 -0
  15. package/dist/{core-fsJmsQDa.js → core-wHw_lMM5.js} +4 -4
  16. package/dist/{core-fsJmsQDa.js.map → core-wHw_lMM5.js.map} +1 -1
  17. package/dist/{index-DMq6F3x9.d.ts → index-BfOn92K5.d.cts} +6 -6
  18. package/dist/{index-qeC-p0Tq.d.cts → index-CL0zRxRl.d.ts} +6 -6
  19. package/dist/{index-Du_IHXAj.d.ts → index-Cxo6j266.d.ts} +2 -2
  20. package/dist/{index-ZKOB86ub.d.cts → index-DyNmc6tD.d.cts} +2 -2
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.d.cts +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/pg.cjs +3 -3
  26. package/dist/pg.cjs.map +1 -1
  27. package/dist/pg.d.cts +1 -1
  28. package/dist/pg.d.ts +1 -1
  29. package/dist/pg.js +3 -3
  30. package/dist/pg.js.map +1 -1
  31. package/dist/shim.cjs +1 -1
  32. package/dist/shim.cjs.map +1 -1
  33. package/dist/shim.d.cts +1 -1
  34. package/dist/shim.d.ts +1 -1
  35. package/dist/shim.js +1 -1
  36. package/dist/shim.js.map +1 -1
  37. package/dist/sqlite3.cjs +2 -2
  38. package/dist/sqlite3.d.cts +2 -2
  39. package/dist/sqlite3.d.ts +2 -2
  40. package/dist/sqlite3.js +2 -2
  41. package/package.json +2 -2
  42. package/dist/core-CwxxuUAn.cjs.map +0 -1
  43. package/dist/core-D_iZiiYe.js.map +0 -1
package/dist/cli.cjs CHANGED
@@ -27,7 +27,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
27
  }) : target, mod));
28
28
 
29
29
  //#endregion
30
- const require_core = require('./core-CwxxuUAn.cjs');
30
+ const require_core = require('./core-BdTIuXiI.cjs');
31
31
  let _event_driven_io_dumbo = require("@event-driven-io/dumbo");
32
32
  let commander = require("commander");
33
33
  let node_fs = require("node:fs");
@@ -228,7 +228,7 @@ const prettifyLogs = (logLevel) => {
228
228
  const startRepl = async (options) => {
229
229
  setLogLevel(process.env.DUMBO_LOG_LEVEL ?? options.logging.logLevel);
230
230
  setLogStyle(process.env.DUMBO_LOG_STYLE ?? options.logging.logStyle);
231
- console.log(_event_driven_io_dumbo.color.green("Starting Pongo Shell (version: 0.17.0-beta.37)"));
231
+ console.log(_event_driven_io_dumbo.color.green("Starting Pongo Shell (version: 0.17.0-beta.39)"));
232
232
  if (options.logging.printOptions) {
233
233
  console.log(_event_driven_io_dumbo.color.green("With Options:"));
234
234
  console.log((0, _event_driven_io_dumbo.prettyJson)(options));
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.cjs","names":["objectEntries","toDbSchemaMetadata","Command","Command","pongoDriverRegistry","pongoSchema","JSONSerializer","color","Table","LogStyle","pongoDriverRegistry","repl","pongoSchema","pongoClient","SQL","LogLevel","Command","Command"],"sources":["../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts","../src/cli.ts"],"sourcesContent":["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 JSONSerializer,\n parseConnectionString,\n runSQLMigrations,\n type DatabaseDriverType,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport {\n pongoDriverRegistry,\n pongoSchema,\n type AnyPongoDriverOptions,\n type PongoCollectionSchema,\n type PongoDatabaseFactoryOptions,\n type PongoDocument,\n} from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n databaseType?: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: string;\n dryRun?: boolean;\n timeoutMs?: number;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n databaseType: string;\n databaseName?: string | undefined;\n databaseDriver: 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 '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n undefined,\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\n )\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 .option(\n '--t, --timeout <ms>',\n 'Set the migration timeout in milliseconds',\n parseInt,\n )\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun, databaseName, databaseDriver, timeoutMs } =\n options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n\n const databaseType =\n options.databaseType ??\n parseConnectionString(connectionString).databaseType;\n\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n });\n\n const pool = dumbo({ connectionString, driverType });\n\n await runSQLMigrations(pool, migrations, {\n dryRun,\n migrationTimeoutMs: timeoutMs,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\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('--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, databaseName, databaseType, databaseDriver } = 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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString: undefined,\n databaseName,\n collectionNames,\n });\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n\nconst getMigrations = ({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n}: {\n driverType: DatabaseDriverType;\n connectionString: string | undefined;\n databaseName: string | undefined;\n collectionNames: string[];\n}) => {\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is registered and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const dbDefinition = pongoSchema.db.from(databaseName, collectionNames);\n\n const driverOptions: PongoDatabaseFactoryOptions<\n Record<string, PongoCollectionSchema<PongoDocument>>,\n AnyPongoDriverOptions\n > = {\n schema: { definition: dbDefinition },\n serializer: JSONSerializer,\n };\n\n const customOptions = {\n connectionString,\n databaseName,\n };\n\n const db = driver.databaseFactory({ ...driverOptions, ...customOptions });\n\n return db.schema.component.migrations;\n};\n","import {\n color,\n LogLevel,\n LogStyle,\n parseConnectionString,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport { checkConnection } from '@event-driven-io/dumbo/pg';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoDriverRegistry,\n pongoSchema,\n type PongoClient,\n type PongoClientOptions,\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 databaseDriver: string;\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.17.0-beta.37)'));\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 { databaseType } = parseConnectionString(connectionString);\n const driverType = `${databaseType}:${options.databaseDriver}` as const;\n\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is installed and the connection string is correct.`,\n );\n process.exit(1);\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 driverOptions: PongoClientOptions = {\n driver,\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n const typedClient = pongoClient({\n ...driverOptions,\n ...customOptions,\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 const driverOptions: PongoClientOptions = {\n driver,\n schema: {\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n pongo = pongoClient({\n ...driverOptions,\n ...customOptions,\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 databaseDriver: 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 '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n 'pg',\n )\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 databaseDriver: options.databaseDriver,\n });\n });\n\nexport { shellCommand };\n","#!/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"],"mappings":";;;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E,OAAO,OAAO,YAA0B;CACvC,MAAM,EAAE,YAAY,aAAa;CACjC,MAAM,mBAAmB,QAAQ;AAEjC,OAAM,UAAU;EACd,SAAS;GACP,cAAc,QAAQ,iBAAiB;GACvC,UAAU,QAAQ,YACdP,gCAAS,SACP,QAAQ,YAAqCA,gCAAS;GAC5D,UAAU,QAAQ,WACb,QAAQ,WACT,QAAQ,YACNM,gCAAS,OACTA,gCAAS;GAChB;EACD,QAAQ;GACN,aAAa;GACb;GACA,eAAe,QAAQ,wBACnB,SACA;GACL;EACD;EACA,gBAAgB,QAAQ;EACzB,CAAC;EACF;;;;ACjWJ,MAAM,UAAU,IAAIE,mBAAS;AAE7B,QAAQ,KAAK,QAAQ,CAAC,YAAY,qBAAqB;AAEvD,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,aAAa;AAEhC,QAAQ,MAAM,QAAQ,KAAK"}
1
+ {"version":3,"file":"cli.cjs","names":["objectEntries","toDbSchemaMetadata","Command","Command","pongoDriverRegistry","pongoSchema","JSONSerializer","color","Table","LogStyle","pongoDriverRegistry","repl","pongoSchema","pongoClient","SQL","LogLevel","Command","Command"],"sources":["../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts","../src/cli.ts"],"sourcesContent":["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 JSONSerializer,\n parseConnectionString,\n runSQLMigrations,\n type DatabaseDriverType,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport {\n pongoDriverRegistry,\n pongoSchema,\n type AnyPongoDriverOptions,\n type PongoCollectionSchema,\n type PongoDatabaseFactoryOptions,\n type PongoDocument,\n} from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n databaseType?: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: string;\n dryRun?: boolean;\n timeoutMs?: number;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n databaseType: string;\n databaseName?: string | undefined;\n databaseDriver: 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 '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n undefined,\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\n )\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 .option(\n '--t, --timeout <ms>',\n 'Set the migration timeout in milliseconds',\n parseInt,\n )\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun, databaseName, databaseDriver, timeoutMs } =\n options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n\n const databaseType =\n options.databaseType ??\n parseConnectionString(connectionString).databaseType;\n\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n });\n\n const pool = dumbo({ connectionString, driverType });\n\n await runSQLMigrations(pool, migrations, {\n dryRun,\n migrationTimeoutMs: timeoutMs,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\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('--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, databaseName, databaseType, databaseDriver } = 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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString: undefined,\n databaseName,\n collectionNames,\n });\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n\nconst getMigrations = ({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n}: {\n driverType: DatabaseDriverType;\n connectionString: string | undefined;\n databaseName: string | undefined;\n collectionNames: string[];\n}) => {\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is registered and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const dbDefinition = pongoSchema.db.from(databaseName, collectionNames);\n\n const driverOptions: PongoDatabaseFactoryOptions<\n Record<string, PongoCollectionSchema<PongoDocument>>,\n AnyPongoDriverOptions\n > = {\n schema: { definition: dbDefinition },\n serializer: JSONSerializer,\n };\n\n const customOptions = {\n connectionString,\n databaseName,\n };\n\n const db = driver.databaseFactory({ ...driverOptions, ...customOptions });\n\n return db.schema.component.migrations;\n};\n","import {\n color,\n LogLevel,\n LogStyle,\n parseConnectionString,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport { checkConnection } from '@event-driven-io/dumbo/pg';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoDriverRegistry,\n pongoSchema,\n type PongoClient,\n type PongoClientOptions,\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 databaseDriver: string;\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.17.0-beta.39)'));\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 { databaseType } = parseConnectionString(connectionString);\n const driverType = `${databaseType}:${options.databaseDriver}` as const;\n\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is installed and the connection string is correct.`,\n );\n process.exit(1);\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 driverOptions: PongoClientOptions = {\n driver,\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n const typedClient = pongoClient({\n ...driverOptions,\n ...customOptions,\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 const driverOptions: PongoClientOptions = {\n driver,\n schema: {\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n pongo = pongoClient({\n ...driverOptions,\n ...customOptions,\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 databaseDriver: 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 '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n 'pg',\n )\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 databaseDriver: options.databaseDriver,\n });\n });\n\nexport { shellCommand };\n","#!/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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAM,kBAAkB,UAA0B;AAChD,KAAI,MAAM,WAAW,EACnB,QAAO;CAGT,IAAI,YAAY,MAAM,OAAO,EAAE,CAAC,aAAa,GAAG,MAAM,MAAM,EAAE;AAE9D,KAAI,UAAU,SAAS,IAAI,CACzB,aAAY,UAAU,MAAM,GAAG,GAAG;AAGpC,QAAO;;AAGT,MAAM,gBAAgB,kBAA4B,CAAC,QAAQ,KAAK;AAe9D,QAAO;;EAdO,gBACX,KACE,SACC,eAAe,eAAe,KAAK,CAAC,sDACvC,CACA,KAAK,KAWH,CAAC;;;;;EATc,gBACjB,KACE,SACC,SAAS,KAAK,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,CAAC,YAAY,qBAAqB;AAEvD,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,aAAa;AAEhC,QAAQ,MAAM,QAAQ,KAAK"}
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { A as objectEntries, _ as toDbSchemaMetadata, o as pongoClient, p as pongoSchema, u as pongoDriverRegistry } from "./core-D_iZiiYe.js";
2
+ import { A as objectEntries, _ as toDbSchemaMetadata, o as pongoClient, p as pongoSchema, u as pongoDriverRegistry } from "./core-Dtn-d-91.js";
3
3
  import { JSONSerializer, LogLevel, LogStyle, SQL, color, combineMigrations, dumbo, parseConnectionString, prettyJson, runSQLMigrations } from "@event-driven-io/dumbo";
4
4
  import { Command } from "commander";
5
5
  import fs from "node:fs";
@@ -197,7 +197,7 @@ const prettifyLogs = (logLevel) => {
197
197
  const startRepl = async (options) => {
198
198
  setLogLevel(process.env.DUMBO_LOG_LEVEL ?? options.logging.logLevel);
199
199
  setLogStyle(process.env.DUMBO_LOG_STYLE ?? options.logging.logStyle);
200
- console.log(color.green("Starting Pongo Shell (version: 0.17.0-beta.37)"));
200
+ console.log(color.green("Starting Pongo Shell (version: 0.17.0-beta.39)"));
201
201
  if (options.logging.printOptions) {
202
202
  console.log(color.green("With Options:"));
203
203
  console.log(prettyJson(options));
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts","../src/cli.ts"],"sourcesContent":["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 JSONSerializer,\n parseConnectionString,\n runSQLMigrations,\n type DatabaseDriverType,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport {\n pongoDriverRegistry,\n pongoSchema,\n type AnyPongoDriverOptions,\n type PongoCollectionSchema,\n type PongoDatabaseFactoryOptions,\n type PongoDocument,\n} from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n databaseType?: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: string;\n dryRun?: boolean;\n timeoutMs?: number;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n databaseType: string;\n databaseName?: string | undefined;\n databaseDriver: 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 '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n undefined,\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\n )\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 .option(\n '--t, --timeout <ms>',\n 'Set the migration timeout in milliseconds',\n parseInt,\n )\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun, databaseName, databaseDriver, timeoutMs } =\n options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n\n const databaseType =\n options.databaseType ??\n parseConnectionString(connectionString).databaseType;\n\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n });\n\n const pool = dumbo({ connectionString, driverType });\n\n await runSQLMigrations(pool, migrations, {\n dryRun,\n migrationTimeoutMs: timeoutMs,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\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('--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, databaseName, databaseType, databaseDriver } = 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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString: undefined,\n databaseName,\n collectionNames,\n });\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n\nconst getMigrations = ({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n}: {\n driverType: DatabaseDriverType;\n connectionString: string | undefined;\n databaseName: string | undefined;\n collectionNames: string[];\n}) => {\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is registered and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const dbDefinition = pongoSchema.db.from(databaseName, collectionNames);\n\n const driverOptions: PongoDatabaseFactoryOptions<\n Record<string, PongoCollectionSchema<PongoDocument>>,\n AnyPongoDriverOptions\n > = {\n schema: { definition: dbDefinition },\n serializer: JSONSerializer,\n };\n\n const customOptions = {\n connectionString,\n databaseName,\n };\n\n const db = driver.databaseFactory({ ...driverOptions, ...customOptions });\n\n return db.schema.component.migrations;\n};\n","import {\n color,\n LogLevel,\n LogStyle,\n parseConnectionString,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport { checkConnection } from '@event-driven-io/dumbo/pg';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoDriverRegistry,\n pongoSchema,\n type PongoClient,\n type PongoClientOptions,\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 databaseDriver: string;\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.17.0-beta.37)'));\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 { databaseType } = parseConnectionString(connectionString);\n const driverType = `${databaseType}:${options.databaseDriver}` as const;\n\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is installed and the connection string is correct.`,\n );\n process.exit(1);\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 driverOptions: PongoClientOptions = {\n driver,\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n const typedClient = pongoClient({\n ...driverOptions,\n ...customOptions,\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 const driverOptions: PongoClientOptions = {\n driver,\n schema: {\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n pongo = pongoClient({\n ...driverOptions,\n ...customOptions,\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 databaseDriver: 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 '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n 'pg',\n )\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 databaseDriver: options.databaseDriver,\n });\n });\n\nexport { shellCommand };\n","#!/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"],"mappings":";;;;;;;;;;AASA,MAAM,kBAAkB,UAA0B;AAChD,KAAI,MAAM,WAAW,EACnB,QAAO;CAGT,IAAI,YAAY,MAAM,OAAO,EAAE,CAAC,aAAa,GAAG,MAAM,MAAM,EAAE;AAE9D,KAAI,UAAU,SAAS,IAAI,CACzB,aAAY,UAAU,MAAM,GAAG,GAAG;AAGpC,QAAO;;AAGT,MAAM,gBAAgB,kBAA4B,CAAC,QA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,wBACnB,SACA;GACL;EACD;EACA,gBAAgB,QAAQ;EACzB,CAAC;EACF;;;;ACjWJ,MAAM,UAAU,IAAI,SAAS;AAE7B,QAAQ,KAAK,QAAQ,CAAC,YAAY,qBAAqB;AAEvD,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,aAAa;AAEhC,QAAQ,MAAM,QAAQ,KAAK"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/commandLine/configFile.ts","../src/commandLine/migrate.ts","../src/commandLine/shell.ts","../src/cli.ts"],"sourcesContent":["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 JSONSerializer,\n parseConnectionString,\n runSQLMigrations,\n type DatabaseDriverType,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport {\n pongoDriverRegistry,\n pongoSchema,\n type AnyPongoDriverOptions,\n type PongoCollectionSchema,\n type PongoDatabaseFactoryOptions,\n type PongoDocument,\n} from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n databaseType?: string;\n databaseName?: string | undefined;\n databaseDriver: string;\n config?: string;\n dryRun?: boolean;\n timeoutMs?: number;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n databaseType: string;\n databaseName?: string | undefined;\n databaseDriver: 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 '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n undefined,\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\n )\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 .option(\n '--t, --timeout <ms>',\n 'Set the migration timeout in milliseconds',\n parseInt,\n )\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun, databaseName, databaseDriver, timeoutMs } =\n options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n\n const databaseType =\n options.databaseType ??\n parseConnectionString(connectionString).databaseType;\n\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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n });\n\n const pool = dumbo({ connectionString, driverType });\n\n await runSQLMigrations(pool, migrations, {\n dryRun,\n migrationTimeoutMs: timeoutMs,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '--dbt, --database-type <string>',\n 'Database type that should be used for connection (e.g., PostgreSQL or SQLite)',\n )\n .option(\n '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n )\n .option(\n '--dbn, --database-name <string>',\n 'Database name to connect to',\n undefined,\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('--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, databaseName, databaseType, databaseDriver } = 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 driverType = `${databaseType}:${databaseDriver}` as const;\n\n const migrations = getMigrations({\n driverType,\n connectionString: undefined,\n databaseName,\n collectionNames,\n });\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n\nconst getMigrations = ({\n driverType,\n connectionString,\n databaseName,\n collectionNames,\n}: {\n driverType: DatabaseDriverType;\n connectionString: string | undefined;\n databaseName: string | undefined;\n collectionNames: string[];\n}) => {\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is registered and the connection string is correct.`,\n );\n process.exit(1);\n }\n\n const dbDefinition = pongoSchema.db.from(databaseName, collectionNames);\n\n const driverOptions: PongoDatabaseFactoryOptions<\n Record<string, PongoCollectionSchema<PongoDocument>>,\n AnyPongoDriverOptions\n > = {\n schema: { definition: dbDefinition },\n serializer: JSONSerializer,\n };\n\n const customOptions = {\n connectionString,\n databaseName,\n };\n\n const db = driver.databaseFactory({ ...driverOptions, ...customOptions });\n\n return db.schema.component.migrations;\n};\n","import {\n color,\n LogLevel,\n LogStyle,\n parseConnectionString,\n prettyJson,\n SQL,\n type MigrationStyle,\n} from '@event-driven-io/dumbo';\nimport { checkConnection } from '@event-driven-io/dumbo/pg';\nimport Table from 'cli-table3';\nimport { Command } from 'commander';\nimport repl from 'node:repl';\nimport {\n pongoClient,\n pongoDriverRegistry,\n pongoSchema,\n type PongoClient,\n type PongoClientOptions,\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 databaseDriver: string;\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.17.0-beta.39)'));\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 { databaseType } = parseConnectionString(connectionString);\n const driverType = `${databaseType}:${options.databaseDriver}` as const;\n\n const driver = pongoDriverRegistry.tryGet(driverType);\n\n if (driver === null) {\n console.error(\n `Error: No database driver found for driver type \"${driverType}\". Make sure the driver is installed and the connection string is correct.`,\n );\n process.exit(1);\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 driverOptions: PongoClientOptions = {\n driver,\n schema: {\n definition: schema,\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n const typedClient = pongoClient({\n ...driverOptions,\n ...customOptions,\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 const driverOptions: PongoClientOptions = {\n driver,\n schema: {\n autoMigration: options.schema.autoMigration,\n },\n };\n\n // TODO: Find a better way to pass custom driver settings\n const customOptions = {\n connectionString,\n };\n\n pongo = pongoClient({\n ...driverOptions,\n ...customOptions,\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 databaseDriver: 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 '--drv, --database-driver <string>',\n 'Database driver that should be used for connection (e.g., \"pg\" for PostgreSQL, \"sqlite3\" for SQLite)',\n 'pg',\n )\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 databaseDriver: options.databaseDriver,\n });\n });\n\nexport { shellCommand };\n","#!/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"],"mappings":";;;;;;;;;;AASA,MAAM,kBAAkB,UAA0B;AAChD,KAAI,MAAM,WAAW,EACnB,QAAO;CAGT,IAAI,YAAY,MAAM,OAAO,EAAE,CAAC,aAAa,GAAG,MAAM,MAAM,EAAE;AAE9D,KAAI,UAAU,SAAS,IAAI,CACzB,aAAY,UAAU,MAAM,GAAG,GAAG;AAGpC,QAAO;;AAGT,MAAM,gBAAgB,kBAA4B,CAAC,QAAQ,KAAK;AAe9D,QAAO;;EAdO,gBACX,KACE,SACC,eAAe,eAAe,KAAK,CAAC,sDACvC,CACA,KAAK,KAWH,CAAC;;;;;EATc,gBACjB,KACE,SACC,SAAS,KAAK,2BAA2B,eAAe,KAAK,CAAC,KAAK,KAAK,KAC3E,CACA,KAAK,KASG,CAAC;;;;;AAMd,MAAM,uBAAuB,wDAAwD,cAAc;AACnG,MAAM,gBAAgB,yDAAyD,cAAc;AAC7F,MAAM,aAAa,yEAAyE,cAAc;AAC1G,MAAM,mBAAmB,iHAAiH,cAAc;AACxJ,MAAM,qBAAqB,wEAAwE,cAAc;AAEjH,MAAa,iBAAiB,OAC5B,eACmC;CACnC,MAAM,YAAY,IAAI,IAAI,YAAY,UAAU,QAAQ,KAAK,CAAC,GAAG;AACjE,KAAI;EAMF,MAAM,SAAS,qBAAqB,MAJ4B,OAC9D,UAAU,MAGiC;AAE7C,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAQ,MAAM,OAAO;AACrB,WA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D,CACA,OACC,qCACA,qCACD,CACA,OAAO,6BAA6B,4BAA4B,WAAW,CAC3E,OACC,8BACA,gCACC,OAAe,aAAuB;AAErC,QAAO,SAAS,OAAO,CAAC,MAAM,CAAC;GAEjC,EAAE,CACH,CACA,OACC,8CACA,+BACD,CACA,OAAO,uBAAuB,sBAAsB,CACpD,OACC,gCACA,+CACA,WACD,CACA,OAAO,qBAAqB,0BAA0B,MAAM,CAC5D,OAAO,oBAAoB,yCAAyC,CACpE,OAAO,OAAO,YAA0B;CACvC,MAAM,EAAE,YAAY,aAAa;CACjC,MAAM,mBAAmB,QAAQ;AAEjC,OAAM,UAAU;EACd,SAAS;GACP,cAAc,QAAQ,iBAAiB;GACvC,UAAU,QAAQ,YACd,SAAS,SACP,QAAQ,YAAqC,SAAS;GAC5D,UAAU,QAAQ,WACb,QAAQ,WACT,QAAQ,YACN,SAAS,OACT,SAAS;GAChB;EACD,QAAQ;GACN,aAAa;GACb;GACA,eAAe,QAAQ,wBACnB,SACA;GACL;EACD;EACA,gBAAgB,QAAQ;EACzB,CAAC;EACF;;;;ACjWJ,MAAM,UAAU,IAAI,SAAS;AAE7B,QAAQ,KAAK,QAAQ,CAAC,YAAY,qBAAqB;AAEvD,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,aAAa;AAEhC,QAAQ,MAAM,QAAQ,KAAK"}
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_core = require('./core-CwxxuUAn.cjs');
2
+ const require_core = require('./core-BdTIuXiI.cjs');
3
3
  const require_cli = require('./cli.cjs');
4
- const require_core$1 = require('./core-DwoTLYbR.cjs');
4
+ const require_core$1 = require('./core-BYk4wCpe.cjs');
5
5
  let _event_driven_io_dumbo = require("@event-driven-io/dumbo");
6
6
  let _event_driven_io_dumbo_cloudflare = require("@event-driven-io/dumbo/cloudflare");
7
7
 
@@ -1,5 +1,5 @@
1
- import { gt as PongoDb, nn as PongoDriverOptions, tn as PongoDriver } from "./index-qeC-p0Tq.cjs";
2
- import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./index-ZKOB86ub.cjs";
1
+ import { gt as PongoDb, nn as PongoDriverOptions, tn as PongoDriver } from "./index-BfOn92K5.cjs";
2
+ import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./index-DyNmc6tD.cjs";
3
3
  import { D1DriverType, D1PoolOptions } from "@event-driven-io/dumbo/cloudflare";
4
4
 
5
5
  //#region src/storage/sqlite/d1/index.d.ts
@@ -1,5 +1,5 @@
1
- import { gt as PongoDb, nn as PongoDriverOptions, tn as PongoDriver } from "./index-DMq6F3x9.js";
2
- import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./index-Du_IHXAj.js";
1
+ import { gt as PongoDb, nn as PongoDriverOptions, tn as PongoDriver } from "./index-CL0zRxRl.js";
2
+ import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./index-Cxo6j266.js";
3
3
  import { D1DriverType, D1PoolOptions } from "@event-driven-io/dumbo/cloudflare";
4
4
 
5
5
  //#region src/storage/sqlite/d1/index.d.ts
@@ -1,5 +1,5 @@
1
- import { I as PongoCollectionSchemaComponent, d as PongoDatabase, f as PongoDatabaseSchemaComponent, p as pongoSchema, u as pongoDriverRegistry } from "./core-D_iZiiYe.js";
2
- import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./core-fsJmsQDa.js";
1
+ import { I as PongoCollectionSchemaComponent, d as PongoDatabase, f as PongoDatabaseSchemaComponent, p as pongoSchema, u as pongoDriverRegistry } from "./core-Dtn-d-91.js";
2
+ import { n as sqliteSQLBuilder, t as pongoCollectionSQLiteMigrations } from "./core-wHw_lMM5.js";
3
3
  import { JSONSerializer } from "@event-driven-io/dumbo";
4
4
  import { D1DriverType, d1Pool } from "@event-driven-io/dumbo/cloudflare";
5
5
 
@@ -1,4 +1,4 @@
1
- const require_core = require('./core-CwxxuUAn.cjs');
1
+ const require_core = require('./core-BdTIuXiI.cjs');
2
2
  const require_cli = require('./cli.cjs');
3
3
  let _event_driven_io_dumbo = require("@event-driven-io/dumbo");
4
4
 
@@ -276,12 +276,12 @@ const sqliteSQLBuilder = (collectionName, serializer) => ({
276
276
  },
277
277
  findOne: (filter) => {
278
278
  const filterQuery = (0, _event_driven_io_dumbo.isSQL)(filter) ? filter : constructFilterQuery(filter, serializer);
279
- return _event_driven_io_dumbo.SQL`SELECT data, _version FROM ${_event_driven_io_dumbo.SQL.identifier(collectionName)} ${where(filterQuery)} LIMIT 1;`;
279
+ return _event_driven_io_dumbo.SQL`SELECT data, _id, _version FROM ${_event_driven_io_dumbo.SQL.identifier(collectionName)} ${where(filterQuery)} LIMIT 1;`;
280
280
  },
281
281
  find: (filter, options) => {
282
282
  const filterQuery = (0, _event_driven_io_dumbo.isSQL)(filter) ? filter : constructFilterQuery(filter, serializer);
283
283
  const query = [];
284
- query.push(_event_driven_io_dumbo.SQL`SELECT data, _version FROM ${_event_driven_io_dumbo.SQL.identifier(collectionName)}`);
284
+ query.push(_event_driven_io_dumbo.SQL`SELECT data, _id, _version FROM ${_event_driven_io_dumbo.SQL.identifier(collectionName)}`);
285
285
  query.push(where(filterQuery));
286
286
  if (options?.sort && Object.keys(options.sort).length > 0) {
287
287
  const clauses = Object.entries(options.sort).map(([field, dir]) => {
@@ -316,4 +316,4 @@ Object.defineProperty(exports, 'sqliteSQLBuilder', {
316
316
  return sqliteSQLBuilder;
317
317
  }
318
318
  });
319
- //# sourceMappingURL=core-DwoTLYbR.cjs.map
319
+ //# sourceMappingURL=core-BYk4wCpe.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"core-DwoTLYbR.cjs","names":["SQL","OperatorMap","objectEntries","SQL","hasOperators","objectEntries","QueryOperators","objectEntries","SQL","SQL","expectedVersionValue"],"sources":["../src/storage/sqlite/core/sqlBuilder/filter/queryOperators.ts","../src/storage/sqlite/core/sqlBuilder/filter/index.ts","../src/storage/sqlite/core/sqlBuilder/update/index.ts","../src/storage/sqlite/core/sqlBuilder/index.ts"],"sourcesContent":["import type { JSONSerializer } from '@event-driven-io/dumbo';\nimport { SQL } from '@event-driven-io/dumbo';\nimport { objectEntries, OperatorMap } from '../../../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n serializer: JSONSerializer,\n): SQL => {\n if (path === '_id' || path === '_version') {\n return handleMetadataOperator(path, operator, value);\n }\n\n switch (operator) {\n case '$eq': {\n const jsonPath = buildJsonPath(path);\n\n return SQL`(\n json_extract(data, '${SQL.plain(jsonPath)}') = ${value}\n OR (\n json_type(data, '${SQL.plain(jsonPath)}') = 'array'\n AND EXISTS(\n SELECT 1 FROM json_each(data, '${SQL.plain(jsonPath)}')\n WHERE json_each.value = ${value}\n )\n )\n )`;\n }\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne': {\n const jsonPath = buildJsonPath(path);\n\n return SQL`json_extract(data, '${SQL.plain(jsonPath)}') ${SQL.plain(OperatorMap[operator])} ${value}`;\n }\n case '$in': {\n const jsonPath = buildJsonPath(path);\n const values = value as unknown[];\n const inClause = SQL.merge(\n values.map((v) => SQL`${v}`),\n ', ',\n );\n\n return SQL`json_extract(data, '${SQL.plain(jsonPath)}') IN (${inClause})`;\n }\n case '$nin': {\n const jsonPath = buildJsonPath(path);\n const values = value as unknown[];\n const inClause = SQL.merge(\n values.map((v) => SQL`${v}`),\n ', ',\n );\n\n return SQL`json_extract(data, '${SQL.plain(jsonPath)}') NOT IN (${inClause})`;\n }\n case '$elemMatch': {\n const subConditions = objectEntries(value as Record<string, unknown>)\n .map(([subKey, subValue]) => {\n const serializedValue = serializer.serialize(subValue);\n return `json_extract(value, '$.${subKey}') = json('${serializedValue}')`;\n })\n .join(' AND ');\n\n const jsonPath = buildJsonPath(path);\n return SQL`EXISTS(SELECT 1 FROM json_each(data, '${SQL.plain(jsonPath)}') WHERE ${SQL.plain(subConditions)})`;\n }\n case '$all': {\n const jsonPath = buildJsonPath(path);\n const serializedValue = serializer.serialize(value);\n\n return SQL`(SELECT COUNT(*) FROM json_each(json(${serializedValue})) WHERE json_each.value NOT IN (SELECT value FROM json_each(data, '${SQL.plain(jsonPath)}'))) = 0`;\n }\n case '$size': {\n const jsonPath = buildJsonPath(path);\n\n return SQL`json_array_length(json_extract(data, '${SQL.plain(jsonPath)}')) = ${value}`;\n }\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleMetadataOperator = (\n fieldName: string,\n operator: string,\n value: unknown,\n): SQL => {\n switch (operator) {\n case '$eq':\n return SQL`${SQL.plain(fieldName)} = ${value}`;\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return SQL`${SQL.plain(fieldName)} ${SQL.plain(OperatorMap[operator])} ${value}`;\n case '$in': {\n const values = value as unknown[];\n const inClause = SQL.merge(\n values.map((v) => SQL`${v}`),\n ', ',\n );\n return SQL`${SQL.plain(fieldName)} IN (${inClause})`;\n }\n case '$nin': {\n const values = value as unknown[];\n const inClause = SQL.merge(\n values.map((v) => SQL`${v}`),\n ', ',\n );\n return SQL`${SQL.plain(fieldName)} NOT IN (${inClause})`;\n }\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildJsonPath = (path: string): string => {\n return `$.${path}`;\n};\n","import type { JSONSerializer } from '@event-driven-io/dumbo';\nimport { SQL } from '@event-driven-io/dumbo';\nimport {\n hasOperators,\n objectEntries,\n QueryOperators,\n type PongoFilter,\n} from '../../../../../core';\nimport { handleOperator } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(\n filter: PongoFilter<T>,\n serializer: JSONSerializer,\n): SQL =>\n SQL.merge(\n Object.entries(filter).map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value, serializer)\n : handleOperator(key, '$eq', value, serializer),\n ),\n ` ${AND} `,\n );\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n serializer: JSONSerializer,\n): SQL => {\n const isEquality = !hasOperators(value);\n\n return SQL.merge(\n objectEntries(value).map(([nestedKey, val]) =>\n isEquality\n ? handleOperator(\n `${key}.${nestedKey}`,\n QueryOperators.$eq,\n val,\n serializer,\n )\n : handleOperator(key, nestedKey, val, serializer),\n ),\n ` ${AND} `,\n );\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import type { JSONSerializer } from '@event-driven-io/dumbo';\nimport { SQL } from '@event-driven-io/dumbo';\nimport {\n objectEntries,\n type $inc,\n type $push,\n type $set,\n type $unset,\n type PongoUpdate,\n} from '../../../../../core';\n\nexport const buildUpdateQuery = <T>(\n update: PongoUpdate<T>,\n serializer: JSONSerializer,\n): SQL =>\n objectEntries(update).reduce(\n (currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery, serializer);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery, serializer);\n default:\n return currentUpdateQuery;\n }\n },\n SQL`data`,\n );\n\nexport const buildSetQuery = <T>(\n set: $set<T>,\n currentUpdateQuery: SQL,\n serializer: JSONSerializer,\n): SQL => SQL`json_patch(${currentUpdateQuery}, ${serializer.serialize(set)})`;\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n const keys = Object.keys(unset);\n let query = currentUpdateQuery;\n for (const key of keys) {\n query = SQL`json_remove(${query}, '$.${SQL.plain(key)}')`;\n }\n return query;\n};\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery =\n typeof value === 'bigint'\n ? SQL`json_set(${currentUpdateQuery}, '$.${SQL.plain(key)}', CAST((COALESCE(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}'), 0) + ${value}) AS TEXT))`\n : SQL`json_set(${currentUpdateQuery}, '$.${SQL.plain(key)}', COALESCE(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}'), 0) + ${value})`;\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n serializer: JSONSerializer,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n const serializedValue = serializer.serialize(value);\n currentUpdateQuery = SQL`json_set(${currentUpdateQuery}, '$.${SQL.plain(key)}', CASE\n WHEN json_type(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}')) = 'array'\n THEN json_insert(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}'), '$[#]', json(${serializedValue}))\n ELSE json_array(json(${serializedValue}))\n END)`;\n }\n return currentUpdateQuery;\n};\n","import type { JSONSerializer } from '@event-driven-io/dumbo';\nimport { isSQL, SQL, sqlMigration } from '@event-driven-io/dumbo';\nimport {\n expectedVersionValue,\n type DeleteOneOptions,\n type FindOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type ReplaceOneOptions,\n type UpdateOneOptions,\n type WithId,\n type WithIdAndVersion,\n type WithoutId,\n} from '../../../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n SQL`\n CREATE TABLE IF NOT EXISTS ${SQL.identifier(collectionName)} (\n _id TEXT PRIMARY KEY,\n data JSON NOT NULL,\n metadata JSON NOT NULL DEFAULT '{}',\n _version INTEGER NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived INTEGER NOT NULL DEFAULT 0,\n _created TEXT NOT NULL DEFAULT (datetime('now')),\n _updated TEXT NOT NULL DEFAULT (datetime('now'))\n )`;\n\nexport const pongoCollectionSQLiteMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const sqliteSQLBuilder = (\n collectionName: string,\n serializer: JSONSerializer,\n): PongoCollectionSQLBuilder => ({\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>): SQL => {\n const serialized = document;\n const id = document._id;\n const version = document._version ?? 1n;\n\n return SQL`\n INSERT OR IGNORE INTO ${SQL.identifier(collectionName)} (_id, data, _version)\n VALUES (${id}, ${serialized}, ${version})\n RETURNING _id;`;\n },\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]): SQL => {\n const values = SQL.merge(\n documents.map(\n (doc) =>\n SQL`(${doc._id}, ${serializer.serialize(doc)}, ${doc._version ?? 1n})`,\n ),\n ',',\n );\n\n return SQL`\n INSERT OR IGNORE INTO ${SQL.identifier(collectionName)} (_id, data, _version) VALUES ${values}\n RETURNING _id;`;\n },\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionCheck =\n expectedVersion != null ? SQL`AND _version = ${expectedVersion}` : SQL``;\n\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n const updateQuery = isSQL(update)\n ? update\n : buildUpdateQuery(update, serializer);\n\n return SQL`\n UPDATE ${SQL.identifier(collectionName)}\n SET\n data = json_patch(${updateQuery}, json_object('_id', _id, '_version', cast(_version + 1 as TEXT))),\n _version = _version + 1,\n _updated = datetime('now')\n WHERE _id = (\n SELECT _id FROM ${SQL.identifier(collectionName)}\n ${where(filterQuery)}\n LIMIT 1\n ) ${expectedVersionCheck}\n RETURNING\n _id,\n cast(_version as TEXT) as version,\n 1 as matched,\n 1 as modified;`;\n },\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionCheck =\n expectedVersion != null ? SQL`AND _version = ${expectedVersion}` : SQL``;\n\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n\n return SQL`\n UPDATE ${SQL.identifier(collectionName)}\n SET\n data = json_patch(${serializer.serialize(document)}, json_object('_id', _id, '_version', cast(_version + 1 as TEXT))),\n _version = _version + 1,\n _updated = datetime('now')\n WHERE _id = (\n SELECT _id FROM ${SQL.identifier(collectionName)}\n ${where(filterQuery)}\n LIMIT 1\n ) ${expectedVersionCheck}\n RETURNING\n _id,\n cast(_version as TEXT) AS version,\n 1 AS matched,\n 1 AS modified;`;\n },\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ): SQL => {\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n const updateQuery = isSQL(update)\n ? update\n : buildUpdateQuery(update, serializer);\n\n return SQL`\n UPDATE ${SQL.identifier(collectionName)}\n SET\n data = json_patch(${updateQuery}, json_object('_version', cast(_version + 1 as TEXT))),\n _version = _version + 1,\n _updated = datetime('now')\n ${where(filterQuery)}\n RETURNING _id;`;\n },\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionCheck =\n expectedVersion != null ? SQL`AND _version = ${expectedVersion}` : SQL``;\n\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n\n return SQL`\n DELETE FROM ${SQL.identifier(collectionName)}\n WHERE _id = (\n SELECT _id FROM ${SQL.identifier(collectionName)}\n ${where(filterQuery)}\n LIMIT 1\n ) ${expectedVersionCheck}\n RETURNING\n _id,\n 1 AS matched,\n 1 AS deleted;`;\n },\n deleteMany: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n\n return SQL`DELETE FROM ${SQL.identifier(collectionName)} ${where(filterQuery)} RETURNING _id`;\n },\n replaceMany: <T>(documents: Array<WithIdAndVersion<T> | WithId<T>>): SQL => {\n const col = SQL.identifier(collectionName);\n const hasVersions = documents.some(\n (d) => '_version' in d && d._version !== undefined,\n );\n\n if (hasVersions) {\n const values = SQL.merge(\n documents.map(\n (d) =>\n SQL`(${d._id}, ${serializer.serialize(d)}, ${(d as WithIdAndVersion<T>)._version ?? 0n})`,\n ),\n ',',\n );\n return SQL`\n WITH replacements(_id, data, expected_version) AS (\n VALUES ${values}\n )\n UPDATE ${col}\n SET\n data = json_patch(r.data, json_object('_id', ${col}._id, '_version', cast(${col}._version + 1 as TEXT))),\n _version = ${col}._version + 1,\n _updated = datetime('now')\n FROM replacements r\n WHERE ${col}._id = r._id AND ${col}._version = r.expected_version\n RETURNING ${col}._id, cast(${col}._version as TEXT) as version;`;\n }\n\n const values = SQL.merge(\n documents.map((d) => SQL`(${d._id}, ${serializer.serialize(d)})`),\n ',',\n );\n return SQL`\n WITH replacements(_id, data) AS (\n VALUES ${values}\n )\n UPDATE ${col}\n SET\n data = json_patch(r.data, json_object('_id', ${col}._id, '_version', cast(${col}._version + 1 as TEXT))),\n _version = ${col}._version + 1,\n _updated = datetime('now')\n FROM replacements r\n WHERE ${col}._id = r._id\n RETURNING ${col}._id, cast(${col}._version as TEXT) as version;`;\n },\n deleteManyByIds: (ids: Array<{ _id: string; _version?: bigint }>): SQL => {\n const hasVersions = ids.some((d) => d._version !== undefined);\n\n if (hasVersions) {\n const values = SQL.merge(\n ids.map((d) => SQL`(${d._id}, ${d._version ?? 0n})`),\n ',',\n );\n\n return SQL`\n WITH targets(_id, expected_version) AS (\n VALUES ${values}\n )\n DELETE FROM ${SQL.identifier(collectionName)}\n WHERE _id IN (SELECT _id FROM targets)\n AND _version = (SELECT expected_version FROM targets WHERE targets._id = ${SQL.identifier(collectionName)}._id)\n RETURNING _id;`;\n }\n\n const idList = SQL.merge(\n ids.map((d) => SQL`${d._id}`),\n ',',\n );\n\n return SQL`\n DELETE FROM ${SQL.identifier(collectionName)}\n WHERE _id IN (${idList})\n RETURNING _id;`;\n },\n findOne: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n\n return SQL`SELECT data, _version FROM ${SQL.identifier(collectionName)} ${where(filterQuery)} LIMIT 1;`;\n },\n find: <T>(filter: PongoFilter<T> | SQL, options?: FindOptions): SQL => {\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n const query: SQL[] = [];\n\n query.push(\n SQL`SELECT data, _version FROM ${SQL.identifier(collectionName)}`,\n );\n\n query.push(where(filterQuery));\n\n if (options?.sort && Object.keys(options.sort).length > 0) {\n const clauses = Object.entries(options.sort).map(([field, dir]) => {\n // _id and _version are native columns, not JSON fields.\n const isMetadata = field === '_id' || field === '_version';\n const accessor = isMetadata\n ? SQL`${SQL.plain(field)}`\n : SQL`json_extract(data, '${SQL.plain(`$.${field}`)}')`;\n return dir === 1 ? SQL`${accessor} ASC` : SQL`${accessor} DESC`;\n });\n query.push(SQL`ORDER BY ${SQL.merge(clauses, ',')}`);\n }\n\n if (options?.limit) {\n query.push(SQL`LIMIT ${options.limit}`);\n }\n\n if (options?.skip) {\n query.push(SQL`OFFSET ${options.skip}`);\n }\n\n return SQL.merge([...query, SQL`;`]);\n },\n countDocuments: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = SQL.check.isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n return SQL`SELECT COUNT(1) as count FROM ${SQL.identifier(collectionName)} ${where(filterQuery)};`;\n },\n rename: (newName: string): SQL =>\n SQL`ALTER TABLE ${SQL.identifier(collectionName)} RENAME TO ${SQL.identifier(newName)};`,\n drop: (targetName: string = collectionName): SQL =>\n SQL`DROP TABLE IF EXISTS ${S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AO,0BAAG,iCAAiCA,2BAAI,WAAW,eAAe,CAAC,GAAG,MAAM,YAAY,CAAC;;CAElG,SAAS,YACP,0BAAG,eAAeA,2BAAI,WAAW,eAAe,CAAC,aAAaA,2BAAI,WAAW,QAAQ,CAAC;CACxF,OAAO,aAAqB,mBAC1B,0BAAG,wBAAwBA,2BAAI,WAAW,WAAW;CACxD;AAED,MAAM,SAAS,gBACbA,2BAAI,MAAM,QAAQ,YAAY,GAC1BA,2BAAI,QACJA,2BAAI,MAAM,CAAC,0BAAG,UAAU,YAAY,CAAC"}
1
+ {"version":3,"file":"core-BYk4wCpe.cjs","names":["SQL","OperatorMap","objectEntries","SQL","hasOperators","objectEntries","QueryOperators","objectEntries","SQL","SQL","expectedVersionValue"],"sources":["../src/storage/sqlite/core/sqlBuilder/filter/queryOperators.ts","../src/storage/sqlite/core/sqlBuilder/filter/index.ts","../src/storage/sqlite/core/sqlBuilder/update/index.ts","../src/storage/sqlite/core/sqlBuilder/index.ts"],"sourcesContent":["import type { JSONSerializer } from '@event-driven-io/dumbo';\nimport { SQL } from '@event-driven-io/dumbo';\nimport { objectEntries, OperatorMap } from '../../../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n serializer: JSONSerializer,\n): SQL => {\n if (path === '_id' || path === '_version') {\n return handleMetadataOperator(path, operator, value);\n }\n\n switch (operator) {\n case '$eq': {\n const jsonPath = buildJsonPath(path);\n\n return SQL`(\n json_extract(data, '${SQL.plain(jsonPath)}') = ${value}\n OR (\n json_type(data, '${SQL.plain(jsonPath)}') = 'array'\n AND EXISTS(\n SELECT 1 FROM json_each(data, '${SQL.plain(jsonPath)}')\n WHERE json_each.value = ${value}\n )\n )\n )`;\n }\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne': {\n const jsonPath = buildJsonPath(path);\n\n return SQL`json_extract(data, '${SQL.plain(jsonPath)}') ${SQL.plain(OperatorMap[operator])} ${value}`;\n }\n case '$in': {\n const jsonPath = buildJsonPath(path);\n const values = value as unknown[];\n const inClause = SQL.merge(\n values.map((v) => SQL`${v}`),\n ', ',\n );\n\n return SQL`json_extract(data, '${SQL.plain(jsonPath)}') IN (${inClause})`;\n }\n case '$nin': {\n const jsonPath = buildJsonPath(path);\n const values = value as unknown[];\n const inClause = SQL.merge(\n values.map((v) => SQL`${v}`),\n ', ',\n );\n\n return SQL`json_extract(data, '${SQL.plain(jsonPath)}') NOT IN (${inClause})`;\n }\n case '$elemMatch': {\n const subConditions = objectEntries(value as Record<string, unknown>)\n .map(([subKey, subValue]) => {\n const serializedValue = serializer.serialize(subValue);\n return `json_extract(value, '$.${subKey}') = json('${serializedValue}')`;\n })\n .join(' AND ');\n\n const jsonPath = buildJsonPath(path);\n return SQL`EXISTS(SELECT 1 FROM json_each(data, '${SQL.plain(jsonPath)}') WHERE ${SQL.plain(subConditions)})`;\n }\n case '$all': {\n const jsonPath = buildJsonPath(path);\n const serializedValue = serializer.serialize(value);\n\n return SQL`(SELECT COUNT(*) FROM json_each(json(${serializedValue})) WHERE json_each.value NOT IN (SELECT value FROM json_each(data, '${SQL.plain(jsonPath)}'))) = 0`;\n }\n case '$size': {\n const jsonPath = buildJsonPath(path);\n\n return SQL`json_array_length(json_extract(data, '${SQL.plain(jsonPath)}')) = ${value}`;\n }\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleMetadataOperator = (\n fieldName: string,\n operator: string,\n value: unknown,\n): SQL => {\n switch (operator) {\n case '$eq':\n return SQL`${SQL.plain(fieldName)} = ${value}`;\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return SQL`${SQL.plain(fieldName)} ${SQL.plain(OperatorMap[operator])} ${value}`;\n case '$in': {\n const values = value as unknown[];\n const inClause = SQL.merge(\n values.map((v) => SQL`${v}`),\n ', ',\n );\n return SQL`${SQL.plain(fieldName)} IN (${inClause})`;\n }\n case '$nin': {\n const values = value as unknown[];\n const inClause = SQL.merge(\n values.map((v) => SQL`${v}`),\n ', ',\n );\n return SQL`${SQL.plain(fieldName)} NOT IN (${inClause})`;\n }\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildJsonPath = (path: string): string => {\n return `$.${path}`;\n};\n","import type { JSONSerializer } from '@event-driven-io/dumbo';\nimport { SQL } from '@event-driven-io/dumbo';\nimport {\n hasOperators,\n objectEntries,\n QueryOperators,\n type PongoFilter,\n} from '../../../../../core';\nimport { handleOperator } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(\n filter: PongoFilter<T>,\n serializer: JSONSerializer,\n): SQL =>\n SQL.merge(\n Object.entries(filter).map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value, serializer)\n : handleOperator(key, '$eq', value, serializer),\n ),\n ` ${AND} `,\n );\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n serializer: JSONSerializer,\n): SQL => {\n const isEquality = !hasOperators(value);\n\n return SQL.merge(\n objectEntries(value).map(([nestedKey, val]) =>\n isEquality\n ? handleOperator(\n `${key}.${nestedKey}`,\n QueryOperators.$eq,\n val,\n serializer,\n )\n : handleOperator(key, nestedKey, val, serializer),\n ),\n ` ${AND} `,\n );\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import type { JSONSerializer } from '@event-driven-io/dumbo';\nimport { SQL } from '@event-driven-io/dumbo';\nimport {\n objectEntries,\n type $inc,\n type $push,\n type $set,\n type $unset,\n type PongoUpdate,\n} from '../../../../../core';\n\nexport const buildUpdateQuery = <T>(\n update: PongoUpdate<T>,\n serializer: JSONSerializer,\n): SQL =>\n objectEntries(update).reduce(\n (currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery, serializer);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery, serializer);\n default:\n return currentUpdateQuery;\n }\n },\n SQL`data`,\n );\n\nexport const buildSetQuery = <T>(\n set: $set<T>,\n currentUpdateQuery: SQL,\n serializer: JSONSerializer,\n): SQL => SQL`json_patch(${currentUpdateQuery}, ${serializer.serialize(set)})`;\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n const keys = Object.keys(unset);\n let query = currentUpdateQuery;\n for (const key of keys) {\n query = SQL`json_remove(${query}, '$.${SQL.plain(key)}')`;\n }\n return query;\n};\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery =\n typeof value === 'bigint'\n ? SQL`json_set(${currentUpdateQuery}, '$.${SQL.plain(key)}', CAST((COALESCE(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}'), 0) + ${value}) AS TEXT))`\n : SQL`json_set(${currentUpdateQuery}, '$.${SQL.plain(key)}', COALESCE(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}'), 0) + ${value})`;\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n serializer: JSONSerializer,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n const serializedValue = serializer.serialize(value);\n currentUpdateQuery = SQL`json_set(${currentUpdateQuery}, '$.${SQL.plain(key)}', CASE\n WHEN json_type(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}')) = 'array'\n THEN json_insert(json_extract(${currentUpdateQuery}, '$.${SQL.plain(key)}'), '$[#]', json(${serializedValue}))\n ELSE json_array(json(${serializedValue}))\n END)`;\n }\n return currentUpdateQuery;\n};\n","import type { JSONSerializer } from '@event-driven-io/dumbo';\nimport { isSQL, SQL, sqlMigration } from '@event-driven-io/dumbo';\nimport {\n expectedVersionValue,\n type DeleteOneOptions,\n type FindOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type ReplaceOneOptions,\n type UpdateOneOptions,\n type WithId,\n type WithIdAndVersion,\n type WithoutId,\n} from '../../../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n SQL`\n CREATE TABLE IF NOT EXISTS ${SQL.identifier(collectionName)} (\n _id TEXT PRIMARY KEY,\n data JSON NOT NULL,\n metadata JSON NOT NULL DEFAULT '{}',\n _version INTEGER NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived INTEGER NOT NULL DEFAULT 0,\n _created TEXT NOT NULL DEFAULT (datetime('now')),\n _updated TEXT NOT NULL DEFAULT (datetime('now'))\n )`;\n\nexport const pongoCollectionSQLiteMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const sqliteSQLBuilder = (\n collectionName: string,\n serializer: JSONSerializer,\n): PongoCollectionSQLBuilder => ({\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>): SQL => {\n const serialized = document;\n const id = document._id;\n const version = document._version ?? 1n;\n\n return SQL`\n INSERT OR IGNORE INTO ${SQL.identifier(collectionName)} (_id, data, _version)\n VALUES (${id}, ${serialized}, ${version})\n RETURNING _id;`;\n },\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]): SQL => {\n const values = SQL.merge(\n documents.map(\n (doc) =>\n SQL`(${doc._id}, ${serializer.serialize(doc)}, ${doc._version ?? 1n})`,\n ),\n ',',\n );\n\n return SQL`\n INSERT OR IGNORE INTO ${SQL.identifier(collectionName)} (_id, data, _version) VALUES ${values}\n RETURNING _id;`;\n },\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionCheck =\n expectedVersion != null ? SQL`AND _version = ${expectedVersion}` : SQL``;\n\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n const updateQuery = isSQL(update)\n ? update\n : buildUpdateQuery(update, serializer);\n\n return SQL`\n UPDATE ${SQL.identifier(collectionName)}\n SET\n data = json_patch(${updateQuery}, json_object('_id', _id, '_version', cast(_version + 1 as TEXT))),\n _version = _version + 1,\n _updated = datetime('now')\n WHERE _id = (\n SELECT _id FROM ${SQL.identifier(collectionName)}\n ${where(filterQuery)}\n LIMIT 1\n ) ${expectedVersionCheck}\n RETURNING\n _id,\n cast(_version as TEXT) as version,\n 1 as matched,\n 1 as modified;`;\n },\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionCheck =\n expectedVersion != null ? SQL`AND _version = ${expectedVersion}` : SQL``;\n\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n\n return SQL`\n UPDATE ${SQL.identifier(collectionName)}\n SET\n data = json_patch(${serializer.serialize(document)}, json_object('_id', _id, '_version', cast(_version + 1 as TEXT))),\n _version = _version + 1,\n _updated = datetime('now')\n WHERE _id = (\n SELECT _id FROM ${SQL.identifier(collectionName)}\n ${where(filterQuery)}\n LIMIT 1\n ) ${expectedVersionCheck}\n RETURNING\n _id,\n cast(_version as TEXT) AS version,\n 1 AS matched,\n 1 AS modified;`;\n },\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ): SQL => {\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n const updateQuery = isSQL(update)\n ? update\n : buildUpdateQuery(update, serializer);\n\n return SQL`\n UPDATE ${SQL.identifier(collectionName)}\n SET\n data = json_patch(${updateQuery}, json_object('_version', cast(_version + 1 as TEXT))),\n _version = _version + 1,\n _updated = datetime('now')\n ${where(filterQuery)}\n RETURNING _id;`;\n },\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionCheck =\n expectedVersion != null ? SQL`AND _version = ${expectedVersion}` : SQL``;\n\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n\n return SQL`\n DELETE FROM ${SQL.identifier(collectionName)}\n WHERE _id = (\n SELECT _id FROM ${SQL.identifier(collectionName)}\n ${where(filterQuery)}\n LIMIT 1\n ) ${expectedVersionCheck}\n RETURNING\n _id,\n 1 AS matched,\n 1 AS deleted;`;\n },\n deleteMany: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n\n return SQL`DELETE FROM ${SQL.identifier(collectionName)} ${where(filterQuery)} RETURNING _id`;\n },\n replaceMany: <T>(documents: Array<WithIdAndVersion<T> | WithId<T>>): SQL => {\n const col = SQL.identifier(collectionName);\n const hasVersions = documents.some(\n (d) => '_version' in d && d._version !== undefined,\n );\n\n if (hasVersions) {\n const values = SQL.merge(\n documents.map(\n (d) =>\n SQL`(${d._id}, ${serializer.serialize(d)}, ${(d as WithIdAndVersion<T>)._version ?? 0n})`,\n ),\n ',',\n );\n return SQL`\n WITH replacements(_id, data, expected_version) AS (\n VALUES ${values}\n )\n UPDATE ${col}\n SET\n data = json_patch(r.data, json_object('_id', ${col}._id, '_version', cast(${col}._version + 1 as TEXT))),\n _version = ${col}._version + 1,\n _updated = datetime('now')\n FROM replacements r\n WHERE ${col}._id = r._id AND ${col}._version = r.expected_version\n RETURNING ${col}._id, cast(${col}._version as TEXT) as version;`;\n }\n\n const values = SQL.merge(\n documents.map((d) => SQL`(${d._id}, ${serializer.serialize(d)})`),\n ',',\n );\n return SQL`\n WITH replacements(_id, data) AS (\n VALUES ${values}\n )\n UPDATE ${col}\n SET\n data = json_patch(r.data, json_object('_id', ${col}._id, '_version', cast(${col}._version + 1 as TEXT))),\n _version = ${col}._version + 1,\n _updated = datetime('now')\n FROM replacements r\n WHERE ${col}._id = r._id\n RETURNING ${col}._id, cast(${col}._version as TEXT) as version;`;\n },\n deleteManyByIds: (ids: Array<{ _id: string; _version?: bigint }>): SQL => {\n const hasVersions = ids.some((d) => d._version !== undefined);\n\n if (hasVersions) {\n const values = SQL.merge(\n ids.map((d) => SQL`(${d._id}, ${d._version ?? 0n})`),\n ',',\n );\n\n return SQL`\n WITH targets(_id, expected_version) AS (\n VALUES ${values}\n )\n DELETE FROM ${SQL.identifier(collectionName)}\n WHERE _id IN (SELECT _id FROM targets)\n AND _version = (SELECT expected_version FROM targets WHERE targets._id = ${SQL.identifier(collectionName)}._id)\n RETURNING _id;`;\n }\n\n const idList = SQL.merge(\n ids.map((d) => SQL`${d._id}`),\n ',',\n );\n\n return SQL`\n DELETE FROM ${SQL.identifier(collectionName)}\n WHERE _id IN (${idList})\n RETURNING _id;`;\n },\n findOne: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n\n return SQL`SELECT data, _id, _version FROM ${SQL.identifier(collectionName)} ${where(filterQuery)} LIMIT 1;`;\n },\n find: <T>(filter: PongoFilter<T> | SQL, options?: FindOptions): SQL => {\n const filterQuery = isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n const query: SQL[] = [];\n\n query.push(\n SQL`SELECT data, _id, _version FROM ${SQL.identifier(collectionName)}`,\n );\n\n query.push(where(filterQuery));\n\n if (options?.sort && Object.keys(options.sort).length > 0) {\n const clauses = Object.entries(options.sort).map(([field, dir]) => {\n // _id and _version are native columns, not JSON fields.\n const isMetadata = field === '_id' || field === '_version';\n const accessor = isMetadata\n ? SQL`${SQL.plain(field)}`\n : SQL`json_extract(data, '${SQL.plain(`$.${field}`)}')`;\n return dir === 1 ? SQL`${accessor} ASC` : SQL`${accessor} DESC`;\n });\n query.push(SQL`ORDER BY ${SQL.merge(clauses, ',')}`);\n }\n\n if (options?.limit) {\n query.push(SQL`LIMIT ${options.limit}`);\n }\n\n if (options?.skip) {\n query.push(SQL`OFFSET ${options.skip}`);\n }\n\n return SQL.merge([...query, SQL`;`]);\n },\n countDocuments: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = SQL.check.isSQL(filter)\n ? filter\n : constructFilterQuery(filter, serializer);\n return SQL`SELECT COUNT(1) as count FROM ${SQL.identifier(collectionName)} ${where(filterQuery)};`;\n },\n rename: (newName: string): SQL =>\n SQL`ALTER TABLE ${SQL.identifier(collectionName)} RENAME TO ${SQL.identifier(newName)};`,\n drop: (targetName: string = collectionName): SQL =>\n SQL`DROP TABLE IF EXISTS ${SQL.identifier(targetName)}`,\n});\n\nconst where = (filterQuery: SQL): SQL =>\n SQL.check.isEmpty(filterQuery)\n ? SQL.EMPTY\n : SQL.merge([SQL`WHERE `, filterQuery]);\n"],"mappings":";;;;;AAIA,MAAa,kBACX,MACA,UACA,OACA,eACQ;AACR,KAAI,SAAS,SAAS,SAAS,WAC7B,QAAO,uBAAuB,MAAM,UAAU,MAAM;AAGtD,SAAQ,UAAR;EACE,KAAK,OAAO;GACV,MAAM,WAAW,cAAc,KAAK;AAEpC,UAAO,0BAAG;8BACcA,2BAAI,MAAM,SAAS,CAAC,OAAO,MAAM;;6BAElCA,2BAAI,MAAM,SAAS,CAAC;;6CAEJA,2BAAI,MAAM,SAAS,CAAC;sCAC3B,MAAM;;;;;EAKxC,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,OAAO;GACV,MAAM,WAAW,cAAc,KAAK;AAEpC,UAAO,0BAAG,uBAAuBA,2BAAI,MAAM,SAAS,CAAC,KAAKA,2BAAI,MAAMC,yBAAY,UAAU,CAAC,GAAG;;EAEhG,KAAK,OAAO;GACV,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