@event-driven-io/emmett 0.20.1-alpha.4 → 0.20.1
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/chunk-CJZAVRMT.cjs +2 -0
- package/dist/chunk-CJZAVRMT.cjs.map +1 -0
- package/dist/cli.cjs +6 -6
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +13 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +12 -12
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 d=(n=>(n.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",n.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",n.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",n))(d||{}),i= exports.e =t=>typeof t=="number"&&t===t,m= exports.f =t=>typeof t=="string",f= exports.g =t=>{if(!m(t)||t.length===0)throw new r("NOT_A_NONEMPTY_STRING");return t},E= exports.h =t=>{if(!i(t)||t<=0)throw new r("NOT_A_POSITIVE_NUMBER");return t},N= exports.i =t=>{let e=BigInt(t);if(e<0)throw new r("NOT_AN_UNSIGNED_BIGINT");return e};var C=t=>typeof t=="function"&&t.prototype&&t.prototype.constructor===t,o= exports.k =class t extends Error{constructor(e){let s=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:i(e)?e:500,n=e&&typeof e=="object"&&"message"in e?e.message:m(e)?e:`Error with status code '${s}' ocurred during Emmett processing`;super(n),this.errorCode=s,Object.setPrototypeOf(this,t.prototype)}},g= exports.l =class t extends o{constructor(s,n,a){super({errorCode:412,message:_nullishCoalesce(a, () => (`Expected version ${n.toString()} does not match current ${_optionalChain([s, 'optionalAccess', _ => _.toString, 'call', _2 => _2()])}`))});this.current=s;this.expected=n;Object.setPrototypeOf(this,t.prototype)}},r= exports.m =class t extends o{constructor(e){super({errorCode:400,message:_nullishCoalesce(e, () => ("Validation Error ocurred during Emmett processing"))}),Object.setPrototypeOf(this,t.prototype)}},p= exports.n =class t extends o{constructor(e){super({errorCode:403,message:_nullishCoalesce(e, () => ("Illegal State ocurred during Emmett processing"))}),Object.setPrototypeOf(this,t.prototype)}},u= exports.o =class t extends o{constructor(e){super({errorCode:404,message:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _3 => _3.message]), () => ((_optionalChain([e, 'optionalAccess', _4 => _4.id])?e.type?`${e.type} with ${e.id} was not found during Emmett processing`:`State with ${e.id} was not found during Emmett processing`:_optionalChain([e, 'optionalAccess', _5 => _5.type])?`${e.type} was not found during Emmett processing`:"State was not found during Emmett processing")))}),Object.setPrototypeOf(this,t.prototype)}};var w=t=>new Intl.DateTimeFormat("en-CA",{timeZone:"UTC",year:"numeric",month:"2-digit",day:"2-digit"}).format(t),c= exports.b =t=>/^\d{4}-\d{2}-\d{2}$/.test(t),I= exports.c =t=>{let e=new Date(t+"T00:00:00Z");if(!c(t))throw new r("Invalid date format, must be yyyy-mm-dd");if(isNaN(e.getTime()))throw new r("Invalid date format");return e};require('commander');var S=t=>t!==void 0&&(typeof t=="string"||"name"in t&&t.name!==void 0&&typeof t.name=="string");exports.a = w; exports.b = c; exports.c = I; exports.d = d; exports.e = i; exports.f = m; exports.g = f; exports.h = E; exports.i = N; exports.j = C; exports.k = o; exports.l = g; exports.m = r; exports.n = p; exports.o = u; exports.p = S;
|
|
2
|
+
//# sourceMappingURL=chunk-CJZAVRMT.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/validation/index.ts","../src/errors/index.ts"],"names":["ValidationErrors","isNumber","val","isString","assertNotEmptyString","value","ValidationError","assertPositiveNumber","assertUnsignedBigInt","number","isErrorConstructor","expect","EmmettError","_EmmettError","options","errorCode","message","ConcurrencyError","_ConcurrencyError","current","expected"],"mappings":"AAEO,qrBAAWA,CAAAA,CAAAA,CAAAA,CAAAA,EAAAA,CAChBA,CAAAA,CAAA,qBAAA,CAAwB,uBAAA,CACxBA,CAAAA,CAAA,qBAAA,CAAwB,uBAAA,CACxBA,CAAAA,CAAA,sBAAA,CAAyB,wBAAA,CAHTA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,EAAA,CAAA,CAAA,CAAA,CAMLC,CAAAA,aAAYC,CAAAA,EACvB,OAAOA,CAAAA,EAAQ,QAAA,EAAYA,CAAAA,GAAQA,CAAAA,CAExBC,CAAAA,aAAYD,CAAAA,EACvB,OAAOA,CAAAA,EAAQ,QAAA,CAEJE,CAAAA,aAAwBC,CAAAA,EAA2B,CAC9D,EAAA,CAAI,CAACF,CAAAA,CAASE,CAAK,CAAA,EAAKA,CAAAA,CAAM,MAAA,GAAW,CAAA,CACvC,MAAM,IAAIC,CAAAA,CAAgB,uBAAsC,CAAA,CAElE,OAAOD,CACT,CAAA,CAEaE,CAAAA,aAAwBF,CAAAA,EAA2B,CAC9D,EAAA,CAAI,CAACJ,CAAAA,CAASI,CAAK,CAAA,EAAKA,CAAAA,EAAS,CAAA,CAC/B,MAAM,IAAIC,CAAAA,CAAgB,uBAAsC,CAAA,CAElE,OAAOD,CACT,CAAA,CAEaG,CAAAA,aAAwBH,CAAAA,EAA0B,CAC7D,IAAMI,CAAAA,CAAS,MAAA,CAAOJ,CAAK,CAAA,CAC3B,EAAA,CAAII,CAAAA,CAAS,CAAA,CACX,MAAM,IAAIH,CAAAA,CAAgB,wBAAuC,CAAA,CAEnE,OAAOG,CACT,CAAA,CC3BO,IAAMC,CAAAA,CAEXC,CAAAA,EAIE,OAAOA,CAAAA,EAAW,UAAA,EAClBA,CAAAA,CAAO,SAAA,EAEPA,CAAAA,CAAO,SAAA,CAAU,WAAA,GAAgBA,CAAAA,CAIxBC,CAAAA,aAAN,MAAMC,EAAAA,QAAoB,KAAM,CAC9B,WAEP,CACEC,CAAAA,CACA,CACA,IAAMC,CAAAA,CACJD,CAAAA,EAAW,OAAOA,CAAAA,EAAY,QAAA,EAAY,WAAA,GAAeA,CAAAA,CACrDA,CAAAA,CAAQ,SAAA,CACRb,CAAAA,CAASa,CAAO,CAAA,CACdA,CAAAA,CACA,GAAA,CACFE,CAAAA,CACJF,CAAAA,EAAW,OAAOA,CAAAA,EAAY,QAAA,EAAY,SAAA,GAAaA,CAAAA,CACnDA,CAAAA,CAAQ,OAAA,CACRX,CAAAA,CAASW,CAAO,CAAA,CACdA,CAAAA,CACA,CAAA,wBAAA,EAA2BC,CAAS,CAAA,kCAAA,CAAA,CAE5C,KAAA,CAAMC,CAAO,CAAA,CACb,IAAA,CAAK,SAAA,CAAYD,CAAAA,CAGjB,MAAA,CAAO,cAAA,CAAe,IAAA,CAAMF,CAAAA,CAAY,SAAS,CACnD,CACF,CAAA,CAEaI,CAAAA,aAAN,MAAMC,EAAAA,QAAyBN,CAAY,CAChD,WAAA,CACSO,CAAAA,CACAC,CAAAA,CACPJ,CAAAA,CACA,CACA,KAAA,CAAM,CACJ,SAAA,CAAW,GAAA,CACX,OAAA,kBACEA,CAAAA,SACA,CAAA,iBAAA,EAAoBI,CAAAA,CAAS,QAAA,CAAS,CAAC,CAAA,wBAAA,kBAA2BD,CAAAA,2BAAS,QAAA,mBAAS,GAAC,CAAA,GAAA","file":"/home/runner/work/emmett/emmett/src/packages/emmett/dist/chunk-CJZAVRMT.cjs","sourcesContent":["import { ValidationError } from '../errors';\n\nexport const enum ValidationErrors {\n NOT_A_NONEMPTY_STRING = 'NOT_A_NONEMPTY_STRING',\n NOT_A_POSITIVE_NUMBER = 'NOT_A_POSITIVE_NUMBER',\n NOT_AN_UNSIGNED_BIGINT = 'NOT_AN_UNSIGNED_BIGINT',\n}\n\nexport const isNumber = (val: unknown): val is number =>\n typeof val === 'number' && val === val;\n\nexport const isString = (val: unknown): val is string =>\n typeof val === 'string';\n\nexport const assertNotEmptyString = (value: unknown): string => {\n if (!isString(value) || value.length === 0) {\n throw new ValidationError(ValidationErrors.NOT_A_NONEMPTY_STRING);\n }\n return value;\n};\n\nexport const assertPositiveNumber = (value: unknown): number => {\n if (!isNumber(value) || value <= 0) {\n throw new ValidationError(ValidationErrors.NOT_A_POSITIVE_NUMBER);\n }\n return value;\n};\n\nexport const assertUnsignedBigInt = (value: string): bigint => {\n const number = BigInt(value);\n if (number < 0) {\n throw new ValidationError(ValidationErrors.NOT_AN_UNSIGNED_BIGINT);\n }\n return number;\n};\n\nexport * from './dates';\n","import { isNumber, isString } from '../validation';\n\nexport type ErrorConstructor<ErrorType extends Error> = new (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: any[]\n) => ErrorType;\n\nexport const isErrorConstructor = <ErrorType extends Error>(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n expect: Function,\n): expect is ErrorConstructor<ErrorType> => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return (\n typeof expect === 'function' &&\n expect.prototype &&\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n expect.prototype.constructor === expect\n );\n};\n\nexport class EmmettError extends Error {\n public errorCode: number;\n\n constructor(\n options?: { errorCode: number; message?: string } | string | number,\n ) {\n const errorCode =\n options && typeof options === 'object' && 'errorCode' in options\n ? options.errorCode\n : isNumber(options)\n ? options\n : 500;\n const message =\n options && typeof options === 'object' && 'message' in options\n ? options.message\n : isString(options)\n ? options\n : `Error with status code '${errorCode}' ocurred during Emmett processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, EmmettError.prototype);\n }\n}\n\nexport class ConcurrencyError extends EmmettError {\n constructor(\n public current: string | undefined,\n public expected: string,\n message?: string,\n ) {\n super({\n errorCode: 412,\n message:\n message ??\n `Expected version ${expected.toString()} does not match current ${current?.toString()}`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n\nexport class ValidationError extends EmmettError {\n constructor(message?: string) {\n super({\n errorCode: 400,\n message: message ?? `Validation Error ocurred during Emmett processing`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class IllegalStateError extends EmmettError {\n constructor(message?: string) {\n super({\n errorCode: 403,\n message: message ?? `Illegal State ocurred during Emmett processing`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, IllegalStateError.prototype);\n }\n}\n\nexport class NotFoundError extends EmmettError {\n constructor(options?: { id: string; type: string; message?: string }) {\n super({\n errorCode: 404,\n message:\n options?.message ??\n (options?.id\n ? options.type\n ? `${options.type} with ${options.id} was not found during Emmett processing`\n : `State with ${options.id} was not found during Emmett processing`\n : options?.type\n ? `${options.type} was not found during Emmett processing`\n : 'State was not found during Emmett processing'),\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n"]}
|
package/dist/cli.cjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";
|
|
2
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } 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 _chunkCJZAVRMTcjs = require('./chunk-CJZAVRMT.cjs');var _commander = require('commander');var _fs = require('fs');var _process = require('process');var s=(e=["emmett-expressjs"])=>`
|
|
3
3
|
export default {
|
|
4
|
-
plugins: ${
|
|
5
|
-
${
|
|
4
|
+
plugins: ${e.length>0?`[
|
|
5
|
+
${e.map(t=>`"${t}"`).join(`,
|
|
6
6
|
`)}
|
|
7
7
|
]`:"[]"},
|
|
8
8
|
};
|
|
9
|
-
`,
|
|
9
|
+
`,h= exports.generateConfigFile =(e,n)=>{try{_fs.writeFileSync.call(void 0, e,s(n),"utf8"),console.log(`Configuration file stored at: ${e}`)}catch(t){console.error(`Error: Couldn't store config file: ${e}!`),console.error(t),process.exit(1)}},C= exports.configCommand =new (0, _commander.Command)("config").description("Manage Pongo configuration");C.command("sample").description("Generate or print sample configuration").option("-plg, --plugins <name>","Specify the plugin name",(e,n)=>n.concat([e]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(e=>{let n=e.plugin.length>0?e.plugin:["@event-driven-io/emmett-expressjs"];!("print"in e)&&!("generate"in e)&&(console.error(`Error: Please provide either:
|
|
10
10
|
--print param to print sample config or
|
|
11
|
-
--generate to generate sample config file`),(0,
|
|
11
|
+
--generate to generate sample config file`),_process.exit.call(void 0, 1)),"print"in e?console.log(`${s(n)}`):"generate"in e&&(e.file||(console.error("Error: You need to provide a config file through a --file"),_process.exit.call(void 0, 1)),h(e.file,n))});var _path = require('path'); var _path2 = _interopRequireDefault(_path);var m={missingDefaultExport:`Error: Config should contain default export, e.g.
|
|
12
12
|
|
|
13
13
|
${s()}`,missingPluginsPropertyExport:`Error: Config should contain default export with plugins array, e.g.
|
|
14
14
|
|
|
15
|
-
${s()}`,wrongPluginStructure:"Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }"},
|
|
15
|
+
${s()}`,wrongPluginStructure:"Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }"},y= exports.importPluginsConfig =async e=>{let n=_path2.default.join(process.cwd(),_nullishCoalesce(_optionalChain([e, 'optionalAccess', _ => _.configPath]), () => ("./dist/emmett.config.js")));console.log("IMPORTING"+n);try{let t=await Promise.resolve().then(() => _interopRequireWildcard(require(n)));return t.default?!t.default.plugins||!Array.isArray(t.default.plugins)?new (0, _chunkCJZAVRMTcjs.k)(m.missingPluginsPropertyExport):t.default.plugins.every(_chunkCJZAVRMTcjs.p)?{plugins:t.default.plugins}:new (0, _chunkCJZAVRMTcjs.k)(m.wrongPluginStructure):new (0, _chunkCJZAVRMTcjs.k)(m.missingDefaultExport)}catch(t){return _optionalChain([e, 'optionalAccess', _2 => _2.configPath])?new (0, _chunkCJZAVRMTcjs.k)("Error: Couldn't load file:"+t.toString()):(console.warn("Didn`t find config file: "+n,t),{plugins:[]})}},u= exports.loadPlugins =async e=>{try{let n=await y({configPath:_optionalChain([e, 'optionalAccess', _3 => _3.configPath])});if(n instanceof _chunkCJZAVRMTcjs.k)throw n;if(n.plugins.length===0)return console.log(`No extensions specified in config ${_optionalChain([e, 'optionalAccess', _4 => _4.configPath])}.`),[];let i=x(n.plugins,_optionalChain([e, 'optionalAccess', _5 => _5.pluginType])).map(async r=>{let l=w(r,_optionalChain([e, 'optionalAccess', _6 => _6.pluginType]));try{let a=await Promise.resolve().then(() => _interopRequireWildcard(require(l)));if(console.info(`Loaded plugin: ${l}`),!a.default)throw new Error(`Plugin: ${l} is missing default export`);return a.default}catch(a){console.error(`Failed to load extension "${l}":`,a);return}});return(await Promise.all(i)).filter(r=>r!==void 0)}catch(n){return console.error(`Failed to load config ${_optionalChain([e, 'optionalAccess', _7 => _7.configPath])}:`,n),[]}},p= exports.registerCliPlugins =async(e,n)=>{let t=[];for(let i of n){let r=i.name;"registerCommands"in i||console.warn(`No registerCommands function found in ${r}`),await i.registerCommands(e),console.log(`Loaded extension: ${i.name}`),t.push(i)}},x=(e,n)=>e.filter(t=>typeof t=="string"||n&&(t.register===void 0||t.register.some(i=>i.pluginType===n))),w=(e,n)=>{if(typeof e=="string")return n?`${e}/${n}`:e;let t=_nullishCoalesce(_optionalChain([e, 'access', _8 => _8.register, 'access', _9 => _9.find, 'call', _10 => _10(i=>n&&i.pluginType===n), 'optionalAccess', _11 => _11.path]), () => (n));return t?`${e.name}/${t}`:e.name};var g=new _commander.Command;g.name("emmett").description("CLI tool for Emmett").option("--config <path>","Path to the configuration file");var v=async()=>{let e=process.argv.indexOf("--config"),n=e!==-1&&process.argv.length>e+1?process.argv[e+1]:void 0;try{let t=await u({pluginType:"cli",configPath:n});await p(g,t),g.parse(process.argv)}catch(t){console.error(`Failed to load config from ${n}:`,t)}};v().catch(e=>{console.error("CLI initialization failed:"),console.error(e)});var Y=g;exports.configCommand = C; exports.default = Y; exports.generateConfigFile = h; exports.importPluginsConfig = y; exports.loadPlugins = u; exports.registerCliPlugins = p; exports.sampleConfig = s;
|
|
16
16
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/commandLine/config.ts","../src/commandLine/plugins.ts","../src/config/plugins/index.ts","../src/validation/index.ts","../src/errors/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option('--config <path>', 'Path to the configuration file');\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const configIndex = process.argv.indexOf('--config');\n\n const configPath =\n configIndex !== -1 && process.argv.length > configIndex + 1\n ? process.argv[configIndex + 1]\n : undefined;\n\n try {\n const plugins = await loadPlugins({\n pluginType: 'cli',\n configPath: configPath,\n });\n await registerCliPlugins(program, plugins);\n\n // Parse the CLI arguments\n program.parse(process.argv);\n } catch (err) {\n console.error(`Failed to load config from ${configPath}:`, err);\n }\n};\n\n//Initialize CLI and handle errors\ninitCLI().catch((err) => {\n console.error(`CLI initialization failed:`);\n console.error(err);\n});\n\nexport default program;\nexport * from './commandLine';\n","import { Command as CliCommand } from 'commander';\n// eslint-disable-next-line no-restricted-imports\nimport { writeFileSync } from 'node:fs';\nimport { exit } from 'process';\n\nexport const sampleConfig = (plugins: string[] = ['emmett-expressjs']) => {\n const pluginsNames =\n plugins.length > 0\n ? `[\\n${plugins.map((p) => `\"${p}\"`).join(',\\n')} \\n]`\n : '[]';\n\n return `\nexport default {\n plugins: ${pluginsNames},\n};\n`;\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n 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 configCommand = new CliCommand('config').description(\n 'Manage Pongo configuration',\n);\n\ntype SampleConfigOptions =\n | {\n plugin: string[];\n print?: boolean;\n }\n | {\n plugin: string[];\n generate?: boolean;\n file?: string;\n };\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-plg, --plugins <name>',\n 'Specify the plugin name',\n (value: string, previous: string[]) => {\n // Accumulate plugins 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 plugins =\n options.plugin.length > 0\n ? options.plugin\n : ['@event-driven-io/emmett-expressjs'];\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 exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(plugins)}`);\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 exit(1);\n }\n\n generateConfigFile(options.file, plugins);\n }\n });\n","import { Command as CliCommand } from 'commander';\nimport path from 'path';\nimport {\n isPluginConfig,\n type EmmettCliPlugin,\n type EmmettPlugin,\n type EmmettPluginConfig,\n type EmmettPluginsConfig,\n type EmmettPluginType,\n} from '../config';\nimport { EmmettError } from '../errors';\nimport { sampleConfig } from './config';\n\nconst PluginsConfigImportError = {\n missingDefaultExport: `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`,\n missingPluginsPropertyExport: `Error: Config should contain default export with plugins array, e.g.\\n\\n${sampleConfig()}`,\n wrongPluginStructure: `Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }`,\n};\nexport const importPluginsConfig = async (options?: {\n configPath?: string | undefined;\n}): Promise<EmmettPluginsConfig | EmmettError> => {\n const configPath = path.join(\n process.cwd(),\n options?.configPath ?? './dist/emmett.config.js',\n );\n\n console.log('IMPORTING' + configPath);\n\n try {\n const imported = (await import(configPath)) as {\n default: Partial<EmmettPluginsConfig>;\n };\n\n if (!imported.default) {\n return new EmmettError(PluginsConfigImportError.missingDefaultExport);\n }\n\n if (!imported.default.plugins || !Array.isArray(imported.default.plugins)) {\n return new EmmettError(\n PluginsConfigImportError.missingPluginsPropertyExport,\n );\n }\n\n if (!imported.default.plugins.every(isPluginConfig)) {\n return new EmmettError(PluginsConfigImportError.wrongPluginStructure);\n }\n\n return { plugins: imported.default.plugins };\n } catch (error) {\n if (!options?.configPath) {\n console.warn('Didn`t find config file: ' + configPath, error);\n return { plugins: [] };\n }\n return new EmmettError(\n `Error: Couldn't load file:` + (error as Error).toString(),\n );\n }\n};\n\nexport const loadPlugins = async (options?: {\n pluginType?: EmmettPluginType;\n configPath?: string;\n}): Promise<EmmettPlugin[]> => {\n try {\n const pluginsConfig = await importPluginsConfig({\n configPath: options?.configPath,\n });\n\n if (pluginsConfig instanceof EmmettError) throw pluginsConfig;\n\n if (pluginsConfig.plugins.length === 0) {\n console.log(`No extensions specified in config ${options?.configPath}.`);\n return [];\n }\n\n const pluginsToLoad = filterPluginsByType(\n pluginsConfig.plugins,\n options?.pluginType,\n );\n\n const pluginsPromises = pluginsToLoad.map(async (pluginConfig) => {\n const importPath = getImportPath(pluginConfig, options?.pluginType);\n try {\n const plugin = (await import(importPath)) as { default: EmmettPlugin };\n\n console.info(`Loaded plugin: ${importPath}`);\n\n if (!plugin.default) {\n throw new Error(`Plugin: ${importPath} is missing default export`);\n }\n\n return plugin.default;\n } catch (error) {\n console.error(`Failed to load extension \"${importPath}\":`, error);\n return undefined;\n }\n });\n\n return (await Promise.all(pluginsPromises)).filter(\n (plugin) => plugin !== undefined,\n );\n } catch (error) {\n console.error(`Failed to load config ${options?.configPath}:`, error);\n return [];\n }\n};\n\nexport const registerCliPlugins = async (\n program: CliCommand,\n plugins: EmmettCliPlugin[],\n): Promise<void> => {\n const result: EmmettCliPlugin[] = [];\n\n for (const plugin of plugins) {\n const pluginName = plugin.name;\n\n if (!('registerCommands' in plugin)) {\n console.warn(`No registerCommands function found in ${pluginName}`);\n }\n await plugin.registerCommands(program);\n console.log(`Loaded extension: ${plugin.name}`);\n result.push(plugin);\n }\n};\n\nconst filterPluginsByType = (\n plugins: EmmettPluginConfig[],\n pluginType?: EmmettPluginType,\n): EmmettPluginConfig[] =>\n plugins.filter(\n (p) =>\n typeof p === 'string' ||\n (pluginType &&\n (p.register === undefined ||\n p.register.some((r) => r.pluginType === pluginType))),\n );\n\nconst getImportPath = (\n pluginConfig: EmmettPluginConfig,\n pluginType: EmmettPluginType | undefined,\n) => {\n if (typeof pluginConfig === 'string') {\n return pluginType ? `${pluginConfig}/${pluginType}` : pluginConfig;\n }\n\n const pluginSubpath =\n pluginConfig.register.find((r) => pluginType && r.pluginType === pluginType)\n ?.path ?? pluginType;\n\n return pluginSubpath\n ? `${pluginConfig.name}/${pluginSubpath}`\n : pluginConfig.name;\n};\n","import { Command as CliCommand } from 'commander';\n\nexport type EmmettPluginConfig =\n | {\n name: string;\n register: EmmettPluginRegistration[];\n }\n | string;\n\nexport type EmmettPluginType = 'cli';\n\nexport type EmmettCliPluginRegistration = { pluginType: 'cli'; path?: string };\n\nexport type EmmettPluginRegistration = EmmettCliPluginRegistration;\n\nexport type EmmettCliPlugin = {\n pluginType: 'cli';\n name: string;\n registerCommands: (program: CliCommand) => Promise<void> | void;\n};\n\nexport type EmmettPlugin = EmmettCliPlugin;\n\nexport const isPluginConfig = (\n plugin: Partial<EmmettPluginConfig> | string | undefined,\n): plugin is EmmettPluginConfig =>\n plugin !== undefined &&\n (typeof plugin === 'string' ||\n ('name' in plugin &&\n plugin.name !== undefined &&\n typeof plugin.name === 'string'));\n","import { ValidationError } from '../errors';\n\nexport const enum ValidationErrors {\n NOT_A_NONEMPTY_STRING = 'NOT_A_NONEMPTY_STRING',\n NOT_A_POSITIVE_NUMBER = 'NOT_A_POSITIVE_NUMBER',\n NOT_AN_UNSIGNED_BIGINT = 'NOT_AN_UNSIGNED_BIGINT',\n}\n\nexport const isNumber = (val: unknown): val is number =>\n typeof val === 'number' && val === val;\n\nexport const isString = (val: unknown): val is string =>\n typeof val === 'string';\n\nexport const assertNotEmptyString = (value: unknown): string => {\n if (!isString(value) || value.length === 0) {\n throw new ValidationError(ValidationErrors.NOT_A_NONEMPTY_STRING);\n }\n return value;\n};\n\nexport const assertPositiveNumber = (value: unknown): number => {\n if (!isNumber(value) || value <= 0) {\n throw new ValidationError(ValidationErrors.NOT_A_POSITIVE_NUMBER);\n }\n return value;\n};\n\nexport const assertUnsignedBigInt = (value: string): bigint => {\n const number = BigInt(value);\n if (number < 0) {\n throw new ValidationError(ValidationErrors.NOT_AN_UNSIGNED_BIGINT);\n }\n return number;\n};\n\nexport * from './dates';\n","import { isNumber, isString } from '../validation';\n\nexport type ErrorConstructor<ErrorType extends Error> = new (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: any[]\n) => ErrorType;\n\nexport const isErrorConstructor = <ErrorType extends Error>(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n expect: Function,\n): expect is ErrorConstructor<ErrorType> => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return (\n typeof expect === 'function' &&\n expect.prototype &&\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n expect.prototype.constructor === expect\n );\n};\n\nexport class EmmettError extends Error {\n public errorCode: number;\n\n constructor(\n options?: { errorCode: number; message?: string } | string | number,\n ) {\n const errorCode =\n options && typeof options === 'object' && 'errorCode' in options\n ? options.errorCode\n : isNumber(options)\n ? options\n : 500;\n const message =\n options && typeof options === 'object' && 'message' in options\n ? options.message\n : isString(options)\n ? options\n : `Error with status code '${errorCode}' ocurred during Emmett processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, EmmettError.prototype);\n }\n}\n\nexport class ConcurrencyError extends EmmettError {\n constructor(\n public current: string | undefined,\n public expected: string,\n message?: string,\n ) {\n super({\n errorCode: 412,\n message:\n message ??\n `Expected version ${expected.toString()} does not match current ${current?.toString()}`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n\nexport class ValidationError extends EmmettError {\n constructor(message?: string) {\n super({\n errorCode: 400,\n message: message ?? `Validation Error ocurred during Emmett processing`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class IllegalStateError extends EmmettError {\n constructor(message?: string) {\n super({\n errorCode: 403,\n message: message ?? `Illegal State ocurred during Emmett processing`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, IllegalStateError.prototype);\n }\n}\n\nexport class NotFoundError extends EmmettError {\n constructor(options?: { id: string; type: string; message?: string }) {\n super({\n errorCode: 404,\n message:\n options?.message ??\n (options?.id\n ? options.type\n ? `${options.type} with ${options.id} was not found during Emmett processing`\n : `State with ${options.id} was not found during Emmett processing`\n : options?.type\n ? `${options.type} was not found during Emmett processing`\n : 'State was not found during Emmett processing'),\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n"],"mappings":"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","names":["cli_exports","__export","configCommand","cli_default","generateConfigFile","importPluginsConfig","loadPlugins","registerCliPlugins","sampleConfig","__toCommonJS","import_commander","import_commander","import_node_fs","import_process","sampleConfig","plugins","p","generateConfigFile","configPath","collectionNames","error","configCommand","CliCommand","value","previous","options","import_commander","import_path","import_commander","isPluginConfig","plugin","isNumber","val","isString","EmmettError","_EmmettError","options","errorCode","isNumber","message","isString","PluginsConfigImportError","sampleConfig","importPluginsConfig","options","configPath","path","imported","EmmettError","isPluginConfig","error","loadPlugins","pluginsConfig","pluginsPromises","filterPluginsByType","pluginConfig","importPath","getImportPath","plugin","registerCliPlugins","program","plugins","result","pluginName","pluginType","p","r","pluginSubpath","program","initCLI","configIndex","configPath","plugins","loadPlugins","registerCliPlugins","err","cli_default"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/emmett/emmett/src/packages/emmett/dist/cli.cjs","../src/cli.ts","../src/commandLine/config.ts","../src/commandLine/plugins.ts"],"names":["sampleConfig","plugins","p","generateConfigFile","configPath","collectionNames","writeFileSync"],"mappings":"AAAA;AACA,2lCAA+C,sCCAvB,wBCCM,kCACT,IAERA,CAAAA,CAAe,CAACC,CAAAA,CAAoB,CAAC,kBAAkB,CAAA,CAAA,EAM3D,CAAA;AAAA;AAAA,WAAA,EAJLA,CAAAA,CAAQ,MAAA,CAAS,CAAA,CACb,CAAA;AAAA,EAAMA,CAAAA,CAAQ,GAAA,CAAKC,CAAAA,EAAM,CAAA,CAAA,EAAIA,CAAC,CAAA,CAAA,CAAG,CAAA,CAAE,IAAA,CAAK,CAAA;AAAA,CAAK,CAAC,CAAA;AAAA,CAAA,CAAA,CAC9C,IAIiB,CAAA;AAAA;AAAA,CAAA,CAKZC,CAAAA,8BAAqB,CAChCC,CAAAA,CACAC,CAAAA,CAAAA,EACS,CACT,GAAI,CACFC,+BAAAA,CAAcF,CAAYJ,CAAAA,CAAaK,CAAe,CAAA,CAAG,MAAM,CAAA,CAC/D,OAAA,CAAQ,GAAA,CAAI,CAAA,8BAAA,EAAiCD,CAAU,CAAA,CAAA;AAiDnD;AAMiC,yCAAA;ACjEjB;AACQ;AAAA;AACR","file":"/home/runner/work/emmett/emmett/src/packages/emmett/dist/cli.cjs","sourcesContent":[null,"#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option('--config <path>', 'Path to the configuration file');\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const configIndex = process.argv.indexOf('--config');\n\n const configPath =\n configIndex !== -1 && process.argv.length > configIndex + 1\n ? process.argv[configIndex + 1]\n : undefined;\n\n try {\n const plugins = await loadPlugins({\n pluginType: 'cli',\n configPath: configPath,\n });\n await registerCliPlugins(program, plugins);\n\n // Parse the CLI arguments\n program.parse(process.argv);\n } catch (err) {\n console.error(`Failed to load config from ${configPath}:`, err);\n }\n};\n\n//Initialize CLI and handle errors\ninitCLI().catch((err) => {\n console.error(`CLI initialization failed:`);\n console.error(err);\n});\n\nexport default program;\nexport * from './commandLine';\n","import { Command as CliCommand } from 'commander';\n// eslint-disable-next-line no-restricted-imports\nimport { writeFileSync } from 'node:fs';\nimport { exit } from 'process';\n\nexport const sampleConfig = (plugins: string[] = ['emmett-expressjs']) => {\n const pluginsNames =\n plugins.length > 0\n ? `[\\n${plugins.map((p) => `\"${p}\"`).join(',\\n')} \\n]`\n : '[]';\n\n return `\nexport default {\n plugins: ${pluginsNames},\n};\n`;\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n 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 configCommand = new CliCommand('config').description(\n 'Manage Pongo configuration',\n);\n\ntype SampleConfigOptions =\n | {\n plugin: string[];\n print?: boolean;\n }\n | {\n plugin: string[];\n generate?: boolean;\n file?: string;\n };\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-plg, --plugins <name>',\n 'Specify the plugin name',\n (value: string, previous: string[]) => {\n // Accumulate plugins 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 plugins =\n options.plugin.length > 0\n ? options.plugin\n : ['@event-driven-io/emmett-expressjs'];\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 exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(plugins)}`);\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 exit(1);\n }\n\n generateConfigFile(options.file, plugins);\n }\n });\n","import { Command as CliCommand } from 'commander';\nimport path from 'path';\nimport {\n isPluginConfig,\n type EmmettCliPlugin,\n type EmmettPlugin,\n type EmmettPluginConfig,\n type EmmettPluginsConfig,\n type EmmettPluginType,\n} from '../config';\nimport { EmmettError } from '../errors';\nimport { sampleConfig } from './config';\n\nconst PluginsConfigImportError = {\n missingDefaultExport: `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`,\n missingPluginsPropertyExport: `Error: Config should contain default export with plugins array, e.g.\\n\\n${sampleConfig()}`,\n wrongPluginStructure: `Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }`,\n};\nexport const importPluginsConfig = async (options?: {\n configPath?: string | undefined;\n}): Promise<EmmettPluginsConfig | EmmettError> => {\n const configPath = path.join(\n process.cwd(),\n options?.configPath ?? './dist/emmett.config.js',\n );\n\n console.log('IMPORTING' + configPath);\n\n try {\n const imported = (await import(configPath)) as {\n default: Partial<EmmettPluginsConfig>;\n };\n\n if (!imported.default) {\n return new EmmettError(PluginsConfigImportError.missingDefaultExport);\n }\n\n if (!imported.default.plugins || !Array.isArray(imported.default.plugins)) {\n return new EmmettError(\n PluginsConfigImportError.missingPluginsPropertyExport,\n );\n }\n\n if (!imported.default.plugins.every(isPluginConfig)) {\n return new EmmettError(PluginsConfigImportError.wrongPluginStructure);\n }\n\n return { plugins: imported.default.plugins };\n } catch (error) {\n if (!options?.configPath) {\n console.warn('Didn`t find config file: ' + configPath, error);\n return { plugins: [] };\n }\n return new EmmettError(\n `Error: Couldn't load file:` + (error as Error).toString(),\n );\n }\n};\n\nexport const loadPlugins = async (options?: {\n pluginType?: EmmettPluginType;\n configPath?: string;\n}): Promise<EmmettPlugin[]> => {\n try {\n const pluginsConfig = await importPluginsConfig({\n configPath: options?.configPath,\n });\n\n if (pluginsConfig instanceof EmmettError) throw pluginsConfig;\n\n if (pluginsConfig.plugins.length === 0) {\n console.log(`No extensions specified in config ${options?.configPath}.`);\n return [];\n }\n\n const pluginsToLoad = filterPluginsByType(\n pluginsConfig.plugins,\n options?.pluginType,\n );\n\n const pluginsPromises = pluginsToLoad.map(async (pluginConfig) => {\n const importPath = getImportPath(pluginConfig, options?.pluginType);\n try {\n const plugin = (await import(importPath)) as { default: EmmettPlugin };\n\n console.info(`Loaded plugin: ${importPath}`);\n\n if (!plugin.default) {\n throw new Error(`Plugin: ${importPath} is missing default export`);\n }\n\n return plugin.default;\n } catch (error) {\n console.error(`Failed to load extension \"${importPath}\":`, error);\n return undefined;\n }\n });\n\n return (await Promise.all(pluginsPromises)).filter(\n (plugin) => plugin !== undefined,\n );\n } catch (error) {\n console.error(`Failed to load config ${options?.configPath}:`, error);\n return [];\n }\n};\n\nexport const registerCliPlugins = async (\n program: CliCommand,\n plugins: EmmettCliPlugin[],\n): Promise<void> => {\n const result: EmmettCliPlugin[] = [];\n\n for (const plugin of plugins) {\n const pluginName = plugin.name;\n\n if (!('registerCommands' in plugin)) {\n console.warn(`No registerCommands function found in ${pluginName}`);\n }\n await plugin.registerCommands(program);\n console.log(`Loaded extension: ${plugin.name}`);\n result.push(plugin);\n }\n};\n\nconst filterPluginsByType = (\n plugins: EmmettPluginConfig[],\n pluginType?: EmmettPluginType,\n): EmmettPluginConfig[] =>\n plugins.filter(\n (p) =>\n typeof p === 'string' ||\n (pluginType &&\n (p.register === undefined ||\n p.register.some((r) => r.pluginType === pluginType))),\n );\n\nconst getImportPath = (\n pluginConfig: EmmettPluginConfig,\n pluginType: EmmettPluginType | undefined,\n) => {\n if (typeof pluginConfig === 'string') {\n return pluginType ? `${pluginConfig}/${pluginType}` : pluginConfig;\n }\n\n const pluginSubpath =\n pluginConfig.register.find((r) => pluginType && r.pluginType === pluginType)\n ?.path ?? pluginType;\n\n return pluginSubpath\n ? `${pluginConfig.name}/${pluginSubpath}`\n : pluginConfig.name;\n};\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";var ze=Object.create;var N=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.getPrototypeOf,rt=Object.prototype.hasOwnProperty;var nt=(e,t)=>{for(var r in t)N(e,r,{get:t[r],enumerable:!0})},ue=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of et(t))!rt.call(e,o)&&o!==r&&N(e,o,{get:()=>t[o],enumerable:!(n=Qe(t,o))||n.enumerable});return e};var ot=(e,t,r)=>(r=e!=null?ze(tt(e)):{},ue(t||!e||!e.__esModule?N(r,"default",{value:e,enumerable:!0}):r,e)),at=e=>ue(N({},"__esModule",{value:!0}),e);var er={};nt(er,{AssertionError:()=>p,BinaryJsonDecoder:()=>O,CaughtUpTransformStream:()=>U,CommandHandler:()=>ie,CommandHandlerStreamVersionConflictRetryOptions:()=>se,CompositeDecoder:()=>Y,ConcurrencyError:()=>h,DeciderCommandHandler:()=>wt,DeciderSpecification:()=>zt,DefaultDecoder:()=>x,EmmettError:()=>f,ExpectedVersionConflictError:()=>C,GlobalStreamCaughtUpType:()=>H,IllegalStateError:()=>Q,InMemoryEventStoreDefaultStreamVersion:()=>S,JSONParser:()=>c,JsonDecoder:()=>P,NO_CONCURRENCY_CHECK:()=>R,NoRetries:()=>ae,NotFoundError:()=>ee,ObjectDecoder:()=>M,ParseError:()=>B,STREAM_DOES_NOT_EXIST:()=>G,STREAM_EXISTS:()=>Ee,StreamingCoordinator:()=>oe,StringDecoder:()=>w,ValidationError:()=>u,ValidationErrors:()=>ye,WrapEventStore:()=>Qt,accept:()=>ft,argMatches:()=>Xt,argValue:()=>Kt,assertDeepEqual:()=>Ke,assertEqual:()=>y,assertExpectedVersionMatchesCurrent:()=>W,assertFails:()=>Gt,assertFalse:()=>Xe,assertIsNotNull:()=>Yt,assertIsNull:()=>Jt,assertMatches:()=>pe,assertNotDeepEqual:()=>Bt,assertNotEmptyString:()=>xt,assertNotEqual:()=>ce,assertOk:()=>J,assertPositiveNumber:()=>gt,assertRejects:()=>qt,assertThat:()=>$t,assertThatArray:()=>Zt,assertThrows:()=>Ut,assertThrowsAsync:()=>Wt,assertTrue:()=>s,assertUnsignedBigInt:()=>ht,asyncProjections:()=>Oe,asyncRetry:()=>D,canCreateEventStoreSession:()=>X,caughtUpEventFrom:()=>yt,collect:()=>At,command:()=>st,complete:()=>ct,concatUint8Arrays:()=>$,deepEquals:()=>d,error:()=>ut,event:()=>Z,formatDateToUtcYYYYMMDD:()=>vt,getInMemoryEventStore:()=>Ct,getInMemoryMessageBus:()=>Mt,globalStreamCaughtUp:()=>j,ignore:()=>lt,inlineProjections:()=>De,isEquatable:()=>Re,isErrorConstructor:()=>te,isExpectedVersionConflictError:()=>re,isGlobalStreamCaughtUp:()=>z,isNotInternalEvent:()=>Tt,isNumber:()=>_,isPluginConfig:()=>Pt,isString:()=>F,isSubscriptionEvent:()=>Et,isSubset:()=>de,isValidYYYYMMDD:()=>fe,matchesExpectedVersion:()=>Te,merge:()=>bt,nulloSessionFactory:()=>L,parseDateFromUtcYYYYMMDD:()=>St,projection:()=>Vt,projections:()=>kt,publish:()=>dt,reply:()=>it,restream:()=>jt,schedule:()=>pt,send:()=>mt,streamGenerators:()=>It,streamTrackingGlobalPosition:()=>ne,streamTransformations:()=>me,sum:()=>Rt,verifyThat:()=>Lt});module.exports=at(er);var X=e=>"withSession"in e,L=e=>({withSession:t=>t({eventStore:e,close:()=>Promise.resolve()})});var st=(e,t,r)=>({type:e,data:t,metadata:r});var Z=(e,t,r)=>({type:e,data:t,metadata:r});var it=e=>({kind:"Reply",message:e}),mt=e=>({kind:"Send",message:e}),dt=e=>({kind:"Publish",message:e}),pt=(e,t)=>({kind:"Schedule",message:e,when:t}),ct=()=>({kind:"Complete"}),lt=e=>({kind:"Ignore",reason:e}),ut=e=>({kind:"Error",reason:e}),ft=()=>({kind:"Accept"});var H="__emt:GlobalStreamCaughtUp",z=e=>e.type===H,yt=e=>t=>t.type===H&&t.metadata?.globalPosition>=e,j=e=>Z(H,e,{globalPosition:e.globalPosition}),Et=e=>z(e),Tt=e=>!z(e);var vt=e=>new Intl.DateTimeFormat("en-CA",{timeZone:"UTC",year:"numeric",month:"2-digit",day:"2-digit"}).format(e),fe=e=>/^\d{4}-\d{2}-\d{2}$/.test(e),St=e=>{let t=new Date(e+"T00:00:00Z");if(!fe(e))throw new u("Invalid date format, must be yyyy-mm-dd");if(isNaN(t.getTime()))throw new u("Invalid date format");return t};var ye=(n=>(n.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",n.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",n.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",n))(ye||{}),_=e=>typeof e=="number"&&e===e,F=e=>typeof e=="string",xt=e=>{if(!F(e)||e.length===0)throw new u("NOT_A_NONEMPTY_STRING");return e},gt=e=>{if(!_(e)||e<=0)throw new u("NOT_A_POSITIVE_NUMBER");return e},ht=e=>{let t=BigInt(e);if(t<0)throw new u("NOT_AN_UNSIGNED_BIGINT");return t};var te=e=>typeof e=="function"&&e.prototype&&e.prototype.constructor===e,f=class e extends Error{errorCode;constructor(t){let r=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:_(t)?t:500,n=t&&typeof t=="object"&&"message"in t?t.message:F(t)?t:`Error with status code '${r}' ocurred during Emmett processing`;super(n),this.errorCode=r,Object.setPrototypeOf(this,e.prototype)}},h=class e extends f{constructor(r,n,o){super({errorCode:412,message:o??`Expected version ${n.toString()} does not match current ${r?.toString()}`});this.current=r;this.expected=n;Object.setPrototypeOf(this,e.prototype)}},u=class e extends f{constructor(t){super({errorCode:400,message:t??"Validation Error ocurred during Emmett processing"}),Object.setPrototypeOf(this,e.prototype)}},Q=class e extends f{constructor(t){super({errorCode:403,message:t??"Illegal State ocurred during Emmett processing"}),Object.setPrototypeOf(this,e.prototype)}},ee=class e extends f{constructor(t){super({errorCode:404,message:t?.message??(t?.id?t.type?`${t.type} with ${t.id} was not found during Emmett processing`:`State with ${t.id} was not found during Emmett processing`:t?.type?`${t.type} was not found during Emmett processing`:"State was not found during Emmett processing")}),Object.setPrototypeOf(this,e.prototype)}};var Ee="STREAM_EXISTS",G="STREAM_DOES_NOT_EXIST",R="NO_CONCURRENCY_CHECK",Te=(e,t,r)=>t===R?!0:t==G?e===r:t==Ee?e!==r:e===t,W=(e,t,r)=>{if(t??=R,!Te(e,t,r))throw new C(e,t)},C=class e extends h{constructor(t,r){super(t?.toString(),r?.toString()),Object.setPrototypeOf(this,e.prototype)}},re=e=>e instanceof C;var Ce=require("uuid");var ve=require("web-streams-polyfill");var ne=e=>new U(e),U=class extends ve.TransformStream{_currentPosition;_logPosition;constructor(t){super({start:r=>{let n=0n;for(let o of t)r.enqueue(o),n=o.metadata.globalPosition;r.enqueue(j({globalPosition:n}))},transform:(r,n)=>{this._currentPosition=r.metadata.globalPosition,n.enqueue(r),!(this._currentPosition<this._logPosition)&&n.enqueue(j({globalPosition:this._currentPosition}))}}),this._currentPosition=this._logPosition=t.length>0?t[t.length-1].metadata.globalPosition:0n}set logPosition(t){this._logPosition=t}};var he=require("uuid");var Se=require("uuid"),xe=require("web-streams-polyfill"),q=(e,t={})=>new b(e,t),b=class extends xe.TransformStream{constructor(r,n={}){super({cancel:o=>{console.log("Stream was canceled. Reason:",o),this.stopChecking()}});this.onNoActiveReaderCallback=r;this.streamId=n?.streamId??(0,Se.v4)(),this.onNoActiveReaderCallback=r,this.startChecking(n?.intervalCheckInMs??20)}checkInterval=null;streamId;_isStopped=!1;get hasActiveSubscribers(){return!this._isStopped}startChecking(r){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},r)}stopChecking(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this._isStopped=!0,this.onNoActiveReaderCallback(this))}checkNoActiveReader(){!this.readable.locked&&!this._isStopped&&this.stopChecking()}};var ge=async(e,t)=>{if(e.writable.locked)return!1;let r=e.writable.getWriter();if(await r.ready,!e.readable.locked)return!1;try{for(let n of t)await r.write(n)}catch(n){console.log(n)}finally{await r.close()}return!0};var oe=()=>{let e=[],t=new Map;return{notify:async r=>{if(r.length!==0){e.push(...r);for(let n of t.values())n.logPosition=r[r.length-1].metadata.globalPosition,await ge(n,r)}},stream:()=>{let r=(0,he.v4)(),n=ne(e);return t.set(r,n),n.readable.pipeThrough(q(o=>{t.has(o.streamId)&&t.delete(o.streamId)},{streamId:r}))}}};var S=0n,Ct=()=>{let e=new Map,t=oe(),r=()=>Array.from(e.values()).map(n=>n.length).reduce((n,o)=>n+o,0);return{async aggregateStream(n,o){let{evolve:a,initialState:i,read:m}=o,l=await this.readStream(n,m),T=l?.events??[];return{currentStreamVersion:BigInt(T.length),state:T.reduce(a,i()),streamExists:l.streamExists}},readStream:(n,o)=>{let a=e.get(n),i=a?BigInt(a.length):S;W(i,o?.expectedStreamVersion,S);let m=Number(o&&"from"in o?o.from:0),l=Number(o&&"to"in o?o.to:o&&"maxCount"in o&&o.maxCount?o.from+o.maxCount:a?.length??1),T=a!==void 0&&a.length>0?a.map(E=>E).slice(m,l):[],g={currentStreamVersion:i,events:T,streamExists:a!==void 0&&a.length>0};return Promise.resolve(g)},appendToStream:async(n,o,a)=>{let i=e.get(n)??[],m=i.length>0?BigInt(i.length):S;W(m,a?.expectedStreamVersion,S);let l=o.map((E,v)=>({...E,metadata:{...E.metadata??{},streamName:n,eventId:(0,Ce.v4)(),streamPosition:BigInt(i.length+v+1),globalPosition:BigInt(r()+v+1)}})),T=BigInt(l.slice(-1)[0].metadata.streamPosition);return e.set(n,[...i,...l]),await t.notify(l),{nextExpectedStreamVersion:T,createdNewStream:m===S}}}};var d=(e,t)=>{if(Re(e))return e.equals(t);if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((o,a)=>d(o,t[a]));if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e===t;if(Array.isArray(t))return!1;let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length||!r.every(o=>n.includes(o)))return!1;for(let o in e){if(e[o]instanceof Function&&t[o]instanceof Function)continue;if(!d(e[o],t[o]))return!1}return!0},Re=e=>e&&typeof e=="object"&&"equals"in e&&typeof e.equals=="function";var Rt=e=>{let t,r,n=0;do({value:t,done:r}=e.next()),n+=t||0;while(!r);return n};var bt=(e,t,r,n,o=()=>{})=>{let a=!1,i=e.map(m=>r(m)?(a=!0,n(m)):m).filter(m=>m!==void 0).map(m=>{if(!m)throw Error("That should not happen");return m});return!a&&o()!==void 0?[...e,t]:i};var be=ot(require("async-retry"),1),ae={retries:0},D=async(e,t)=>t===void 0||t.retries===0?e():(0,be.default)(async r=>{try{return await e()}catch(n){throw t?.shouldRetryError&&!t.shouldRetryError(n)&&r(n),n}},t??{retries:0});var se={retries:3,minTimeout:100,factor:1.5,shouldRetryError:re},Dt=e=>e===void 0?ae:"onVersionConflict"in e?typeof e.onVersionConflict=="boolean"?se:typeof e.onVersionConflict=="number"?{...se,retries:e.onVersionConflict}:e.onVersionConflict:e,ie=e=>async(t,r,n,o)=>D(async()=>await Ot(t,async({eventStore:i})=>{let{evolve:m,initialState:l}=e,g=(e.mapToStreamId??(Ze=>Ze))(r),E=await i.aggregateStream(g,{evolve:m,initialState:l,read:{expectedStreamVersion:o?.expectedStreamVersion??R}}),v=E.state,le=E.currentStreamVersion,K=await n(v),I=Array.isArray(K)?K:[K];if(I.length===0)return{newEvents:[],newState:v,nextExpectedStreamVersion:le,createdNewStream:!1};let Le=o?.expectedStreamVersion??(E.streamExists?le:G);return{...await i.appendToStream(g,I,{...o,expectedStreamVersion:Le}),newEvents:I,newState:I.reduce(m,v)}}),Dt(o&&"retry"in o?o.retry:e.retry)),Ot=(e,t)=>(X(e)?e:L(e)).withSession(t);var wt=e=>async(t,r,n,o)=>{let{decide:a,...i}=e;return ie(i)(t,r,m=>a(n,m),o)};var En=require("commander"),Pt=e=>e!==void 0&&(typeof e=="string"||"name"in e&&e.name!==void 0&&typeof e.name=="string");var Mt=()=>{let e=new Map,t=[];return{send:async r=>{let n=e.get(r.type);if(n===void 0||n.length===0)throw new f(`No handler registered for command ${r.type}!`);let o=n[0];await o(r)},publish:async r=>{let n=e.get(r.type)??[];for(let o of n)await o(r)},schedule:(r,n)=>{t=[...t,{message:r,options:n}]},handle:(r,...n)=>{let o=[...e.keys()].filter(a=>n.includes(a));if(o.length>0)throw new f(`Cannot register handler for commands ${o.join(", ")} as they're already registered!`);for(let a of n)e.set(a,[r])},subscribe(r,...n){for(let o of n)e.has(o)||e.set(o,[]),e.set(o,[...e.get(o)??[],r])},dequeue:()=>{let r=t;return t=[],r}}};var Vt=e=>e,De=e=>e.map(t=>({type:"inline",projection:t})),Oe=e=>e.map(t=>({type:"async",projection:t})),kt={inline:De,async:Oe};var B=class extends Error{constructor(t){super(`Cannot parse! ${t}`)}},c={stringify:(e,t)=>JSON.stringify(t?.map?t.map(e):e,(r,n)=>typeof n=="bigint"?n.toString():n),parse:(e,t)=>{let r=JSON.parse(e,t?.reviver);if(t?.typeCheck&&!t?.typeCheck(r))throw new B(e);return t?.map?t.map(r):r}};var $=e=>{let t=e.reduce((o,a)=>o+a.length,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r};var At=async e=>{let t=[];for await(let r of e)t.push(r);return t};var O=class{buffer=[];addToBuffer(t){this.buffer.push(t)}clearBuffer(){this.buffer=[]}hasCompleteMessage(){let t=$(this.buffer);return new TextDecoder().decode(t).includes(`
|
|
2
|
-
`)}decode(){if(!this.hasCompleteMessage())return null;let
|
|
3
|
-
`);if(n===-1)return null;let o=r.slice(0,n),a=new Uint8Array(
|
|
4
|
-
`))}decode(){let
|
|
5
|
-
`),n=
|
|
6
|
-
${
|
|
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 _class4; var _class5; var _class6;var _chunkCJZAVRMTcjs = require('./chunk-CJZAVRMT.cjs');var L=t=>"withSession"in t,Y= exports.nulloSessionFactory =t=>({withSession:e=>e({eventStore:t,close:()=>Promise.resolve()})});var ot=(t,e,r)=>({type:t,data:e,metadata:r});var z=(t,e,r)=>({type:t,data:e,metadata:r});var it=t=>({kind:"Reply",message:t}),mt= exports.send =t=>({kind:"Send",message:t}),dt= exports.publish =t=>({kind:"Publish",message:t}),pt= exports.schedule =(t,e)=>({kind:"Schedule",message:t,when:e}),lt= exports.complete =()=>({kind:"Complete"}),ct= exports.ignore =t=>({kind:"Ignore",reason:t}),ut= exports.error =t=>({kind:"Error",reason:t}),ft= exports.accept =()=>({kind:"Accept"});var F="__emt:GlobalStreamCaughtUp",Q= exports.isGlobalStreamCaughtUp =t=>t.type===F,Ct= exports.caughtUpEventFrom =t=>e=>e.type===F&&_optionalChain([e, 'access', _2 => _2.metadata, 'optionalAccess', _3 => _3.globalPosition])>=t,N= exports.globalStreamCaughtUp =t=>z(F,t,{globalPosition:t.globalPosition}),Rt= exports.isSubscriptionEvent =t=>Q(t),bt= exports.isNotInternalEvent =t=>!Q(t);var he="STREAM_EXISTS",W= exports.STREAM_DOES_NOT_EXIST ="STREAM_DOES_NOT_EXIST",O= exports.NO_CONCURRENCY_CHECK ="NO_CONCURRENCY_CHECK",Ce= exports.matchesExpectedVersion =(t,e,r)=>e===O?!0:e==W?t===r:e==he?t!==r:t===e,_= exports.assertExpectedVersionMatchesCurrent =(t,e,r)=>{if(e??=O,!Ce(t,e,r))throw new D(t,e)},D= exports.ExpectedVersionConflictError =class t extends _chunkCJZAVRMTcjs.l{constructor(e,r){super(_optionalChain([e, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]),_optionalChain([r, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()])),Object.setPrototypeOf(this,t.prototype)}},Z= exports.isExpectedVersionConflictError =t=>t instanceof D;var _uuid = require('uuid');var _webstreamspolyfill = require('web-streams-polyfill');var Oe={ReadableStream:_webstreamspolyfill.ReadableStream,WritableStream:_webstreamspolyfill.WritableStream,TransformStream:_webstreamspolyfill.TransformStream};var Vt=typeof process<"u"&&process.versions!=null&&process.versions.bun!=null,w;if(globalThis&&globalThis.WritableStream&&globalThis.ReadableStream&&globalThis.TransformStream)w=globalThis;else try{w=await Promise.resolve().then(() => _interopRequireWildcard(require("stream/web")))}catch (e2){w=Oe}var s=w;var ee=t=>new G(t),G= exports.CaughtUpTransformStream =class extends s.TransformStream{constructor(e){super({start:r=>{let n=0n;for(let o of e)r.enqueue(o),n=o.metadata.globalPosition;r.enqueue(N({globalPosition:n}))},transform:(r,n)=>{this._currentPosition=r.metadata.globalPosition,n.enqueue(r),!(this._currentPosition<this._logPosition)&&n.enqueue(N({globalPosition:this._currentPosition}))}}),this._currentPosition=this._logPosition=e.length>0?e[e.length-1].metadata.globalPosition:0n}set logPosition(e){this._logPosition=e}};var M=(t,e={})=>new E(t,e),E= (_class =class extends s.TransformStream{constructor(r,n={}){super({cancel:o=>{console.log("Stream was canceled. Reason:",o),this.stopChecking()}});_class.prototype.__init.call(this);_class.prototype.__init2.call(this);;this.onNoActiveReaderCallback=r;this.streamId=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _8 => _8.streamId]), () => (_uuid.v4.call(void 0, ))),this.onNoActiveReaderCallback=r,this.startChecking(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _9 => _9.intervalCheckInMs]), () => (20)))}__init() {this.checkInterval=null}__init2() {this._isStopped=!1}get hasActiveSubscribers(){return!this._isStopped}startChecking(r){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},r)}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 te=async(t,e)=>{if(t.writable.locked)return!1;let r=t.writable.getWriter();if(await r.ready,!t.readable.locked)return!1;try{for(let n of e)await r.write(n)}catch(n){console.log(n)}finally{await r.close()}return!0};var re=()=>{let t=[],e=new Map;return{notify:async r=>{if(r.length!==0){t.push(...r);for(let n of e.values())n.logPosition=r[r.length-1].metadata.globalPosition,await te(n,r)}},stream:()=>{let r=_uuid.v4.call(void 0, ),n=ee(t);return e.set(r,n),n.readable.pipeThrough(M(o=>{e.has(o.streamId)&&e.delete(o.streamId)},{streamId:r}))}}};var x=0n,or= exports.getInMemoryEventStore =()=>{let t=new Map,e=re(),r=()=>Array.from(t.values()).map(n=>n.length).reduce((n,o)=>n+o,0);return{async aggregateStream(n,o){let{evolve:a,initialState:m,read:d}=o,c=await this.readStream(n,d),v=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _10 => _10.events]), () => ([]));return{currentStreamVersion:BigInt(v.length),state:v.reduce(a,m()),streamExists:c.streamExists}},readStream:(n,o)=>{let a=t.get(n),m=a?BigInt(a.length):x;_(m,_optionalChain([o, 'optionalAccess', _11 => _11.expectedStreamVersion]),x);let d=Number(o&&"from"in o?o.from:0),c=Number(o&&"to"in o?o.to:o&&"maxCount"in o&&o.maxCount?o.from+o.maxCount:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _12 => _12.length]), () => (1))),v=a!==void 0&&a.length>0?a.map(y=>y).slice(d,c):[],T={currentStreamVersion:m,events:v,streamExists:a!==void 0&&a.length>0};return Promise.resolve(T)},appendToStream:async(n,o,a)=>{let m=_nullishCoalesce(t.get(n), () => ([])),d=m.length>0?BigInt(m.length):x;_(d,_optionalChain([a, 'optionalAccess', _13 => _13.expectedStreamVersion]),x);let c=o.map((y,S)=>({...y,metadata:{..._nullishCoalesce(y.metadata, () => ({})),streamName:n,eventId:_uuid.v4.call(void 0, ),streamPosition:BigInt(m.length+S+1),globalPosition:BigInt(r()+S+1)}})),v=BigInt(c.slice(-1)[0].metadata.streamPosition);return t.set(n,[...m,...c]),await e.notify(c),{nextExpectedStreamVersion:v,createdNewStream:d===x}}}};var p=(t,e)=>{if(Pe(t))return t.equals(e);if(Array.isArray(t))return Array.isArray(e)&&t.length===e.length&&t.every((o,a)=>p(o,e[a]));if(typeof t!="object"||typeof e!="object"||t===null||e===null)return t===e;if(Array.isArray(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length||!r.every(o=>n.includes(o)))return!1;for(let o in t){if(t[o]instanceof Function&&e[o]instanceof Function)continue;if(!p(t[o],e[o]))return!1}return!0},Pe= exports.isEquatable =t=>t&&typeof t=="object"&&"equals"in t&&typeof t.equals=="function";var ur=t=>{let e,r,n=0;do({value:e,done:r}=t.next()),n+=e||0;while(!r);return n};var yr=(t,e,r,n,o=()=>{})=>{let a=!1,m=t.map(d=>r(d)?(a=!0,n(d)):d).filter(d=>d!==void 0).map(d=>{if(!d)throw Error("That should not happen");return d});return!a&&o()!==void 0?[...t,e]:m};var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);var ne={retries:0},V= exports.asyncRetry =async(t,e)=>e===void 0||e.retries===0?t():_asyncretry2.default.call(void 0, async r=>{try{return await t()}catch(n){throw _optionalChain([e, 'optionalAccess', _14 => _14.shouldRetryError])&&!e.shouldRetryError(n)&&r(n),n}},_nullishCoalesce(e, () => ({retries:0})));var oe={retries:3,minTimeout:100,factor:1.5,shouldRetryError:Z},Ae=t=>t===void 0?ne:"onVersionConflict"in t?typeof t.onVersionConflict=="boolean"?oe:typeof t.onVersionConflict=="number"?{...oe,retries:t.onVersionConflict}:t.onVersionConflict:t,ae= exports.CommandHandler =t=>async(e,r,n,o)=>V(async()=>await Ie(e,async({eventStore:m})=>{let{evolve:d,initialState:c}=t,T=(_nullishCoalesce(t.mapToStreamId, () => ((ge=>ge))))(r),y=await m.aggregateStream(T,{evolve:d,initialState:c,read:{expectedStreamVersion:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _15 => _15.expectedStreamVersion]), () => (O))}}),S=y.state,J=y.currentStreamVersion,H=await n(S),b=Array.isArray(H)?H:[H];if(b.length===0)return{newEvents:[],newState:S,nextExpectedStreamVersion:J,createdNewStream:!1};let xe=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _16 => _16.expectedStreamVersion]), () => ((y.streamExists?J:W)));return{...await m.appendToStream(T,b,{...o,expectedStreamVersion:xe}),newEvents:b,newState:b.reduce(d,S)}}),Ae(o&&"retry"in o?o.retry:t.retry)),Ie=(t,e)=>(L(t)?t:Y(t)).withSession(e);var wr=t=>async(e,r,n,o)=>{let{decide:a,...m}=t;return ae(m)(e,r,d=>a(n,d),o)};var Hr=()=>{let t=new Map,e=[];return{send:async r=>{let n=t.get(r.type);if(n===void 0||n.length===0)throw new (0, _chunkCJZAVRMTcjs.k)(`No handler registered for command ${r.type}!`);let o=n[0];await o(r)},publish:async r=>{let n=_nullishCoalesce(t.get(r.type), () => ([]));for(let o of n)await o(r)},schedule:(r,n)=>{e=[...e,{message:r,options:n}]},handle:(r,...n)=>{let o=[...t.keys()].filter(a=>n.includes(a));if(o.length>0)throw new (0, _chunkCJZAVRMTcjs.k)(`Cannot register handler for commands ${o.join(", ")} as they're already registered!`);for(let a of n)t.set(a,[r])},subscribe(r,...n){for(let o of n)t.has(o)||t.set(o,[]),t.set(o,[..._nullishCoalesce(t.get(o), () => ([])),r])},dequeue:()=>{let r=e;return e=[],r}}};var Fr=t=>t,He= exports.inlineProjections =t=>t.map(e=>({type:"inline",projection:e})),je= exports.asyncProjections =t=>t.map(e=>({type:"async",projection:e})),Nr= exports.projections ={inline:He,async:je};var q=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},u= exports.JSONParser ={stringify:(t,e)=>JSON.stringify(_optionalChain([e, 'optionalAccess', _17 => _17.map])?e.map(t):t,(r,n)=>typeof n=="bigint"?n.toString():n),parse:(t,e)=>{let r=JSON.parse(t,_optionalChain([e, 'optionalAccess', _18 => _18.reviver]));if(_optionalChain([e, 'optionalAccess', _19 => _19.typeCheck])&&!_optionalChain([e, 'optionalAccess', _20 => _20.typeCheck, 'call', _21 => _21(r)]))throw new q(t);return _optionalChain([e, 'optionalAccess', _22 => _22.map])?e.map(r):r}};var B=t=>{let e=t.reduce((o,a)=>o+a.length,0),r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r};var Jr=async t=>{let e=[];for await(let r of t)e.push(r);return e};var P= (_class2 =class{constructor() { _class2.prototype.__init3.call(this); }__init3() {this.buffer=[]}addToBuffer(e){this.buffer.push(e)}clearBuffer(){this.buffer=[]}hasCompleteMessage(){let e=B(this.buffer);return new TextDecoder().decode(e).includes(`
|
|
2
|
+
`)}decode(){if(!this.hasCompleteMessage())return null;let e=B(this.buffer),r=new TextDecoder().decode(e),n=r.indexOf(`
|
|
3
|
+
`);if(n===-1)return null;let o=r.slice(0,n),a=new Uint8Array(e.buffer,n+1);return this.buffer=a.byteLength>0?[a]:[],JSON.parse(o)}}, _class2);var k= (_class3 =class{constructor(e){;_class3.prototype.__init4.call(this);this.transform=e;this.transform=e}__init4() {this.buffer=[]}addToBuffer(e){this.buffer.push(e)}clearBuffer(){this.buffer=[]}hasCompleteMessage(){return this.buffer.some(e=>e.includes(`
|
|
4
|
+
`))}decode(){let e=this.buffer.join("");if(!this.hasCompleteMessage()){if(e.trim().length>0)throw new Error("Unterminated string in JSON at position");return null}let r=e.indexOf(`
|
|
5
|
+
`),n=e.slice(0,r).trim();return this.buffer=[e.slice(r+1)],this.transform(n)}}, _class3);var A=class extends k{constructor(){super(e=>JSON.parse(e))}};var I= (_class4 =class{constructor() { _class4.prototype.__init5.call(this); }__init5() {this.buffer=null}addToBuffer(e){this.buffer=e}clearBuffer(){this.buffer=null}hasCompleteMessage(){return this.buffer!==null}decode(){if(!this.hasCompleteMessage()||!this.buffer)return null;let e=this.buffer;return this.clearBuffer(),e}}, _class4);var U=class{constructor(e){this.decoders=e}decoderFor(e){let r=this.decoders.find(n=>n[0](e));return r?r[1]:null}addToBuffer(e){_optionalChain([this, 'access', _23 => _23.decoderFor, 'call', _24 => _24(e), 'optionalAccess', _25 => _25.addToBuffer, 'call', _26 => _26(e)])}clearBuffer(){for(let e of this.decoders.map(r=>r[1]))e.clearBuffer()}hasCompleteMessage(){return this.decoders.some(e=>e[1].hasCompleteMessage())}decode(){return _nullishCoalesce(_optionalChain([this, 'access', _27 => _27.decoders, 'access', _28 => _28.map, 'call', _29 => _29(r=>r[1]), 'access', _30 => _30.find, 'call', _31 => _31(r=>r.hasCompleteMessage()), 'optionalAccess', _32 => _32.decode, 'call', _33 => _33()]), () => (null))}},g= exports.DefaultDecoder =class extends U{constructor(){super([[e=>typeof e=="string",new A],[e=>e instanceof Uint8Array,new P],[e=>typeof e=="object",new I]])}};var se=t=>new s.ReadableStream({start(e){for(let r of t)e.enqueue(r);e.close()}});var fn={fromArray:se};var ie=t=>new s.TransformStream({transform(e,r){t(e)&&r.enqueue(e)}});var me=t=>new s.TransformStream({transform(e,r){r.enqueue(t(e))}});var de=(t,e)=>new h(t,e),h=class extends s.TransformStream{constructor(e,r){super({transform:n=>{this.accumulator=this.reducer(this.accumulator,n)},flush:n=>{n.enqueue(this.accumulator),n.terminate()}}),this.accumulator=r,this.reducer=e}};var pe=(t,e,r={forever:!0,minTimeout:25})=>new s.TransformStream({start(n){V(()=>Fe(t,e,n),r).catch(o=>{n.error(o)})}}),Fe=async(t,e,r)=>{let o=t().getReader();try{let a;do{let m=await o.read();a=m.done,await e(m,r),a&&r.terminate()}while(!a)}finally{o.releaseLock()}};var le=t=>new C(t),C= (_class5 =class extends s.TransformStream{__init6() {this.count=0}constructor(e){super({transform:(r,n)=>{this.count++,this.count>this.skip&&n.enqueue(r)}});_class5.prototype.__init6.call(this);,this.skip=e}}, _class5);var ce=t=>new s.TransformStream({transform(e,r){r.enqueue(e),t(e)&&r.terminate()}});var ue=t=>new s.TransformStream({async transform(e,r){if(!t(e)){r.enqueue(e);return}await Promise.resolve(),r.terminate()}});var fe=t=>new R(t),R= (_class6 =class extends s.TransformStream{__init7() {this.count=0}constructor(e){super({transform:(r,n)=>{this.count<this.limit?(this.count++,n.enqueue(r)):n.terminate()}});_class6.prototype.__init7.call(this);,this.limit=e}}, _class6);var ye=t=>new s.TransformStream({start(e){let r=setTimeout(()=>{e.terminate()},t),n=e.terminate.bind(e);e.terminate=()=>{clearTimeout(r),n()}},transform(e,r){r.enqueue(e)}});var ve={filter:ie,take:fe,TakeTransformStream:R,skip:le,SkipTransformStream:C,map:me,notifyAboutNoActiveReadersStream:M,NotifyAboutNoActiveReadersStream:E,reduce:de,ReduceTransformStream:h,retry:pe,stopAfter:ce,stopOn:ue,waitAtMost:ye};var{retry:Ne}=ve,Ln= exports.restream =(t,e=o=>o,r={forever:!0,minTimeout:25},n=new g)=>Ne(t,We(e,n),r).readable,We=(t=r=>r,e=new g)=>(r,n)=>{let{done:o,value:a}=r;a&&e.addToBuffer(a),!(!o&&!e.hasCompleteMessage())&&_e(e,t,n)},_e=(t,e,r)=>{try{let n=t.decode();if(!n)return;let o=e(n);r.enqueue(o)}catch(n){r.error(new Error(`Decoding error: ${_optionalChain([n, 'optionalAccess', _34 => _34.toString, 'call', _35 => _35()])}`))}};var l=class extends Error{constructor(e){super(e)}},Se= exports.isSubset =(t,e)=>{let r=t,n=e;return $(r),$(n),Object.keys(n).every(o=>typeof n[o]=="object"?Se(r[o],n[o]):n[o]===r[o])},so= exports.assertFails =t=>{throw new l(_nullishCoalesce(t, () => ("That should not ever happened, right?")))},io= exports.assertThrowsAsync =async(t,e)=>{try{throw await t(),new l("Function didn't throw expected error")}catch(r){let n=r;return e&&i(e(n)),n}},mo= exports.assertThrows =(t,e)=>{try{throw t(),new l("Function didn't throw expected error")}catch(r){let n=r;return e&&i(e(n)),n}},po= exports.assertRejects =async(t,e)=>{try{throw await t,new l("Function didn't throw expected error")}catch(r){if(!e)return;e instanceof Error?Ge(r,e):i(e(r))}},Te= exports.assertMatches =(t,e,r)=>{if(!Se(t,e))throw new l(_nullishCoalesce(r, () => (`subObj:
|
|
6
|
+
${u.stringify(e)}
|
|
7
7
|
is not subset of
|
|
8
|
-
${
|
|
9
|
-
${
|
|
8
|
+
${u.stringify(t)}`)))},Ge= exports.assertDeepEqual =(t,e,r)=>{if(!p(t,e))throw new l(_nullishCoalesce(r, () => (`subObj:
|
|
9
|
+
${u.stringify(e)}
|
|
10
10
|
is not equal to
|
|
11
|
-
${
|
|
12
|
-
${
|
|
11
|
+
${u.stringify(t)}`)))},lo= exports.assertNotDeepEqual =(t,e,r)=>{if(p(t,e))throw new l(_nullishCoalesce(r, () => (`subObj:
|
|
12
|
+
${u.stringify(e)}
|
|
13
13
|
is equals to
|
|
14
|
-
${
|
|
15
|
-
Expected: ${
|
|
16
|
-
Actual:${
|
|
14
|
+
${u.stringify(t)}`)))},co= exports.assertThat =t=>({isEqualTo:e=>i(p(t,e))});function qe(t,e){if(t)throw new l(_nullishCoalesce(e, () => ("Condition is false")))}function i(t,e){if(!t)throw new l(_nullishCoalesce(e, () => ("Condition is false")))}function $(t,e){if(!t)throw new l(_nullishCoalesce(e, () => ("Condition is not truthy")))}function f(t,e,r){if(t!==e)throw new l(`${_nullishCoalesce(r, () => ("Objects are not equal"))}:
|
|
15
|
+
Expected: ${u.stringify(t)}
|
|
16
|
+
Actual:${u.stringify(e)}`)}function Ee(t,e,r){if(t===e)throw new l(_nullishCoalesce(r, () => (`Objects are equal: ${u.stringify(t)}`)))}function uo(t){Ee(t,null),$(t)}function fo(t){f(t,null)}var yo=t=>e=>p(e,t),vo= exports.argMatches =t=>e=>t(e);function So(t){return{calledTimes:e=>{f(_optionalChain([t, 'access', _36 => _36.mock, 'optionalAccess', _37 => _37.calls, 'optionalAccess', _38 => _38.length]),e)},notCalled:()=>{f(_optionalChain([t, 'optionalAccess', _39 => _39.mock, 'optionalAccess', _40 => _40.calls, 'optionalAccess', _41 => _41.length]),0)},called:()=>{i(_optionalChain([t, 'access', _42 => _42.mock, 'optionalAccess', _43 => _43.calls, 'access', _44 => _44.length])!==void 0&&t.mock.calls.length>0)},calledWith:(...e)=>{i(_optionalChain([t, 'access', _45 => _45.mock, 'optionalAccess', _46 => _46.calls, 'access', _47 => _47.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(r=>p(r.arguments,e)))},calledOnceWith:(...e)=>{i(_optionalChain([t, 'access', _48 => _48.mock, 'optionalAccess', _49 => _49.calls, 'access', _50 => _50.length])!==void 0&&t.mock.calls.length===1&&t.mock.calls.some(r=>p(r.arguments,e)))},calledWithArgumentMatching:(...e)=>{i(_optionalChain([t, 'access', _51 => _51.mock, 'optionalAccess', _52 => _52.calls, 'access', _53 => _53.length])!==void 0&&t.mock.calls.length>=1),i(_optionalChain([t, 'access', _54 => _54.mock, 'optionalAccess', _55 => _55.calls, 'access', _56 => _56.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(r=>r.arguments&&r.arguments.length>=e.length&&e.every((n,o)=>n(r.arguments[o]))))},notCalledWithArgumentMatching:(...e)=>{qe(_optionalChain([t, 'access', _57 => _57.mock, 'optionalAccess', _58 => _58.calls, 'access', _59 => _59.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls[0].arguments&&t.mock.calls[0].arguments.length>=e.length&&e.every((r,n)=>r(t.mock.calls[0].arguments[n])))}}}var To=t=>({isEmpty:()=>f(t.length,0),isNotEmpty:()=>Ee(t.length,0),hasSize:e=>f(t.length,e),containsElements:(...e)=>{i(e.every(r=>e.some(n=>p(r,n))))},containsExactlyInAnyOrder:(...e)=>{f(t.length,e.length),i(t.every(r=>e.some(n=>p(r,n))))},containsExactlyInAnyOrderElementsOf:e=>{f(t.length,e.length),i(t.every(r=>e.some(n=>p(r,n))))},containsExactlyElementsOf:e=>{f(t.length,e.length);for(let r=0;r<t.length;r++)i(p(t[r],e[r]))},containsExactly:e=>{f(t.length,1),i(p(t[0],e))},contains:e=>{i(t.some(r=>p(r,e)))},containsOnlyOnceElementsOf:e=>{i(e.map(r=>t.filter(n=>p(n,r)).length).filter(r=>r===1).length===e.length)},containsAnyOf:(...e)=>{i(t.some(r=>e.some(n=>p(r,n))))},allMatch:e=>{i(t.every(e))},anyMatches:e=>{i(t.some(e))},allMatchAsync:async e=>{for(let r of t)i(await e(r))}});var ho={for:t=>e=>({when:r=>{let n=()=>{let a=(Array.isArray(e)?e:[e]).reduce(t.evolve,t.initialState());return t.decide(r,a)};return{then:o=>{let a=n(),m=Array.isArray(a)?a:[a],d=Array.isArray(o)?o:[o];Te(m,d)},thenThrows:(...o)=>{try{throw n(),new l("Handler did not fail as expected")}catch(a){if(a instanceof l)throw a;if(o.length===0)return;if(!_chunkCJZAVRMTcjs.j.call(void 0, o[0])){i(o[0](a),`Error didn't match the error condition: ${_optionalChain([a, 'optionalAccess', _60 => _60.toString, 'call', _61 => _61()])}`);return}i(a instanceof o[0],`Caught error is not an instance of the expected type: ${_optionalChain([a, 'optionalAccess', _62 => _62.toString, 'call', _63 => _63()])}`),o[1]&&i(o[1](a),`Error didn't match the error condition: ${_optionalChain([a, 'optionalAccess', _64 => _64.toString, 'call', _65 => _65()])}`)}}}}})};var bo=t=>{let e=new Map;return{async aggregateStream(r,n){return t.aggregateStream(r,n)},readStream(r,n){return t.readStream(r,n)},appendToStream:async(r,n,o)=>{let a=await t.appendToStream(r,n,o),m=_nullishCoalesce(e.get(r), () => ([r,[]]));return e.set(r,[r,[...m[1],...n]]),a},appendedEvents:e,setup:async(r,n)=>t.appendToStream(r,n)}};exports.AssertionError = l; exports.BinaryJsonDecoder = P; exports.CaughtUpTransformStream = G; exports.CommandHandler = ae; exports.CommandHandlerStreamVersionConflictRetryOptions = oe; exports.CompositeDecoder = U; exports.ConcurrencyError = _chunkCJZAVRMTcjs.l; exports.DeciderCommandHandler = wr; exports.DeciderSpecification = ho; exports.DefaultDecoder = g; exports.EmmettError = _chunkCJZAVRMTcjs.k; exports.ExpectedVersionConflictError = D; exports.GlobalStreamCaughtUpType = F; exports.IllegalStateError = _chunkCJZAVRMTcjs.n; exports.InMemoryEventStoreDefaultStreamVersion = x; exports.JSONParser = u; exports.JsonDecoder = A; exports.NO_CONCURRENCY_CHECK = O; exports.NoRetries = ne; exports.NotFoundError = _chunkCJZAVRMTcjs.o; exports.ObjectDecoder = I; exports.ParseError = q; exports.STREAM_DOES_NOT_EXIST = W; exports.STREAM_EXISTS = he; exports.StreamingCoordinator = re; exports.StringDecoder = k; exports.ValidationError = _chunkCJZAVRMTcjs.m; exports.ValidationErrors = _chunkCJZAVRMTcjs.d; exports.WrapEventStore = bo; exports.accept = ft; exports.argMatches = vo; exports.argValue = yo; exports.assertDeepEqual = Ge; exports.assertEqual = f; exports.assertExpectedVersionMatchesCurrent = _; exports.assertFails = so; exports.assertFalse = qe; exports.assertIsNotNull = uo; exports.assertIsNull = fo; exports.assertMatches = Te; exports.assertNotDeepEqual = lo; exports.assertNotEmptyString = _chunkCJZAVRMTcjs.g; exports.assertNotEqual = Ee; exports.assertOk = $; exports.assertPositiveNumber = _chunkCJZAVRMTcjs.h; exports.assertRejects = po; exports.assertThat = co; exports.assertThatArray = To; exports.assertThrows = mo; exports.assertThrowsAsync = io; exports.assertTrue = i; exports.assertUnsignedBigInt = _chunkCJZAVRMTcjs.i; exports.asyncProjections = je; exports.asyncRetry = V; exports.canCreateEventStoreSession = L; exports.caughtUpEventFrom = Ct; exports.collect = Jr; exports.command = ot; exports.complete = lt; exports.concatUint8Arrays = B; exports.deepEquals = p; exports.error = ut; exports.event = z; exports.formatDateToUtcYYYYMMDD = _chunkCJZAVRMTcjs.a; exports.getInMemoryEventStore = or; exports.getInMemoryMessageBus = Hr; exports.globalStreamCaughtUp = N; exports.ignore = ct; exports.inlineProjections = He; exports.isEquatable = Pe; exports.isErrorConstructor = _chunkCJZAVRMTcjs.j; exports.isExpectedVersionConflictError = Z; exports.isGlobalStreamCaughtUp = Q; exports.isNotInternalEvent = bt; exports.isNumber = _chunkCJZAVRMTcjs.e; exports.isPluginConfig = _chunkCJZAVRMTcjs.p; exports.isString = _chunkCJZAVRMTcjs.f; exports.isSubscriptionEvent = Rt; exports.isSubset = Se; exports.isValidYYYYMMDD = _chunkCJZAVRMTcjs.b; exports.matchesExpectedVersion = Ce; exports.merge = yr; exports.nulloSessionFactory = Y; exports.parseDateFromUtcYYYYMMDD = _chunkCJZAVRMTcjs.c; exports.projection = Fr; exports.projections = Nr; exports.publish = dt; exports.reply = it; exports.restream = Ln; exports.schedule = pt; exports.send = mt; exports.streamGenerators = fn; exports.streamTrackingGlobalPosition = ee; exports.streamTransformations = ve; exports.sum = ur; exports.verifyThat = So;
|
|
17
17
|
//# sourceMappingURL=index.cjs.map
|