@event-driven-io/emmett 0.18.0 → 0.19.0-alpha.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.
@@ -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-6TXKRKDJ.js.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-6TXKRKDJ.js","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"]}
@@ -0,0 +1,2 @@
1
+ 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=t=>typeof t=="number"&&t===t,m=t=>typeof t=="string",f=t=>{if(!m(t)||t.length===0)throw new r("NOT_A_NONEMPTY_STRING");return t},E=t=>{if(!i(t)||t<=0)throw new r("NOT_A_POSITIVE_NUMBER");return t},N=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=class t extends Error{errorCode;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=class t extends o{constructor(s,n,a){super({errorCode:412,message:a??`Expected version ${n.toString()} does not match current ${s?.toString()}`});this.current=s;this.expected=n;Object.setPrototypeOf(this,t.prototype)}},r=class t extends o{constructor(e){super({errorCode:400,message:e??"Validation Error ocurred during Emmett processing"}),Object.setPrototypeOf(this,t.prototype)}},p=class t extends o{constructor(e){super({errorCode:403,message:e??"Illegal State ocurred during Emmett processing"}),Object.setPrototypeOf(this,t.prototype)}},u=class t extends o{constructor(e){super({errorCode:404,message:e?.message??(e?.id?e.type?`${e.type} with ${e.id} was not found during Emmett processing`:`State with ${e.id} was not found during Emmett processing`:e?.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=t=>/^\d{4}-\d{2}-\d{2}$/.test(t),I=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};import"commander";var S=t=>t!==void 0&&(typeof t=="string"||"name"in t&&t.name!==void 0&&typeof t.name=="string");export{w as a,c as b,I as c,d,i as e,m as f,f as g,E as h,N as i,C as j,o as k,g as l,r as m,p as n,u as o,S as p};
2
+ //# sourceMappingURL=chunk-ZTAED4F4.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/validation/index.ts","../src/errors/index.ts","../src/validation/dates.ts","../src/config/plugins/index.ts"],"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","import { ValidationError } from '../errors';\n\nexport const formatDateToUtcYYYYMMDD = (date: Date) => {\n // Use the 'en-CA' locale which formats as 'yyyy-mm-dd'\n const formatter = new Intl.DateTimeFormat('en-CA', {\n timeZone: 'UTC',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n });\n\n // Format the date\n return formatter.format(date);\n};\n\n// Function to validate 'yyyy-mm-dd' format\nexport const isValidYYYYMMDD = (dateString: string) => {\n const regex = /^\\d{4}-\\d{2}-\\d{2}$/;\n return regex.test(dateString);\n};\n\nexport const parseDateFromUtcYYYYMMDD = (dateString: string) => {\n const date = new Date(dateString + 'T00:00:00Z');\n\n if (!isValidYYYYMMDD(dateString)) {\n throw new ValidationError('Invalid date format, must be yyyy-mm-dd');\n }\n\n if (isNaN(date.getTime())) {\n throw new ValidationError('Invalid date format');\n }\n\n return date;\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"],"mappings":"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","names":["ValidationErrors","isNumber","val","isString","assertNotEmptyString","value","ValidationError","assertPositiveNumber","assertUnsignedBigInt","number","isErrorConstructor","expect","EmmettError","_EmmettError","options","errorCode","isNumber","message","isString","ConcurrencyError","_ConcurrencyError","current","expected","ValidationError","_ValidationError","IllegalStateError","_IllegalStateError","NotFoundError","_NotFoundError","formatDateToUtcYYYYMMDD","date","isValidYYYYMMDD","dateString","parseDateFromUtcYYYYMMDD","ValidationError","isPluginConfig","plugin"]}
package/dist/cli.d.mts ADDED
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { a as EmmettPluginsConfig, j as EmmettError, c as EmmettPluginType, g as EmmettPlugin, f as EmmettCliPlugin } from './index-D9zse73H.mjs';
4
+
5
+ declare const sampleConfig: (plugins?: string[]) => string;
6
+ declare const generateConfigFile: (configPath: string, collectionNames: string[]) => void;
7
+ declare const configCommand: Command;
8
+
9
+ declare const importPluginsConfig: (options?: {
10
+ configPath?: string | undefined;
11
+ }) => Promise<EmmettPluginsConfig | EmmettError>;
12
+ declare const loadPlugins: (options?: {
13
+ pluginType?: EmmettPluginType;
14
+ configPath?: string;
15
+ }) => Promise<EmmettPlugin[]>;
16
+ declare const registerCliPlugins: (program: Command, plugins: EmmettCliPlugin[]) => Promise<void>;
17
+
18
+ declare const program: Command;
19
+
20
+ export { configCommand, program as default, generateConfigFile, importPluginsConfig, loadPlugins, registerCliPlugins, sampleConfig };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { a as EmmettPluginsConfig, j as EmmettError, c as EmmettPluginType, g as EmmettPlugin, f as EmmettCliPlugin } from './index-D9zse73H.js';
4
+
5
+ declare const sampleConfig: (plugins?: string[]) => string;
6
+ declare const generateConfigFile: (configPath: string, collectionNames: string[]) => void;
7
+ declare const configCommand: Command;
8
+
9
+ declare const importPluginsConfig: (options?: {
10
+ configPath?: string | undefined;
11
+ }) => Promise<EmmettPluginsConfig | EmmettError>;
12
+ declare const loadPlugins: (options?: {
13
+ pluginType?: EmmettPluginType;
14
+ configPath?: string;
15
+ }) => Promise<EmmettPlugin[]>;
16
+ declare const registerCliPlugins: (program: Command, plugins: EmmettCliPlugin[]) => Promise<void>;
17
+
18
+ declare const program: Command;
19
+
20
+ export { configCommand, program as default, generateConfigFile, importPluginsConfig, loadPlugins, registerCliPlugins, sampleConfig };
package/dist/cli.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } 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 _chunk6TXKRKDJjs = require('./chunk-6TXKRKDJ.js');var _commander = require('commander');require('ts-node/esm');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var _process = require('process'); var _process2 = _interopRequireDefault(_process);var r=(n=["emmett-expressjs"])=>`
3
+ export default {
4
+ plugins: ${n.length>0?`[
5
+ ${n.map(t=>`"${t}"`).join(`,
6
+ `)}
7
+ ]`:"[]"},
8
+ };
9
+ `,h= exports.generateConfigFile =(n,e)=>{try{_fs2.default.writeFileSync(n,r(e),"utf8"),console.log(`Configuration file stored at: ${n}`)}catch(t){console.error(`Error: Couldn't store config file: ${n}!`),console.error(t),_process2.default.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",(n,e)=>e.concat([n]),[]).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(n=>{let e=n.plugin.length>0?n.plugin:["@event-driven-io/emmett-expressjs"];!("print"in n)&&!("generate"in n)&&(console.error(`Error: Please provide either:
10
+ --print param to print sample config or
11
+ --generate to generate sample config file`),_process2.default.exit(1)),"print"in n?console.log(`${r(e)}`):"generate"in n&&(n.file||(console.error("Error: You need to provide a config file through a --file"),_process2.default.exit(1)),h(n.file,e))});var _path = require('path'); var _path2 = _interopRequireDefault(_path);var f={missingDefaultExport:`Error: Config should contain default export, e.g.
12
+
13
+ ${r()}`,missingPluginsPropertyExport:`Error: Config should contain default export with plugins array, e.g.
14
+
15
+ ${r()}`,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 n=>{let e=_path2.default.join(process.cwd(),_nullishCoalesce(_optionalChain([n, 'optionalAccess', _ => _.configPath]), () => ("emmett.config.mts")));try{let t=await Promise.resolve().then(() => _interopRequireWildcard(require(e)));return t.default?!t.default.plugins||!Array.isArray(t.default.plugins)?new (0, _chunk6TXKRKDJjs.k)(f.missingPluginsPropertyExport):t.default.plugins.every(_chunk6TXKRKDJjs.p)?{plugins:t.default.plugins}:new (0, _chunk6TXKRKDJjs.k)(f.wrongPluginStructure):new (0, _chunk6TXKRKDJjs.k)(f.missingDefaultExport)}catch(t){return _optionalChain([n, 'optionalAccess', _2 => _2.configPath])?new (0, _chunk6TXKRKDJjs.k)("Error: Couldn't load file:"+t.toString()):(console.warn("Didn`t find config file: "+e),{plugins:[]})}},c= exports.loadPlugins =async n=>{try{let e=await y({configPath:_optionalChain([n, 'optionalAccess', _3 => _3.configPath])});if(e instanceof _chunk6TXKRKDJjs.k)throw e;if(e.plugins.length===0)return console.log("No extensions specified in emmett.config.ts."),[];let o=x(e.plugins,_optionalChain([n, 'optionalAccess', _4 => _4.pluginType])).map(async l=>{let g=w(l,_optionalChain([n, 'optionalAccess', _5 => _5.pluginType]));try{let a=await Promise.resolve().then(() => _interopRequireWildcard(require(g)));return console.info(`Loaded plugin: ${g}`),a}catch(a){console.error(`Failed to load extension "${g}":`,a);return}});return(await Promise.all(o)).filter(l=>l!==void 0)}catch(e){return console.error("Failed to load emmett.config.ts:",e),[]}},u= exports.registerCliPlugins =async(n,e)=>{let t=[];for(let o of e)"registerCommands"in o&&console.warn(`No registerCommands function found in ${o.name}`),await o.registerCommands(n),console.log(`Loaded extension: ${o.name}`),t.push(o)},x=(n,e)=>n.filter(t=>typeof t=="string"||e&&(t.register===void 0||t.register.some(o=>o.pluginType===e))),w=(n,e)=>{if(typeof n=="string")return e?`${n}/${e}`:n;let t=_nullishCoalesce(_optionalChain([n, 'access', _6 => _6.register, 'access', _7 => _7.find, 'call', _8 => _8(o=>e&&o.pluginType===e), 'optionalAccess', _9 => _9.path]), () => (e));return t?`${n.name}/${t}`:n.name};var s=new _commander.Command;s.name("emmett").description("CLI tool for Emmett").option("--config <path>","Path to the configuration file","emmett.config.ts");var v=async()=>{let e=s.opts().config;try{let t=await c({pluginType:"cli",configPath:e});await u(s,t),s.parse(process.argv)}catch(t){console.error(`Failed to load config from ${e}:`,t)}};v().catch(n=>{console.error("CLI initialization failed:"),console.error(n)});var q=s;exports.configCommand = C; exports.default = q; exports.generateConfigFile = h; exports.importPluginsConfig = y; exports.loadPlugins = c; exports.registerCliPlugins = u; exports.sampleConfig = r;
16
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/emmett/emmett/src/packages/emmett/dist/cli.js","../src/cli.ts","../src/commandLine/config.ts","../src/commandLine/plugins.ts"],"names":["sampleConfig","plugins","p","generateConfigFile","configPath","collectionNames","fs"],"mappings":"AAAA;AACA,ylCAAyC,sCCAjB,uBACjB,gECAQ,oFACK,IAEPA,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,YAAAA,CAAG,aAAA,CAAcF,CAAAA,CAAYJ,CAAAA,CAAaK,CAAe,CAAA,CAAG,MAAM,CAAA,CAClE,OAAA,CAAQ,GAAA,CAAI,CAAA,8BAAA,EAAiCD,CAAU,CAAA,CAAA;AAiDnD;AAOO,yCAAA;AClES;AACQ;AAAA;AACR","file":"/home/runner/work/emmett/emmett/src/packages/emmett/dist/cli.js","sourcesContent":[null,"#!/usr/bin/env node\nimport { Command } from 'commander';\nimport 'ts-node/esm'; // Allows dynamic TypeScript imports\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option(\n '--config <path>',\n 'Path to the configuration file',\n `emmett.config.ts`,\n );\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const options = program.opts<{ config: string }>();\n const configPath = options.config;\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 fs from 'node:fs';\nimport process 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 fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const 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 process.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 process.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 ?? 'emmett.config.mts',\n );\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);\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 emmett.config.ts.');\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 EmmettPlugin;\n\n console.info(`Loaded plugin: ${importPath}`);\n\n return plugin;\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 emmett.config.ts:', 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 if ('registerCommands' in plugin) {\n console.warn(`No registerCommands function found in ${plugin.name}`);\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/cli.mjs ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import{k as i,p}from"./chunk-ZTAED4F4.mjs";import{Command as $}from"commander";import"ts-node/esm";import{Command as d}from"commander";import P from"node:fs";import m from"process";var r=(n=["emmett-expressjs"])=>`
3
+ export default {
4
+ plugins: ${n.length>0?`[
5
+ ${n.map(t=>`"${t}"`).join(`,
6
+ `)}
7
+ ]`:"[]"},
8
+ };
9
+ `,h=(n,e)=>{try{P.writeFileSync(n,r(e),"utf8"),console.log(`Configuration file stored at: ${n}`)}catch(t){console.error(`Error: Couldn't store config file: ${n}!`),console.error(t),m.exit(1)}},C=new d("config").description("Manage Pongo configuration");C.command("sample").description("Generate or print sample configuration").option("-plg, --plugins <name>","Specify the plugin name",(n,e)=>e.concat([n]),[]).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(n=>{let e=n.plugin.length>0?n.plugin:["@event-driven-io/emmett-expressjs"];!("print"in n)&&!("generate"in n)&&(console.error(`Error: Please provide either:
10
+ --print param to print sample config or
11
+ --generate to generate sample config file`),m.exit(1)),"print"in n?console.log(`${r(e)}`):"generate"in n&&(n.file||(console.error("Error: You need to provide a config file through a --file"),m.exit(1)),h(n.file,e))});import"commander";import E from"path";var f={missingDefaultExport:`Error: Config should contain default export, e.g.
12
+
13
+ ${r()}`,missingPluginsPropertyExport:`Error: Config should contain default export with plugins array, e.g.
14
+
15
+ ${r()}`,wrongPluginStructure:"Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }"},y=async n=>{let e=E.join(process.cwd(),n?.configPath??"emmett.config.mts");try{let t=await import(e);return t.default?!t.default.plugins||!Array.isArray(t.default.plugins)?new i(f.missingPluginsPropertyExport):t.default.plugins.every(p)?{plugins:t.default.plugins}:new i(f.wrongPluginStructure):new i(f.missingDefaultExport)}catch(t){return n?.configPath?new i("Error: Couldn't load file:"+t.toString()):(console.warn("Didn`t find config file: "+e),{plugins:[]})}},c=async n=>{try{let e=await y({configPath:n?.configPath});if(e instanceof i)throw e;if(e.plugins.length===0)return console.log("No extensions specified in emmett.config.ts."),[];let o=x(e.plugins,n?.pluginType).map(async l=>{let g=w(l,n?.pluginType);try{let a=await import(g);return console.info(`Loaded plugin: ${g}`),a}catch(a){console.error(`Failed to load extension "${g}":`,a);return}});return(await Promise.all(o)).filter(l=>l!==void 0)}catch(e){return console.error("Failed to load emmett.config.ts:",e),[]}},u=async(n,e)=>{let t=[];for(let o of e)"registerCommands"in o&&console.warn(`No registerCommands function found in ${o.name}`),await o.registerCommands(n),console.log(`Loaded extension: ${o.name}`),t.push(o)},x=(n,e)=>n.filter(t=>typeof t=="string"||e&&(t.register===void 0||t.register.some(o=>o.pluginType===e))),w=(n,e)=>{if(typeof n=="string")return e?`${n}/${e}`:n;let t=n.register.find(o=>e&&o.pluginType===e)?.path??e;return t?`${n.name}/${t}`:n.name};var s=new $;s.name("emmett").description("CLI tool for Emmett").option("--config <path>","Path to the configuration file","emmett.config.ts");var v=async()=>{let e=s.opts().config;try{let t=await c({pluginType:"cli",configPath:e});await u(s,t),s.parse(process.argv)}catch(t){console.error(`Failed to load config from ${e}:`,t)}};v().catch(n=>{console.error("CLI initialization failed:"),console.error(n)});var q=s;export{C as configCommand,q as default,h as generateConfigFile,y as importPluginsConfig,c as loadPlugins,u as registerCliPlugins,r as sampleConfig};
16
+ //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts","../src/commandLine/config.ts","../src/commandLine/plugins.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport 'ts-node/esm'; // Allows dynamic TypeScript imports\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option(\n '--config <path>',\n 'Path to the configuration file',\n `emmett.config.ts`,\n );\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const options = program.opts<{ config: string }>();\n const configPath = options.config;\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 fs from 'node:fs';\nimport process 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 fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const 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 process.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 process.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 ?? 'emmett.config.mts',\n );\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);\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 emmett.config.ts.');\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 EmmettPlugin;\n\n console.info(`Loaded plugin: ${importPath}`);\n\n return plugin;\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 emmett.config.ts:', 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 if ('registerCommands' in plugin) {\n console.warn(`No registerCommands function found in ${plugin.name}`);\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"],"mappings":";2CACA,OAAS,WAAAA,MAAe,YACxB,MAAO,cCFP,OAAS,WAAWC,MAAkB,YAEtC,OAAOC,MAAQ,UACf,OAAOC,MAAa,UAEb,IAAMC,EAAe,CAACC,EAAoB,CAAC,kBAAkB,IAM3D;AAAA;AAAA,aAJLA,EAAQ,OAAS,EACb;AAAA,EAAMA,EAAQ,IAAKC,GAAM,IAAIA,CAAC,GAAG,EAAE,KAAK;AAAA,CAAK,CAAC;AAAA,GAC9C,IAIiB;AAAA;AAAA,EAKZC,EAAqB,CAChCC,EACAC,IACS,CACT,GAAI,CACFP,EAAG,cAAcM,EAAYJ,EAAaK,CAAe,EAAG,MAAM,EAClE,QAAQ,IAAI,iCAAiCD,CAAU,EAAE,CAC3D,OAASE,EAAO,CACd,QAAQ,MAAM,sCAAsCF,CAAU,GAAG,EACjE,QAAQ,MAAME,CAAK,EACnBP,EAAQ,KAAK,CAAC,CAChB,CACF,EAEaQ,EAAgB,IAAIV,EAAW,QAAQ,EAAE,YACpD,4BACF,EAaAU,EACG,QAAQ,QAAQ,EAChB,YAAY,wCAAwC,EACpD,OACC,yBACA,0BACA,CAACC,EAAeC,IAEPA,EAAS,OAAO,CAACD,CAAK,CAAC,EAEhC,CAAC,CACH,EACC,OACC,oBACA,iDACF,EACC,OAAO,iBAAkB,6BAA6B,EACtD,OAAO,cAAe,0BAA0B,EAChD,OAAQE,GAAiC,CACxC,IAAMT,EACJS,EAAQ,OAAO,OAAS,EACpBA,EAAQ,OACR,CAAC,mCAAmC,EAEtC,EAAE,UAAWA,IAAY,EAAE,aAAcA,KAC3C,QAAQ,MACN;AAAA;AAAA,0CACF,EACAX,EAAQ,KAAK,CAAC,GAGZ,UAAWW,EACb,QAAQ,IAAI,GAAGV,EAAaC,CAAO,CAAC,EAAE,EAC7B,aAAcS,IAClBA,EAAQ,OACX,QAAQ,MACN,2DACF,EACAX,EAAQ,KAAK,CAAC,GAGhBI,EAAmBO,EAAQ,KAAMT,CAAO,EAE5C,CAAC,EC1FH,MAAsC,YACtC,OAAOU,MAAU,OAYjB,IAAMC,EAA2B,CAC/B,qBAAsB;AAAA;AAAA,EAAwDC,EAAa,CAAC,GAC5F,6BAA8B;AAAA;AAAA,EAA2EA,EAAa,CAAC,GACvH,qBAAsB,6HACxB,EACaC,EAAsB,MAAOC,GAEQ,CAChD,IAAMC,EAAaC,EAAK,KACtB,QAAQ,IAAI,EACZF,GAAS,YAAc,mBACzB,EAEA,GAAI,CACF,IAAMG,EAAY,MAAM,OAAOF,GAI/B,OAAKE,EAAS,QAIV,CAACA,EAAS,QAAQ,SAAW,CAAC,MAAM,QAAQA,EAAS,QAAQ,OAAO,EAC/D,IAAIC,EACTP,EAAyB,4BAC3B,EAGGM,EAAS,QAAQ,QAAQ,MAAME,CAAc,EAI3C,CAAE,QAASF,EAAS,QAAQ,OAAQ,EAHlC,IAAIC,EAAYP,EAAyB,oBAAoB,EAV7D,IAAIO,EAAYP,EAAyB,oBAAoB,CAcxE,OAASS,EAAO,CACd,OAAKN,GAAS,WAIP,IAAII,EACT,6BAAgCE,EAAgB,SAAS,CAC3D,GALE,QAAQ,KAAK,4BAA8BL,CAAU,EAC9C,CAAE,QAAS,CAAC,CAAE,EAKzB,CACF,EAEaM,EAAc,MAAOP,GAGH,CAC7B,GAAI,CACF,IAAMQ,EAAgB,MAAMT,EAAoB,CAC9C,WAAYC,GAAS,UACvB,CAAC,EAED,GAAIQ,aAAyBJ,EAAa,MAAMI,EAEhD,GAAIA,EAAc,QAAQ,SAAW,EACnC,eAAQ,IAAI,8CAA8C,EACnD,CAAC,EAQV,IAAMC,EALgBC,EACpBF,EAAc,QACdR,GAAS,UACX,EAEsC,IAAI,MAAOW,GAAiB,CAChE,IAAMC,EAAaC,EAAcF,EAAcX,GAAS,UAAU,EAClE,GAAI,CACF,IAAMc,EAAU,MAAM,OAAOF,GAE7B,eAAQ,KAAK,kBAAkBA,CAAU,EAAE,EAEpCE,CACT,OAASR,EAAO,CACd,QAAQ,MAAM,6BAA6BM,CAAU,KAAMN,CAAK,EAChE,MACF,CACF,CAAC,EAED,OAAQ,MAAM,QAAQ,IAAIG,CAAe,GAAG,OACzCK,GAAWA,IAAW,MACzB,CACF,OAASR,EAAO,CACd,eAAQ,MAAM,mCAAoCA,CAAK,EAChD,CAAC,CACV,CACF,EAEaS,EAAqB,MAChCC,EACAC,IACkB,CAClB,IAAMC,EAA4B,CAAC,EAEnC,QAAWJ,KAAUG,EACf,qBAAsBH,GACxB,QAAQ,KAAK,yCAAyCA,EAAO,IAAI,EAAE,EAErE,MAAMA,EAAO,iBAAiBE,CAAO,EACrC,QAAQ,IAAI,qBAAqBF,EAAO,IAAI,EAAE,EAC9CI,EAAO,KAAKJ,CAAM,CAEtB,EAEMJ,EAAsB,CAC1BO,EACAE,IAEAF,EAAQ,OACLG,GACC,OAAOA,GAAM,UACZD,IACEC,EAAE,WAAa,QACdA,EAAE,SAAS,KAAMC,GAAMA,EAAE,aAAeF,CAAU,EAC1D,EAEIN,EAAgB,CACpBF,EACAQ,IACG,CACH,GAAI,OAAOR,GAAiB,SAC1B,OAAOQ,EAAa,GAAGR,CAAY,IAAIQ,CAAU,GAAKR,EAGxD,IAAMW,EACJX,EAAa,SAAS,KAAMU,GAAMF,GAAcE,EAAE,aAAeF,CAAU,GACvE,MAAQA,EAEd,OAAOG,EACH,GAAGX,EAAa,IAAI,IAAIW,CAAa,GACrCX,EAAa,IACnB,EF3IA,IAAMY,EAAU,IAAIC,EAEpBD,EACG,KAAK,QAAQ,EACb,YAAY,qBAAqB,EACjC,OACC,kBACA,iCACA,kBACF,EAGF,IAAME,EAAU,SAAY,CAE1B,IAAMC,EADUH,EAAQ,KAAyB,EACtB,OAE3B,GAAI,CACF,IAAMI,EAAU,MAAMC,EAAY,CAChC,WAAY,MACZ,WAAYF,CACd,CAAC,EACD,MAAMG,EAAmBN,EAASI,CAAO,EAGzCJ,EAAQ,MAAM,QAAQ,IAAI,CAC5B,OAASO,EAAK,CACZ,QAAQ,MAAM,8BAA8BJ,CAAU,IAAKI,CAAG,CAChE,CACF,EAGAL,EAAQ,EAAE,MAAOK,GAAQ,CACvB,QAAQ,MAAM,4BAA4B,EAC1C,QAAQ,MAAMA,CAAG,CACnB,CAAC,EAED,IAAOC,EAAQR","names":["Command","CliCommand","fs","process","sampleConfig","plugins","p","generateConfigFile","configPath","collectionNames","error","configCommand","value","previous","options","path","PluginsConfigImportError","sampleConfig","importPluginsConfig","options","configPath","path","imported","EmmettError","isPluginConfig","error","loadPlugins","pluginsConfig","pluginsPromises","filterPluginsByType","pluginConfig","importPath","getImportPath","plugin","registerCliPlugins","program","plugins","result","pluginType","p","r","pluginSubpath","program","Command","initCLI","configPath","plugins","loadPlugins","registerCliPlugins","err","cli_default"]}
@@ -0,0 +1,53 @@
1
+ import { Command } from 'commander';
2
+
3
+ type ErrorConstructor<ErrorType extends Error> = new (...args: any[]) => ErrorType;
4
+ declare const isErrorConstructor: <ErrorType extends Error>(expect: Function) => expect is ErrorConstructor<ErrorType>;
5
+ declare class EmmettError extends Error {
6
+ errorCode: number;
7
+ constructor(options?: {
8
+ errorCode: number;
9
+ message?: string;
10
+ } | string | number);
11
+ }
12
+ declare class ConcurrencyError extends EmmettError {
13
+ current: string | undefined;
14
+ expected: string;
15
+ constructor(current: string | undefined, expected: string, message?: string);
16
+ }
17
+ declare class ValidationError extends EmmettError {
18
+ constructor(message?: string);
19
+ }
20
+ declare class IllegalStateError extends EmmettError {
21
+ constructor(message?: string);
22
+ }
23
+ declare class NotFoundError extends EmmettError {
24
+ constructor(options?: {
25
+ id: string;
26
+ type: string;
27
+ message?: string;
28
+ });
29
+ }
30
+
31
+ type EmmettPluginConfig = {
32
+ name: string;
33
+ register: EmmettPluginRegistration[];
34
+ } | string;
35
+ type EmmettPluginType = 'cli';
36
+ type EmmettCliPluginRegistration = {
37
+ pluginType: 'cli';
38
+ path?: string;
39
+ };
40
+ type EmmettPluginRegistration = EmmettCliPluginRegistration;
41
+ type EmmettCliPlugin = {
42
+ pluginType: 'cli';
43
+ name: string;
44
+ registerCommands: (program: Command) => Promise<void> | void;
45
+ };
46
+ type EmmettPlugin = EmmettCliPlugin;
47
+ declare const isPluginConfig: (plugin: Partial<EmmettPluginConfig> | string | undefined) => plugin is EmmettPluginConfig;
48
+
49
+ type EmmettPluginsConfig = {
50
+ plugins: EmmettPluginConfig[];
51
+ };
52
+
53
+ export { ConcurrencyError as C, type ErrorConstructor as E, IllegalStateError as I, NotFoundError as N, ValidationError as V, type EmmettPluginsConfig as a, type EmmettPluginConfig as b, type EmmettPluginType as c, type EmmettCliPluginRegistration as d, type EmmettPluginRegistration as e, type EmmettCliPlugin as f, type EmmettPlugin as g, isErrorConstructor as h, isPluginConfig as i, EmmettError as j };
@@ -0,0 +1,53 @@
1
+ import { Command } from 'commander';
2
+
3
+ type ErrorConstructor<ErrorType extends Error> = new (...args: any[]) => ErrorType;
4
+ declare const isErrorConstructor: <ErrorType extends Error>(expect: Function) => expect is ErrorConstructor<ErrorType>;
5
+ declare class EmmettError extends Error {
6
+ errorCode: number;
7
+ constructor(options?: {
8
+ errorCode: number;
9
+ message?: string;
10
+ } | string | number);
11
+ }
12
+ declare class ConcurrencyError extends EmmettError {
13
+ current: string | undefined;
14
+ expected: string;
15
+ constructor(current: string | undefined, expected: string, message?: string);
16
+ }
17
+ declare class ValidationError extends EmmettError {
18
+ constructor(message?: string);
19
+ }
20
+ declare class IllegalStateError extends EmmettError {
21
+ constructor(message?: string);
22
+ }
23
+ declare class NotFoundError extends EmmettError {
24
+ constructor(options?: {
25
+ id: string;
26
+ type: string;
27
+ message?: string;
28
+ });
29
+ }
30
+
31
+ type EmmettPluginConfig = {
32
+ name: string;
33
+ register: EmmettPluginRegistration[];
34
+ } | string;
35
+ type EmmettPluginType = 'cli';
36
+ type EmmettCliPluginRegistration = {
37
+ pluginType: 'cli';
38
+ path?: string;
39
+ };
40
+ type EmmettPluginRegistration = EmmettCliPluginRegistration;
41
+ type EmmettCliPlugin = {
42
+ pluginType: 'cli';
43
+ name: string;
44
+ registerCommands: (program: Command) => Promise<void> | void;
45
+ };
46
+ type EmmettPlugin = EmmettCliPlugin;
47
+ declare const isPluginConfig: (plugin: Partial<EmmettPluginConfig> | string | undefined) => plugin is EmmettPluginConfig;
48
+
49
+ type EmmettPluginsConfig = {
50
+ plugins: EmmettPluginConfig[];
51
+ };
52
+
53
+ export { ConcurrencyError as C, type ErrorConstructor as E, IllegalStateError as I, NotFoundError as N, ValidationError as V, type EmmettPluginsConfig as a, type EmmettPluginConfig as b, type EmmettPluginType as c, type EmmettCliPluginRegistration as d, type EmmettPluginRegistration as e, type EmmettCliPlugin as f, type EmmettPlugin as g, isErrorConstructor as h, isPluginConfig as i, EmmettError as j };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,8 @@
1
+ import { C as ConcurrencyError, E as ErrorConstructor } from './index-D9zse73H.mjs';
2
+ export { f as EmmettCliPlugin, d as EmmettCliPluginRegistration, j as EmmettError, g as EmmettPlugin, b as EmmettPluginConfig, e as EmmettPluginRegistration, c as EmmettPluginType, a as EmmettPluginsConfig, I as IllegalStateError, N as NotFoundError, V as ValidationError, h as isErrorConstructor, i as isPluginConfig } from './index-D9zse73H.mjs';
1
3
  import { ReadableStream } from 'web-streams-polyfill';
2
4
  import retry from 'async-retry';
5
+ import 'commander';
3
6
 
4
7
  type Primitive = undefined | null | boolean | string | number | bigint | symbol | Function;
5
8
  type ImmutableTypes = Date | RegExp;
@@ -126,34 +129,6 @@ type Flavour<K, T> = K & {
126
129
  };
127
130
  type DefaultRecord = Record<string, unknown>;
128
131
 
129
- type ErrorConstructor<ErrorType extends Error> = new (...args: any[]) => ErrorType;
130
- declare const isErrorConstructor: <ErrorType extends Error>(expect: Function) => expect is ErrorConstructor<ErrorType>;
131
- declare class EmmettError extends Error {
132
- errorCode: number;
133
- constructor(options?: {
134
- errorCode: number;
135
- message?: string;
136
- } | string | number);
137
- }
138
- declare class ConcurrencyError extends EmmettError {
139
- current: string | undefined;
140
- expected: string;
141
- constructor(current: string | undefined, expected: string, message?: string);
142
- }
143
- declare class ValidationError extends EmmettError {
144
- constructor(message?: string);
145
- }
146
- declare class IllegalStateError extends EmmettError {
147
- constructor(message?: string);
148
- }
149
- declare class NotFoundError extends EmmettError {
150
- constructor(options?: {
151
- id: string;
152
- type: string;
153
- message?: string;
154
- });
155
- }
156
-
157
132
  type ExpectedStreamVersion<VersionType = DefaultStreamVersionType> = ExpectedStreamVersionWithValue<VersionType> | ExpectedStreamVersionGeneral;
158
133
  type ExpectedStreamVersionWithValue<VersionType = DefaultStreamVersionType> = Flavour<VersionType, 'StreamVersion'>;
159
134
  type ExpectedStreamVersionGeneral = Flavour<'STREAM_EXISTS' | 'STREAM_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK', 'StreamVersion'>;
@@ -481,4 +456,4 @@ declare const assertNotEmptyString: (value: unknown) => string;
481
456
  declare const assertPositiveNumber: (value: unknown) => number;
482
457
  declare const assertUnsignedBigInt: (value: string) => bigint;
483
458
 
484
- export { type AggregateStreamOptions, type AggregateStreamResult, type AppendToStreamOptions, type AppendToStreamResult, type ArgumentMatcher, AssertionError, BinaryJsonDecoder, type Brand, type CanHandle, type Command, type CommandBus, type CommandDataOf, CommandHandler$1 as CommandHandler, type CommandHandlerResult, type CommandMetaDataOf, type CommandProcessor, type CommandSender, type CommandTypeOf, CompositeDecoder, ConcurrencyError, type CreateCommandType, type CreateEventType, type Decider, DeciderCommandHandler, type DeciderSpecfication, DeciderSpecification, type Decoder, type DeepReadonly, type DefaultCommandMetadata, DefaultDecoder, type DefaultRecord, type DefaultStreamVersionType, EmmettError, type Equatable, type ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventHandler$1 as EventHandler, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreSession, type EventStoreSessionFactory, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, IllegalStateError, JSONParser, JsonDecoder, type Mapper, type MapperArgs, type MessageBus, type MessageHandler, type MessageProcessor, type MessageScheduler, type MockedFunction, type Mutable, NO_CONCURRENCY_CHECK, NotFoundError, ObjectDecoder, ParseError, type ParseOptions, type ProjectionDefinition, type ProjectionHandler, type ProjectionHandlingType, type ProjectionRegistration, type ReadEvent, type ReadEventMetadata, type ReadEventMetadataWithGlobalPosition, type ReadStreamOptions, type ReadStreamResult, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, StringDecoder, type StringifyOptions, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationError, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, assertEqual, assertExpectedVersionMatchesCurrent, assertFails, assertFalse, assertIsNotNull, assertIsNull, assertMatches, assertNotDeepEqual, assertNotEmptyString, assertNotEqual, assertOk, assertPositiveNumber, assertThat, assertThatArray, assertThrows, assertThrowsAsync, assertTrue, assertUnsignedBigInt, asyncProjections, canCreateEventStoreSession, collectStream, command, complete, concatUint8Arrays, deepEquals, error, event, formatDateToUtcYYYYMMDD, getInMemoryEventStore, getInMemoryMessageBus, ignore, inlineProjections, isEquatable, isErrorConstructor, isNumber, isString, isSubset, isValidYYYYMMDD, matchesExpectedVersion, merge, nulloSessionFactory, parseDateFromUtcYYYYMMDD, projection, projections, publish, reply, restream, schedule, send, sum, verifyThat };
459
+ export { type AggregateStreamOptions, type AggregateStreamResult, type AppendToStreamOptions, type AppendToStreamResult, type ArgumentMatcher, AssertionError, BinaryJsonDecoder, type Brand, type CanHandle, type Command, type CommandBus, type CommandDataOf, CommandHandler$1 as CommandHandler, type CommandHandlerResult, type CommandMetaDataOf, type CommandProcessor, type CommandSender, type CommandTypeOf, CompositeDecoder, ConcurrencyError, type CreateCommandType, type CreateEventType, type Decider, DeciderCommandHandler, type DeciderSpecfication, DeciderSpecification, type Decoder, type DeepReadonly, type DefaultCommandMetadata, DefaultDecoder, type DefaultRecord, type DefaultStreamVersionType, type Equatable, ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventHandler$1 as EventHandler, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreSession, type EventStoreSessionFactory, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, JSONParser, JsonDecoder, type Mapper, type MapperArgs, type MessageBus, type MessageHandler, type MessageProcessor, type MessageScheduler, type MockedFunction, type Mutable, NO_CONCURRENCY_CHECK, ObjectDecoder, ParseError, type ParseOptions, type ProjectionDefinition, type ProjectionHandler, type ProjectionHandlingType, type ProjectionRegistration, type ReadEvent, type ReadEventMetadata, type ReadEventMetadataWithGlobalPosition, type ReadStreamOptions, type ReadStreamResult, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, StringDecoder, type StringifyOptions, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, assertEqual, assertExpectedVersionMatchesCurrent, assertFails, assertFalse, assertIsNotNull, assertIsNull, assertMatches, assertNotDeepEqual, assertNotEmptyString, assertNotEqual, assertOk, assertPositiveNumber, assertThat, assertThatArray, assertThrows, assertThrowsAsync, assertTrue, assertUnsignedBigInt, asyncProjections, canCreateEventStoreSession, collectStream, command, complete, concatUint8Arrays, deepEquals, error, event, formatDateToUtcYYYYMMDD, getInMemoryEventStore, getInMemoryMessageBus, ignore, inlineProjections, isEquatable, isNumber, isString, isSubset, isValidYYYYMMDD, matchesExpectedVersion, merge, nulloSessionFactory, parseDateFromUtcYYYYMMDD, projection, projections, publish, reply, restream, schedule, send, sum, verifyThat };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
+ import { C as ConcurrencyError, E as ErrorConstructor } from './index-D9zse73H.js';
2
+ export { f as EmmettCliPlugin, d as EmmettCliPluginRegistration, j as EmmettError, g as EmmettPlugin, b as EmmettPluginConfig, e as EmmettPluginRegistration, c as EmmettPluginType, a as EmmettPluginsConfig, I as IllegalStateError, N as NotFoundError, V as ValidationError, h as isErrorConstructor, i as isPluginConfig } from './index-D9zse73H.js';
1
3
  import { ReadableStream } from 'web-streams-polyfill';
2
4
  import retry from 'async-retry';
5
+ import 'commander';
3
6
 
4
7
  type Primitive = undefined | null | boolean | string | number | bigint | symbol | Function;
5
8
  type ImmutableTypes = Date | RegExp;
@@ -126,34 +129,6 @@ type Flavour<K, T> = K & {
126
129
  };
127
130
  type DefaultRecord = Record<string, unknown>;
128
131
 
129
- type ErrorConstructor<ErrorType extends Error> = new (...args: any[]) => ErrorType;
130
- declare const isErrorConstructor: <ErrorType extends Error>(expect: Function) => expect is ErrorConstructor<ErrorType>;
131
- declare class EmmettError extends Error {
132
- errorCode: number;
133
- constructor(options?: {
134
- errorCode: number;
135
- message?: string;
136
- } | string | number);
137
- }
138
- declare class ConcurrencyError extends EmmettError {
139
- current: string | undefined;
140
- expected: string;
141
- constructor(current: string | undefined, expected: string, message?: string);
142
- }
143
- declare class ValidationError extends EmmettError {
144
- constructor(message?: string);
145
- }
146
- declare class IllegalStateError extends EmmettError {
147
- constructor(message?: string);
148
- }
149
- declare class NotFoundError extends EmmettError {
150
- constructor(options?: {
151
- id: string;
152
- type: string;
153
- message?: string;
154
- });
155
- }
156
-
157
132
  type ExpectedStreamVersion<VersionType = DefaultStreamVersionType> = ExpectedStreamVersionWithValue<VersionType> | ExpectedStreamVersionGeneral;
158
133
  type ExpectedStreamVersionWithValue<VersionType = DefaultStreamVersionType> = Flavour<VersionType, 'StreamVersion'>;
159
134
  type ExpectedStreamVersionGeneral = Flavour<'STREAM_EXISTS' | 'STREAM_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK', 'StreamVersion'>;
@@ -481,4 +456,4 @@ declare const assertNotEmptyString: (value: unknown) => string;
481
456
  declare const assertPositiveNumber: (value: unknown) => number;
482
457
  declare const assertUnsignedBigInt: (value: string) => bigint;
483
458
 
484
- export { type AggregateStreamOptions, type AggregateStreamResult, type AppendToStreamOptions, type AppendToStreamResult, type ArgumentMatcher, AssertionError, BinaryJsonDecoder, type Brand, type CanHandle, type Command, type CommandBus, type CommandDataOf, CommandHandler$1 as CommandHandler, type CommandHandlerResult, type CommandMetaDataOf, type CommandProcessor, type CommandSender, type CommandTypeOf, CompositeDecoder, ConcurrencyError, type CreateCommandType, type CreateEventType, type Decider, DeciderCommandHandler, type DeciderSpecfication, DeciderSpecification, type Decoder, type DeepReadonly, type DefaultCommandMetadata, DefaultDecoder, type DefaultRecord, type DefaultStreamVersionType, EmmettError, type Equatable, type ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventHandler$1 as EventHandler, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreSession, type EventStoreSessionFactory, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, IllegalStateError, JSONParser, JsonDecoder, type Mapper, type MapperArgs, type MessageBus, type MessageHandler, type MessageProcessor, type MessageScheduler, type MockedFunction, type Mutable, NO_CONCURRENCY_CHECK, NotFoundError, ObjectDecoder, ParseError, type ParseOptions, type ProjectionDefinition, type ProjectionHandler, type ProjectionHandlingType, type ProjectionRegistration, type ReadEvent, type ReadEventMetadata, type ReadEventMetadataWithGlobalPosition, type ReadStreamOptions, type ReadStreamResult, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, StringDecoder, type StringifyOptions, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationError, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, assertEqual, assertExpectedVersionMatchesCurrent, assertFails, assertFalse, assertIsNotNull, assertIsNull, assertMatches, assertNotDeepEqual, assertNotEmptyString, assertNotEqual, assertOk, assertPositiveNumber, assertThat, assertThatArray, assertThrows, assertThrowsAsync, assertTrue, assertUnsignedBigInt, asyncProjections, canCreateEventStoreSession, collectStream, command, complete, concatUint8Arrays, deepEquals, error, event, formatDateToUtcYYYYMMDD, getInMemoryEventStore, getInMemoryMessageBus, ignore, inlineProjections, isEquatable, isErrorConstructor, isNumber, isString, isSubset, isValidYYYYMMDD, matchesExpectedVersion, merge, nulloSessionFactory, parseDateFromUtcYYYYMMDD, projection, projections, publish, reply, restream, schedule, send, sum, verifyThat };
459
+ export { type AggregateStreamOptions, type AggregateStreamResult, type AppendToStreamOptions, type AppendToStreamResult, type ArgumentMatcher, AssertionError, BinaryJsonDecoder, type Brand, type CanHandle, type Command, type CommandBus, type CommandDataOf, CommandHandler$1 as CommandHandler, type CommandHandlerResult, type CommandMetaDataOf, type CommandProcessor, type CommandSender, type CommandTypeOf, CompositeDecoder, ConcurrencyError, type CreateCommandType, type CreateEventType, type Decider, DeciderCommandHandler, type DeciderSpecfication, DeciderSpecification, type Decoder, type DeepReadonly, type DefaultCommandMetadata, DefaultDecoder, type DefaultRecord, type DefaultStreamVersionType, type Equatable, ErrorConstructor, type Event, type EventBus, type EventDataOf, type EventHandler$1 as EventHandler, type EventMetaDataOf, type EventProcessor, type EventStore, type EventStoreSession, type EventStoreSessionFactory, type EventTypeOf, type EventsPublisher, type ExpectedStreamVersion, type ExpectedStreamVersionGeneral, type ExpectedStreamVersionWithValue, ExpectedVersionConflictError, type Flavour, JSONParser, JsonDecoder, type Mapper, type MapperArgs, type MessageBus, type MessageHandler, type MessageProcessor, type MessageScheduler, type MockedFunction, type Mutable, NO_CONCURRENCY_CHECK, ObjectDecoder, ParseError, type ParseOptions, type ProjectionDefinition, type ProjectionHandler, type ProjectionHandlingType, type ProjectionRegistration, type ReadEvent, type ReadEventMetadata, type ReadEventMetadataWithGlobalPosition, type ReadStreamOptions, type ReadStreamResult, STREAM_DOES_NOT_EXIST, STREAM_EXISTS, type ScheduleOptions, type ScheduledMessage, type ScheduledMessageProcessor, StringDecoder, type StringifyOptions, type TestEventStream, type ThenThrows, type TypedProjectionDefinition, ValidationErrors, type Workflow, type WorkflowCommand, type WorkflowEvent, type WorkflowOutput, WrapEventStore, accept, argMatches, argValue, assertDeepEqual, assertEqual, assertExpectedVersionMatchesCurrent, assertFails, assertFalse, assertIsNotNull, assertIsNull, assertMatches, assertNotDeepEqual, assertNotEmptyString, assertNotEqual, assertOk, assertPositiveNumber, assertThat, assertThatArray, assertThrows, assertThrowsAsync, assertTrue, assertUnsignedBigInt, asyncProjections, canCreateEventStoreSession, collectStream, command, complete, concatUint8Arrays, deepEquals, error, event, formatDateToUtcYYYYMMDD, getInMemoryEventStore, getInMemoryMessageBus, ignore, inlineProjections, isEquatable, isNumber, isString, isSubset, isValidYYYYMMDD, matchesExpectedVersion, merge, nulloSessionFactory, parseDateFromUtcYYYYMMDD, projection, projections, publish, reply, restream, schedule, send, sum, verifyThat };
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
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 I=t=>"withSession"in t,F= exports.nulloSessionFactory =t=>({withSession:e=>e({eventStore:t,close:()=>Promise.resolve()})});var ue=t=>new Intl.DateTimeFormat("en-CA",{timeZone:"UTC",year:"numeric",month:"2-digit",day:"2-digit"}).format(t),J= exports.isValidYYYYMMDD =t=>/^\d{4}-\d{2}-\d{2}$/.test(t),le= exports.parseDateFromUtcYYYYMMDD =t=>{let e=new Date(t+"T00:00:00Z");if(!J(t))throw new l("Invalid date format, must be yyyy-mm-dd");if(isNaN(e.getTime()))throw new l("Invalid date format");return e};var X=(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))(X||{}),w= exports.isNumber =t=>typeof t=="number"&&t===t,M= exports.isString =t=>typeof t=="string",Ee= exports.assertNotEmptyString =t=>{if(!M(t)||t.length===0)throw new l("NOT_A_NONEMPTY_STRING");return t},fe= exports.assertPositiveNumber =t=>{if(!w(t)||t<=0)throw new l("NOT_A_POSITIVE_NUMBER");return t},Se= exports.assertUnsignedBigInt =t=>{let e=BigInt(t);if(e<0)throw new l("NOT_AN_UNSIGNED_BIGINT");return e};var W=t=>typeof t=="function"&&t.prototype&&t.prototype.constructor===t,y= exports.EmmettError =class t extends Error{constructor(e){let r=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:w(e)?e:500,n=e&&typeof e=="object"&&"message"in e?e.message:M(e)?e:`Error with status code '${r}' ocurred during Emmett processing`;super(n),this.errorCode=r,Object.setPrototypeOf(this,t.prototype)}},v= exports.ConcurrencyError =class t extends y{constructor(r,n,o){super({errorCode:412,message:_nullishCoalesce(o, () => (`Expected version ${n.toString()} does not match current ${_optionalChain([r, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))});this.current=r;this.expected=n;Object.setPrototypeOf(this,t.prototype)}},l= exports.ValidationError =class t extends y{constructor(e){super({errorCode:400,message:_nullishCoalesce(e, () => ("Validation Error ocurred during Emmett processing"))}),Object.setPrototypeOf(this,t.prototype)}},_= exports.IllegalStateError =class t extends y{constructor(e){super({errorCode:403,message:_nullishCoalesce(e, () => ("Illegal State ocurred during Emmett processing"))}),Object.setPrototypeOf(this,t.prototype)}},B= exports.NotFoundError =class t extends y{constructor(e){super({errorCode:404,message:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _4 => _4.message]), () => ((_optionalChain([e, 'optionalAccess', _5 => _5.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', _6 => _6.type])?`${e.type} was not found during Emmett processing`:"State was not found during Emmett processing")))}),Object.setPrototypeOf(this,t.prototype)}};var L="STREAM_EXISTS",P= exports.STREAM_DOES_NOT_EXIST ="STREAM_DOES_NOT_EXIST",x= exports.NO_CONCURRENCY_CHECK ="NO_CONCURRENCY_CHECK",Z= exports.matchesExpectedVersion =(t,e)=>e===x?!0:e==P?t===void 0:e==L?t!==void 0:t===e,k= exports.assertExpectedVersionMatchesCurrent =(t,e)=>{if(e??=x,!Z(t,e))throw new b(t,e)},b= exports.ExpectedVersionConflictError =class t extends v{constructor(e,r){super(_optionalChain([e, 'optionalAccess', _7 => _7.toString, 'call', _8 => _8()]),_optionalChain([r, 'optionalAccess', _9 => _9.toString, 'call', _10 => _10()])),Object.setPrototypeOf(this,t.prototype)}};var _uuid = require('uuid');var we=()=>{let t=new Map,e=()=>Array.from(t.values()).map(r=>r.length).reduce((r,n)=>r+n,0);return{async aggregateStream(r,n){let{evolve:o,initialState:a,read:d}=n,i=await this.readStream(r,d);if(!i)return null;let c=_nullishCoalesce(_optionalChain([i, 'optionalAccess', _11 => _11.events]), () => ([]));return{currentStreamVersion:BigInt(c.length),state:c.reduce(o,a())}},readStream:(r,n)=>{let o=t.get(r),a=o?BigInt(o.length):void 0;k(a,_optionalChain([n, 'optionalAccess', _12 => _12.expectedStreamVersion]));let d=Number(n&&"from"in n?n.from:0),i=Number(n&&"to"in n?n.to:n&&"maxCount"in n&&n.maxCount?n.from+n.maxCount:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _13 => _13.length]), () => (1))),c=o&&o.length>0?o.map(E=>E).slice(d,i):[],f=o&&o.length>0?{currentStreamVersion:a,events:c}:null;return Promise.resolve(f)},appendToStream:(r,n,o)=>{let a=_nullishCoalesce(t.get(r), () => ([])),d=a.length>0?BigInt(a.length):void 0;k(d,_optionalChain([o, 'optionalAccess', _14 => _14.expectedStreamVersion]));let i=n.map((E,S)=>({...E,metadata:{..._nullishCoalesce(E.metadata, () => ({})),streamName:r,eventId:_uuid.v4.call(void 0, ),streamPosition:BigInt(a.length+S+1),globalPosition:BigInt(e()+S+1)}})),c=BigInt(i.slice(-1)[0].metadata.streamPosition);t.set(r,[...a,...i]);let f={nextExpectedStreamVersion:c};return Promise.resolve(f)}}};var U=(t,e,r=n=>n)=>async(n,o,a,d)=>await Q(n,async({eventStore:c})=>{let f=r(o),E=await c.aggregateStream(f,{evolve:t,initialState:e,read:{expectedStreamVersion:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _15 => _15.expectedStreamVersion]), () => (x))}}),S=_nullishCoalesce(_optionalChain([E, 'optionalAccess', _16 => _16.state]), () => (e())),Y=_optionalChain([E, 'optionalAccess', _17 => _17.currentStreamVersion]),R=a(S),V=Array.isArray(R)?R:[R],K=_nullishCoalesce(_nullishCoalesce(_optionalChain([d, 'optionalAccess', _18 => _18.expectedStreamVersion]), () => (Y)), () => (P));return{...await c.appendToStream(f,V,{...d,expectedStreamVersion:K}),newEvents:V,newState:V.reduce(t,S)}}),Q=(t,e)=>(I(t)?t:F(t)).withSession(e);var Ie=({decide:t,evolve:e,initialState:r},n=o=>o)=>async(o,a,d,i)=>U(e,r,n)(o,a,c=>t(d,c),i);var Ue=(t,e,r)=>({type:t,data:e,metadata:r});var qe=(t,e,r)=>({type:t,data:e,metadata:r});var Ye=t=>({kind:"Reply",message:t}),Ke= exports.send =t=>({kind:"Send",message:t}),Je= exports.publish =t=>({kind:"Publish",message:t}),Xe= exports.schedule =(t,e)=>({kind:"Schedule",message:t,when:e}),Le= exports.complete =()=>({kind:"Complete"}),Ze= exports.ignore =t=>({kind:"Ignore",reason:t}),ze= exports.error =t=>({kind:"Error",reason:t}),Qe= exports.accept =()=>({kind:"Accept"});var mt=()=>{let t=new Map,e=[];return{send:async r=>{let n=t.get(r.type);if(n===void 0||n.length===0)throw new y(`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 y(`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 ct=t=>t,ee= exports.inlineProjections =t=>t.map(e=>({type:"inline",projection:e})),te= exports.asyncProjections =t=>t.map(e=>({type:"async",projection:e})),ut= exports.projections ={inline:ee,async:te};var A=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},u= exports.JSONParser ={stringify:(t,e)=>JSON.stringify(_optionalChain([e, 'optionalAccess', _19 => _19.map])?e.map(t):t,(r,n)=>typeof n=="bigint"?n.toString():n),parse:(t,e)=>{let r=JSON.parse(t,_optionalChain([e, 'optionalAccess', _20 => _20.reviver]));if(_optionalChain([e, 'optionalAccess', _21 => _21.typeCheck])&&!_optionalChain([e, 'optionalAccess', _22 => _22.typeCheck, 'call', _23 => _23(r)]))throw new A(t);return _optionalChain([e, 'optionalAccess', _24 => _24.map])?e.map(r):r}};var j=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 xt=async t=>{let e=[];for await(let r of t)e.push(r);return e};var g= (_class =class{constructor() { _class.prototype.__init.call(this); }__init() {this.buffer=[]}addToBuffer(e){this.buffer.push(e)}clearBuffer(){this.buffer=[]}hasCompleteMessage(){let e=j(this.buffer);return new TextDecoder().decode(e).includes(`
2
- `)}decode(){if(!this.hasCompleteMessage())return null;let e=j(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)}}, _class);var h= (_class2 =class{constructor(e){;_class2.prototype.__init2.call(this);this.transform=e;this.transform=e}__init2() {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)}}, _class2);var C=class extends h{constructor(){super(e=>JSON.parse(e))}};var D= (_class3 =class{constructor() { _class3.prototype.__init3.call(this); }__init3() {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}}, _class3);var N=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', _25 => _25.decoderFor, 'call', _26 => _26(e), 'optionalAccess', _27 => _27.addToBuffer, 'call', _28 => _28(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', _29 => _29.decoders, 'access', _30 => _30.map, 'call', _31 => _31(r=>r[1]), 'access', _32 => _32.find, 'call', _33 => _33(r=>r.hasCompleteMessage()), 'optionalAccess', _34 => _34.decode, 'call', _35 => _35()]), () => (null))}},O= exports.DefaultDecoder =class extends N{constructor(){super([[e=>typeof e=="string",new C],[e=>e instanceof Uint8Array,new g],[e=>typeof e=="object",new D]])}};var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);var _webstreamspolyfill = require('web-streams-polyfill');var qt=(t,e=o=>o,r={forever:!0,minTimeout:25},n=new O)=>new (0, _webstreamspolyfill.TransformStream)({start(o){_asyncretry2.default.call(void 0, ()=>oe(t,o,e,n),r).catch(a=>{o.error(a)})}}).readable,oe=async(t,e,r,n)=>{let a=t().getReader();try{let d;do d=await ae(a,e,r,n);while(!d)}finally{a.releaseLock()}},ae=async(t,e,r,n)=>{let{done:o,value:a}=await t.read();return a&&n.addToBuffer(a),!o&&!n.hasCompleteMessage()?!1:(se(n,r,e),o&&e.terminate(),o)},se=(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', _36 => _36.toString, 'call', _37 => _37()])}`))}};var m=(t,e)=>{if(ie(t))return t.equals(e);if(Array.isArray(t))return Array.isArray(e)&&t.length===e.length&&t.every((o,a)=>m(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(!m(t[o],e[o]))return!1}return!0},ie= exports.isEquatable =t=>t&&typeof t=="object"&&"equals"in t&&typeof t.equals=="function";var zt=t=>{let e,r,n=0;do({value:e,done:r}=t.next()),n+=e||0;while(!r);return n};var er=(t,e,r,n,o=()=>{})=>{let a=!1,d=t.map(i=>r(i)?(a=!0,n(i)):i).filter(i=>i!==void 0).map(i=>{if(!i)throw Error("That should not happen");return i});return!a&&o()!==void 0?[...t,e]:d};var p=class extends Error{constructor(e){super(e)}},$= exports.isSubset =(t,e)=>{let r=t,n=e;return H(r),H(n),Object.keys(n).every(o=>typeof n[o]=="object"?$(r[o],n[o]):n[o]===r[o])},dr= exports.assertFails =t=>{throw new p(_nullishCoalesce(t, () => ("That should not ever happened, right?")))},mr= exports.assertThrowsAsync =async(t,e)=>{try{throw await t(),new p("Function didn't throw expected error")}catch(r){let n=r;return e&&s(e(n)),n}},pr= exports.assertThrows =(t,e)=>{try{throw t(),new p("Function didn't throw expected error")}catch(r){let n=r;return e&&s(e(n)),n}},q= exports.assertMatches =(t,e,r)=>{if(!$(t,e))throw new p(_nullishCoalesce(r, () => (`subObj:
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 _chunk6TXKRKDJjs = require('./chunk-6TXKRKDJ.js');var H=t=>"withSession"in t,F= exports.nulloSessionFactory =t=>({withSession:e=>e({eventStore:t,close:()=>Promise.resolve()})});var U="STREAM_EXISTS",O= exports.STREAM_DOES_NOT_EXIST ="STREAM_DOES_NOT_EXIST",f= exports.NO_CONCURRENCY_CHECK ="NO_CONCURRENCY_CHECK",$= exports.matchesExpectedVersion =(t,e)=>e===f?!0:e==O?t===void 0:e==U?t!==void 0:t===e,M= exports.assertExpectedVersionMatchesCurrent =(t,e)=>{if(e??=f,!$(t,e))throw new V(t,e)},V= exports.ExpectedVersionConflictError =class t extends _chunk6TXKRKDJjs.l{constructor(e,n){super(_optionalChain([e, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()]),_optionalChain([n, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()])),Object.setPrototypeOf(this,t.prototype)}};var _uuid = require('uuid');var he=()=>{let t=new Map,e=()=>Array.from(t.values()).map(n=>n.length).reduce((n,r)=>n+r,0);return{async aggregateStream(n,r){let{evolve:o,initialState:a,read:i}=r,d=await this.readStream(n,i);if(!d)return null;let c=_nullishCoalesce(_optionalChain([d, 'optionalAccess', _6 => _6.events]), () => ([]));return{currentStreamVersion:BigInt(c.length),state:c.reduce(o,a())}},readStream:(n,r)=>{let o=t.get(n),a=o?BigInt(o.length):void 0;M(a,_optionalChain([r, 'optionalAccess', _7 => _7.expectedStreamVersion]));let i=Number(r&&"from"in r?r.from:0),d=Number(r&&"to"in r?r.to:r&&"maxCount"in r&&r.maxCount?r.from+r.maxCount:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _8 => _8.length]), () => (1))),c=o&&o.length>0?o.map(y=>y).slice(i,d):[],T=o&&o.length>0?{currentStreamVersion:a,events:c}:null;return Promise.resolve(T)},appendToStream:(n,r,o)=>{let a=_nullishCoalesce(t.get(n), () => ([])),i=a.length>0?BigInt(a.length):void 0;M(i,_optionalChain([o, 'optionalAccess', _9 => _9.expectedStreamVersion]));let d=r.map((y,E)=>({...y,metadata:{..._nullishCoalesce(y.metadata, () => ({})),streamName:n,eventId:_uuid.v4.call(void 0, ),streamPosition:BigInt(a.length+E+1),globalPosition:BigInt(e()+E+1)}})),c=BigInt(d.slice(-1)[0].metadata.streamPosition);t.set(n,[...a,...d]);let T={nextExpectedStreamVersion:c};return Promise.resolve(T)}}};var I=(t,e,n=r=>r)=>async(r,o,a,i)=>await K(r,async({eventStore:c})=>{let T=n(o),y=await c.aggregateStream(T,{evolve:t,initialState:e,read:{expectedStreamVersion:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _10 => _10.expectedStreamVersion]), () => (f))}}),E=_nullishCoalesce(_optionalChain([y, 'optionalAccess', _11 => _11.state]), () => (e())),B=_optionalChain([y, 'optionalAccess', _12 => _12.currentStreamVersion]),C=a(E),D=Array.isArray(C)?C:[C],q=_nullishCoalesce(_nullishCoalesce(_optionalChain([i, 'optionalAccess', _13 => _13.expectedStreamVersion]), () => (B)), () => (O));return{...await c.appendToStream(T,D,{...i,expectedStreamVersion:q}),newEvents:D,newState:D.reduce(t,E)}}),K=(t,e)=>(H(t)?t:F(t)).withSession(e);var Pe=({decide:t,evolve:e,initialState:n},r=o=>o)=>async(o,a,i,d)=>I(e,n,r)(o,a,c=>t(i,c),d);var Fe=(t,e,n)=>({type:t,data:e,metadata:n});var Ne=(t,e,n)=>({type:t,data:e,metadata:n});var _e=t=>({kind:"Reply",message:t}),Be= exports.send =t=>({kind:"Send",message:t}),qe= exports.publish =t=>({kind:"Publish",message:t}),Ue= exports.schedule =(t,e)=>({kind:"Schedule",message:t,when:e}),$e= exports.complete =()=>({kind:"Complete"}),Ge= exports.ignore =t=>({kind:"Ignore",reason:t}),Ke= exports.error =t=>({kind:"Error",reason:t}),Je= exports.accept =()=>({kind:"Accept"});var rt=()=>{let t=new Map,e=[];return{send:async n=>{let r=t.get(n.type);if(r===void 0||r.length===0)throw new (0, _chunk6TXKRKDJjs.k)(`No handler registered for command ${n.type}!`);let o=r[0];await o(n)},publish:async n=>{let r=_nullishCoalesce(t.get(n.type), () => ([]));for(let o of r)await o(n)},schedule:(n,r)=>{e=[...e,{message:n,options:r}]},handle:(n,...r)=>{let o=[...t.keys()].filter(a=>r.includes(a));if(o.length>0)throw new (0, _chunk6TXKRKDJjs.k)(`Cannot register handler for commands ${o.join(", ")} as they're already registered!`);for(let a of r)t.set(a,[n])},subscribe(n,...r){for(let o of r)t.has(o)||t.set(o,[]),t.set(o,[..._nullishCoalesce(t.get(o), () => ([])),n])},dequeue:()=>{let n=e;return e=[],n}}};var at=t=>t,J= exports.inlineProjections =t=>t.map(e=>({type:"inline",projection:e})),X= exports.asyncProjections =t=>t.map(e=>({type:"async",projection:e})),st= exports.projections ={inline:J,async:X};var w=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},u= exports.JSONParser ={stringify:(t,e)=>JSON.stringify(_optionalChain([e, 'optionalAccess', _14 => _14.map])?e.map(t):t,(n,r)=>typeof r=="bigint"?r.toString():r),parse:(t,e)=>{let n=JSON.parse(t,_optionalChain([e, 'optionalAccess', _15 => _15.reviver]));if(_optionalChain([e, 'optionalAccess', _16 => _16.typeCheck])&&!_optionalChain([e, 'optionalAccess', _17 => _17.typeCheck, 'call', _18 => _18(n)]))throw new w(t);return _optionalChain([e, 'optionalAccess', _19 => _19.map])?e.map(n):n}};var b=t=>{let e=t.reduce((o,a)=>o+a.length,0),n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.length;return n};var yt=async t=>{let e=[];for await(let n of t)e.push(n);return e};var v= (_class =class{constructor() { _class.prototype.__init.call(this); }__init() {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),n=new TextDecoder().decode(e),r=n.indexOf(`
3
+ `);if(r===-1)return null;let o=n.slice(0,r),a=new Uint8Array(e.buffer,r+1);return this.buffer=a.byteLength>0?[a]:[],JSON.parse(o)}}, _class);var S= (_class2 =class{constructor(e){;_class2.prototype.__init2.call(this);this.transform=e;this.transform=e}__init2() {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 n=e.indexOf(`
5
+ `),r=e.slice(0,n).trim();return this.buffer=[e.slice(n+1)],this.transform(r)}}, _class2);var x=class extends S{constructor(){super(e=>JSON.parse(e))}};var g= (_class3 =class{constructor() { _class3.prototype.__init3.call(this); }__init3() {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}}, _class3);var P=class{constructor(e){this.decoders=e}decoderFor(e){let n=this.decoders.find(r=>r[0](e));return n?n[1]:null}addToBuffer(e){_optionalChain([this, 'access', _20 => _20.decoderFor, 'call', _21 => _21(e), 'optionalAccess', _22 => _22.addToBuffer, 'call', _23 => _23(e)])}clearBuffer(){for(let e of this.decoders.map(n=>n[1]))e.clearBuffer()}hasCompleteMessage(){return this.decoders.some(e=>e[1].hasCompleteMessage())}decode(){return _nullishCoalesce(_optionalChain([this, 'access', _24 => _24.decoders, 'access', _25 => _25.map, 'call', _26 => _26(n=>n[1]), 'access', _27 => _27.find, 'call', _28 => _28(n=>n.hasCompleteMessage()), 'optionalAccess', _29 => _29.decode, 'call', _30 => _30()]), () => (null))}},h= exports.DefaultDecoder =class extends P{constructor(){super([[e=>typeof e=="string",new x],[e=>e instanceof Uint8Array,new v],[e=>typeof e=="object",new g]])}};var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);var _webstreamspolyfill = require('web-streams-polyfill');var Nt=(t,e=o=>o,n={forever:!0,minTimeout:25},r=new h)=>new (0, _webstreamspolyfill.TransformStream)({start(o){_asyncretry2.default.call(void 0, ()=>z(t,o,e,r),n).catch(a=>{o.error(a)})}}).readable,z=async(t,e,n,r)=>{let a=t().getReader();try{let i;do i=await Q(a,e,n,r);while(!i)}finally{a.releaseLock()}},Q=async(t,e,n,r)=>{let{done:o,value:a}=await t.read();return a&&r.addToBuffer(a),!o&&!r.hasCompleteMessage()?!1:(Z(r,n,e),o&&e.terminate(),o)},Z=(t,e,n)=>{try{let r=t.decode();if(!r)return;let o=e(r);n.enqueue(o)}catch(r){n.error(new Error(`Decoding error: ${_optionalChain([r, 'optionalAccess', _31 => _31.toString, 'call', _32 => _32()])}`))}};var m=(t,e)=>{if(ee(t))return t.equals(e);if(Array.isArray(t))return Array.isArray(e)&&t.length===e.length&&t.every((o,a)=>m(o,e[a]));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),r=Object.keys(e);if(n.length!==r.length||!n.every(o=>r.includes(o)))return!1;for(let o in t){if(t[o]instanceof Function&&e[o]instanceof Function)continue;if(!m(t[o],e[o]))return!1}return!0},ee= exports.isEquatable =t=>t&&typeof t=="object"&&"equals"in t&&typeof t.equals=="function";var Kt=t=>{let e,n,r=0;do({value:e,done:n}=t.next()),r+=e||0;while(!n);return r};var Xt=(t,e,n,r,o=()=>{})=>{let a=!1,i=t.map(d=>n(d)?(a=!0,r(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]:i};var p=class extends Error{constructor(e){super(e)}},N= exports.isSubset =(t,e)=>{let n=t,r=e;return k(n),k(r),Object.keys(r).every(o=>typeof r[o]=="object"?N(n[o],r[o]):r[o]===n[o])},nn= exports.assertFails =t=>{throw new p(_nullishCoalesce(t, () => ("That should not ever happened, right?")))},rn= exports.assertThrowsAsync =async(t,e)=>{try{throw await t(),new p("Function didn't throw expected error")}catch(n){let r=n;return e&&s(e(r)),r}},on= exports.assertThrows =(t,e)=>{try{throw t(),new p("Function didn't throw expected error")}catch(n){let r=n;return e&&s(e(r)),r}},W= exports.assertMatches =(t,e,n)=>{if(!N(t,e))throw new p(_nullishCoalesce(n, () => (`subObj:
6
6
  ${u.stringify(e)}
7
7
  is not subset of
8
- ${u.stringify(t)}`)))},cr= exports.assertDeepEqual =(t,e,r)=>{if(!m(t,e))throw new p(_nullishCoalesce(r, () => (`subObj:
8
+ ${u.stringify(t)}`)))},an= exports.assertDeepEqual =(t,e,n)=>{if(!m(t,e))throw new p(_nullishCoalesce(n, () => (`subObj:
9
9
  ${u.stringify(e)}
10
10
  is not equal to
11
- ${u.stringify(t)}`)))},ur= exports.assertNotDeepEqual =(t,e,r)=>{if(m(t,e))throw new p(_nullishCoalesce(r, () => (`subObj:
11
+ ${u.stringify(t)}`)))},sn= exports.assertNotDeepEqual =(t,e,n)=>{if(m(t,e))throw new p(_nullishCoalesce(n, () => (`subObj:
12
12
  ${u.stringify(e)}
13
13
  is equals to
14
- ${u.stringify(t)}`)))},lr= exports.assertThat =t=>({isEqualTo:e=>s(m(t,e))});function de(t,e){if(t)throw new p(_nullishCoalesce(e, () => ("Condition is false")))}function s(t,e){if(!t)throw new p(_nullishCoalesce(e, () => ("Condition is false")))}function H(t,e){if(!t)throw new p(_nullishCoalesce(e, () => ("Condition is not truthy")))}function T(t,e,r){if(t!==e)throw new p(`${_nullishCoalesce(r, () => ("Objects are not equal"))}:
14
+ ${u.stringify(t)}`)))},dn= exports.assertThat =t=>({isEqualTo:e=>s(m(t,e))});function te(t,e){if(t)throw new p(_nullishCoalesce(e, () => ("Condition is false")))}function s(t,e){if(!t)throw new p(_nullishCoalesce(e, () => ("Condition is false")))}function k(t,e){if(!t)throw new p(_nullishCoalesce(e, () => ("Condition is not truthy")))}function l(t,e,n){if(t!==e)throw new p(`${_nullishCoalesce(n, () => ("Objects are not equal"))}:
15
15
  Expected: ${u.stringify(t)}
16
- Actual:${u.stringify(e)}`)}function G(t,e,r){if(t===e)throw new p(_nullishCoalesce(r, () => (`Objects are equal: ${u.stringify(t)}`)))}function yr(t){G(t,null),H(t)}function Tr(t){T(t,null)}var Er=t=>e=>m(e,t),fr= exports.argMatches =t=>e=>t(e);function Sr(t){return{calledTimes:e=>{T(_optionalChain([t, 'access', _38 => _38.mock, 'optionalAccess', _39 => _39.calls, 'optionalAccess', _40 => _40.length]),e)},notCalled:()=>{T(_optionalChain([t, 'optionalAccess', _41 => _41.mock, 'optionalAccess', _42 => _42.calls, 'optionalAccess', _43 => _43.length]),0)},called:()=>{s(_optionalChain([t, 'access', _44 => _44.mock, 'optionalAccess', _45 => _45.calls, 'access', _46 => _46.length])!==void 0&&t.mock.calls.length>0)},calledWith:(...e)=>{s(_optionalChain([t, 'access', _47 => _47.mock, 'optionalAccess', _48 => _48.calls, 'access', _49 => _49.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(r=>m(r.arguments,e)))},calledOnceWith:(...e)=>{s(_optionalChain([t, 'access', _50 => _50.mock, 'optionalAccess', _51 => _51.calls, 'access', _52 => _52.length])!==void 0&&t.mock.calls.length===1&&t.mock.calls.some(r=>m(r.arguments,e)))},calledWithArgumentMatching:(...e)=>{s(_optionalChain([t, 'access', _53 => _53.mock, 'optionalAccess', _54 => _54.calls, 'access', _55 => _55.length])!==void 0&&t.mock.calls.length>=1),s(_optionalChain([t, 'access', _56 => _56.mock, 'optionalAccess', _57 => _57.calls, 'access', _58 => _58.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)=>{de(_optionalChain([t, 'access', _59 => _59.mock, 'optionalAccess', _60 => _60.calls, 'access', _61 => _61.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 vr=t=>({isEmpty:()=>T(t.length,0),isNotEmpty:()=>G(t.length,0),hasSize:e=>T(t.length,e),containsElements:(...e)=>{s(e.every(r=>e.some(n=>m(r,n))))},containsExactlyInAnyOrder:(...e)=>{T(t.length,e.length),s(t.every(r=>e.some(n=>m(r,n))))},containsExactlyInAnyOrderElementsOf:e=>{T(t.length,e.length),s(t.every(r=>e.some(n=>m(r,n))))},containsExactlyElementsOf:e=>{T(t.length,e.length);for(let r=0;r<t.length;r++)s(m(t[r],e[r]))},containsExactly:e=>{T(t.length,1),s(m(t[0],e))},contains:e=>{s(t.some(r=>m(r,e)))},containsOnlyOnceElementsOf:e=>{s(e.map(r=>t.filter(n=>m(n,r)).length).filter(r=>r===1).length===e.length)},containsAnyOf:(...e)=>{s(t.some(r=>e.some(n=>m(r,n))))},allMatch:e=>{s(t.every(e))},anyMatches:e=>{s(t.some(e))},allMatchAsync:async e=>{for(let r of t)s(await e(r))}});var Cr={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(),d=Array.isArray(a)?a:[a],i=Array.isArray(o)?o:[o];q(d,i)},thenThrows:(...o)=>{try{throw n(),new p("Handler did not fail as expected")}catch(a){if(a instanceof p)throw a;if(o.length===0)return;if(!W(o[0])){s(o[0](a),`Error didn't match the error condition: ${_optionalChain([a, 'optionalAccess', _62 => _62.toString, 'call', _63 => _63()])}`);return}s(a instanceof o[0],`Caught error is not an instance of the expected type: ${_optionalChain([a, 'optionalAccess', _64 => _64.toString, 'call', _65 => _65()])}`),o[1]&&s(o[1](a),`Error didn't match the error condition: ${_optionalChain([a, 'optionalAccess', _66 => _66.toString, 'call', _67 => _67()])}`)}}}}})};var Rr=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),d=_nullishCoalesce(e.get(r), () => ([r,[]]));return e.set(r,[r,[...d[1],...n]]),a},appendedEvents:e,setup:async(r,n)=>t.appendToStream(r,n)}};exports.AssertionError = p; exports.BinaryJsonDecoder = g; exports.CommandHandler = U; exports.CompositeDecoder = N; exports.ConcurrencyError = v; exports.DeciderCommandHandler = Ie; exports.DeciderSpecification = Cr; exports.DefaultDecoder = O; exports.EmmettError = y; exports.ExpectedVersionConflictError = b; exports.IllegalStateError = _; exports.JSONParser = u; exports.JsonDecoder = C; exports.NO_CONCURRENCY_CHECK = x; exports.NotFoundError = B; exports.ObjectDecoder = D; exports.ParseError = A; exports.STREAM_DOES_NOT_EXIST = P; exports.STREAM_EXISTS = L; exports.StringDecoder = h; exports.ValidationError = l; exports.ValidationErrors = X; exports.WrapEventStore = Rr; exports.accept = Qe; exports.argMatches = fr; exports.argValue = Er; exports.assertDeepEqual = cr; exports.assertEqual = T; exports.assertExpectedVersionMatchesCurrent = k; exports.assertFails = dr; exports.assertFalse = de; exports.assertIsNotNull = yr; exports.assertIsNull = Tr; exports.assertMatches = q; exports.assertNotDeepEqual = ur; exports.assertNotEmptyString = Ee; exports.assertNotEqual = G; exports.assertOk = H; exports.assertPositiveNumber = fe; exports.assertThat = lr; exports.assertThatArray = vr; exports.assertThrows = pr; exports.assertThrowsAsync = mr; exports.assertTrue = s; exports.assertUnsignedBigInt = Se; exports.asyncProjections = te; exports.canCreateEventStoreSession = I; exports.collectStream = xt; exports.command = Ue; exports.complete = Le; exports.concatUint8Arrays = j; exports.deepEquals = m; exports.error = ze; exports.event = qe; exports.formatDateToUtcYYYYMMDD = ue; exports.getInMemoryEventStore = we; exports.getInMemoryMessageBus = mt; exports.ignore = Ze; exports.inlineProjections = ee; exports.isEquatable = ie; exports.isErrorConstructor = W; exports.isNumber = w; exports.isString = M; exports.isSubset = $; exports.isValidYYYYMMDD = J; exports.matchesExpectedVersion = Z; exports.merge = er; exports.nulloSessionFactory = F; exports.parseDateFromUtcYYYYMMDD = le; exports.projection = ct; exports.projections = ut; exports.publish = Je; exports.reply = Ye; exports.restream = qt; exports.schedule = Xe; exports.send = Ke; exports.sum = zt; exports.verifyThat = Sr;
16
+ Actual:${u.stringify(e)}`)}function _(t,e,n){if(t===e)throw new p(_nullishCoalesce(n, () => (`Objects are equal: ${u.stringify(t)}`)))}function mn(t){_(t,null),k(t)}function pn(t){l(t,null)}var cn=t=>e=>m(e,t),un= exports.argMatches =t=>e=>t(e);function ln(t){return{calledTimes:e=>{l(_optionalChain([t, 'access', _33 => _33.mock, 'optionalAccess', _34 => _34.calls, 'optionalAccess', _35 => _35.length]),e)},notCalled:()=>{l(_optionalChain([t, 'optionalAccess', _36 => _36.mock, 'optionalAccess', _37 => _37.calls, 'optionalAccess', _38 => _38.length]),0)},called:()=>{s(_optionalChain([t, 'access', _39 => _39.mock, 'optionalAccess', _40 => _40.calls, 'access', _41 => _41.length])!==void 0&&t.mock.calls.length>0)},calledWith:(...e)=>{s(_optionalChain([t, 'access', _42 => _42.mock, 'optionalAccess', _43 => _43.calls, 'access', _44 => _44.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(n=>m(n.arguments,e)))},calledOnceWith:(...e)=>{s(_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(n=>m(n.arguments,e)))},calledWithArgumentMatching:(...e)=>{s(_optionalChain([t, 'access', _48 => _48.mock, 'optionalAccess', _49 => _49.calls, 'access', _50 => _50.length])!==void 0&&t.mock.calls.length>=1),s(_optionalChain([t, 'access', _51 => _51.mock, 'optionalAccess', _52 => _52.calls, 'access', _53 => _53.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls.some(n=>n.arguments&&n.arguments.length>=e.length&&e.every((r,o)=>r(n.arguments[o]))))},notCalledWithArgumentMatching:(...e)=>{te(_optionalChain([t, 'access', _54 => _54.mock, 'optionalAccess', _55 => _55.calls, 'access', _56 => _56.length])!==void 0&&t.mock.calls.length>=1&&t.mock.calls[0].arguments&&t.mock.calls[0].arguments.length>=e.length&&e.every((n,r)=>n(t.mock.calls[0].arguments[r])))}}}var yn=t=>({isEmpty:()=>l(t.length,0),isNotEmpty:()=>_(t.length,0),hasSize:e=>l(t.length,e),containsElements:(...e)=>{s(e.every(n=>e.some(r=>m(n,r))))},containsExactlyInAnyOrder:(...e)=>{l(t.length,e.length),s(t.every(n=>e.some(r=>m(n,r))))},containsExactlyInAnyOrderElementsOf:e=>{l(t.length,e.length),s(t.every(n=>e.some(r=>m(n,r))))},containsExactlyElementsOf:e=>{l(t.length,e.length);for(let n=0;n<t.length;n++)s(m(t[n],e[n]))},containsExactly:e=>{l(t.length,1),s(m(t[0],e))},contains:e=>{s(t.some(n=>m(n,e)))},containsOnlyOnceElementsOf:e=>{s(e.map(n=>t.filter(r=>m(r,n)).length).filter(n=>n===1).length===e.length)},containsAnyOf:(...e)=>{s(t.some(n=>e.some(r=>m(n,r))))},allMatch:e=>{s(t.every(e))},anyMatches:e=>{s(t.some(e))},allMatchAsync:async e=>{for(let n of t)s(await e(n))}});var vn={for:t=>e=>({when:n=>{let r=()=>{let a=(Array.isArray(e)?e:[e]).reduce(t.evolve,t.initialState());return t.decide(n,a)};return{then:o=>{let a=r(),i=Array.isArray(a)?a:[a],d=Array.isArray(o)?o:[o];W(i,d)},thenThrows:(...o)=>{try{throw r(),new p("Handler did not fail as expected")}catch(a){if(a instanceof p)throw a;if(o.length===0)return;if(!_chunk6TXKRKDJjs.j.call(void 0, o[0])){s(o[0](a),`Error didn't match the error condition: ${_optionalChain([a, 'optionalAccess', _57 => _57.toString, 'call', _58 => _58()])}`);return}s(a instanceof o[0],`Caught error is not an instance of the expected type: ${_optionalChain([a, 'optionalAccess', _59 => _59.toString, 'call', _60 => _60()])}`),o[1]&&s(o[1](a),`Error didn't match the error condition: ${_optionalChain([a, 'optionalAccess', _61 => _61.toString, 'call', _62 => _62()])}`)}}}}})};var gn=t=>{let e=new Map;return{async aggregateStream(n,r){return t.aggregateStream(n,r)},readStream(n,r){return t.readStream(n,r)},appendToStream:async(n,r,o)=>{let a=await t.appendToStream(n,r,o),i=_nullishCoalesce(e.get(n), () => ([n,[]]));return e.set(n,[n,[...i[1],...r]]),a},appendedEvents:e,setup:async(n,r)=>t.appendToStream(n,r)}};exports.AssertionError = p; exports.BinaryJsonDecoder = v; exports.CommandHandler = I; exports.CompositeDecoder = P; exports.ConcurrencyError = _chunk6TXKRKDJjs.l; exports.DeciderCommandHandler = Pe; exports.DeciderSpecification = vn; exports.DefaultDecoder = h; exports.EmmettError = _chunk6TXKRKDJjs.k; exports.ExpectedVersionConflictError = V; exports.IllegalStateError = _chunk6TXKRKDJjs.n; exports.JSONParser = u; exports.JsonDecoder = x; exports.NO_CONCURRENCY_CHECK = f; exports.NotFoundError = _chunk6TXKRKDJjs.o; exports.ObjectDecoder = g; exports.ParseError = w; exports.STREAM_DOES_NOT_EXIST = O; exports.STREAM_EXISTS = U; exports.StringDecoder = S; exports.ValidationError = _chunk6TXKRKDJjs.m; exports.ValidationErrors = _chunk6TXKRKDJjs.d; exports.WrapEventStore = gn; exports.accept = Je; exports.argMatches = un; exports.argValue = cn; exports.assertDeepEqual = an; exports.assertEqual = l; exports.assertExpectedVersionMatchesCurrent = M; exports.assertFails = nn; exports.assertFalse = te; exports.assertIsNotNull = mn; exports.assertIsNull = pn; exports.assertMatches = W; exports.assertNotDeepEqual = sn; exports.assertNotEmptyString = _chunk6TXKRKDJjs.g; exports.assertNotEqual = _; exports.assertOk = k; exports.assertPositiveNumber = _chunk6TXKRKDJjs.h; exports.assertThat = dn; exports.assertThatArray = yn; exports.assertThrows = on; exports.assertThrowsAsync = rn; exports.assertTrue = s; exports.assertUnsignedBigInt = _chunk6TXKRKDJjs.i; exports.asyncProjections = X; exports.canCreateEventStoreSession = H; exports.collectStream = yt; exports.command = Fe; exports.complete = $e; exports.concatUint8Arrays = b; exports.deepEquals = m; exports.error = Ke; exports.event = Ne; exports.formatDateToUtcYYYYMMDD = _chunk6TXKRKDJjs.a; exports.getInMemoryEventStore = he; exports.getInMemoryMessageBus = rt; exports.ignore = Ge; exports.inlineProjections = J; exports.isEquatable = ee; exports.isErrorConstructor = _chunk6TXKRKDJjs.j; exports.isNumber = _chunk6TXKRKDJjs.e; exports.isPluginConfig = _chunk6TXKRKDJjs.p; exports.isString = _chunk6TXKRKDJjs.f; exports.isSubset = N; exports.isValidYYYYMMDD = _chunk6TXKRKDJjs.b; exports.matchesExpectedVersion = $; exports.merge = Xt; exports.nulloSessionFactory = F; exports.parseDateFromUtcYYYYMMDD = _chunk6TXKRKDJjs.c; exports.projection = at; exports.projections = st; exports.publish = qe; exports.reply = _e; exports.restream = Nt; exports.schedule = Ue; exports.send = Be; exports.sum = Kt; exports.verifyThat = ln;
17
17
  //# sourceMappingURL=index.js.map