@event-driven-io/emmett-postgresql 0.20.1 → 0.20.2-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"names":["migrateCommand","Command","options","collection","cli","program","cli_default"],"mappings":"AAAA,mNAAwB,IAeXA,CAAAA,CAAiB,IAAIC,uBAAAA,CAAQ,SAAS,CAAA,CAAE,WAAA,CACnD,4BACF,CAAA,CAEAD,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,yBAAyB,CAAA,CACrC,MAAA,CACC,kCAAA,CACA,oCACF,CAAA,CAUC,MAAA,CAAO,eAAA,CAAiB,2CAAA,CAA6C,CAAA,CAAK,CAAA,CAC1E,MAAA,CAAQE,CAAAA,EAA+B,CAAA,kBAGpCA,CAAAA,CAAQ,gBAAA,SAAoB,OAAA,CAAQ,GAAA,CAAI,sBAAA,CAAA,EAAA,CAIxC,OAAA,CAAQ,KAAA,CACN,uJACF,CAAA,CACA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAGhB,OAAA,CAAQ,GAAA,CAAI,+CAA+C,CAyB7D,CAAC,CAAA,CAEHF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,qCAAqC,CAAA,CAUjD,MAAA,CAAO,SAAA,CAAW,wCAAA,CAA0C,CAAA,CAAI,CAAA,CAEhE,MAAA,CAAQE,CAAAA,EAA+B,CACtC,GAAM,CAAE,UAAA,CAAAC,CAAW,CAAA,CAAID,CAAAA,CAElBC,CAAAA,EAAAA,CACH,OAAA,CAAQ,KAAA,CACN,8GACF,CAAA,CACA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAGhB,OAAA,CAAQ,GAAA,CAAI,gDAAgD,CAe9D,CAAC,CAAA,CChHH,IAAMC,CAAAA,CAAuB,CAC3B,UAAA,CAAY,KAAA,CACZ,IAAA,CAAM,mBAAA,CACN,gBAAA,CAAmBC,CAAAA,EAAY,CAC7BA,CAAAA,CAAQ,UAAA,CAAWL,CAAc,CACnC,CACF,CAAA,CAEOM,CAAAA,mBAAQF,CAAAA,CAAAA,oBAAAA","file":"/home/runner/work/emmett/emmett/src/packages/emmett-postgresql/dist/cli.cjs","sourcesContent":["import { Command } from 'commander';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <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('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action((options: MigrateRunOptions) => {\n //const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n //let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful');\n // if (options.config) {\n // const config = await loadConfigFile(options.config);\n\n // collectionNames = config.collections.map((c) => c.name);\n // } else if (collection) {\n // collectionNames = collection;\n // } else {\n // console.error(\n // 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n // );\n // process.exit(1);\n // }\n\n // const pool = dumbo({ connectionString });\n\n // const migrations = collectionNames.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // );\n\n // await runPostgreSQLMigrations(pool, migrations, {\n // dryRun,\n // });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n // .option(\n // '-col, --collection <name>',\n // 'Specify the collection name',\n // (value: string, previous: string[]) => {\n // // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n // return previous.concat([value]);\n // },\n // [] as string[],\n // )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful!');\n // const coreMigrations = migrationTableSchemaComponent.migrations({\n // connector: 'PostgreSQL:pg',\n // });\n // const migrations = [\n // ...coreMigrations,\n // ...collection.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // ),\n // ];\n\n // console.log('Printing SQL:');\n // console.log(combineMigrations(...migrations));\n });\n","import type { EmmettCliPlugin } from '@event-driven-io/emmett';\nimport { migrateCommand } from './commandLine';\n\nconst cli: EmmettCliPlugin = {\n pluginType: 'cli',\n name: 'emmett-postgresql',\n registerCommands: (program) => {\n program.addCommand(migrateCommand);\n },\n};\n\nexport default cli;\n"]}
1
+ {"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"names":["migrateCommand","Command","options","collection","cli","program","cli_default"],"mappings":"AAAA,mNAAwB,IAeXA,CAAAA,CAAiB,IAAIC,uBAAAA,CAAQ,SAAS,CAAA,CAAE,WAAA,CACnD,4BACF,CAAA,CAEAD,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,yBAAyB,CAAA,CACrC,MAAA,CACC,kCAAA,CACA,oCACF,CAAA,CAUC,MAAA,CAAO,eAAA,CAAiB,2CAAA,CAA6C,CAAA,CAAK,CAAA,CAC1E,MAAA,CAAQE,CAAAA,EAA+B,CAAA,kBAGpCA,CAAAA,CAAQ,gBAAA,SAAoB,OAAA,CAAQ,GAAA,CAAI,sBAAA,CAAA,EAAA,CAIxC,OAAA,CAAQ,KAAA,CACN,uJACF,CAAA,CACA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAGhB,OAAA,CAAQ,GAAA,CAAI,+CAA+C,CAyB7D,CAAC,CAAA,CAEHF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,qCAAqC,CAAA,CAUjD,MAAA,CAAO,SAAA,CAAW,wCAAA,CAA0C,CAAA,CAAI,CAAA,CAEhE,MAAA,CAAQE,CAAAA,EAA+B,CACtC,GAAM,CAAE,UAAA,CAAAC,CAAW,CAAA,CAAID,CAAAA,CAElBC,CAAAA,EAAAA,CACH,OAAA,CAAQ,KAAA,CACN,8GACF,CAAA,CACA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAGhB,OAAA,CAAQ,GAAA,CAAI,gDAAgD,CAe9D,CAAC,CAAA,CC7GH,IAAMC,CAAAA,CAAuB,CAC3B,UAAA,CAAY,KAAA,CACZ,IAAA,CAAM,mBAAA,CACN,gBAAA,CAAmBC,CAAAA,EAA8B,CAC/CA,CAAAA,CAAQ,UAAA,CAAWL,CAAc,CACnC,CACF,CAAA,CAEOM,CAAAA,mBAAQF,CAAAA,CAAAA,oBAAAA","file":"/home/runner/work/emmett/emmett/src/packages/emmett-postgresql/dist/cli.cjs","sourcesContent":["import { Command } from 'commander';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <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('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action((options: MigrateRunOptions) => {\n //const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n //let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful');\n // if (options.config) {\n // const config = await loadConfigFile(options.config);\n\n // collectionNames = config.collections.map((c) => c.name);\n // } else if (collection) {\n // collectionNames = collection;\n // } else {\n // console.error(\n // 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n // );\n // process.exit(1);\n // }\n\n // const pool = dumbo({ connectionString });\n\n // const migrations = collectionNames.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // );\n\n // await runPostgreSQLMigrations(pool, migrations, {\n // dryRun,\n // });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n // .option(\n // '-col, --collection <name>',\n // 'Specify the collection name',\n // (value: string, previous: string[]) => {\n // // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n // return previous.concat([value]);\n // },\n // [] as string[],\n // )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful!');\n // const coreMigrations = migrationTableSchemaComponent.migrations({\n // connector: 'PostgreSQL:pg',\n // });\n // const migrations = [\n // ...coreMigrations,\n // ...collection.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // ),\n // ];\n\n // console.log('Printing SQL:');\n // console.log(combineMigrations(...migrations));\n });\n","import type {\n EmmettCliCommand,\n EmmettCliPlugin,\n} from '@event-driven-io/emmett';\nimport { migrateCommand } from './commandLine';\n\nconst cli: EmmettCliPlugin = {\n pluginType: 'cli',\n name: 'emmett-postgresql',\n registerCommands: (program: EmmettCliCommand) => {\n program.addCommand(migrateCommand);\n },\n};\n\nexport default cli;\n"]}
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"sourcesContent":["import { Command } from 'commander';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <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('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action((options: MigrateRunOptions) => {\n //const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n //let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful');\n // if (options.config) {\n // const config = await loadConfigFile(options.config);\n\n // collectionNames = config.collections.map((c) => c.name);\n // } else if (collection) {\n // collectionNames = collection;\n // } else {\n // console.error(\n // 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n // );\n // process.exit(1);\n // }\n\n // const pool = dumbo({ connectionString });\n\n // const migrations = collectionNames.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // );\n\n // await runPostgreSQLMigrations(pool, migrations, {\n // dryRun,\n // });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n // .option(\n // '-col, --collection <name>',\n // 'Specify the collection name',\n // (value: string, previous: string[]) => {\n // // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n // return previous.concat([value]);\n // },\n // [] as string[],\n // )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful!');\n // const coreMigrations = migrationTableSchemaComponent.migrations({\n // connector: 'PostgreSQL:pg',\n // });\n // const migrations = [\n // ...coreMigrations,\n // ...collection.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // ),\n // ];\n\n // console.log('Printing SQL:');\n // console.log(combineMigrations(...migrations));\n });\n","import type { EmmettCliPlugin } from '@event-driven-io/emmett';\nimport { migrateCommand } from './commandLine';\n\nconst cli: EmmettCliPlugin = {\n pluginType: 'cli',\n name: 'emmett-postgresql',\n registerCommands: (program) => {\n program.addCommand(migrateCommand);\n },\n};\n\nexport default cli;\n"],"mappings":"AAAA,OAAS,WAAAA,MAAe,YAejB,IAAMC,EAAiB,IAAID,EAAQ,SAAS,EAAE,YACnD,4BACF,EAEAC,EACG,QAAQ,KAAK,EACb,YAAY,yBAAyB,EACrC,OACC,mCACA,oCACF,EAUC,OAAO,gBAAiB,4CAA6C,EAAK,EAC1E,OAAQC,GAA+B,EAGpCA,EAAQ,kBAAoB,QAAQ,IAAI,wBAIxC,QAAQ,MACN,uJACF,EACA,QAAQ,KAAK,CAAC,GAGhB,QAAQ,IAAI,+CAA+C,CAyB7D,CAAC,EAEHD,EACG,QAAQ,KAAK,EACb,YAAY,qCAAqC,EAUjD,OAAO,UAAW,yCAA0C,EAAI,EAEhE,OAAQC,GAA+B,CACtC,GAAM,CAAE,WAAAC,CAAW,EAAID,EAElBC,IACH,QAAQ,MACN,8GACF,EACA,QAAQ,KAAK,CAAC,GAGhB,QAAQ,IAAI,gDAAgD,CAe9D,CAAC,EChHH,IAAMC,EAAuB,CAC3B,WAAY,MACZ,KAAM,oBACN,iBAAmBC,GAAY,CAC7BA,EAAQ,WAAWC,CAAc,CACnC,CACF,EAEOC,EAAQH","names":["Command","migrateCommand","options","collection","cli","program","migrateCommand","cli_default"]}
1
+ {"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"sourcesContent":["import { Command } from 'commander';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <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('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action((options: MigrateRunOptions) => {\n //const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n //let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful');\n // if (options.config) {\n // const config = await loadConfigFile(options.config);\n\n // collectionNames = config.collections.map((c) => c.name);\n // } else if (collection) {\n // collectionNames = collection;\n // } else {\n // console.error(\n // 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n // );\n // process.exit(1);\n // }\n\n // const pool = dumbo({ connectionString });\n\n // const migrations = collectionNames.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // );\n\n // await runPostgreSQLMigrations(pool, migrations, {\n // dryRun,\n // });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n // .option(\n // '-col, --collection <name>',\n // 'Specify the collection name',\n // (value: string, previous: string[]) => {\n // // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n // return previous.concat([value]);\n // },\n // [] as string[],\n // )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful!');\n // const coreMigrations = migrationTableSchemaComponent.migrations({\n // connector: 'PostgreSQL:pg',\n // });\n // const migrations = [\n // ...coreMigrations,\n // ...collection.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // ),\n // ];\n\n // console.log('Printing SQL:');\n // console.log(combineMigrations(...migrations));\n });\n","import type {\n EmmettCliCommand,\n EmmettCliPlugin,\n} from '@event-driven-io/emmett';\nimport { migrateCommand } from './commandLine';\n\nconst cli: EmmettCliPlugin = {\n pluginType: 'cli',\n name: 'emmett-postgresql',\n registerCommands: (program: EmmettCliCommand) => {\n program.addCommand(migrateCommand);\n },\n};\n\nexport default cli;\n"],"mappings":"AAAA,OAAS,WAAAA,MAAe,YAejB,IAAMC,EAAiB,IAAID,EAAQ,SAAS,EAAE,YACnD,4BACF,EAEAC,EACG,QAAQ,KAAK,EACb,YAAY,yBAAyB,EACrC,OACC,mCACA,oCACF,EAUC,OAAO,gBAAiB,4CAA6C,EAAK,EAC1E,OAAQC,GAA+B,EAGpCA,EAAQ,kBAAoB,QAAQ,IAAI,wBAIxC,QAAQ,MACN,uJACF,EACA,QAAQ,KAAK,CAAC,GAGhB,QAAQ,IAAI,+CAA+C,CAyB7D,CAAC,EAEHD,EACG,QAAQ,KAAK,EACb,YAAY,qCAAqC,EAUjD,OAAO,UAAW,yCAA0C,EAAI,EAEhE,OAAQC,GAA+B,CACtC,GAAM,CAAE,WAAAC,CAAW,EAAID,EAElBC,IACH,QAAQ,MACN,8GACF,EACA,QAAQ,KAAK,CAAC,GAGhB,QAAQ,IAAI,gDAAgD,CAe9D,CAAC,EC7GH,IAAMC,EAAuB,CAC3B,WAAY,MACZ,KAAM,oBACN,iBAAmBC,GAA8B,CAC/CA,EAAQ,WAAWC,CAAc,CACnC,CACF,EAEOC,EAAQH","names":["Command","migrateCommand","options","collection","cli","program","migrateCommand","cli_default"]}
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3;var _dumbo = require('@event-driven-io/dumbo');require('commander');var z=(e=>(e.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",e.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",e.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",e))(z||{}),H=e=>typeof e=="number"&&e===e,Y=e=>typeof e=="string";var U=e=>typeof e=="function"&&e.prototype&&e.prototype.constructor===e,J=class K extends Error{constructor(t){let n=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:H(t)?t:500,a=t&&typeof t=="object"&&"message"in t?t.message:Y(t)?t:`Error with status code '${n}' ocurred during Emmett processing`;super(a),this.errorCode=n,Object.setPrototypeOf(this,K.prototype)}},Z=class ee extends J{constructor(t,n,a){super({errorCode:412,message:_nullishCoalesce(a, () => (`Expected version ${n.toString()} does not match current ${_optionalChain([t, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))}),this.current=t,this.expected=n,Object.setPrototypeOf(this,ee.prototype)}};var _uuid = require('uuid');var _webstreamspolyfill = require('web-streams-polyfill');var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);var $=(e,t,n)=>({type:e,data:t,metadata:n});var xe="__emt:GlobalStreamCaughtUp";var te=e=>$(xe,e,{globalPosition:e.globalPosition});var j="STREAM_EXISTS",Q="STREAM_DOES_NOT_EXIST",O="NO_CONCURRENCY_CHECK",we=(e,t,n)=>t===O?!0:t==Q?e===n:t==j?e!==n:e===t,ne=(e,t,n)=>{if(t??=O,!we(e,t,n))throw new B(e,t)},B=class ae extends Z{constructor(t,n){super(_optionalChain([t, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]),_optionalChain([n, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()])),Object.setPrototypeOf(this,ae.prototype)}};var Fe={ReadableStream:_webstreamspolyfill.ReadableStream,WritableStream:_webstreamspolyfill.WritableStream,TransformStream:_webstreamspolyfill.TransformStream},Qt=typeof process<"u"&&process.versions!=null&&process.versions.bun!=null,x;if(globalThis&&globalThis.WritableStream&&globalThis.ReadableStream&&globalThis.TransformStream)x=globalThis;else try{x=await Promise.resolve().then(() => _interopRequireWildcard(require("stream/web")))}catch (e2){x=Fe}var g=x;var Bt=class extends g.TransformStream{constructor(e){super({start:t=>{let n=0n;for(let a of e)t.enqueue(a),n=a.metadata.globalPosition;t.enqueue(te({globalPosition:n}))},transform:(t,n)=>{this._currentPosition=t.metadata.globalPosition,n.enqueue(t),!(this._currentPosition<this._logPosition)&&n.enqueue(te({globalPosition:this._currentPosition}))}}),this._currentPosition=this._logPosition=e.length>0?e[e.length-1].metadata.globalPosition:0n}set logPosition(e){this._logPosition=e}},$e=(e,t={})=>new oe(e,t),oe= (_class =class extends g.TransformStream{constructor(e,t={}){super({cancel:n=>{console.log("Stream was canceled. Reason:",n),this.stopChecking()}});_class.prototype.__init.call(this);_class.prototype.__init2.call(this);,this.onNoActiveReaderCallback=e,this.streamId=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _8 => _8.streamId]), () => (_uuid.v4.call(void 0, ))),this.onNoActiveReaderCallback=e,this.startChecking(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _9 => _9.intervalCheckInMs]), () => (20)))}__init() {this.checkInterval=null}__init2() {this._isStopped=!1}get hasActiveSubscribers(){return!this._isStopped}startChecking(e){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},e)}stopChecking(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this._isStopped=!0,this.onNoActiveReaderCallback(this))}checkNoActiveReader(){!this.readable.locked&&!this._isStopped&&this.stopChecking()}}, _class);var u=(e,t)=>{if(je(e))return e.equals(t);if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((o,i)=>u(o,t[i]));if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e===t;if(Array.isArray(t))return!1;let n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length||!n.every(o=>a.includes(o)))return!1;for(let o in e)if(!(e[o]instanceof Function&&t[o]instanceof Function)&&!u(e[o],t[o]))return!1;return!0},je=e=>e&&typeof e=="object"&&"equals"in e&&typeof e.equals=="function";var Be=async(e,t)=>t===void 0||t.retries===0?e():_asyncretry2.default.call(void 0, async n=>{try{return await e()}catch(a){throw _optionalChain([t, 'optionalAccess', _10 => _10.shouldRetryError])&&!t.shouldRetryError(a)&&n(a),a}},_nullishCoalesce(t, () => ({retries:0})));var re=e=>e;var Xe=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},P={stringify:(e,t)=>JSON.stringify(_optionalChain([t, 'optionalAccess', _11 => _11.map])?t.map(e):e,(n,a)=>typeof a=="bigint"?a.toString():a),parse:(e,t)=>{let n=JSON.parse(e,_optionalChain([t, 'optionalAccess', _12 => _12.reviver]));if(_optionalChain([t, 'optionalAccess', _13 => _13.typeCheck])&&!_optionalChain([t, 'optionalAccess', _14 => _14.typeCheck, 'call', _15 => _15(n)]))throw new Xe(e);return _optionalChain([t, 'optionalAccess', _16 => _16.map])?t.map(n):n}};var Ve=e=>new g.TransformStream({transform(t,n){e(t)&&n.enqueue(t)}}),Ge=e=>new g.TransformStream({transform(t,n){n.enqueue(e(t))}}),ke=(e,t)=>new ie(e,t),ie=class extends g.TransformStream{constructor(e,t){super({transform:n=>{this.accumulator=this.reducer(this.accumulator,n)},flush:n=>{n.enqueue(this.accumulator),n.terminate()}}),this.accumulator=t,this.reducer=e}},We=(e,t,n={forever:!0,minTimeout:25})=>new g.TransformStream({start(a){Be(()=>qe(e,t,a),n).catch(o=>{a.error(o)})}}),qe=async(e,t,n)=>{let a=e().getReader();try{let o;do{let i=await a.read();o=i.done,await t(i,n),o&&n.terminate()}while(!o)}finally{a.releaseLock()}},ze=e=>new se(e),se= (_class2 =class extends g.TransformStream{__init3() {this.count=0}constructor(e){super({transform:(t,n)=>{this.count++,this.count>this.skip&&n.enqueue(t)}});_class2.prototype.__init3.call(this);,this.skip=e}}, _class2),He=e=>new g.TransformStream({transform(t,n){n.enqueue(t),e(t)&&n.terminate()}}),Ye=e=>new g.TransformStream({async transform(t,n){if(!e(t)){n.enqueue(t);return}await Promise.resolve(),n.terminate()}}),Je=e=>new ce(e),ce= (_class3 =class extends g.TransformStream{__init4() {this.count=0}constructor(e){super({transform:(t,n)=>{this.count<this.limit?(this.count++,n.enqueue(t)):n.terminate()}});_class3.prototype.__init4.call(this);,this.limit=e}}, _class3),Ke=e=>new g.TransformStream({start(t){let n=setTimeout(()=>{t.terminate()},e),a=t.terminate.bind(t);t.terminate=()=>{clearTimeout(n),a()}},transform(t,n){n.enqueue(t)}}),Ze={filter:Ve,take:Je,TakeTransformStream:ce,skip:ze,SkipTransformStream:se,map:Ge,notifyAboutNoActiveReadersStream:$e,NotifyAboutNoActiveReadersStream:oe,reduce:ke,ReduceTransformStream:ie,retry:We,stopAfter:He,stopOn:Ye,waitAtMost:Ke},{retry:Wt}=Ze;var h=class extends Error{constructor(e){super(e)}};var me=e=>{throw new h(_nullishCoalesce(e, () => ("That should not ever happened, right?")))};var le=(e,t,n)=>{if(!u(e,t))throw new h(_nullishCoalesce(n, () => (`subObj:
2
- ${P.stringify(t)}
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3;var _dumbo = require('@event-driven-io/dumbo');var k=t=>typeof t=="number"&&t===t,W=t=>typeof t=="string";var M=t=>typeof t=="function"&&t.prototype&&t.prototype.constructor===t,H=class q extends Error{constructor(e){let n=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:k(e)?e:500,o=e&&typeof e=="object"&&"message"in e?e.message:W(e)?e:`Error with status code '${n}' ocurred during Emmett processing`;super(o),this.errorCode=n,Object.setPrototypeOf(this,q.prototype)}},z=class Y extends H{constructor(e,n,o){super({errorCode:412,message:_nullishCoalesce(o, () => (`Expected version ${n.toString()} does not match current ${_optionalChain([e, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))}),this.current=e,this.expected=n,Object.setPrototypeOf(this,Y.prototype)}};var _uuid = require('uuid');var _webstreamspolyfill = require('web-streams-polyfill');var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);var J=(t,e,n)=>({type:t,data:e,metadata:n});var F="STREAM_EXISTS",U="STREAM_DOES_NOT_EXIST",N="NO_CONCURRENCY_CHECK",Re=(t,e,n)=>e===N?!0:e==U?t===n:e==F?t!==n:t===e,K=(t,e,n)=>{if(e??=N,!Re(t,e,n))throw new $(t,e)},$=class Z extends z{constructor(e,n){super(_optionalChain([e, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]),_optionalChain([n, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()])),Object.setPrototypeOf(this,Z.prototype)}};var De=(t,e={})=>new ee(t,e),ee= (_class =class extends _webstreamspolyfill.TransformStream{constructor(t,e={}){super({cancel:n=>{console.log("Stream was canceled. Reason:",n),this.stopChecking()}});_class.prototype.__init.call(this);_class.prototype.__init2.call(this);,this.onNoActiveReaderCallback=t,this.streamId=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _8 => _8.streamId]), () => (_uuid.v4.call(void 0, ))),this.onNoActiveReaderCallback=t,this.startChecking(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _9 => _9.intervalCheckInMs]), () => (20)))}__init() {this.checkInterval=null}__init2() {this._isStopped=!1}get hasActiveSubscribers(){return!this._isStopped}startChecking(t){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},t)}stopChecking(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this._isStopped=!0,this.onNoActiveReaderCallback(this))}checkNoActiveReader(){!this.readable.locked&&!this._isStopped&&this.stopChecking()}}, _class);var T=(t,e)=>{if(xe(t))return t.equals(e);if(Array.isArray(t))return Array.isArray(e)&&t.length===e.length&&t.every((a,r)=>T(a,e[r]));if(typeof t!="object"||typeof e!="object"||t===null||e===null)return t===e;if(Array.isArray(e))return!1;let n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length||!n.every(a=>o.includes(a)))return!1;for(let a in t){if(t[a]instanceof Function&&e[a]instanceof Function)continue;if(!T(t[a],e[a]))return!1}return!0},xe=t=>t&&typeof t=="object"&&"equals"in t&&typeof t.equals=="function";var Ce=async(t,e)=>e===void 0||e.retries===0?t():_asyncretry2.default.call(void 0, async n=>{try{return await t()}catch(o){throw _optionalChain([e, 'optionalAccess', _10 => _10.shouldRetryError])&&!e.shouldRetryError(o)&&n(o),o}},_nullishCoalesce(e, () => ({retries:0})));var te=t=>t;var be=class extends Error{constructor(t){super(`Cannot parse! ${t}`)}},h={stringify:(t,e)=>JSON.stringify(_optionalChain([e, 'optionalAccess', _11 => _11.map])?e.map(t):t,(n,o)=>typeof o=="bigint"?o.toString():o),parse:(t,e)=>{let n=JSON.parse(t,_optionalChain([e, 'optionalAccess', _12 => _12.reviver]));if(_optionalChain([e, 'optionalAccess', _13 => _13.typeCheck])&&!_optionalChain([e, 'optionalAccess', _14 => _14.typeCheck, 'call', _15 => _15(n)]))throw new be(t);return _optionalChain([e, 'optionalAccess', _16 => _16.map])?e.map(n):n}};var Fe=t=>new (0, _webstreamspolyfill.TransformStream)({transform(e,n){t(e)&&n.enqueue(e)}}),$e=t=>new (0, _webstreamspolyfill.TransformStream)({transform(e,n){n.enqueue(t(e))}}),Qe=(t,e)=>new ne(t,e),ne=class extends _webstreamspolyfill.TransformStream{constructor(t,e){super({transform:n=>{this.accumulator=this.reducer(this.accumulator,n)},flush:n=>{n.enqueue(this.accumulator),n.terminate()}}),this.accumulator=e,this.reducer=t}},Xe=(t,e,n={forever:!0,minTimeout:25})=>new (0, _webstreamspolyfill.TransformStream)({start(o){Ce(()=>Ve(t,e,o),n).catch(a=>{o.error(a)})}}),Ve=async(t,e,n)=>{let a=t().getReader();try{let r;do{let l=await a.read();r=l.done,await e(l,n),r&&n.terminate()}while(!r)}finally{a.releaseLock()}},ke=t=>new oe(t),oe= (_class2 =class extends _webstreamspolyfill.TransformStream{__init3() {this.count=0}constructor(t){super({transform:(e,n)=>{this.count++,this.count>this.skip&&n.enqueue(e)}});_class2.prototype.__init3.call(this);,this.skip=t}}, _class2),He=t=>new (0, _webstreamspolyfill.TransformStream)({transform(e,n){n.enqueue(e),t(e)&&n.terminate()}}),ze=t=>new (0, _webstreamspolyfill.TransformStream)({async transform(e,n){if(!t(e)){n.enqueue(e);return}await Promise.resolve(),n.terminate()}}),Je=t=>new ae(t),ae= (_class3 =class extends _webstreamspolyfill.TransformStream{__init4() {this.count=0}constructor(t){super({transform:(e,n)=>{this.count<this.limit?(this.count++,n.enqueue(e)):n.terminate()}});_class3.prototype.__init4.call(this);,this.limit=t}}, _class3),Ze=t=>new (0, _webstreamspolyfill.TransformStream)({start(e){let n=setTimeout(()=>{e.terminate()},t),o=e.terminate.bind(e);e.terminate=()=>{clearTimeout(n),o()}},transform(e,n){n.enqueue(e)}}),et={filter:Fe,take:Je,TakeTransformStream:ae,skip:ke,SkipTransformStream:oe,map:$e,notifyAboutNoActiveReadersStream:De,NotifyAboutNoActiveReadersStream:ee,reduce:Qe,ReduceTransformStream:ne,retry:Xe,stopAfter:He,stopOn:ze,waitAtMost:Ze},{retry:rn}=et;var y=class extends Error{constructor(t){super(t)}};var re=t=>{throw new y(_nullishCoalesce(t, () => ("That should not ever happened, right?")))};var ie=(t,e,n)=>{if(!T(t,e))throw new y(_nullishCoalesce(n, () => (`subObj:
2
+ ${h.stringify(e)}
3
3
  is not equal to
4
- ${P.stringify(e)}`)))};function T(e,t){if(!e)throw new h(_nullishCoalesce(t, () => ("Condition is false")))}function et(e,t){if(!e)throw new h(_nullishCoalesce(t, () => ("Condition is not truthy")))}function y(e,t,n){if(e!==t)throw new h(`${_nullishCoalesce(n, () => ("Objects are not equal"))}:
5
- Expected: ${P.stringify(e)}
6
- Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoalesce(n, () => (`Objects are equal: ${P.stringify(e)}`)))}function X(e){de(e,null),et(e)}var A=e=>({isEmpty:()=>y(e.length,0),isNotEmpty:()=>de(e.length,0),hasSize:t=>y(e.length,t),containsElements:(...t)=>{T(t.every(n=>t.some(a=>u(n,a))))},containsExactlyInAnyOrder:(...t)=>{y(e.length,t.length),T(e.every(n=>t.some(a=>u(n,a))))},containsExactlyInAnyOrderElementsOf:t=>{y(e.length,t.length),T(e.every(n=>t.some(a=>u(n,a))))},containsExactlyElementsOf:t=>{y(e.length,t.length);for(let n=0;n<e.length;n++)T(u(e[n],t[n]))},containsExactly:t=>{y(e.length,1),T(u(e[0],t))},contains:t=>{T(e.some(n=>u(n,t)))},containsOnlyOnceElementsOf:t=>{T(t.map(n=>e.filter(a=>u(a,n)).length).filter(n=>n===1).length===t.length)},containsAnyOf:(...t)=>{T(e.some(n=>t.some(a=>u(n,a))))},allMatch:t=>{T(e.every(t))},anyMatches:t=>{T(e.some(t))},allMatchAsync:async t=>{for(let n of e)T(await t(n))}});require('pg');var _pongo = require('@event-driven-io/pongo');var L=(e,t)=>{let{pool:n,connectionString:a,inDatabase:o,inCollection:i}=t;return n.withConnection(async p=>{let m=_pongo.pongoClient.call(void 0, a,{connectionOptions:{connection:p}});try{let E=m.db(o).collection(i);return e(E)}finally{await m.close()}})},Ee=e=>{let{_id:t,_version:n,...a}=e;return a},nt=(e,t)=>("_id"in t&&y(t._id,e._id,`Document ids are not matching! Expected: ${t._id}, actual: ${e._id}`),le(Ee(e),Ee(t))),at= exports.documentExists =(e,t)=>n=>L(async a=>{let o=await a.findOne("withId"in t?{_id:t.withId}:t.matchingFilter);X(o),nt(o,e)},{...t,...n}),ot= exports.documentsAreTheSame =(e,t)=>n=>L(async a=>{let o=await a.find("withId"in t?{_id:t.withId}:t.matchingFilter);y(e.length,o.length,"Different Documents Count than expected");for(let i=0;i<e.length;i++)A(o).contains(e[i])},{...t,...n}),rt= exports.documentsMatchingHaveCount =(e,t)=>n=>L(async a=>{let o=await a.find("withId"in t?{_id:t.withId}:t.matchingFilter);y(e,o.length,"Different Documents Count than expected")},{...t,...n}),pe= exports.documentMatchingExists =e=>t=>L(async n=>{let a=await n.find("withId"in e?{_id:e.withId}:e.matchingFilter);A(a).isNotEmpty()},{...e,...t}),ve= exports.documentDoesNotExist =e=>t=>L(async n=>{let a=await n.findOne("withId"in e?{_id:e.withId}:e.matchingFilter);X(a)},{...e,...t}),rn= exports.expectPongoDocuments ={fromCollection:e=>({withId:t=>({toBeEqual:n=>at(n,{withId:t,inCollection:e}),toExist:()=>pe({withId:t,inCollection:e}),notToExist:()=>ve({withId:t,inCollection:e})}),matching:t=>({toBeTheSame:n=>ot(n,{matchingFilter:t,inCollection:e}),toHaveCount:n=>rt(n,{matchingFilter:t,inCollection:e}),toExist:()=>pe({matchingFilter:t,inCollection:e}),notToExist:()=>ve({matchingFilter:t,inCollection:e})})})};var st=({handle:e,canHandle:t})=>V({canHandle:t,handle:async(n,a)=>{let{connectionString:o,client:i}=a,p=_pongo.pongoClient.call(void 0, o,{connectionOptions:{client:i}});await e(n,{...a,pongo:p})}}),ct= exports.pongoMultiStreamProjection =e=>{let{collectionName:t,getDocumentId:n,canHandle:a}=e;return st({handle:async(o,{pongo:i})=>{let p=i.db().collection(t);for(let m of o)await p.handle(n(m),async E=>"initialState"in e?await e.evolve(_nullishCoalesce(E, () => (e.initialState())),m):await e.evolve(E,m))},canHandle:a})},dn= exports.pongoSingleStreamProjection =e=>ct({...e,getDocumentId:t=>t.metadata.streamName});var yn={for:e=>{{let{projection:t,...n}=e,{connectionString:a}=n;return o=>({when:(i,p)=>{let m=[],E=async c=>{let d=0n,l=_nullishCoalesce(_optionalChain([p, 'optionalAccess', _17 => _17.numberOfTimes]), () => (1));for(let v of[...o,...Array.from({length:l}).flatMap(()=>i)])m.push({...v,metadata:{globalPosition:++d,streamPosition:d,streamName:`test-${_uuid.v4.call(void 0, )}`,eventId:_uuid.v4.call(void 0, ),..._nullishCoalesce(v.metadata, () => ({}))}});await c.withTransaction(v=>w({events:m,projections:[t],connection:{connectionString:a,transaction:v}}))};return{then:async(c,d)=>{let l=_dumbo.dumbo.call(void 0, n);try{await E(l);let v=await c({pool:l,connectionString:a});v!==void 0&&v===!1&&me(_nullishCoalesce(d, () => ("Projection specification didn't match the criteria")))}finally{await l.close()}},thenThrows:async(...c)=>{let d=_dumbo.dumbo.call(void 0, n);try{throw await E(d),new h("Handler did not fail as expected")}catch(l){if(l instanceof h)throw l;if(c.length===0)return;if(!U(c[0])){T(c[0](l),`Error didn't match the error condition: ${_optionalChain([l, 'optionalAccess', _18 => _18.toString, 'call', _19 => _19()])}`);return}T(l instanceof c[0],`Caught error is not an instance of the expected type: ${_optionalChain([l, 'optionalAccess', _20 => _20.toString, 'call', _21 => _21()])}`),c[1]&&T(c[1](l),`Error didn't match the error condition: ${_optionalChain([l, 'optionalAccess', _22 => _22.toString, 'call', _23 => _23()])}`)}finally{await d.close()}}}}})}}},mt= exports.eventInStream =(e,t)=>({...t,metadata:{..._nullishCoalesce(t.metadata, () => ({})),streamName:_nullishCoalesce(_optionalChain([t, 'access', _24 => _24.metadata, 'optionalAccess', _25 => _25.streamName]), () => (e))}}),lt= exports.eventsInStream =(e,t)=>t.map(n=>mt(e,n)),fn= exports.newEventsInStream =lt,dt= exports.assertSQLQueryResultMatches =(e,t)=>async({pool:{execute:n}})=>{let a=await n.query(e);A(t).containsExactlyInAnyOrder(...a.rows)},hn= exports.expectSQL ={query:e=>({resultRows:{toBeTheSame:t=>dt(e,t)}})};var w=async e=>{let{projections:t,events:n,connection:{transaction:a,connectionString:o}}=e,i=n.map(E=>E.type),p=t.filter(E=>E.canHandle.some(c=>i.includes(c))),m=await a.connection.open();for(let E of p)await E.handle(n,{connectionString:o,client:m,transaction:a,execute:a.execute})},V= exports.postgreSQLProjection =e=>re(e),Et= exports.postgreSQLRawBatchSQLProjection =(e,...t)=>V({canHandle:t,handle:async(n,a)=>{let o=await e(n,a);await a.execute.batchCommand(o)}}),On= exports.postgreSQLRawSQLProjection =(e,...t)=>Et(async(n,a)=>{let o=[];for(let i of n)o.push(await e(i,a));return o},...t);var C="emt",_= exports.globalTag ="global",R= exports.defaultTag ="emt:default",Dn= exports.globalNames ={module:`${C}:module:${_}`,tenant:`${C}:tenant:${_}`},b={partition:{name:"partition"},isArchived:{name:"is_archived"}},s= exports.streamsTable ={name:`${C}_streams`,columns:{partition:b.partition,isArchived:b.isArchived}},r= exports.eventsTable ={name:`${C}_events`,columns:{partition:b.partition,isArchived:b.isArchived}};var ue=_dumbo.rawSql.call(void 0, `CREATE OR REPLACE FUNCTION emt_append_event(
4
+ ${h.stringify(t)}`)))};function _(t,e){if(!t)throw new y(_nullishCoalesce(e, () => ("Condition is false")))}function tt(t,e){if(!t)throw new y(_nullishCoalesce(e, () => ("Condition is not truthy")))}function S(t,e,n){if(t!==e)throw new y(`${_nullishCoalesce(n, () => ("Objects are not equal"))}:
5
+ Expected: ${h.stringify(t)}
6
+ Actual:${h.stringify(e)}`)}function se(t,e,n){if(t===e)throw new y(_nullishCoalesce(n, () => (`Objects are equal: ${h.stringify(t)}`)))}function j(t){se(t,null),tt(t)}var R=t=>({isEmpty:()=>S(t.length,0),isNotEmpty:()=>se(t.length,0),hasSize:e=>S(t.length,e),containsElements:(...e)=>{_(e.every(n=>e.some(o=>T(n,o))))},containsExactlyInAnyOrder:(...e)=>{S(t.length,e.length),_(t.every(n=>e.some(o=>T(n,o))))},containsExactlyInAnyOrderElementsOf:e=>{S(t.length,e.length),_(t.every(n=>e.some(o=>T(n,o))))},containsExactlyElementsOf:e=>{S(t.length,e.length);for(let n=0;n<t.length;n++)_(T(t[n],e[n]))},containsExactly:e=>{S(t.length,1),_(T(t[0],e))},contains:e=>{_(t.some(n=>T(n,e)))},containsOnlyOnceElementsOf:e=>{_(e.map(n=>t.filter(o=>T(o,n)).length).filter(n=>n===1).length===e.length)},containsAnyOf:(...e)=>{_(t.some(n=>e.some(o=>T(n,o))))},allMatch:e=>{_(t.every(e))},anyMatches:e=>{_(t.some(e))},allMatchAsync:async e=>{for(let n of t)_(await e(n))}});require('pg');var _pongo = require('@event-driven-io/pongo');var A=(t,e)=>{let{pool:n,connectionString:o,inDatabase:a,inCollection:r}=e;return n.withConnection(async l=>{let m=_pongo.pongoClient.call(void 0, o,{connectionOptions:{connection:l}});try{let p=m.db(a).collection(r);return t(p)}finally{await m.close()}})},ce=t=>{let{_id:e,_version:n,...o}=t;return o},ot=(t,e)=>("_id"in e&&S(e._id,t._id,`Document ids are not matching! Expected: ${e._id}, actual: ${t._id}`),ie(ce(t),ce(e))),at= exports.documentExists =(t,e)=>n=>A(async o=>{let a=await o.findOne("withId"in e?{_id:e.withId}:e.matchingFilter);j(a),ot(a,t)},{...e,...n}),rt= exports.documentsAreTheSame =(t,e)=>n=>A(async o=>{let a=await o.find("withId"in e?{_id:e.withId}:e.matchingFilter);S(t.length,a.length,"Different Documents Count than expected");for(let r=0;r<t.length;r++)R(a).contains(t[r])},{...e,...n}),it= exports.documentsMatchingHaveCount =(t,e)=>n=>A(async o=>{let a=await o.find("withId"in e?{_id:e.withId}:e.matchingFilter);S(t,a.length,"Different Documents Count than expected")},{...e,...n}),me= exports.documentMatchingExists =t=>e=>A(async n=>{let o=await n.find("withId"in t?{_id:t.withId}:t.matchingFilter);R(o).isNotEmpty()},{...t,...e}),de= exports.documentDoesNotExist =t=>e=>A(async n=>{let o=await n.findOne("withId"in t?{_id:t.withId}:t.matchingFilter);j(o)},{...t,...e}),gn= exports.expectPongoDocuments ={fromCollection:t=>({withId:e=>({toBeEqual:n=>at(n,{withId:e,inCollection:t}),toExist:()=>me({withId:e,inCollection:t}),notToExist:()=>de({withId:e,inCollection:t})}),matching:e=>({toBeTheSame:n=>rt(n,{matchingFilter:e,inCollection:t}),toHaveCount:n=>it(n,{matchingFilter:e,inCollection:t}),toExist:()=>me({matchingFilter:e,inCollection:t}),notToExist:()=>de({matchingFilter:e,inCollection:t})})})};var ct=({handle:t,canHandle:e})=>Q({canHandle:e,handle:async(n,o)=>{let{connectionString:a,client:r}=o,l=_pongo.pongoClient.call(void 0, a,{connectionOptions:{client:r}});await t(n,{...o,pongo:l})}}),mt= exports.pongoMultiStreamProjection =t=>{let{collectionName:e,getDocumentId:n,canHandle:o}=t;return ct({handle:async(a,{pongo:r})=>{let l=r.db().collection(e);for(let m of a)await l.handle(n(m),async p=>"initialState"in t?await t.evolve(_nullishCoalesce(p, () => (t.initialState())),m):await t.evolve(p,m))},canHandle:o})},Pn= exports.pongoSingleStreamProjection =t=>mt({...t,getDocumentId:e=>e.metadata.streamName});var wn={for:t=>{{let{projection:e,...n}=t,{connectionString:o}=n;return a=>({when:(r,l)=>{let m=[],p=async c=>{let E=0n,d=_nullishCoalesce(_optionalChain([l, 'optionalAccess', _17 => _17.numberOfTimes]), () => (1));for(let v of[...a,...Array.from({length:d}).flatMap(()=>r)])m.push({...v,metadata:{globalPosition:++E,streamPosition:E,streamName:`test-${_uuid.v4.call(void 0, )}`,eventId:_uuid.v4.call(void 0, ),..._nullishCoalesce(v.metadata, () => ({}))}});await c.withTransaction(v=>D({events:m,projections:[e],connection:{connectionString:o,transaction:v}}))};return{then:async(c,E)=>{let d=_dumbo.dumbo.call(void 0, n);try{await p(d);let v=await c({pool:d,connectionString:o});v!==void 0&&v===!1&&re(_nullishCoalesce(E, () => ("Projection specification didn't match the criteria")))}finally{await d.close()}},thenThrows:async(...c)=>{let E=_dumbo.dumbo.call(void 0, n);try{throw await p(E),new y("Handler did not fail as expected")}catch(d){if(d instanceof y)throw d;if(c.length===0)return;if(!M(c[0])){_(c[0](d),`Error didn't match the error condition: ${_optionalChain([d, 'optionalAccess', _18 => _18.toString, 'call', _19 => _19()])}`);return}_(d instanceof c[0],`Caught error is not an instance of the expected type: ${_optionalChain([d, 'optionalAccess', _20 => _20.toString, 'call', _21 => _21()])}`),c[1]&&_(c[1](d),`Error didn't match the error condition: ${_optionalChain([d, 'optionalAccess', _22 => _22.toString, 'call', _23 => _23()])}`)}finally{await E.close()}}}}})}}},dt= exports.eventInStream =(t,e)=>({...e,metadata:{..._nullishCoalesce(e.metadata, () => ({})),streamName:_nullishCoalesce(_optionalChain([e, 'access', _24 => _24.metadata, 'optionalAccess', _25 => _25.streamName]), () => (t))}}),lt= exports.eventsInStream =(t,e)=>e.map(n=>dt(t,n)),Cn= exports.newEventsInStream =lt,Et= exports.assertSQLQueryResultMatches =(t,e)=>async({pool:{execute:n}})=>{let o=await n.query(t);R(e).containsExactlyInAnyOrder(...o.rows)},bn= exports.expectSQL ={query:t=>({resultRows:{toBeTheSame:e=>Et(t,e)}})};var D=async t=>{let{projections:e,events:n,connection:{transaction:o,connectionString:a}}=t,r=n.map(p=>p.type),l=e.filter(p=>p.canHandle.some(c=>r.includes(c))),m=await o.connection.open();for(let p of l)await p.handle(n,{connectionString:a,client:m,transaction:o,execute:o.execute})},Q= exports.postgreSQLProjection =t=>te(t),pt= exports.postgreSQLRawBatchSQLProjection =(t,...e)=>Q({canHandle:e,handle:async(n,o)=>{let a=await t(n,o);await o.execute.batchCommand(a)}}),$n= exports.postgreSQLRawSQLProjection =(t,...e)=>pt(async(n,o)=>{let a=[];for(let r of n)a.push(await t(r,o));return a},...e);var x="emt",u= exports.globalTag ="global",O= exports.defaultTag ="emt:default",Xn= exports.globalNames ={module:`${x}:module:${u}`,tenant:`${x}:tenant:${u}`},w={partition:{name:"partition"},isArchived:{name:"is_archived"}},s= exports.streamsTable ={name:`${x}_streams`,columns:{partition:w.partition,isArchived:w.isArchived}},i= exports.eventsTable ={name:`${x}_events`,columns:{partition:w.partition,isArchived:w.isArchived}};var pe=_dumbo.rawSql.call(void 0, `CREATE OR REPLACE FUNCTION emt_append_event(
7
7
  v_event_ids text[],
8
8
  v_events_data jsonb[],
9
9
  v_events_metadata jsonb[],
@@ -51,7 +51,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
51
51
  ) AS event
52
52
  ),
53
53
  all_events_insert AS (
54
- INSERT INTO ${r.name}
54
+ INSERT INTO ${i.name}
55
55
  (stream_id, stream_position, partition, event_data, event_metadata, event_schema_version, event_type, event_id, transaction_id)
56
56
  SELECT
57
57
  v_stream_id, ev.stream_position, v_partition, ev.event_data, ev.event_metadata, ev.schema_version, ev.event_type, ev.event_id, v_transaction_id
@@ -85,7 +85,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
85
85
  RETURN QUERY SELECT TRUE, v_next_stream_position, v_last_global_position, v_transaction_id;
86
86
  END;
87
87
  $$;
88
- `),ge= exports.appendToStream =(e,t,n,a,o)=>e.withTransaction(async i=>{let{execute:p}=i;if(a.length===0)return{success:!1,result:{success:!1}};let m;try{let v=Tt(_optionalChain([o, 'optionalAccess', _26 => _26.expectedStreamVersion])),I=a.map((N,f)=>({...N,metadata:{streamName:t,eventId:_uuid.v4.call(void 0, ),streamPosition:BigInt(f),...N.metadata}}));m=await gt(p,t,n,I,{expectedStreamVersion:v}),_optionalChain([o, 'optionalAccess', _27 => _27.preCommitHook])&&await o.preCommitHook(I,{transaction:i})}catch(v){if(!ut(v))throw v;m={success:!1,last_global_position:null,next_stream_position:null,transaction_id:null}}let{success:E,next_stream_position:c,last_global_position:d,transaction_id:l}=m;return{success:E,result:E&&c&&d&&l?{success:!0,nextStreamPosition:BigInt(c),lastGlobalPosition:BigInt(d),transactionId:l}:{success:!1}}}),Tt=e=>e===void 0||e===O||e==Q||e==j?null:e,ut=e=>e instanceof Error&&"code"in e&&e.code==="23505",gt=(e,t,n,a,o)=>_dumbo.single.call(void 0, e.command(_dumbo.sql.call(void 0, `SELECT * FROM emt_append_event(
88
+ `),ve= exports.appendToStream =(t,e,n,o,a)=>t.withTransaction(async r=>{let{execute:l}=r;if(o.length===0)return{success:!1,result:{success:!1}};let m;try{let v=Tt(_optionalChain([a, 'optionalAccess', _26 => _26.expectedStreamVersion])),P=o.map((I,f)=>({...I,metadata:{streamName:e,eventId:_uuid.v4.call(void 0, ),streamPosition:BigInt(f),...I.metadata}}));m=await St(l,e,n,P,{expectedStreamVersion:v}),_optionalChain([a, 'optionalAccess', _27 => _27.preCommitHook])&&await a.preCommitHook(P,{transaction:r})}catch(v){if(!gt(v))throw v;m={success:!1,last_global_position:null,next_stream_position:null,transaction_id:null}}let{success:p,next_stream_position:c,last_global_position:E,transaction_id:d}=m;return{success:p,result:p&&c&&E&&d?{success:!0,nextStreamPosition:BigInt(c),lastGlobalPosition:BigInt(E),transactionId:d}:{success:!1}}}),Tt=t=>t===void 0||t===N||t==U||t==F?null:t,gt=t=>t instanceof Error&&"code"in t&&t.code==="23505",St=(t,e,n,o,a)=>_dumbo.single.call(void 0, t.command(_dumbo.sql.call(void 0, `SELECT * FROM emt_append_event(
89
89
  ARRAY[%s]::text[],
90
90
  ARRAY[%s]::jsonb[],
91
91
  ARRAY[%s]::jsonb[],
@@ -95,22 +95,22 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
95
95
  %L::text,
96
96
  %s::bigint,
97
97
  %L::text
98
- )`,a.map(i=>_dumbo.sql.call(void 0, "%L",i.metadata.eventId)).join(","),a.map(i=>_dumbo.sql.call(void 0, "%L",P.stringify(i.data))).join(","),a.map(i=>_dumbo.sql.call(void 0, "%L",P.stringify(_nullishCoalesce(i.metadata, () => ({}))))).join(","),a.map(()=>"'1'").join(","),a.map(i=>_dumbo.sql.call(void 0, "%L",i.type)).join(","),t,n,_nullishCoalesce(_optionalChain([o, 'optionalAccess', _28 => _28.expectedStreamVersion]), () => ("NULL")),_nullishCoalesce(_optionalChain([o, 'optionalAccess', _29 => _29.partition]), () => (R)))));var Se=_dumbo.rawSql.call(void 0, `CREATE TABLE IF NOT EXISTS ${s.name}(
98
+ )`,o.map(r=>_dumbo.sql.call(void 0, "%L",r.metadata.eventId)).join(","),o.map(r=>_dumbo.sql.call(void 0, "%L",h.stringify(r.data))).join(","),o.map(r=>_dumbo.sql.call(void 0, "%L",h.stringify(_nullishCoalesce(r.metadata, () => ({}))))).join(","),o.map(()=>"'1'").join(","),o.map(r=>_dumbo.sql.call(void 0, "%L",r.type)).join(","),e,n,_nullishCoalesce(_optionalChain([a, 'optionalAccess', _28 => _28.expectedStreamVersion]), () => ("NULL")),_nullishCoalesce(_optionalChain([a, 'optionalAccess', _29 => _29.partition]), () => (O)))));var ue=_dumbo.rawSql.call(void 0, `CREATE TABLE IF NOT EXISTS ${s.name}(
99
99
  stream_id TEXT NOT NULL,
100
100
  stream_position BIGINT NOT NULL,
101
- partition TEXT NOT NULL DEFAULT '${_}__${_}',
101
+ partition TEXT NOT NULL DEFAULT '${u}__${u}',
102
102
  stream_type TEXT NOT NULL,
103
103
  stream_metadata JSONB NOT NULL,
104
104
  is_archived BOOLEAN NOT NULL DEFAULT FALSE,
105
105
  PRIMARY KEY (stream_id, stream_position, partition, is_archived),
106
106
  UNIQUE (stream_id, partition, is_archived)
107
- ) PARTITION BY LIST (partition);`),ye= exports.eventsTableSQL =_dumbo.rawSql.call(void 0, `
107
+ ) PARTITION BY LIST (partition);`),_e= exports.eventsTableSQL =_dumbo.rawSql.call(void 0, `
108
108
  CREATE SEQUENCE IF NOT EXISTS emt_global_event_position;
109
109
 
110
- CREATE TABLE IF NOT EXISTS ${r.name}(
110
+ CREATE TABLE IF NOT EXISTS ${i.name}(
111
111
  stream_id TEXT NOT NULL,
112
112
  stream_position BIGINT NOT NULL,
113
- partition TEXT NOT NULL DEFAULT '${_}',
113
+ partition TEXT NOT NULL DEFAULT '${u}',
114
114
  event_data JSONB NOT NULL,
115
115
  event_metadata JSONB NOT NULL,
116
116
  event_schema_version TEXT NOT NULL,
@@ -121,7 +121,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
121
121
  transaction_id XID8 NOT NULL,
122
122
  created TIMESTAMPTZ NOT NULL DEFAULT now(),
123
123
  PRIMARY KEY (stream_id, stream_position, partition, is_archived)
124
- ) PARTITION BY LIST (partition);`),fe= exports.subscriptionsTableSQL =_dumbo.rawSql.call(void 0, `
124
+ ) PARTITION BY LIST (partition);`),Te= exports.subscriptionsTableSQL =_dumbo.rawSql.call(void 0, `
125
125
  CREATE TABLE IF NOT EXISTS emt_subscriptions(
126
126
  subscription_id TEXT NOT NULL PRIMARY KEY,
127
127
  version INT NOT NULL DEFAULT 1,
@@ -130,11 +130,11 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
130
130
  last_processed_position BIGINT NOT NULL,
131
131
  last_processed_transaction_id BIGINT NOT NULL
132
132
  );
133
- `),he= exports.sanitizeNameSQL =_dumbo.rawSql.call(void 0, `CREATE OR REPLACE FUNCTION emt_sanitize_name(input_name TEXT) RETURNS TEXT AS $$
133
+ `),ge= exports.sanitizeNameSQL =_dumbo.rawSql.call(void 0, `CREATE OR REPLACE FUNCTION emt_sanitize_name(input_name TEXT) RETURNS TEXT AS $$
134
134
  BEGIN
135
135
  RETURN REGEXP_REPLACE(input_name, '[^a-zA-Z0-9_]', '_', 'g');
136
136
  END;
137
- $$ LANGUAGE plpgsql;`),Pe= exports.addTablePartitions =_dumbo.rawSql.call(void 0, `
137
+ $$ LANGUAGE plpgsql;`),Se= exports.addTablePartitions =_dumbo.rawSql.call(void 0, `
138
138
  CREATE OR REPLACE FUNCTION emt_add_table_partition(tableName TEXT, partition_name TEXT) RETURNS void AS $$
139
139
  DECLARE
140
140
  v_main_partiton_name TEXT;
@@ -171,74 +171,74 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
171
171
  v_archived_partiton_name, v_main_partiton_name
172
172
  );
173
173
  END;
174
- $$ LANGUAGE plpgsql;`),Ie= exports.addEventsPartitions =_dumbo.rawSql.call(void 0, `
174
+ $$ LANGUAGE plpgsql;`),fe= exports.addEventsPartitions =_dumbo.rawSql.call(void 0, `
175
175
  CREATE OR REPLACE FUNCTION emt_add_partition(partition_name TEXT) RETURNS void AS $$
176
176
  BEGIN
177
- PERFORM emt_add_table_partition('${r.name}', partition_name);
177
+ PERFORM emt_add_table_partition('${i.name}', partition_name);
178
178
  PERFORM emt_add_table_partition('${s.name}', partition_name);
179
179
  END;
180
- $$ LANGUAGE plpgsql;`),Ne= exports.addModuleSQL =_dumbo.rawSql.call(void 0, `
180
+ $$ LANGUAGE plpgsql;`),ye= exports.addModuleSQL =_dumbo.rawSql.call(void 0, `
181
181
  CREATE OR REPLACE FUNCTION add_module(new_module TEXT) RETURNS void AS $$
182
182
  BEGIN
183
- -- For ${r.name} table
183
+ -- For ${i.name} table
184
184
  EXECUTE format('
185
185
  CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
186
186
  FOR VALUES IN (emt_sanitize_name(%L || ''__'' || %L)) PARTITION BY LIST (is_archived);',
187
- emt_sanitize_name('${r.name}_' || new_module || '__' || '${_}'), '${r.name}', new_module, '${_}'
187
+ emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}'), '${i.name}', new_module, '${u}'
188
188
  );
189
189
 
190
190
  EXECUTE format('
191
191
  CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
192
192
  FOR VALUES IN (FALSE);',
193
- emt_sanitize_name('${r.name}_' || new_module || '__' || '${_}' || '_active'), emt_sanitize_name('${r.name}_' || new_module || '__' || '${_}')
193
+ emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}' || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}')
194
194
  );
195
195
 
196
196
  EXECUTE format('
197
197
  CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
198
198
  FOR VALUES IN (TRUE);',
199
- emt_sanitize_name('${r.name}_' || new_module || '__' || '${_}' || '_archived'), emt_sanitize_name('${r.name}_' || new_module || '__' || '${_}')
199
+ emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}' || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}')
200
200
  );
201
201
 
202
202
  -- For ${s.name} table
203
203
  EXECUTE format('
204
204
  CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
205
205
  FOR VALUES IN (emt_sanitize_name(%L || ''__'' || %L)) PARTITION BY LIST (is_archived);',
206
- emt_sanitize_name('${s.name}_' || new_module || '__' || '${_}'), '${s.name}', new_module, '${_}'
206
+ emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}'), '${s.name}', new_module, '${u}'
207
207
  );
208
208
 
209
209
  EXECUTE format('
210
210
  CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
211
211
  FOR VALUES IN (FALSE);',
212
- emt_sanitize_name('${s.name}_' || new_module || '__' || '${_}' || '_active'), emt_sanitize_name('${s.name}_' || new_module || '__' || '${_}')
212
+ emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}' || '_active'), emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}')
213
213
  );
214
214
 
215
215
  EXECUTE format('
216
216
  CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
217
217
  FOR VALUES IN (TRUE);',
218
- emt_sanitize_name('${s.name}_' || new_module || '__' || '${_}' || '_archived'), emt_sanitize_name('${s.name}_' || new_module || '__' || '${_}')
218
+ emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}' || '_archived'), emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}')
219
219
  );
220
220
  END;
221
221
  $$ LANGUAGE plpgsql;
222
- `),Oe= exports.addTenantSQL =_dumbo.rawSql.call(void 0, `
222
+ `),he= exports.addTenantSQL =_dumbo.rawSql.call(void 0, `
223
223
  CREATE OR REPLACE FUNCTION add_tenant(new_module TEXT, new_tenant TEXT) RETURNS void AS $$
224
224
  BEGIN
225
- -- For ${r.name} table
225
+ -- For ${i.name} table
226
226
  EXECUTE format('
227
227
  CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
228
228
  FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
229
- emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant), '${r.name}', new_module, new_tenant
229
+ emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant), '${i.name}', new_module, new_tenant
230
230
  );
231
231
 
232
232
  EXECUTE format('
233
233
  CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
234
234
  FOR VALUES IN (FALSE);',
235
- emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant || '_active'), emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant)
235
+ emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant)
236
236
  );
237
237
 
238
238
  EXECUTE format('
239
239
  CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
240
240
  FOR VALUES IN (TRUE);',
241
- emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant || '_archived'), emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant)
241
+ emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant)
242
242
  );
243
243
 
244
244
  -- For ${s.name} table
@@ -261,32 +261,32 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
261
261
  );
262
262
  END;
263
263
  $$ LANGUAGE plpgsql;
264
- `),Re= exports.addModuleForAllTenantsSQL =_dumbo.rawSql.call(void 0, `
264
+ `),Pe= exports.addModuleForAllTenantsSQL =_dumbo.rawSql.call(void 0, `
265
265
  CREATE OR REPLACE FUNCTION add_module_for_all_tenants(new_module TEXT) RETURNS void AS $$
266
266
  DECLARE
267
267
  tenant_record RECORD;
268
268
  BEGIN
269
269
  PERFORM add_module(new_module);
270
270
 
271
- FOR tenant_record IN SELECT DISTINCT tenant FROM ${r.name}
271
+ FOR tenant_record IN SELECT DISTINCT tenant FROM ${i.name}
272
272
  LOOP
273
- -- For ${r.name} table
273
+ -- For ${i.name} table
274
274
  EXECUTE format('
275
275
  CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
276
276
  FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
277
- emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant), '${r.name}', new_module, tenant_record.tenant
277
+ emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant), '${i.name}', new_module, tenant_record.tenant
278
278
  );
279
279
 
280
280
  EXECUTE format('
281
281
  CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
282
282
  FOR VALUES IN (FALSE);',
283
- emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant || '_active'), emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant)
283
+ emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant)
284
284
  );
285
285
 
286
286
  EXECUTE format('
287
287
  CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
288
288
  FOR VALUES IN (TRUE);',
289
- emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant || '_archived'), emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant)
289
+ emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant)
290
290
  );
291
291
 
292
292
  -- For ${s.name} table
@@ -310,30 +310,30 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
310
310
  END LOOP;
311
311
  END;
312
312
  $$ LANGUAGE plpgsql;
313
- `),Ae= exports.addTenantForAllModulesSQL =_dumbo.rawSql.call(void 0, `
313
+ `),Ie= exports.addTenantForAllModulesSQL =_dumbo.rawSql.call(void 0, `
314
314
  CREATE OR REPLACE FUNCTION add_tenant_for_all_modules(new_tenant TEXT) RETURNS void AS $$
315
315
  DECLARE
316
316
  module_record RECORD;
317
317
  BEGIN
318
- FOR module_record IN SELECT DISTINCT partitionname FROM pg_partman.part_config WHERE parent_table = '${r.name}'
318
+ FOR module_record IN SELECT DISTINCT partitionname FROM pg_partman.part_config WHERE parent_table = '${i.name}'
319
319
  LOOP
320
- -- For ${r.name} table
320
+ -- For ${i.name} table
321
321
  EXECUTE format('
322
322
  CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
323
323
  FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
324
- emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant), '${r.name}', module_record.partitionname, new_tenant
324
+ emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant), '${i.name}', module_record.partitionname, new_tenant
325
325
  );
326
326
 
327
327
  EXECUTE format('
328
328
  CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
329
329
  FOR VALUES IN (FALSE);',
330
- emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant || '_active'), emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant)
330
+ emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant || '_active'), emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant)
331
331
  );
332
332
 
333
333
  EXECUTE format('
334
334
  CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
335
335
  FOR VALUES IN (TRUE);',
336
- emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant || '_archived'), emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant)
336
+ emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant || '_archived'), emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant)
337
337
  );
338
338
 
339
339
  -- For ${s.name} table
@@ -357,7 +357,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
357
357
  END LOOP;
358
358
  END;
359
359
  $$ LANGUAGE plpgsql;
360
- `),Le= exports.addDefaultPartition =_dumbo.rawSql.call(void 0, `SELECT emt_add_partition('${R}');`);var De=async(e,t,n)=>{let a=n&&"from"in n?`AND stream_position >= ${n.from}`:"",o=Number(n&&"to"in n?n.to:n&&"maxCount"in n&&n.maxCount?n.from+n.maxCount:NaN),i=isNaN(o)?"":`AND stream_position <= ${o}`,p=await _dumbo.mapRows.call(void 0, e.query(_dumbo.sql.call(void 0, `SELECT stream_id, stream_position, global_position, event_data, event_metadata, event_schema_version, event_type, event_id
361
- FROM ${r.name}
362
- WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${a} ${i}`,t,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _30 => _30.partition]), () => (R)))),m=>{let E=$(m.event_type,m.event_data,m.event_metadata);return{...E,metadata:{...E.metadata,eventId:m.event_id,streamName:t,streamPosition:BigInt(m.stream_position),globalPosition:BigInt(m.global_position)}}});return p.length>0?{currentStreamVersion:p[p.length-1].metadata.streamPosition,events:p,streamExists:!0}:{currentStreamVersion:G,events:[],streamExists:!1}};var M=[Se,ye,fe,he,Pe,Ie,Ne,Oe,Re,Ae,ue,Le],k= exports.createEventStoreSchema =async e=>{await e.withTransaction(({execute:t})=>t.batchCommand(M))};var ht={projections:[],schema:{autoMigration:"CreateOrUpdate"}},G= exports.PostgreSQLEventStoreDefaultStreamVersion =0n,Pt= exports.getPostgreSQLEventStore =(e,t=ht)=>{let n={connectionString:e,...t.connectionOptions?t.connectionOptions:{}},a="dumbo"in n?n.dumbo:_dumbo.dumbo.call(void 0, n),o,i=_optionalChain([t, 'access', _31 => _31.schema, 'optionalAccess', _32 => _32.autoMigration])===void 0||_optionalChain([t, 'access', _33 => _33.schema, 'optionalAccess', _34 => _34.autoMigration])!=="None",p=()=>i?(o||(o=k(a)),o):Promise.resolve(),m=(_nullishCoalesce(t.projections, () => ([]))).filter(({type:c})=>c==="inline").map(({projection:c})=>c),E=m.length>0?(c,{transaction:d})=>w({projections:m,connection:{connectionString:e,transaction:d},events:c}):void 0;return{schema:{sql:()=>M.join(""),print:()=>console.log(M.join("")),migrate:async()=>{await(o=k(a))}},async aggregateStream(c,d){let{evolve:l,initialState:v,read:I}=d,N=_optionalChain([I, 'optionalAccess', _35 => _35.expectedStreamVersion]),f=v(),F=await this.readStream(c,d.read),W=F.currentStreamVersion;ne(W,N,G);for(let q of F.events)q&&(f=l(f,q));return{currentStreamVersion:W,state:f,streamExists:F.streamExists}},readStream:async(c,d)=>(await p(),De(a.execute,c,d)),appendToStream:async(c,d,l)=>{await p();let[v,...I]=c.split("-"),N=v&&I.length>0?v:"emt:unknown",f=await ge(a,c,N,d,{...l,preCommitHook:E});if(!f.success)throw new B(-1n,_nullishCoalesce(_optionalChain([l, 'optionalAccess', _36 => _36.expectedStreamVersion]), () => (O)));return{nextExpectedStreamVersion:f.nextStreamPosition,createdNewStream:f.nextStreamPosition>=BigInt(d.length)}},close:()=>a.close(),async withSession(c){return await a.withConnection(async d=>{let l={...t,connectionOptions:{connection:d}},v=Pt(e,l);return c({eventStore:v,close:()=>Promise.resolve()})})}}};exports.PostgreSQLEventStoreDefaultStreamVersion = G; exports.PostgreSQLProjectionSpec = yn; exports.addDefaultPartition = Le; exports.addEventsPartitions = Ie; exports.addModuleForAllTenantsSQL = Re; exports.addModuleSQL = Ne; exports.addTablePartitions = Pe; exports.addTenantForAllModulesSQL = Ae; exports.addTenantSQL = Oe; exports.appendEventsSQL = ue; exports.appendToStream = ge; exports.assertSQLQueryResultMatches = dt; exports.createEventStoreSchema = k; exports.defaultPostgreSQLOptions = ht; exports.defaultTag = R; exports.documentDoesNotExist = ve; exports.documentExists = at; exports.documentMatchingExists = pe; exports.documentsAreTheSame = ot; exports.documentsMatchingHaveCount = rt; exports.emmettPrefix = C; exports.eventInStream = mt; exports.eventsInStream = lt; exports.eventsTable = r; exports.eventsTableSQL = ye; exports.expectPongoDocuments = rn; exports.expectSQL = hn; exports.getPostgreSQLEventStore = Pt; exports.globalNames = Dn; exports.globalTag = _; exports.handleProjections = w; exports.newEventsInStream = fn; exports.pongoMultiStreamProjection = ct; exports.pongoProjection = st; exports.pongoSingleStreamProjection = dn; exports.postgreSQLProjection = V; exports.postgreSQLRawBatchSQLProjection = Et; exports.postgreSQLRawSQLProjection = On; exports.readStream = De; exports.sanitizeNameSQL = he; exports.schemaSQL = M; exports.streamsTable = s; exports.streamsTableSQL = Se; exports.subscriptionsTableSQL = fe;
360
+ `),Ne= exports.addDefaultPartition =_dumbo.rawSql.call(void 0, `SELECT emt_add_partition('${O}');`);var Oe=async(t,e,n)=>{let o=n&&"from"in n?`AND stream_position >= ${n.from}`:"",a=Number(n&&"to"in n?n.to:n&&"maxCount"in n&&n.maxCount?n.from+n.maxCount:NaN),r=isNaN(a)?"":`AND stream_position <= ${a}`,l=await _dumbo.mapRows.call(void 0, t.query(_dumbo.sql.call(void 0, `SELECT stream_id, stream_position, global_position, event_data, event_metadata, event_schema_version, event_type, event_id
361
+ FROM ${i.name}
362
+ WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${o} ${r}`,e,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _30 => _30.partition]), () => (O)))),m=>{let p=J(m.event_type,m.event_data,m.event_metadata);return{...p,metadata:{...p.metadata,eventId:m.event_id,streamName:e,streamPosition:BigInt(m.stream_position),globalPosition:BigInt(m.global_position)}}});return l.length>0?{currentStreamVersion:l[l.length-1].metadata.streamPosition,events:l,streamExists:!0}:{currentStreamVersion:B,events:[],streamExists:!1}};var C=[ue,_e,Te,ge,Se,fe,ye,he,Pe,Ie,pe,Ne],X= exports.createEventStoreSchema =async t=>{await t.withTransaction(({execute:e})=>e.batchCommand(C))};var Pt={projections:[],schema:{autoMigration:"CreateOrUpdate"}},B= exports.PostgreSQLEventStoreDefaultStreamVersion =0n,It= exports.getPostgreSQLEventStore =(t,e=Pt)=>{let n={connectionString:t,...e.connectionOptions?e.connectionOptions:{}},o="dumbo"in n?n.dumbo:_dumbo.dumbo.call(void 0, n),a,r=_optionalChain([e, 'access', _31 => _31.schema, 'optionalAccess', _32 => _32.autoMigration])===void 0||_optionalChain([e, 'access', _33 => _33.schema, 'optionalAccess', _34 => _34.autoMigration])!=="None",l=()=>r?(a||(a=X(o)),a):Promise.resolve(),m=(_nullishCoalesce(e.projections, () => ([]))).filter(({type:c})=>c==="inline").map(({projection:c})=>c),p=m.length>0?(c,{transaction:E})=>D({projections:m,connection:{connectionString:t,transaction:E},events:c}):void 0;return{schema:{sql:()=>C.join(""),print:()=>console.log(C.join("")),migrate:async()=>{await(a=X(o))}},async aggregateStream(c,E){let{evolve:d,initialState:v,read:P}=E,I=_optionalChain([P, 'optionalAccess', _35 => _35.expectedStreamVersion]),f=v(),b=await this.readStream(c,E.read),V=b.currentStreamVersion;K(V,I,B);for(let G of b.events)G&&(f=d(f,G));return{currentStreamVersion:V,state:f,streamExists:b.streamExists}},readStream:async(c,E)=>(await l(),Oe(o.execute,c,E)),appendToStream:async(c,E,d)=>{await l();let[v,...P]=c.split("-"),I=v&&P.length>0?v:"emt:unknown",f=await ve(o,c,I,E,{...d,preCommitHook:p});if(!f.success)throw new $(-1n,_nullishCoalesce(_optionalChain([d, 'optionalAccess', _36 => _36.expectedStreamVersion]), () => (N)));return{nextExpectedStreamVersion:f.nextStreamPosition,createdNewStream:f.nextStreamPosition>=BigInt(E.length)}},close:()=>o.close(),async withSession(c){return await o.withConnection(async E=>{let d={...e,connectionOptions:{connection:E}},v=It(t,d);return c({eventStore:v,close:()=>Promise.resolve()})})}}};exports.PostgreSQLEventStoreDefaultStreamVersion = B; exports.PostgreSQLProjectionSpec = wn; exports.addDefaultPartition = Ne; exports.addEventsPartitions = fe; exports.addModuleForAllTenantsSQL = Pe; exports.addModuleSQL = ye; exports.addTablePartitions = Se; exports.addTenantForAllModulesSQL = Ie; exports.addTenantSQL = he; exports.appendEventsSQL = pe; exports.appendToStream = ve; exports.assertSQLQueryResultMatches = Et; exports.createEventStoreSchema = X; exports.defaultPostgreSQLOptions = Pt; exports.defaultTag = O; exports.documentDoesNotExist = de; exports.documentExists = at; exports.documentMatchingExists = me; exports.documentsAreTheSame = rt; exports.documentsMatchingHaveCount = it; exports.emmettPrefix = x; exports.eventInStream = dt; exports.eventsInStream = lt; exports.eventsTable = i; exports.eventsTableSQL = _e; exports.expectPongoDocuments = gn; exports.expectSQL = bn; exports.getPostgreSQLEventStore = It; exports.globalNames = Xn; exports.globalTag = u; exports.handleProjections = D; exports.newEventsInStream = Cn; exports.pongoMultiStreamProjection = mt; exports.pongoProjection = ct; exports.pongoSingleStreamProjection = Pn; exports.postgreSQLProjection = Q; exports.postgreSQLRawBatchSQLProjection = pt; exports.postgreSQLRawSQLProjection = $n; exports.readStream = Oe; exports.sanitizeNameSQL = ge; exports.schemaSQL = C; exports.streamsTable = s; exports.streamsTableSQL = ue; exports.subscriptionsTableSQL = Te;
363
363
  //# sourceMappingURL=index.cjs.map