@event-driven-io/emmett-fastify 0.9.0 → 0.10.0

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 _chunkUXU77SIWjs = require('./chunk-UXU77SIW.js');var _chunkYTHGSSIVjs = require('./chunk-YTHGSSIV.js');var S=(p=>(p.CART_ALREADY_EXISTS="CART_ALREADY_EXISTS",p.CART_IS_ALREADY_CLOSED="CART_IS_ALREADY_CLOSED",p.PRODUCT_ITEM_NOT_FOUND="PRODUCT_ITEM_NOT_FOUND",p.CART_IS_EMPTY="CART_IS_EMPTY",p.UNKNOWN_EVENT_TYPE="UNKNOWN_EVENT_TYPE",p.UNKNOWN_COMMAND_TYPE="UNKNOWN_COMMAND_TYPE",p))(S||{}),I= exports.b =(o,{productId:t,quantity:r,unitPrice:n})=>{if((_nullishCoalesce(_optionalChain([o, 'access', _ => _.find, 'call', _2 => _2(i=>i.productId===t&&i.unitPrice==n), 'optionalAccess', _3 => _3.quantity]), () => (0)))<r)throw new (0, _chunkYTHGSSIVjs.f)("PRODUCT_ITEM_NOT_FOUND")},g= exports.c =({type:o,data:t},r)=>{switch(o){case"OpenShoppingCart":{if(r.status!=="Empty")throw new (0, _chunkYTHGSSIVjs.f)("CART_ALREADY_EXISTS");return{type:"ShoppingCartOpened",data:{shoppingCartId:t.shoppingCartId,clientId:t.clientId,openedAt:t.now}}}case"AddProductItemToShoppingCart":{if(r.status!=="Pending")throw new (0, _chunkYTHGSSIVjs.f)("CART_IS_ALREADY_CLOSED");return{type:"ProductItemAddedToShoppingCart",data:{shoppingCartId:t.shoppingCartId,productItem:t.productItem}}}case"RemoveProductItemFromShoppingCart":{if(r.status!=="Pending")throw new (0, _chunkYTHGSSIVjs.f)("CART_IS_ALREADY_CLOSED");return I(r.productItems,t.productItem),{type:"ProductItemRemovedFromShoppingCart",data:{shoppingCartId:t.shoppingCartId,productItem:t.productItem}}}case"ConfirmShoppingCart":{if(r.status!=="Pending")throw new (0, _chunkYTHGSSIVjs.f)("CART_IS_ALREADY_CLOSED");if(r.productItems.length===0)throw new (0, _chunkYTHGSSIVjs.f)("CART_IS_EMPTY");return{type:"ShoppingCartConfirmed",data:{shoppingCartId:t.shoppingCartId,confirmedAt:t.now}}}case"CancelShoppingCart":{if(r.status!=="Pending")throw new (0, _chunkYTHGSSIVjs.f)("CART_IS_ALREADY_CLOSED");return{type:"ShoppingCartCanceled",data:{shoppingCartId:t.shoppingCartId,canceledAt:t.now}}}default:{let n=t;throw new (0, _chunkYTHGSSIVjs.e)("UNKNOWN_COMMAND_TYPE")}}},u= exports.d ={decide:g,evolve:_chunkUXU77SIWjs.c,initialState:()=>_chunkUXU77SIWjs.b};exports.a = S; exports.b = I; exports.c = g; exports.d = u;
2
+ //# sourceMappingURL=chunk-EMCVUR73.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/e2e/decider/businessLogic.ts"],"names":["ShoppingCartErrors","assertProductItemExists","productItems","productId","quantity","unitPrice","p","d","decide","type","command","shoppingCart","_","s","decider","evolve","emptyShoppingCart"],"mappings":"8FAuEO,IAAWA,OAChBA,EAAA,oBAAsB,sBACtBA,EAAA,uBAAyB,yBACzBA,EAAA,uBAAyB,yBACzBA,EAAA,cAAgB,gBAChBA,EAAA,mBAAqB,qBACrBA,EAAA,qBAAuB,uBANPA,OAAA,IASLC,EAA0B,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WAAYA,EAAQ,GACtB,CACF,CACF,CACA,QAAS,CACP,IAAME,EAAWF,EACjB,MAAM,IAAIG,EAAY,sBAAuC,CAC/D,CACF,CACF,EAEaC,EAIT,CACF,OAAAN,EACA,OAAAO,EACA,aAAc,IAAMC,CACtB","sourcesContent":["import {\n EmmettError,\n IllegalStateError,\n type Decider,\n} from '@event-driven-io/emmett';\n\nimport {\n ShoppingCartStatus,\n emptyShoppingCart,\n evolve,\n type PricedProductItem,\n type ShoppingCart,\n type ShoppingCartEvent,\n} from './shoppingCart';\n\n//////////////////////////////////////\n/// Commands\n//////////////////////////////////////\n\nexport type OpenShoppingCart = {\n type: 'OpenShoppingCart';\n data: {\n shoppingCartId: string;\n clientId: string;\n now: Date;\n };\n};\n\nexport type AddProductItemToShoppingCart = {\n type: 'AddProductItemToShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n};\n\nexport type RemoveProductItemFromShoppingCart = {\n type: 'RemoveProductItemFromShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n};\n\nexport type ConfirmShoppingCart = {\n type: 'ConfirmShoppingCart';\n data: {\n shoppingCartId: string;\n now: Date;\n };\n};\n\nexport type CancelShoppingCart = {\n type: 'CancelShoppingCart';\n data: {\n shoppingCartId: string;\n now: Date;\n };\n};\n\nexport type ShoppingCartCommand =\n | OpenShoppingCart\n | AddProductItemToShoppingCart\n | RemoveProductItemFromShoppingCart\n | ConfirmShoppingCart\n | CancelShoppingCart;\n\n//////////////////////////////////////\n/// Decide\n//////////////////////////////////////\n\nexport const enum ShoppingCartErrors {\n CART_ALREADY_EXISTS = 'CART_ALREADY_EXISTS',\n CART_IS_ALREADY_CLOSED = 'CART_IS_ALREADY_CLOSED',\n PRODUCT_ITEM_NOT_FOUND = 'PRODUCT_ITEM_NOT_FOUND',\n CART_IS_EMPTY = 'CART_IS_EMPTY',\n UNKNOWN_EVENT_TYPE = 'UNKNOWN_EVENT_TYPE',\n UNKNOWN_COMMAND_TYPE = 'UNKNOWN_COMMAND_TYPE',\n}\n\nexport const assertProductItemExists = (\n productItems: PricedProductItem[],\n { productId, quantity, unitPrice }: PricedProductItem,\n): void => {\n const currentQuantity =\n productItems.find(\n (p) => p.productId === productId && p.unitPrice == unitPrice,\n )?.quantity ?? 0;\n\n if (currentQuantity < quantity) {\n throw new IllegalStateError(ShoppingCartErrors.PRODUCT_ITEM_NOT_FOUND);\n }\n};\n\nexport const decide = (\n { type, data: command }: ShoppingCartCommand,\n shoppingCart: ShoppingCart,\n): ShoppingCartEvent => {\n switch (type) {\n case 'OpenShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Empty) {\n throw new IllegalStateError(ShoppingCartErrors.CART_ALREADY_EXISTS);\n }\n return {\n type: 'ShoppingCartOpened',\n data: {\n shoppingCartId: command.shoppingCartId,\n clientId: command.clientId,\n openedAt: command.now,\n },\n };\n }\n\n case 'AddProductItemToShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n return {\n type: 'ProductItemAddedToShoppingCart',\n data: {\n shoppingCartId: command.shoppingCartId,\n productItem: command.productItem,\n },\n };\n }\n\n case 'RemoveProductItemFromShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n assertProductItemExists(shoppingCart.productItems, command.productItem);\n\n return {\n type: 'ProductItemRemovedFromShoppingCart',\n data: {\n shoppingCartId: command.shoppingCartId,\n productItem: command.productItem,\n },\n };\n }\n\n case 'ConfirmShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n if (shoppingCart.productItems.length === 0) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_EMPTY);\n }\n\n return {\n type: 'ShoppingCartConfirmed',\n data: {\n shoppingCartId: command.shoppingCartId,\n confirmedAt: command.now,\n },\n };\n }\n\n case 'CancelShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n return {\n type: 'ShoppingCartCanceled',\n data: {\n shoppingCartId: command.shoppingCartId,\n canceledAt: command.now,\n },\n };\n }\n default: {\n const _: never = command;\n throw new EmmettError(ShoppingCartErrors.UNKNOWN_COMMAND_TYPE);\n }\n }\n};\n\nexport const decider: Decider<\n ShoppingCart,\n ShoppingCartCommand,\n ShoppingCartEvent\n> = {\n decide,\n evolve,\n initialState: () => emptyShoppingCart,\n};\n"]}
@@ -0,0 +1,5 @@
1
+ var c=class extends Error{constructor(t){super(t)}},p=(t,e)=>{let r=t,a=e;return Object.keys(a).every(s=>typeof a[s]=="object"?p(r[s],a[s]):a[s]===r[s])};var N=(t,e,r)=>{if(!p(t,e))throw new c(r??`subObj:
2
+ ${JSON.stringify(e)}
3
+ is not subset of
4
+ ${JSON.stringify(t)}`)};function k(t,e){if(!t)throw new c(e??"Condition is not truthy")}var O=(t=>(t.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",t.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",t.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",t))(O||{}),u=t=>typeof t=="number"&&t===t,g=t=>typeof t=="string",C=t=>{if(!g(t)||t.length===0)throw new f("NOT_A_NONEMPTY_STRING");return t},_=t=>{if(!u(t)||t<=0)throw new f("NOT_A_POSITIVE_NUMBER");return t};var h=class w extends Error{errorCode;constructor(e){let r=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:u(e)?e:500,a=e&&typeof e=="object"&&"message"in e?e.message:g(e)?e:`Error with status code '${r}' ocurred during Emmett processing`;super(a),this.errorCode=r,Object.setPrototypeOf(this,w.prototype)}};var f=class x extends h{constructor(e){super({errorCode:400,message:e??"Validation Error ocurred during Emmett processing"}),Object.setPrototypeOf(this,x.prototype)}},M=class A extends h{constructor(e){super({errorCode:403,message:e??"Illegal State ocurred during Emmett processing"}),Object.setPrototypeOf(this,A.prototype)}};var j=(t,e,r,a,s=()=>{})=>{let i=!1,n=t.map(o=>r(o)?(i=!0,a(o)):o).filter(o=>o!==void 0).map(o=>{if(!o)throw Error("That should not happen");return o});return!i&&s()!==void 0?[...t,e]:n};var y="STREAM_DOES_NOT_EXIST",E="NO_CONCURRENCY_CHECK";var S=(t,e,r=a=>a)=>async(a,s,i,n)=>{let o=r(s),l=await a.aggregateStream(o,{evolve:t,initialState:e,read:{expectedStreamVersion:n?.expectedStreamVersion??E}}),v=l?.state??e(),I=l?.currentStreamVersion,m=i(v),d=Array.isArray(m)?m:[m],T=n?.expectedStreamVersion??I??y;return{...await a.appendToStream(o,d,{...n,expectedStreamVersion:T}),newEvents:d,newState:d.reduce(t,v)}};var V=({decide:t,evolve:e,initialState:r},a=s=>s)=>async(s,i,n,o)=>S(e,r,a)(s,i,l=>t(n,l),o);import{v4 as ct}from"uuid";export{N as a,k as b,C as c,_ as d,h as e,M as f,j as g,V as h};
5
+ //# sourceMappingURL=chunk-IA2ESUCU.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../emmett/src/testing/assertions.ts","../../emmett/src/validation/index.ts","../../emmett/src/errors/index.ts","../../emmett/src/validation/dates.ts","../../emmett/src/utils/merge.ts","../../emmett/src/eventStore/expectedVersion.ts","../../emmett/src/commandHandling/handleCommand.ts","../../emmett/src/commandHandling/handleCommandWithDecider.ts","../../emmett/src/eventStore/inMemoryEventStore.ts"],"sourcesContent":["import type { DefaultRecord } from '../typing';\nimport { deepEquals } from '../utils';\n\nexport class AssertionError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\nexport const isSubset = (superObj: unknown, subObj: unknown): boolean => {\n const sup = superObj as DefaultRecord;\n const sub = subObj as DefaultRecord;\n\n return Object.keys(sub).every((ele: string) => {\n if (typeof sub[ele] == 'object') {\n return isSubset(sup[ele], sub[ele]);\n }\n return sub[ele] === sup[ele];\n });\n};\n\nexport const assertFails = () => {\n throw new AssertionError('That should not ever happened, right?');\n};\n\nexport const assertThrows = (\n fun: () => void,\n errorCheck?: (error: Error) => boolean,\n) => {\n try {\n fun();\n throw new AssertionError(\"Function didn't throw expected error\");\n } catch (error) {\n if (errorCheck) assertTrue(errorCheck(error as Error));\n }\n};\n\nexport const assertMatches = (\n actual: unknown,\n expected: unknown,\n message?: string,\n) => {\n if (!isSubset(actual, expected))\n throw new AssertionError(\n message ??\n `subObj:\\n${JSON.stringify(expected)}\\nis not subset of\\n${JSON.stringify(actual)}`,\n );\n};\n\nexport const assertDeepEqual = (\n actual: unknown,\n expected: unknown,\n message?: string,\n) => {\n if (!deepEquals(actual, expected))\n throw new AssertionError(\n message ??\n `subObj:\\n${JSON.stringify(expected)}\\nis equals to\\n${JSON.stringify(actual)}`,\n );\n};\n\nexport const assertThat = <T>(item: T) => {\n return {\n isEqualTo: (other: T) => assertTrue(deepEquals(item, other)),\n };\n};\n\nexport function assertFalse(\n condition: boolean,\n message?: string,\n): asserts condition is false {\n if (condition) throw new AssertionError(message ?? `Condition is false`);\n}\n\nexport function assertTrue(\n condition: boolean,\n message?: string,\n): asserts condition is true {\n if (!condition) throw new AssertionError(message ?? `Condition is false`);\n}\n\nexport function assertOk<T>(\n obj: T | null | undefined,\n message?: string,\n): asserts obj is T {\n if (!obj) throw new AssertionError(message ?? `Condition is not truthy`);\n}\n\nexport function assertEqual<T>(\n obj: T | null | undefined,\n other: T | null | undefined,\n message?: string,\n): void {\n if (obj !== other)\n throw new AssertionError(\n message ??\n `Objects are not equal:\\n ${JSON.stringify(obj)}\\ncompared:\\n${JSON.stringify(other)}`,\n );\n}\n\nexport function assertNotEqual<T>(\n obj: T | null | undefined,\n other: T | null | undefined,\n message?: string,\n): void {\n if (obj === other)\n throw new AssertionError(\n message ?? `Objects are equal: ${JSON.stringify(obj)}`,\n );\n}\n\nexport function assertIsNotNull<T extends object>(\n result: T | null,\n): asserts result is T {\n assertNotEqual(result, null);\n assertOk(result);\n}\n\nexport function assertIsNull<T extends object>(\n result: T | null,\n): asserts result is null {\n assertEqual(result, null);\n}\n\ntype Call = {\n arguments: unknown[];\n result: unknown;\n target: unknown;\n this: unknown;\n};\n\nexport type ArgumentMatcher = (arg: unknown) => boolean;\n\nexport const argValue =\n <T>(value: T): ArgumentMatcher =>\n (arg) =>\n deepEquals(arg, value);\n\nexport const argMatches =\n <T>(matches: (arg: T) => boolean): ArgumentMatcher =>\n (arg) =>\n matches(arg as T);\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport type MockedFunction = Function & { mock?: { calls: Call[] } };\n\nexport function verifyThat(fn: MockedFunction) {\n return {\n calledTimes: (times: number) => {\n assertEqual(fn.mock?.calls?.length, times);\n },\n notCalled: () => {\n assertEqual(fn?.mock?.calls?.length, 0);\n },\n called: () => {\n assertTrue(\n fn.mock?.calls.length !== undefined && fn.mock.calls.length > 0,\n );\n },\n calledWith: (...args: unknown[]) => {\n assertTrue(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length >= 1 &&\n fn.mock.calls.some((call) => deepEquals(call.arguments, args)),\n );\n },\n calledOnceWith: (...args: unknown[]) => {\n assertTrue(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length === 1 &&\n fn.mock.calls.some((call) => deepEquals(call.arguments, args)),\n );\n },\n calledWithArgumentMatching: (...matches: ArgumentMatcher[]) => {\n assertTrue(\n fn.mock?.calls.length !== undefined && fn.mock.calls.length >= 1,\n );\n assertTrue(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length >= 1 &&\n fn.mock.calls.some(\n (call) =>\n call.arguments &&\n call.arguments.length >= matches.length &&\n matches.every((match, index) => match(call.arguments[index])),\n ),\n );\n },\n notCalledWithArgumentMatching: (...matches: ArgumentMatcher[]) => {\n assertFalse(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length >= 1 &&\n fn.mock.calls[0]!.arguments &&\n fn.mock.calls[0]!.arguments.length >= matches.length &&\n matches.every((match, index) =>\n match(fn.mock!.calls[0]!.arguments[index]),\n ),\n );\n },\n };\n}\n\nexport const assertThatArray = <T>(array: T[]) => {\n return {\n isEmpty: () => assertEqual(array.length, 0),\n hasSize: (length: number) => assertEqual(array.length, length),\n containsElements: (...other: T[]) => {\n assertTrue(other.every((ts) => other.some((o) => deepEquals(ts, o))));\n },\n containsExactlyInAnyOrder: (...other: T[]) => {\n assertEqual(array.length, other.length);\n assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));\n },\n containsExactlyInAnyOrderElementsOf: (other: T[]) => {\n assertEqual(array.length, other.length);\n assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));\n },\n containsExactlyElementsOf: (other: T[]) => {\n assertEqual(array.length, other.length);\n for (let i = 0; i < array.length; i++) {\n assertTrue(deepEquals(array[i], other[i]));\n }\n },\n containsExactly: (elem: T) => {\n assertEqual(array.length, 1);\n assertTrue(deepEquals(array[0], elem));\n },\n contains: (elem: T) => {\n assertTrue(array.some((a) => deepEquals(a, elem)));\n },\n containsOnlyOnceElementsOf: (other: T[]) => {\n assertTrue(\n other\n .map((o) => array.filter((a) => deepEquals(a, o)).length)\n .filter((a) => a === 1).length === other.length,\n );\n },\n containsAnyOf: (...other: T[]) => {\n assertTrue(array.some((a) => other.some((o) => deepEquals(a, o))));\n },\n allMatch: (matches: (item: T) => boolean) => {\n assertTrue(array.every(matches));\n },\n anyMatches: (matches: (item: T) => boolean) => {\n assertTrue(array.some(matches));\n },\n allMatchAsync: async (\n matches: (item: T) => Promise<boolean>,\n ): Promise<void> => {\n for (const item of array) {\n assertTrue(await matches(item));\n }\n },\n };\n};\n","import { ValidationError } from '../errors';\n\nexport const enum ValidationErrors {\n NOT_A_NONEMPTY_STRING = 'NOT_A_NONEMPTY_STRING',\n NOT_A_POSITIVE_NUMBER = 'NOT_A_POSITIVE_NUMBER',\n NOT_AN_UNSIGNED_BIGINT = 'NOT_AN_UNSIGNED_BIGINT',\n}\n\nexport const isNumber = (val: unknown): val is number =>\n typeof val === 'number' && val === val;\n\nexport const isString = (val: unknown): val is string =>\n typeof val === 'string';\n\nexport const assertNotEmptyString = (value: unknown): string => {\n if (!isString(value) || value.length === 0) {\n throw new ValidationError(ValidationErrors.NOT_A_NONEMPTY_STRING);\n }\n return value;\n};\n\nexport const assertPositiveNumber = (value: unknown): number => {\n if (!isNumber(value) || value <= 0) {\n throw new ValidationError(ValidationErrors.NOT_A_POSITIVE_NUMBER);\n }\n return value;\n};\n\nexport const assertUnsignedBigInt = (value: string): bigint => {\n const number = BigInt(value);\n if (number < 0) {\n throw new ValidationError(ValidationErrors.NOT_AN_UNSIGNED_BIGINT);\n }\n return number;\n};\n\nexport * from './dates';\n","import { isNumber, isString } from '../validation';\n\nexport type ErrorConstructor<ErrorType extends Error> = new (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: any[]\n) => ErrorType;\n\nexport const isErrorConstructor = <ErrorType extends Error>(\n // eslint-disable-next-line @typescript-eslint/ban-types\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 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\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","export const merge = <T>(\n array: T[],\n item: T,\n where: (current: T) => boolean,\n onExisting: (current: T) => T,\n onNotFound: () => T | undefined = () => undefined,\n) => {\n let wasFound = false;\n\n const result = array\n // merge the existing item if matches condition\n .map((p: T) => {\n if (!where(p)) return p;\n\n wasFound = true;\n return onExisting(p);\n })\n // filter out item if undefined was returned\n // for cases of removal\n .filter((p) => p !== undefined)\n // make TypeScript happy\n .map((p) => {\n if (!p) throw Error('That should not happen');\n\n return p;\n });\n\n // if item was not found and onNotFound action is defined\n // try to generate new item\n if (!wasFound) {\n const result = onNotFound();\n\n if (result !== undefined) return [...array, item];\n }\n\n return result;\n};\n","import { ConcurrencyError } from '../errors';\nimport type { Flavour } from '../typing';\nimport type { DefaultStreamVersionType } from './eventStore';\n\nexport type ExpectedStreamVersion<VersionType = DefaultStreamVersionType> =\n | ExpectedStreamVersionWithValue<VersionType>\n | ExpectedStreamVersionGeneral;\n\nexport type ExpectedStreamVersionWithValue<\n VersionType = DefaultStreamVersionType,\n> = Flavour<VersionType, 'StreamVersion'>;\n\nexport type ExpectedStreamVersionGeneral = Flavour<\n 'STREAM_EXISTS' | 'STREAM_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK',\n 'StreamVersion'\n>;\n\nexport const STREAM_EXISTS = 'STREAM_EXISTS' as ExpectedStreamVersionGeneral;\nexport const STREAM_DOES_NOT_EXIST =\n 'STREAM_DOES_NOT_EXIST' as ExpectedStreamVersionGeneral;\nexport const NO_CONCURRENCY_CHECK =\n 'NO_CONCURRENCY_CHECK' as ExpectedStreamVersionGeneral;\n\nexport const matchesExpectedVersion = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion | undefined,\n expected: ExpectedStreamVersion<StreamVersion>,\n): boolean => {\n if (expected === NO_CONCURRENCY_CHECK) return true;\n\n if (expected == STREAM_DOES_NOT_EXIST) return current === undefined;\n\n if (expected == STREAM_EXISTS) return current !== undefined;\n\n return current === expected;\n};\n\nexport const assertExpectedVersionMatchesCurrent = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion | undefined,\n expected: ExpectedStreamVersion<StreamVersion> | undefined,\n): void => {\n expected ??= NO_CONCURRENCY_CHECK;\n\n if (!matchesExpectedVersion(current, expected))\n throw new ExpectedVersionConflictError(current, expected);\n};\n\nexport class ExpectedVersionConflictError<\n VersionType = DefaultStreamVersionType,\n> extends ConcurrencyError {\n constructor(\n current: VersionType | undefined,\n expected: ExpectedStreamVersion<VersionType>,\n ) {\n super(current?.toString(), expected?.toString());\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ExpectedVersionConflictError.prototype);\n }\n}\n","import {\n NO_CONCURRENCY_CHECK,\n STREAM_DOES_NOT_EXIST,\n type AppendToStreamResult,\n type DefaultStreamVersionType,\n type EventStore,\n type ExpectedStreamVersion,\n} from '../eventStore';\nimport type { Event } from '../typing';\n\n// #region command-handler\nexport type CommandHandlerResult<\n State,\n StreamEvent extends Event,\n StreamVersion = DefaultStreamVersionType,\n> = AppendToStreamResult<StreamVersion> & {\n newState: State;\n newEvents: StreamEvent[];\n};\n\nexport const CommandHandler =\n <State, StreamEvent extends Event, StreamVersion = DefaultStreamVersionType>(\n evolve: (state: State, event: StreamEvent) => State,\n initialState: () => State,\n mapToStreamId: (id: string) => string = (id) => id,\n ) =>\n async <Store extends EventStore<StreamVersion>>(\n eventStore: Store,\n id: string,\n handle: (state: State) => StreamEvent | StreamEvent[],\n options?: Parameters<Store['appendToStream']>[2] & {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n },\n ): Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>> => {\n const streamName = mapToStreamId(id);\n\n // 1. Aggregate the stream\n const aggregationResult = await eventStore.aggregateStream<\n State,\n StreamEvent\n >(streamName, {\n evolve,\n initialState,\n read: {\n // expected stream version is passed to fail fast\n // if stream is in the wrong state\n expectedStreamVersion:\n options?.expectedStreamVersion ?? NO_CONCURRENCY_CHECK,\n },\n });\n\n // 2. Use the aggregate state or the initial one (when e.g. stream does not exist)\n const state = aggregationResult?.state ?? initialState();\n const currentStreamVersion = aggregationResult?.currentStreamVersion;\n\n // 3. Run business logic\n const result = handle(state);\n\n const newEvents = Array.isArray(result) ? result : [result];\n\n // Either use:\n // - provided expected stream version,\n // - current stream version got from stream aggregation,\n // - or expect stream not to exists otherwise.\n const expectedStreamVersion: ExpectedStreamVersion<StreamVersion> =\n options?.expectedStreamVersion ??\n currentStreamVersion ??\n STREAM_DOES_NOT_EXIST;\n\n // 4. Append result to the stream\n const appendResult = await eventStore.appendToStream(\n streamName,\n newEvents,\n {\n ...options,\n expectedStreamVersion,\n },\n );\n\n // 5. Return result with updated state\n return {\n ...appendResult,\n newEvents,\n newState: newEvents.reduce(evolve, state),\n };\n };\n// #endregion command-handler\n","import type {\n DefaultStreamVersionType,\n EventStore,\n ExpectedStreamVersion,\n} from '../eventStore';\nimport type { Command, Event } from '../typing';\nimport type { Decider } from '../typing/decider';\nimport { CommandHandler } from './handleCommand';\n\n// #region command-handler\nexport const DeciderCommandHandler =\n <\n State,\n CommandType extends Command,\n StreamEvent extends Event,\n StreamVersion = DefaultStreamVersionType,\n >(\n { decide, evolve, initialState }: Decider<State, CommandType, StreamEvent>,\n mapToStreamId: (id: string) => string = (id) => id,\n ) =>\n async (\n eventStore: EventStore<StreamVersion>,\n id: string,\n command: CommandType,\n options?: {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n },\n ) =>\n CommandHandler<State, StreamEvent, StreamVersion>(\n evolve,\n initialState,\n mapToStreamId,\n )(eventStore, id, (state) => decide(command, state), options);\n// #endregion command-handler\n","import { v4 as randomUUID } from 'uuid';\nimport type {\n Event,\n ReadEvent,\n ReadEventMetadataWithGlobalPosition,\n} from '../typing';\nimport {\n type AggregateStreamOptions,\n type AggregateStreamResult,\n type AppendToStreamOptions,\n type AppendToStreamResult,\n type DefaultStreamVersionType,\n type EventStore,\n type ReadStreamOptions,\n type ReadStreamResult,\n} from './eventStore';\nimport { assertExpectedVersionMatchesCurrent } from './expectedVersion';\n\nexport type EventHandler<E extends Event = Event> = (\n eventEnvelope: ReadEvent<E>,\n) => void;\n\nexport const getInMemoryEventStore = (): EventStore<\n DefaultStreamVersionType,\n ReadEventMetadataWithGlobalPosition\n> => {\n const streams = new Map<string, ReadEvent[]>();\n\n const getAllEventsCount = () => {\n return Array.from<ReadEvent[]>(streams.values())\n .map((s) => s.length)\n .reduce((p, c) => p + c, 0);\n };\n\n return {\n async aggregateStream<State, EventType extends Event>(\n streamName: string,\n options: AggregateStreamOptions<State, EventType>,\n ): Promise<AggregateStreamResult<State> | null> {\n const { evolve, initialState, read } = options;\n\n const result = await this.readStream<EventType>(streamName, read);\n\n if (!result) return null;\n\n const events = result?.events ?? [];\n\n return {\n currentStreamVersion: BigInt(events.length),\n state: events.reduce(evolve, initialState()),\n };\n },\n\n readStream: <EventType extends Event>(\n streamName: string,\n options?: ReadStreamOptions,\n ): Promise<\n ReadStreamResult<\n EventType,\n DefaultStreamVersionType,\n ReadEventMetadataWithGlobalPosition\n >\n > => {\n const events = streams.get(streamName);\n const currentStreamVersion = events ? BigInt(events.length) : undefined;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n );\n\n const from = Number(options && 'from' in options ? options.from : 0);\n const to = Number(\n options && 'to' in options\n ? options.to\n : options && 'maxCount' in options && options.maxCount\n ? options.from + options.maxCount\n : events?.length ?? 1,\n );\n\n const resultEvents =\n events && events.length > 0\n ? events\n .map(\n (e) =>\n e as ReadEvent<\n EventType,\n ReadEventMetadataWithGlobalPosition\n >,\n )\n .slice(from, to)\n : [];\n\n const result: ReadStreamResult<\n EventType,\n DefaultStreamVersionType,\n ReadEventMetadataWithGlobalPosition\n > =\n events && events.length > 0\n ? {\n currentStreamVersion: currentStreamVersion!,\n events: resultEvents,\n }\n : null;\n\n return Promise.resolve(result);\n },\n\n appendToStream: <EventType extends Event>(\n streamName: string,\n events: EventType[],\n options?: AppendToStreamOptions,\n ): Promise<AppendToStreamResult> => {\n const currentEvents = streams.get(streamName) ?? [];\n const currentStreamVersion =\n currentEvents.length > 0 ? BigInt(currentEvents.length) : undefined;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n );\n\n const eventEnvelopes: ReadEvent<\n EventType,\n ReadEventMetadataWithGlobalPosition\n >[] = events.map((event, index) => {\n return {\n ...event,\n metadata: {\n ...(event.metadata ?? {}),\n streamName,\n eventId: randomUUID(),\n streamPosition: BigInt(currentEvents.length + index + 1),\n globalPosition: BigInt(getAllEventsCount() + index + 1),\n },\n };\n });\n\n const positionOfLastEventInTheStream = BigInt(\n eventEnvelopes.slice(-1)[0]!.metadata.streamPosition,\n );\n\n streams.set(streamName, [...currentEvents, ...eventEnvelopes]);\n\n const result: AppendToStreamResult = {\n nextExpectedStreamVersion: positionOfLastEventInTheStream,\n };\n\n return Promise.resolve(result);\n },\n };\n};\n"],"mappings":"AAGO,IAAMA,EAAN,cAA6B,KAAM,CACxC,YAAYC,EAAiB,CAC3B,MAAMA,CAAO,CACf,CACF,EACaC,EAAW,CAACC,EAAmBC,IAA6B,CACvE,IAAMC,EAAMF,EACNG,EAAMF,EAEZ,OAAO,OAAO,KAAKE,CAAG,EAAE,MAAOC,GACzB,OAAOD,EAAIC,CAAG,GAAK,SACdL,EAASG,EAAIE,CAAG,EAAGD,EAAIC,CAAG,CAAC,EAE7BD,EAAIC,CAAG,IAAMF,EAAIE,CAAG,CAC5B,CACH,EAfO,IAiCMC,EAAgB,CAC3BC,EACAC,EACAC,IACG,CACH,GAAI,CAACC,EAASH,EAAQC,CAAQ,EAC5B,MAAM,IAAIG,EACRF,GACE;EAAY,KAAK,UAAUD,CAAQ,CAAC;;EAAuB,KAAK,UAAUD,CAAM,CAAC,EACrF,CACJ,EAkCO,S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MG,OAAkB","names":["AssertionError","message","isSubset","superObj","subObj","sup","sub","ele","assertMatches","actual","expected","message","isSubset","AssertionError","assertOk","obj","message","AssertionError","ValidationErrors","isNumber","val","isString","assertNotEmptyString","value","ValidationError","assertPositiveNumber","EmmettError","_EmmettError","options","errorCode","isNumber","message","isString","ValidationError","_ValidationError","EmmettError","message","IllegalStateError","_IllegalStateError","merge","array","item","where","onExisting","onNotFound","wasFound","result","p","STREAM_DOES_NOT_EXIST","NO_CONCURRENCY_CHECK","CommandHandler","evolve","initialState","mapToStreamId","id","eventStore","handle","options","streamName","aggregationResult","NO_CONCURRENCY_CHECK","state","currentStreamVersion","result","newEvents","expectedStreamVersion","STREAM_DOES_NOT_EXIST","DeciderCommandHandler","decide","evolve","initialState","mapToStreamId","id","eventStore","command","options","CommandHandler","state","randomUUID"]}
@@ -0,0 +1,2 @@
1
+ import{b as C,c as d}from"./chunk-ZSD2HWZE.mjs";import{e as a,f as e}from"./chunk-IA2ESUCU.mjs";var S=(p=>(p.CART_ALREADY_EXISTS="CART_ALREADY_EXISTS",p.CART_IS_ALREADY_CLOSED="CART_IS_ALREADY_CLOSED",p.PRODUCT_ITEM_NOT_FOUND="PRODUCT_ITEM_NOT_FOUND",p.CART_IS_EMPTY="CART_IS_EMPTY",p.UNKNOWN_EVENT_TYPE="UNKNOWN_EVENT_TYPE",p.UNKNOWN_COMMAND_TYPE="UNKNOWN_COMMAND_TYPE",p))(S||{}),I=(o,{productId:t,quantity:r,unitPrice:n})=>{if((o.find(i=>i.productId===t&&i.unitPrice==n)?.quantity??0)<r)throw new e("PRODUCT_ITEM_NOT_FOUND")},g=({type:o,data:t},r)=>{switch(o){case"OpenShoppingCart":{if(r.status!=="Empty")throw new e("CART_ALREADY_EXISTS");return{type:"ShoppingCartOpened",data:{shoppingCartId:t.shoppingCartId,clientId:t.clientId,openedAt:t.now}}}case"AddProductItemToShoppingCart":{if(r.status!=="Pending")throw new e("CART_IS_ALREADY_CLOSED");return{type:"ProductItemAddedToShoppingCart",data:{shoppingCartId:t.shoppingCartId,productItem:t.productItem}}}case"RemoveProductItemFromShoppingCart":{if(r.status!=="Pending")throw new e("CART_IS_ALREADY_CLOSED");return I(r.productItems,t.productItem),{type:"ProductItemRemovedFromShoppingCart",data:{shoppingCartId:t.shoppingCartId,productItem:t.productItem}}}case"ConfirmShoppingCart":{if(r.status!=="Pending")throw new e("CART_IS_ALREADY_CLOSED");if(r.productItems.length===0)throw new e("CART_IS_EMPTY");return{type:"ShoppingCartConfirmed",data:{shoppingCartId:t.shoppingCartId,confirmedAt:t.now}}}case"CancelShoppingCart":{if(r.status!=="Pending")throw new e("CART_IS_ALREADY_CLOSED");return{type:"ShoppingCartCanceled",data:{shoppingCartId:t.shoppingCartId,canceledAt:t.now}}}default:{let n=t;throw new a("UNKNOWN_COMMAND_TYPE")}}},u={decide:g,evolve:d,initialState:()=>C};export{S as a,I as b,g as c,u as d};
2
+ //# sourceMappingURL=chunk-UQKUA465.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/e2e/decider/businessLogic.ts"],"sourcesContent":["import {\n EmmettError,\n IllegalStateError,\n type Decider,\n} from '@event-driven-io/emmett';\n\nimport {\n ShoppingCartStatus,\n emptyShoppingCart,\n evolve,\n type PricedProductItem,\n type ShoppingCart,\n type ShoppingCartEvent,\n} from './shoppingCart';\n\n//////////////////////////////////////\n/// Commands\n//////////////////////////////////////\n\nexport type OpenShoppingCart = {\n type: 'OpenShoppingCart';\n data: {\n shoppingCartId: string;\n clientId: string;\n now: Date;\n };\n};\n\nexport type AddProductItemToShoppingCart = {\n type: 'AddProductItemToShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n};\n\nexport type RemoveProductItemFromShoppingCart = {\n type: 'RemoveProductItemFromShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n};\n\nexport type ConfirmShoppingCart = {\n type: 'ConfirmShoppingCart';\n data: {\n shoppingCartId: string;\n now: Date;\n };\n};\n\nexport type CancelShoppingCart = {\n type: 'CancelShoppingCart';\n data: {\n shoppingCartId: string;\n now: Date;\n };\n};\n\nexport type ShoppingCartCommand =\n | OpenShoppingCart\n | AddProductItemToShoppingCart\n | RemoveProductItemFromShoppingCart\n | ConfirmShoppingCart\n | CancelShoppingCart;\n\n//////////////////////////////////////\n/// Decide\n//////////////////////////////////////\n\nexport const enum ShoppingCartErrors {\n CART_ALREADY_EXISTS = 'CART_ALREADY_EXISTS',\n CART_IS_ALREADY_CLOSED = 'CART_IS_ALREADY_CLOSED',\n PRODUCT_ITEM_NOT_FOUND = 'PRODUCT_ITEM_NOT_FOUND',\n CART_IS_EMPTY = 'CART_IS_EMPTY',\n UNKNOWN_EVENT_TYPE = 'UNKNOWN_EVENT_TYPE',\n UNKNOWN_COMMAND_TYPE = 'UNKNOWN_COMMAND_TYPE',\n}\n\nexport const assertProductItemExists = (\n productItems: PricedProductItem[],\n { productId, quantity, unitPrice }: PricedProductItem,\n): void => {\n const currentQuantity =\n productItems.find(\n (p) => p.productId === productId && p.unitPrice == unitPrice,\n )?.quantity ?? 0;\n\n if (currentQuantity < quantity) {\n throw new IllegalStateError(ShoppingCartErrors.PRODUCT_ITEM_NOT_FOUND);\n }\n};\n\nexport const decide = (\n { type, data: command }: ShoppingCartCommand,\n shoppingCart: ShoppingCart,\n): ShoppingCartEvent => {\n switch (type) {\n case 'OpenShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Empty) {\n throw new IllegalStateError(ShoppingCartErrors.CART_ALREADY_EXISTS);\n }\n return {\n type: 'ShoppingCartOpened',\n data: {\n shoppingCartId: command.shoppingCartId,\n clientId: command.clientId,\n openedAt: command.now,\n },\n };\n }\n\n case 'AddProductItemToShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n return {\n type: 'ProductItemAddedToShoppingCart',\n data: {\n shoppingCartId: command.shoppingCartId,\n productItem: command.productItem,\n },\n };\n }\n\n case 'RemoveProductItemFromShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n assertProductItemExists(shoppingCart.productItems, command.productItem);\n\n return {\n type: 'ProductItemRemovedFromShoppingCart',\n data: {\n shoppingCartId: command.shoppingCartId,\n productItem: command.productItem,\n },\n };\n }\n\n case 'ConfirmShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n if (shoppingCart.productItems.length === 0) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_EMPTY);\n }\n\n return {\n type: 'ShoppingCartConfirmed',\n data: {\n shoppingCartId: command.shoppingCartId,\n confirmedAt: command.now,\n },\n };\n }\n\n case 'CancelShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n return {\n type: 'ShoppingCartCanceled',\n data: {\n shoppingCartId: command.shoppingCartId,\n canceledAt: command.now,\n },\n };\n }\n default: {\n const _: never = command;\n throw new EmmettError(ShoppingCartErrors.UNKNOWN_COMMAND_TYPE);\n }\n }\n};\n\nexport const decider: Decider<\n ShoppingCart,\n ShoppingCartCommand,\n ShoppingCartEvent\n> = {\n decide,\n evolve,\n getInitialState: () => emptyShoppingCart,\n};\n"],"mappings":"yDAuEO,IAAWA,OAChBA,EAAA,oBAAsB,sBACtBA,EAAA,uBAAyB,yBACzBA,EAAA,uBAAyB,yBACzBA,EAAA,cAAgB,gBAChBA,EAAA,mBAAqB,qBACrBA,EAAA,qBAAuB,uBANPA,OAAA,IASLC,EAA0B,CACrCC,EACA,CAAE,UAAAC,EAAW,SAAAC,EAAU,UAAAC,CAAU,IACxB,CAMT,IAJEH,EAAa,KACVI,GAAMA,EAAE,YAAcH,GAAaG,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EAIT,CACF,OAAAN,EACA,OAAAO,EACA,gBAAiB,IAAMC,CACzB","names":["ShoppingCartErrors","assertProductItemExists","productItems","productId","quantity","unitPrice","p","u","decide","type","command","shoppingCart","_","s","decider","evolve","emptyShoppingCart"]}
1
+ {"version":3,"sources":["../src/e2e/decider/businessLogic.ts"],"sourcesContent":["import {\n EmmettError,\n IllegalStateError,\n type Decider,\n} from '@event-driven-io/emmett';\n\nimport {\n ShoppingCartStatus,\n emptyShoppingCart,\n evolve,\n type PricedProductItem,\n type ShoppingCart,\n type ShoppingCartEvent,\n} from './shoppingCart';\n\n//////////////////////////////////////\n/// Commands\n//////////////////////////////////////\n\nexport type OpenShoppingCart = {\n type: 'OpenShoppingCart';\n data: {\n shoppingCartId: string;\n clientId: string;\n now: Date;\n };\n};\n\nexport type AddProductItemToShoppingCart = {\n type: 'AddProductItemToShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n};\n\nexport type RemoveProductItemFromShoppingCart = {\n type: 'RemoveProductItemFromShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n};\n\nexport type ConfirmShoppingCart = {\n type: 'ConfirmShoppingCart';\n data: {\n shoppingCartId: string;\n now: Date;\n };\n};\n\nexport type CancelShoppingCart = {\n type: 'CancelShoppingCart';\n data: {\n shoppingCartId: string;\n now: Date;\n };\n};\n\nexport type ShoppingCartCommand =\n | OpenShoppingCart\n | AddProductItemToShoppingCart\n | RemoveProductItemFromShoppingCart\n | ConfirmShoppingCart\n | CancelShoppingCart;\n\n//////////////////////////////////////\n/// Decide\n//////////////////////////////////////\n\nexport const enum ShoppingCartErrors {\n CART_ALREADY_EXISTS = 'CART_ALREADY_EXISTS',\n CART_IS_ALREADY_CLOSED = 'CART_IS_ALREADY_CLOSED',\n PRODUCT_ITEM_NOT_FOUND = 'PRODUCT_ITEM_NOT_FOUND',\n CART_IS_EMPTY = 'CART_IS_EMPTY',\n UNKNOWN_EVENT_TYPE = 'UNKNOWN_EVENT_TYPE',\n UNKNOWN_COMMAND_TYPE = 'UNKNOWN_COMMAND_TYPE',\n}\n\nexport const assertProductItemExists = (\n productItems: PricedProductItem[],\n { productId, quantity, unitPrice }: PricedProductItem,\n): void => {\n const currentQuantity =\n productItems.find(\n (p) => p.productId === productId && p.unitPrice == unitPrice,\n )?.quantity ?? 0;\n\n if (currentQuantity < quantity) {\n throw new IllegalStateError(ShoppingCartErrors.PRODUCT_ITEM_NOT_FOUND);\n }\n};\n\nexport const decide = (\n { type, data: command }: ShoppingCartCommand,\n shoppingCart: ShoppingCart,\n): ShoppingCartEvent => {\n switch (type) {\n case 'OpenShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Empty) {\n throw new IllegalStateError(ShoppingCartErrors.CART_ALREADY_EXISTS);\n }\n return {\n type: 'ShoppingCartOpened',\n data: {\n shoppingCartId: command.shoppingCartId,\n clientId: command.clientId,\n openedAt: command.now,\n },\n };\n }\n\n case 'AddProductItemToShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n return {\n type: 'ProductItemAddedToShoppingCart',\n data: {\n shoppingCartId: command.shoppingCartId,\n productItem: command.productItem,\n },\n };\n }\n\n case 'RemoveProductItemFromShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n assertProductItemExists(shoppingCart.productItems, command.productItem);\n\n return {\n type: 'ProductItemRemovedFromShoppingCart',\n data: {\n shoppingCartId: command.shoppingCartId,\n productItem: command.productItem,\n },\n };\n }\n\n case 'ConfirmShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n if (shoppingCart.productItems.length === 0) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_EMPTY);\n }\n\n return {\n type: 'ShoppingCartConfirmed',\n data: {\n shoppingCartId: command.shoppingCartId,\n confirmedAt: command.now,\n },\n };\n }\n\n case 'CancelShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n return {\n type: 'ShoppingCartCanceled',\n data: {\n shoppingCartId: command.shoppingCartId,\n canceledAt: command.now,\n },\n };\n }\n default: {\n const _: never = command;\n throw new EmmettError(ShoppingCartErrors.UNKNOWN_COMMAND_TYPE);\n }\n }\n};\n\nexport const decider: Decider<\n ShoppingCart,\n ShoppingCartCommand,\n ShoppingCartEvent\n> = {\n decide,\n evolve,\n initialState: () => emptyShoppingCart,\n};\n"],"mappings":"gGAuEO,IAAWA,OAChBA,EAAA,oBAAsB,sBACtBA,EAAA,uBAAyB,yBACzBA,EAAA,uBAAyB,yBACzBA,EAAA,cAAgB,gBAChBA,EAAA,mBAAqB,qBACrBA,EAAA,qBAAuB,uBANPA,OAAA,IASLC,EAA0B,CACrCC,EACA,CAAE,UAAAC,EAAW,SAAAC,EAAU,UAAAC,CAAU,IACxB,CAMT,IAJEH,EAAa,KACVI,GAAMA,EAAE,YAAcH,GAAaG,EAAE,WAAaD,CACrD,GAAG,UAAY,GAEKD,EACpB,MAAM,IAAIG,EAAkB,wBAAyC,CAEzE,EAEaC,EAAS,CACpB,CAAE,KAAAC,EAAM,KAAMC,CAAQ,EACtBC,IACsB,CACtB,OAAQF,EAAM,CACZ,IAAK,mBAAoB,CACvB,GAAIE,EAAa,iBACf,MAAM,IAAIJ,EAAkB,qBAAsC,EAEpE,MAAO,CACL,KAAM,qBACN,KAAM,CACJ,eAAgBG,EAAQ,eACxB,SAAUA,EAAQ,SAClB,SAAUA,EAAQ,GACpB,CACF,CACF,CAEA,IAAK,+BAAgC,CACnC,GAAIC,EAAa,mBACf,MAAM,IAAIJ,EAAkB,wBAAyC,EAEvE,MAAO,CACL,KAAM,iCACN,KAAM,CACJ,eAAgBG,EAAQ,eACxB,YAAaA,EAAQ,WACvB,CACF,CACF,CAEA,IAAK,oCAAqC,CACxC,GAAIC,EAAa,mBACf,MAAM,IAAIJ,EAAkB,wBAAyC,EAGvE,OAAAN,EAAwBU,EAAa,aAAcD,EAAQ,WAAW,EAE/D,CACL,KAAM,qCACN,KAAM,CACJ,eAAgBA,EAAQ,eACxB,YAAaA,EAAQ,WACvB,CACF,CACF,CAEA,IAAK,sBAAuB,CAC1B,GAAIC,EAAa,mBACf,MAAM,IAAIJ,EAAkB,wBAAyC,EAGvE,GAAII,EAAa,aAAa,SAAW,EACvC,MAAM,IAAIJ,EAAkB,eAAgC,EAG9D,MAAO,CACL,KAAM,wBACN,KAAM,CACJ,eAAgBG,EAAQ,eACxB,YAAaA,EAAQ,GACvB,CACF,CACF,CAEA,IAAK,qBAAsB,CACzB,GAAIC,EAAa,mBACf,MAAM,IAAIJ,EAAkB,wBAAyC,EAGvE,MAAO,CACL,KAAM,uBACN,KAAM,CACJ,eAAgBG,EAAQ,eACxB,WAAYA,EAAQ,GACtB,CACF,CACF,CACA,QAAS,CACP,IAAME,EAAWF,EACjB,MAAM,IAAIG,EAAY,sBAAuC,CAC/D,CACF,CACF,EAEaC,EAIT,CACF,OAAAN,EACA,OAAAO,EACA,aAAc,IAAMC,CACtB","names":["ShoppingCartErrors","assertProductItemExists","productItems","productId","quantity","unitPrice","p","d","decide","type","command","shoppingCart","_","s","decider","evolve","emptyShoppingCart"]}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkYTHGSSIVjs = require('./chunk-YTHGSSIV.js');var o=(n=>(n.Empty="Empty",n.Pending="Pending",n.Confirmed="Confirmed",n.Canceled="Canceled",n))(o||{}),c= exports.b ={status:"Empty"},a= exports.c =(e,{type:i,data:r})=>{switch(i){case"ShoppingCartOpened":return{id:r.shoppingCartId,clientId:r.clientId,openedAt:r.openedAt,productItems:[],status:"Pending"};case"ProductItemAddedToShoppingCart":{if(e.status!=="Pending")return e;let{productItems:d}=e,{productItem:n}=r;return{...e,productItems:_chunkYTHGSSIVjs.g.call(void 0, d,n,t=>t.productId===n.productId&&t.unitPrice===n.unitPrice,t=>({...t,quantity:t.quantity+n.quantity}),()=>n)}}case"ProductItemRemovedFromShoppingCart":{if(e.status!=="Pending")return e;let{productItems:d}=e,{productItem:n}=r;return{...e,productItems:_chunkYTHGSSIVjs.g.call(void 0, d,n,t=>t.productId===n.productId&&t.unitPrice===n.unitPrice,t=>({...t,quantity:t.quantity-n.quantity}))}}case"ShoppingCartConfirmed":return e.status!=="Pending"?e:{...e,status:"Confirmed",confirmedAt:r.confirmedAt};case"ShoppingCartCanceled":return e.status!=="Pending"?e:{...e,status:"Canceled",canceledAt:r.canceledAt}}},s= exports.d =e=>e.reduce(a,c),u= exports.e =(t=>(t.CART_IS_ALREADY_CLOSED="CART_IS_ALREADY_CLOSED",t.PRODUCT_ITEM_NOT_FOUND="PRODUCT_ITEM_NOT_FOUND",t.CART_IS_EMPTY="CART_IS_EMPTY",t.UNKNOWN_EVENT_TYPE="UNKNOWN_EVENT_TYPE",t.UNKNOWN_COMMAND_TYPE="UNKNOWN_COMMAND_TYPE",t))(u||{});exports.a = o; exports.b = c; exports.c = a; exports.d = s; exports.e = u;
2
+ //# sourceMappingURL=chunk-UXU77SIW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/e2e/decider/shoppingCart.ts"],"names":["ShoppingCartStatus","emptyShoppingCart","evolve","state","type","event","productItems","productItem","i","p","getShoppingCart","events","ShoppingCartErrors"],"mappings":"wCAiDO,IAAKA,OACVA,EAAA,MAAQ,QACRA,EAAA,QAAU,UACVA,EAAA,UAAY,YACZA,EAAA,SAAW,WAJDA,OAAA,IAmCCC,EAA2B,CAAE,OAAQ,OAAyB,EAE9DC,EAAS,CACpBC,EACA,CAAE,KAAAC,EAAM,KAAMC,CAAM,IACH,CACjB,OAAQD,EAAM,CACZ,IAAK,qBACH,MAAO,CACL,GAAIC,EAAM,eACV,SAAUA,EAAM,SAChB,SAAUA,EAAM,SAChB,aAAc,CAAC,EACf,OAAQ,SACV,EACF,IAAK,iCAAkC,CACrC,GAAIF,EAAM,SAAW,UAA4B,OAAOA,EAExD,GAAM,CAAE,aAAAG,CAAa,EAAIH,EACnB,CAAE,YAAAI,CAAY,EAAIF,EAExB,MAAO,CACL,GAAGF,EACH,aAAcK,EACZF,EACAC,EACCE,GACCA,EAAE,YAAcF,EAAY,WAC5BE,EAAE,YAAcF,EAAY,UAC7BE,IACQ,CACL,GAAGA,EACH,SAAUA,EAAE,SAAWF,EAAY,QACrC,GAEF,IAAMA,CACR,CACF,CACF,CACA,IAAK,qCAAsC,CACzC,GAAIJ,EAAM,SAAW,UAA4B,OAAOA,EAExD,GAAM,CAAE,aAAAG,CAAa,EAAIH,EACnB,CAAE,YAAAI,CAAY,EAAIF,EACxB,MAAO,CACL,GAAGF,EACH,aAAcK,EACZF,EACAC,EACCE,GACCA,EAAE,YAAcF,EAAY,WAC5BE,EAAE,YAAcF,EAAY,UAC7BE,IACQ,CACL,GAAGA,EACH,SAAUA,EAAE,SAAWF,EAAY,QACrC,EAEJ,CACF,CACF,CACA,IAAK,wBACH,OAAIJ,EAAM,SAAW,UAAmCA,EAEjD,CACL,GAAGA,EACH,OAAQ,YACR,YAAaE,EAAM,WACrB,EACF,IAAK,uBACH,OAAIF,EAAM,SAAW,UAAmCA,EAEjD,CACL,GAAGA,EACH,OAAQ,WACR,WAAYE,EAAM,UACpB,CACJ,CACF,EAEaK,EAAmBC,GACvBA,EAAO,OAAqBT,EAAQD,CAAiB,EAG5CW,OAChBA,EAAA,uBAAyB,yBACzBA,EAAA,uBAAyB,yBACzBA,EAAA,cAAgB,gBAChBA,EAAA,mBAAqB,qBACrBA,EAAA,qBAAuB,uBALPA,OAAA","sourcesContent":["import { merge } from '@event-driven-io/emmett';\n\nexport interface ProductItem {\n productId: string;\n quantity: number;\n}\n\nexport type PricedProductItem = ProductItem & {\n unitPrice: number;\n};\n\nexport type ShoppingCartEvent =\n | {\n type: 'ShoppingCartOpened';\n data: {\n shoppingCartId: string;\n clientId: string;\n openedAt: Date;\n };\n }\n | {\n type: 'ProductItemAddedToShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n }\n | {\n type: 'ProductItemRemovedFromShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n }\n | {\n type: 'ShoppingCartConfirmed';\n data: {\n shoppingCartId: string;\n confirmedAt: Date;\n };\n }\n | {\n type: 'ShoppingCartCanceled';\n data: {\n shoppingCartId: string;\n canceledAt: Date;\n };\n };\n\nexport enum ShoppingCartStatus {\n Empty = 'Empty',\n Pending = 'Pending',\n Confirmed = 'Confirmed',\n Canceled = 'Canceled',\n}\n\nexport type Empty = { status: ShoppingCartStatus.Empty };\n\nexport type Pending = {\n status: ShoppingCartStatus.Pending;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n openedAt: Date;\n};\n\nexport type Confirmed = {\n status: ShoppingCartStatus.Confirmed;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n confirmedAt: Date;\n};\n\nexport type Canceled = {\n status: ShoppingCartStatus.Canceled;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n canceledAt: Date;\n};\n\nexport type ShoppingCart = Empty | Pending | Confirmed | Canceled;\n\nexport const emptyShoppingCart: Empty = { status: ShoppingCartStatus.Empty };\n\nexport const evolve = (\n state: ShoppingCart,\n { type, data: event }: ShoppingCartEvent,\n): ShoppingCart => {\n switch (type) {\n case 'ShoppingCartOpened':\n return {\n id: event.shoppingCartId,\n clientId: event.clientId,\n openedAt: event.openedAt,\n productItems: [],\n status: ShoppingCartStatus.Pending,\n };\n case 'ProductItemAddedToShoppingCart': {\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n const { productItems } = state;\n const { productItem } = event;\n\n return {\n ...state,\n productItems: merge(\n productItems,\n productItem,\n (p) =>\n p.productId === productItem.productId &&\n p.unitPrice === productItem.unitPrice,\n (p) => {\n return {\n ...p,\n quantity: p.quantity + productItem.quantity,\n };\n },\n () => productItem,\n ),\n };\n }\n case 'ProductItemRemovedFromShoppingCart': {\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n const { productItems } = state;\n const { productItem } = event;\n return {\n ...state,\n productItems: merge(\n productItems,\n productItem,\n (p) =>\n p.productId === productItem.productId &&\n p.unitPrice === productItem.unitPrice,\n (p) => {\n return {\n ...p,\n quantity: p.quantity - productItem.quantity,\n };\n },\n ),\n };\n }\n case 'ShoppingCartConfirmed':\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n return {\n ...state,\n status: ShoppingCartStatus.Confirmed,\n confirmedAt: event.confirmedAt,\n };\n case 'ShoppingCartCanceled':\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n return {\n ...state,\n status: ShoppingCartStatus.Canceled,\n canceledAt: event.canceledAt,\n };\n }\n};\n\nexport const getShoppingCart = (events: ShoppingCartEvent[]): ShoppingCart => {\n return events.reduce<ShoppingCart>(evolve, emptyShoppingCart);\n};\n\nexport const enum ShoppingCartErrors {\n CART_IS_ALREADY_CLOSED = 'CART_IS_ALREADY_CLOSED',\n PRODUCT_ITEM_NOT_FOUND = 'PRODUCT_ITEM_NOT_FOUND',\n CART_IS_EMPTY = 'CART_IS_EMPTY',\n UNKNOWN_EVENT_TYPE = 'UNKNOWN_EVENT_TYPE',\n UNKNOWN_COMMAND_TYPE = 'UNKNOWN_COMMAND_TYPE',\n}\n"]}
@@ -0,0 +1,5 @@
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 c=class extends Error{constructor(t){super(t)}},p=(t,e)=>{let r=t,a=e;return Object.keys(a).every(s=>typeof a[s]=="object"?p(r[s],a[s]):a[s]===r[s])};var N=(t,e,r)=>{if(!p(t,e))throw new c(_nullishCoalesce(r, () => (`subObj:
2
+ ${JSON.stringify(e)}
3
+ is not subset of
4
+ ${JSON.stringify(t)}`)))};function k(t,e){if(!t)throw new c(_nullishCoalesce(e, () => ("Condition is not truthy")))}var O=(t=>(t.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",t.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",t.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",t))(O||{}),u=t=>typeof t=="number"&&t===t,g=t=>typeof t=="string",C= exports.c =t=>{if(!g(t)||t.length===0)throw new f("NOT_A_NONEMPTY_STRING");return t},_= exports.d =t=>{if(!u(t)||t<=0)throw new f("NOT_A_POSITIVE_NUMBER");return t};var h=class w extends Error{constructor(e){let r=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:u(e)?e:500,a=e&&typeof e=="object"&&"message"in e?e.message:g(e)?e:`Error with status code '${r}' ocurred during Emmett processing`;super(a),this.errorCode=r,Object.setPrototypeOf(this,w.prototype)}};var f=class x extends h{constructor(e){super({errorCode:400,message:_nullishCoalesce(e, () => ("Validation Error ocurred during Emmett processing"))}),Object.setPrototypeOf(this,x.prototype)}},M= exports.f =class A extends h{constructor(e){super({errorCode:403,message:_nullishCoalesce(e, () => ("Illegal State ocurred during Emmett processing"))}),Object.setPrototypeOf(this,A.prototype)}};var j=(t,e,r,a,s=()=>{})=>{let i=!1,n=t.map(o=>r(o)?(i=!0,a(o)):o).filter(o=>o!==void 0).map(o=>{if(!o)throw Error("That should not happen");return o});return!i&&s()!==void 0?[...t,e]:n};var y="STREAM_DOES_NOT_EXIST",E="NO_CONCURRENCY_CHECK";var S=(t,e,r=a=>a)=>async(a,s,i,n)=>{let o=r(s),l=await a.aggregateStream(o,{evolve:t,initialState:e,read:{expectedStreamVersion:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _2 => _2.expectedStreamVersion]), () => (E))}}),v=_nullishCoalesce(_optionalChain([l, 'optionalAccess', _3 => _3.state]), () => (e())),I=_optionalChain([l, 'optionalAccess', _4 => _4.currentStreamVersion]),m=i(v),d=Array.isArray(m)?m:[m],T=_nullishCoalesce(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _5 => _5.expectedStreamVersion]), () => (I)), () => (y));return{...await a.appendToStream(o,d,{...n,expectedStreamVersion:T}),newEvents:d,newState:d.reduce(t,v)}};var V=({decide:t,evolve:e,initialState:r},a=s=>s)=>async(s,i,n,o)=>S(e,r,a)(s,i,l=>t(n,l),o);var _uuid = require('uuid');exports.a = N; exports.b = k; exports.c = C; exports.d = _; exports.e = h; exports.f = M; exports.g = j; exports.h = V;
5
+ //# sourceMappingURL=chunk-YTHGSSIV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../emmett/src/testing/assertions.ts","../../emmett/src/validation/index.ts","../../emmett/src/errors/index.ts","../../emmett/src/utils/merge.ts","../../emmett/src/eventStore/expectedVersion.ts","../../emmett/src/commandHandling/handleCommand.ts","../../emmett/src/commandHandling/handleCommandWithDecider.ts","../../emmett/src/eventStore/inMemoryEventStore.ts"],"names":["AssertionError","message","isSubset","superObj","subObj","sup","sub","ele","assertMatches","actual","expected","assertOk","obj","ValidationErrors","isNumber","val","isString","assertNotEmptyString","value","ValidationError","assertPositiveNumber","EmmettError","_EmmettError","options","errorCode","_ValidationError","IllegalStateError","_IllegalStateError","merge","array","item","where","onExisting","onNotFound","wasFound","result","p","STREAM_DOES_NOT_EXIST","NO_CONCURRENCY_CHECK","CommandHandler","evolve","initialState","mapToStreamId","id","eventStore","handle","streamName","aggregationResult","state","currentStreamVersion","newEvents","expect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GAAS,uBAAyBe,CACtC,CACF,CAAC,EAGKU,EAAQD,GAAmB,OAASN,EAAa,EACjDQ,EAAuBF,GAAmB,qBAG1CZ,EAASU,EAAOG,CAAK,EAErBE,EAAY,MAAM,QAAQf,CAAM,EAAIA,EAAS,CAACA,CAAM,EAMpDgB,EACJ5B,GAAS,uBACT0B,GACAZ,EAaF,MAAO,CACL,GAXmB,MAAMO,EAAW,eACpCE,EACAI,EACA,CACE,GAAG3B,EACH,sBAAA4B,CACF,CACF,EAKE,UAAAD,EACA,SAAUA,EAAU,OAAOV,EAAQQ,CAAK,CAC1C,CACF,EC3EK,IAAMI,EACX,CAME,CAAE,OAAAC,EAAQ,OAAAb,EAAQ,aAAAC,CAAa,EAC/BC,EAAyCC,GAAOA,IAElD,MACEC,EACAD,EACAW,EACA/B,IAIAgB,EACEC,EACAC,EACAC,CACF,EAAEE,EAAYD,EAAKK,GAAUK,EAAOC,EAASN,CAAK,EAAGzB,CAAO,EChChE,OAAS,MAAMgC,OAAkB","sourcesContent":["import type { DefaultRecord } from '../typing';\nimport { deepEquals } from '../utils';\n\nexport class AssertionError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\nexport const isSubset = (superObj: unknown, subObj: unknown): boolean => {\n const sup = superObj as DefaultRecord;\n const sub = subObj as DefaultRecord;\n\n return Object.keys(sub).every((ele: string) => {\n if (typeof sub[ele] == 'object') {\n return isSubset(sup[ele], sub[ele]);\n }\n return sub[ele] === sup[ele];\n });\n};\n\nexport const assertFails = () => {\n throw new AssertionError('That should not ever happened, right?');\n};\n\nexport const assertThrows = (\n fun: () => void,\n errorCheck?: (error: Error) => boolean,\n) => {\n try {\n fun();\n throw new AssertionError(\"Function didn't throw expected error\");\n } catch (error) {\n if (errorCheck) assertTrue(errorCheck(error as Error));\n }\n};\n\nexport const assertMatches = (\n actual: unknown,\n expected: unknown,\n message?: string,\n) => {\n if (!isSubset(actual, expected))\n throw new AssertionError(\n message ??\n `subObj:\\n${JSON.stringify(expected)}\\nis not subset of\\n${JSON.stringify(actual)}`,\n );\n};\n\nexport const assertDeepEqual = (\n actual: unknown,\n expected: unknown,\n message?: string,\n) => {\n if (!deepEquals(actual, expected))\n throw new AssertionError(\n message ??\n `subObj:\\n${JSON.stringify(expected)}\\nis equals to\\n${JSON.stringify(actual)}`,\n );\n};\n\nexport const assertThat = <T>(item: T) => {\n return {\n isEqualTo: (other: T) => assertTrue(deepEquals(item, other)),\n };\n};\n\nexport function assertFalse(\n condition: boolean,\n message?: string,\n): asserts condition is false {\n if (condition) throw new AssertionError(message ?? `Condition is false`);\n}\n\nexport function assertTrue(\n condition: boolean,\n message?: string,\n): asserts condition is true {\n if (!condition) throw new AssertionError(message ?? `Condition is false`);\n}\n\nexport function assertOk<T>(\n obj: T | null | undefined,\n message?: string,\n): asserts obj is T {\n if (!obj) throw new AssertionError(message ?? `Condition is not truthy`);\n}\n\nexport function assertEqual<T>(\n obj: T | null | undefined,\n other: T | null | undefined,\n message?: string,\n): void {\n if (obj !== other)\n throw new AssertionError(\n message ??\n `Objects are not equal:\\n ${JSON.stringify(obj)}\\ncompared:\\n${JSON.stringify(other)}`,\n );\n}\n\nexport function assertNotEqual<T>(\n obj: T | null | undefined,\n other: T | null | undefined,\n message?: string,\n): void {\n if (obj === other)\n throw new AssertionError(\n message ?? `Objects are equal: ${JSON.stringify(obj)}`,\n );\n}\n\nexport function assertIsNotNull<T extends object>(\n result: T | null,\n): asserts result is T {\n assertNotEqual(result, null);\n assertOk(result);\n}\n\nexport function assertIsNull<T extends object>(\n result: T | null,\n): asserts result is null {\n assertEqual(result, null);\n}\n\ntype Call = {\n arguments: unknown[];\n result: unknown;\n target: unknown;\n this: unknown;\n};\n\nexport type ArgumentMatcher = (arg: unknown) => boolean;\n\nexport const argValue =\n <T>(value: T): ArgumentMatcher =>\n (arg) =>\n deepEquals(arg, value);\n\nexport const argMatches =\n <T>(matches: (arg: T) => boolean): ArgumentMatcher =>\n (arg) =>\n matches(arg as T);\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport type MockedFunction = Function & { mock?: { calls: Call[] } };\n\nexport function verifyThat(fn: MockedFunction) {\n return {\n calledTimes: (times: number) => {\n assertEqual(fn.mock?.calls?.length, times);\n },\n notCalled: () => {\n assertEqual(fn?.mock?.calls?.length, 0);\n },\n called: () => {\n assertTrue(\n fn.mock?.calls.length !== undefined && fn.mock.calls.length > 0,\n );\n },\n calledWith: (...args: unknown[]) => {\n assertTrue(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length >= 1 &&\n fn.mock.calls.some((call) => deepEquals(call.arguments, args)),\n );\n },\n calledOnceWith: (...args: unknown[]) => {\n assertTrue(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length === 1 &&\n fn.mock.calls.some((call) => deepEquals(call.arguments, args)),\n );\n },\n calledWithArgumentMatching: (...matches: ArgumentMatcher[]) => {\n assertTrue(\n fn.mock?.calls.length !== undefined && fn.mock.calls.length >= 1,\n );\n assertTrue(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length >= 1 &&\n fn.mock.calls.some(\n (call) =>\n call.arguments &&\n call.arguments.length >= matches.length &&\n matches.every((match, index) => match(call.arguments[index])),\n ),\n );\n },\n notCalledWithArgumentMatching: (...matches: ArgumentMatcher[]) => {\n assertFalse(\n fn.mock?.calls.length !== undefined &&\n fn.mock.calls.length >= 1 &&\n fn.mock.calls[0]!.arguments &&\n fn.mock.calls[0]!.arguments.length >= matches.length &&\n matches.every((match, index) =>\n match(fn.mock!.calls[0]!.arguments[index]),\n ),\n );\n },\n };\n}\n\nexport const assertThatArray = <T>(array: T[]) => {\n return {\n isEmpty: () => assertEqual(array.length, 0),\n hasSize: (length: number) => assertEqual(array.length, length),\n containsElements: (...other: T[]) => {\n assertTrue(other.every((ts) => other.some((o) => deepEquals(ts, o))));\n },\n containsExactlyInAnyOrder: (...other: T[]) => {\n assertEqual(array.length, other.length);\n assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));\n },\n containsExactlyInAnyOrderElementsOf: (other: T[]) => {\n assertEqual(array.length, other.length);\n assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));\n },\n containsExactlyElementsOf: (other: T[]) => {\n assertEqual(array.length, other.length);\n for (let i = 0; i < array.length; i++) {\n assertTrue(deepEquals(array[i], other[i]));\n }\n },\n containsExactly: (elem: T) => {\n assertEqual(array.length, 1);\n assertTrue(deepEquals(array[0], elem));\n },\n contains: (elem: T) => {\n assertTrue(array.some((a) => deepEquals(a, elem)));\n },\n containsOnlyOnceElementsOf: (other: T[]) => {\n assertTrue(\n other\n .map((o) => array.filter((a) => deepEquals(a, o)).length)\n .filter((a) => a === 1).length === other.length,\n );\n },\n containsAnyOf: (...other: T[]) => {\n assertTrue(array.some((a) => other.some((o) => deepEquals(a, o))));\n },\n allMatch: (matches: (item: T) => boolean) => {\n assertTrue(array.every(matches));\n },\n anyMatches: (matches: (item: T) => boolean) => {\n assertTrue(array.some(matches));\n },\n allMatchAsync: async (\n matches: (item: T) => Promise<boolean>,\n ): Promise<void> => {\n for (const item of array) {\n assertTrue(await matches(item));\n }\n },\n };\n};\n","import { ValidationError } from '../errors';\n\nexport const enum ValidationErrors {\n NOT_A_NONEMPTY_STRING = 'NOT_A_NONEMPTY_STRING',\n NOT_A_POSITIVE_NUMBER = 'NOT_A_POSITIVE_NUMBER',\n NOT_AN_UNSIGNED_BIGINT = 'NOT_AN_UNSIGNED_BIGINT',\n}\n\nexport const isNumber = (val: unknown): val is number =>\n typeof val === 'number' && val === val;\n\nexport const isString = (val: unknown): val is string =>\n typeof val === 'string';\n\nexport const assertNotEmptyString = (value: unknown): string => {\n if (!isString(value) || value.length === 0) {\n throw new ValidationError(ValidationErrors.NOT_A_NONEMPTY_STRING);\n }\n return value;\n};\n\nexport const assertPositiveNumber = (value: unknown): number => {\n if (!isNumber(value) || value <= 0) {\n throw new ValidationError(ValidationErrors.NOT_A_POSITIVE_NUMBER);\n }\n return value;\n};\n\nexport const assertUnsignedBigInt = (value: string): bigint => {\n const number = BigInt(value);\n if (number < 0) {\n throw new ValidationError(ValidationErrors.NOT_AN_UNSIGNED_BIGINT);\n }\n return number;\n};\n\nexport * from './dates';\n","import { isNumber, isString } from '../validation';\n\nexport type ErrorConstructor<ErrorType extends Error> = new (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: any[]\n) => ErrorType;\n\nexport const isErrorConstructor = <ErrorType extends Error>(\n // eslint-disable-next-line @typescript-eslint/ban-types\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 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\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","export const merge = <T>(\n array: T[],\n item: T,\n where: (current: T) => boolean,\n onExisting: (current: T) => T,\n onNotFound: () => T | undefined = () => undefined,\n) => {\n let wasFound = false;\n\n const result = array\n // merge the existing item if matches condition\n .map((p: T) => {\n if (!where(p)) return p;\n\n wasFound = true;\n return onExisting(p);\n })\n // filter out item if undefined was returned\n // for cases of removal\n .filter((p) => p !== undefined)\n // make TypeScript happy\n .map((p) => {\n if (!p) throw Error('That should not happen');\n\n return p;\n });\n\n // if item was not found and onNotFound action is defined\n // try to generate new item\n if (!wasFound) {\n const result = onNotFound();\n\n if (result !== undefined) return [...array, item];\n }\n\n return result;\n};\n","import { ConcurrencyError } from '../errors';\nimport type { Flavour } from '../typing';\nimport type { DefaultStreamVersionType } from './eventStore';\n\nexport type ExpectedStreamVersion<VersionType = DefaultStreamVersionType> =\n | ExpectedStreamVersionWithValue<VersionType>\n | ExpectedStreamVersionGeneral;\n\nexport type ExpectedStreamVersionWithValue<\n VersionType = DefaultStreamVersionType,\n> = Flavour<VersionType, 'StreamVersion'>;\n\nexport type ExpectedStreamVersionGeneral = Flavour<\n 'STREAM_EXISTS' | 'STREAM_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK',\n 'StreamVersion'\n>;\n\nexport const STREAM_EXISTS = 'STREAM_EXISTS' as ExpectedStreamVersionGeneral;\nexport const STREAM_DOES_NOT_EXIST =\n 'STREAM_DOES_NOT_EXIST' as ExpectedStreamVersionGeneral;\nexport const NO_CONCURRENCY_CHECK =\n 'NO_CONCURRENCY_CHECK' as ExpectedStreamVersionGeneral;\n\nexport const matchesExpectedVersion = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion | undefined,\n expected: ExpectedStreamVersion<StreamVersion>,\n): boolean => {\n if (expected === NO_CONCURRENCY_CHECK) return true;\n\n if (expected == STREAM_DOES_NOT_EXIST) return current === undefined;\n\n if (expected == STREAM_EXISTS) return current !== undefined;\n\n return current === expected;\n};\n\nexport const assertExpectedVersionMatchesCurrent = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion | undefined,\n expected: ExpectedStreamVersion<StreamVersion> | undefined,\n): void => {\n expected ??= NO_CONCURRENCY_CHECK;\n\n if (!matchesExpectedVersion(current, expected))\n throw new ExpectedVersionConflictError(current, expected);\n};\n\nexport class ExpectedVersionConflictError<\n VersionType = DefaultStreamVersionType,\n> extends ConcurrencyError {\n constructor(\n current: VersionType | undefined,\n expected: ExpectedStreamVersion<VersionType>,\n ) {\n super(current?.toString(), expected?.toString());\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ExpectedVersionConflictError.prototype);\n }\n}\n","import {\n NO_CONCURRENCY_CHECK,\n STREAM_DOES_NOT_EXIST,\n type AppendToStreamResult,\n type DefaultStreamVersionType,\n type EventStore,\n type ExpectedStreamVersion,\n} from '../eventStore';\nimport type { Event } from '../typing';\n\n// #region command-handler\nexport type CommandHandlerResult<\n State,\n StreamEvent extends Event,\n StreamVersion = DefaultStreamVersionType,\n> = AppendToStreamResult<StreamVersion> & {\n newState: State;\n newEvents: StreamEvent[];\n};\n\nexport const CommandHandler =\n <State, StreamEvent extends Event, StreamVersion = DefaultStreamVersionType>(\n evolve: (state: State, event: StreamEvent) => State,\n initialState: () => State,\n mapToStreamId: (id: string) => string = (id) => id,\n ) =>\n async <Store extends EventStore<StreamVersion>>(\n eventStore: Store,\n id: string,\n handle: (state: State) => StreamEvent | StreamEvent[],\n options?: Parameters<Store['appendToStream']>[2] & {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n },\n ): Promise<CommandHandlerResult<State, StreamEvent, StreamVersion>> => {\n const streamName = mapToStreamId(id);\n\n // 1. Aggregate the stream\n const aggregationResult = await eventStore.aggregateStream<\n State,\n StreamEvent\n >(streamName, {\n evolve,\n initialState,\n read: {\n // expected stream version is passed to fail fast\n // if stream is in the wrong state\n expectedStreamVersion:\n options?.expectedStreamVersion ?? NO_CONCURRENCY_CHECK,\n },\n });\n\n // 2. Use the aggregate state or the initial one (when e.g. stream does not exist)\n const state = aggregationResult?.state ?? initialState();\n const currentStreamVersion = aggregationResult?.currentStreamVersion;\n\n // 3. Run business logic\n const result = handle(state);\n\n const newEvents = Array.isArray(result) ? result : [result];\n\n // Either use:\n // - provided expected stream version,\n // - current stream version got from stream aggregation,\n // - or expect stream not to exists otherwise.\n const expectedStreamVersion: ExpectedStreamVersion<StreamVersion> =\n options?.expectedStreamVersion ??\n currentStreamVersion ??\n STREAM_DOES_NOT_EXIST;\n\n // 4. Append result to the stream\n const appendResult = await eventStore.appendToStream(\n streamName,\n newEvents,\n {\n ...options,\n expectedStreamVersion,\n },\n );\n\n // 5. Return result with updated state\n return {\n ...appendResult,\n newEvents,\n newState: newEvents.reduce(evolve, state),\n };\n };\n// #endregion command-handler\n","import type {\n DefaultStreamVersionType,\n EventStore,\n ExpectedStreamVersion,\n} from '../eventStore';\nimport type { Command, Event } from '../typing';\nimport type { Decider } from '../typing/decider';\nimport { CommandHandler } from './handleCommand';\n\n// #region command-handler\nexport const DeciderCommandHandler =\n <\n State,\n CommandType extends Command,\n StreamEvent extends Event,\n StreamVersion = DefaultStreamVersionType,\n >(\n { decide, evolve, initialState }: Decider<State, CommandType, StreamEvent>,\n mapToStreamId: (id: string) => string = (id) => id,\n ) =>\n async (\n eventStore: EventStore<StreamVersion>,\n id: string,\n command: CommandType,\n options?: {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n },\n ) =>\n CommandHandler<State, StreamEvent, StreamVersion>(\n evolve,\n initialState,\n mapToStreamId,\n )(eventStore, id, (state) => decide(command, state), options);\n// #endregion command-handler\n","import { v4 as randomUUID } from 'uuid';\nimport type {\n Event,\n ReadEvent,\n ReadEventMetadataWithGlobalPosition,\n} from '../typing';\nimport {\n type AggregateStreamOptions,\n type AggregateStreamResult,\n type AppendToStreamOptions,\n type AppendToStreamResult,\n type DefaultStreamVersionType,\n type EventStore,\n type ReadStreamOptions,\n type ReadStreamResult,\n} from './eventStore';\nimport { assertExpectedVersionMatchesCurrent } from './expectedVersion';\n\nexport type EventHandler<E extends Event = Event> = (\n eventEnvelope: ReadEvent<E>,\n) => void;\n\nexport const getInMemoryEventStore = (): EventStore<\n DefaultStreamVersionType,\n ReadEventMetadataWithGlobalPosition\n> => {\n const streams = new Map<string, ReadEvent[]>();\n\n const getAllEventsCount = () => {\n return Array.from<ReadEvent[]>(streams.values())\n .map((s) => s.length)\n .reduce((p, c) => p + c, 0);\n };\n\n return {\n async aggregateStream<State, EventType extends Event>(\n streamName: string,\n options: AggregateStreamOptions<State, EventType>,\n ): Promise<AggregateStreamResult<State> | null> {\n const { evolve, initialState, read } = options;\n\n const result = await this.readStream<EventType>(streamName, read);\n\n if (!result) return null;\n\n const events = result?.events ?? [];\n\n return {\n currentStreamVersion: BigInt(events.length),\n state: events.reduce(evolve, initialState()),\n };\n },\n\n readStream: <EventType extends Event>(\n streamName: string,\n options?: ReadStreamOptions,\n ): Promise<\n ReadStreamResult<\n EventType,\n DefaultStreamVersionType,\n ReadEventMetadataWithGlobalPosition\n >\n > => {\n const events = streams.get(streamName);\n const currentStreamVersion = events ? BigInt(events.length) : undefined;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n );\n\n const from = Number(options && 'from' in options ? options.from : 0);\n const to = Number(\n options && 'to' in options\n ? options.to\n : options && 'maxCount' in options && options.maxCount\n ? options.from + options.maxCount\n : events?.length ?? 1,\n );\n\n const resultEvents =\n events && events.length > 0\n ? events\n .map(\n (e) =>\n e as ReadEvent<\n EventType,\n ReadEventMetadataWithGlobalPosition\n >,\n )\n .slice(from, to)\n : [];\n\n const result: ReadStreamResult<\n EventType,\n DefaultStreamVersionType,\n ReadEventMetadataWithGlobalPosition\n > =\n events && events.length > 0\n ? {\n currentStreamVersion: currentStreamVersion!,\n events: resultEvents,\n }\n : null;\n\n return Promise.resolve(result);\n },\n\n appendToStream: <EventType extends Event>(\n streamName: string,\n events: EventType[],\n options?: AppendToStreamOptions,\n ): Promise<AppendToStreamResult> => {\n const currentEvents = streams.get(streamName) ?? [];\n const currentStreamVersion =\n currentEvents.length > 0 ? BigInt(currentEvents.length) : undefined;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n );\n\n const eventEnvelopes: ReadEvent<\n EventType,\n ReadEventMetadataWithGlobalPosition\n >[] = events.map((event, index) => {\n return {\n ...event,\n metadata: {\n ...(event.metadata ?? {}),\n streamName,\n eventId: randomUUID(),\n streamPosition: BigInt(currentEvents.length + index + 1),\n globalPosition: BigInt(getAllEventsCount() + index + 1),\n },\n };\n });\n\n const positionOfLastEventInTheStream = BigInt(\n eventEnvelopes.slice(-1)[0]!.metadata.streamPosition,\n );\n\n streams.set(streamName, [...currentEvents, ...eventEnvelopes]);\n\n const result: AppendToStreamResult = {\n nextExpectedStreamVersion: positionOfLastEventInTheStream,\n };\n\n return Promise.resolve(result);\n },\n };\n};\n"]}
@@ -0,0 +1,2 @@
1
+ import{g as p}from"./chunk-IA2ESUCU.mjs";var o=(n=>(n.Empty="Empty",n.Pending="Pending",n.Confirmed="Confirmed",n.Canceled="Canceled",n))(o||{}),c={status:"Empty"},a=(e,{type:i,data:r})=>{switch(i){case"ShoppingCartOpened":return{id:r.shoppingCartId,clientId:r.clientId,openedAt:r.openedAt,productItems:[],status:"Pending"};case"ProductItemAddedToShoppingCart":{if(e.status!=="Pending")return e;let{productItems:d}=e,{productItem:n}=r;return{...e,productItems:p(d,n,t=>t.productId===n.productId&&t.unitPrice===n.unitPrice,t=>({...t,quantity:t.quantity+n.quantity}),()=>n)}}case"ProductItemRemovedFromShoppingCart":{if(e.status!=="Pending")return e;let{productItems:d}=e,{productItem:n}=r;return{...e,productItems:p(d,n,t=>t.productId===n.productId&&t.unitPrice===n.unitPrice,t=>({...t,quantity:t.quantity-n.quantity}))}}case"ShoppingCartConfirmed":return e.status!=="Pending"?e:{...e,status:"Confirmed",confirmedAt:r.confirmedAt};case"ShoppingCartCanceled":return e.status!=="Pending"?e:{...e,status:"Canceled",canceledAt:r.canceledAt}}},s=e=>e.reduce(a,c),u=(t=>(t.CART_IS_ALREADY_CLOSED="CART_IS_ALREADY_CLOSED",t.PRODUCT_ITEM_NOT_FOUND="PRODUCT_ITEM_NOT_FOUND",t.CART_IS_EMPTY="CART_IS_EMPTY",t.UNKNOWN_EVENT_TYPE="UNKNOWN_EVENT_TYPE",t.UNKNOWN_COMMAND_TYPE="UNKNOWN_COMMAND_TYPE",t))(u||{});export{o as a,c as b,a as c,s as d,u as e};
2
+ //# sourceMappingURL=chunk-ZSD2HWZE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/e2e/decider/shoppingCart.ts"],"sourcesContent":["import { merge } from '@event-driven-io/emmett';\n\nexport interface ProductItem {\n productId: string;\n quantity: number;\n}\n\nexport type PricedProductItem = ProductItem & {\n unitPrice: number;\n};\n\nexport type ShoppingCartEvent =\n | {\n type: 'ShoppingCartOpened';\n data: {\n shoppingCartId: string;\n clientId: string;\n openedAt: Date;\n };\n }\n | {\n type: 'ProductItemAddedToShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n }\n | {\n type: 'ProductItemRemovedFromShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n }\n | {\n type: 'ShoppingCartConfirmed';\n data: {\n shoppingCartId: string;\n confirmedAt: Date;\n };\n }\n | {\n type: 'ShoppingCartCanceled';\n data: {\n shoppingCartId: string;\n canceledAt: Date;\n };\n };\n\nexport enum ShoppingCartStatus {\n Empty = 'Empty',\n Pending = 'Pending',\n Confirmed = 'Confirmed',\n Canceled = 'Canceled',\n}\n\nexport type Empty = { status: ShoppingCartStatus.Empty };\n\nexport type Pending = {\n status: ShoppingCartStatus.Pending;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n openedAt: Date;\n};\n\nexport type Confirmed = {\n status: ShoppingCartStatus.Confirmed;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n confirmedAt: Date;\n};\n\nexport type Canceled = {\n status: ShoppingCartStatus.Canceled;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n canceledAt: Date;\n};\n\nexport type ShoppingCart = Empty | Pending | Confirmed | Canceled;\n\nexport const emptyShoppingCart: Empty = { status: ShoppingCartStatus.Empty };\n\nexport const evolve = (\n state: ShoppingCart,\n { type, data: event }: ShoppingCartEvent,\n): ShoppingCart => {\n switch (type) {\n case 'ShoppingCartOpened':\n return {\n id: event.shoppingCartId,\n clientId: event.clientId,\n openedAt: event.openedAt,\n productItems: [],\n status: ShoppingCartStatus.Pending,\n };\n case 'ProductItemAddedToShoppingCart': {\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n const { productItems } = state;\n const { productItem } = event;\n\n return {\n ...state,\n productItems: merge(\n productItems,\n productItem,\n (p) =>\n p.productId === productItem.productId &&\n p.unitPrice === productItem.unitPrice,\n (p) => {\n return {\n ...p,\n quantity: p.quantity + productItem.quantity,\n };\n },\n () => productItem,\n ),\n };\n }\n case 'ProductItemRemovedFromShoppingCart': {\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n const { productItems } = state;\n const { productItem } = event;\n return {\n ...state,\n productItems: merge(\n productItems,\n productItem,\n (p) =>\n p.productId === productItem.productId &&\n p.unitPrice === productItem.unitPrice,\n (p) => {\n return {\n ...p,\n quantity: p.quantity - productItem.quantity,\n };\n },\n ),\n };\n }\n case 'ShoppingCartConfirmed':\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n return {\n ...state,\n status: ShoppingCartStatus.Confirmed,\n confirmedAt: event.confirmedAt,\n };\n case 'ShoppingCartCanceled':\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n return {\n ...state,\n status: ShoppingCartStatus.Canceled,\n canceledAt: event.canceledAt,\n };\n }\n};\n\nexport const getShoppingCart = (events: ShoppingCartEvent[]): ShoppingCart => {\n return events.reduce<ShoppingCart>(evolve, emptyShoppingCart);\n};\n\nexport const enum ShoppingCartErrors {\n CART_IS_ALREADY_CLOSED = 'CART_IS_ALREADY_CLOSED',\n PRODUCT_ITEM_NOT_FOUND = 'PRODUCT_ITEM_NOT_FOUND',\n CART_IS_EMPTY = 'CART_IS_EMPTY',\n UNKNOWN_EVENT_TYPE = 'UNKNOWN_EVENT_TYPE',\n UNKNOWN_COMMAND_TYPE = 'UNKNOWN_COMMAND_TYPE',\n}\n"],"mappings":"yCAiDO,IAAKA,OACVA,EAAA,MAAQ,QACRA,EAAA,QAAU,UACVA,EAAA,UAAY,YACZA,EAAA,SAAW,WAJDA,OAAA,IAmCCC,EAA2B,CAAE,OAAQ,OAAyB,EAE9DC,EAAS,CACpBC,EACA,CAAE,KAAAC,EAAM,KAAMC,CAAM,IACH,CACjB,OAAQD,EAAM,CACZ,IAAK,qBACH,MAAO,CACL,GAAIC,EAAM,eACV,SAAUA,EAAM,SAChB,SAAUA,EAAM,SAChB,aAAc,CAAC,EACf,OAAQ,SACV,EACF,IAAK,iCAAkC,CACrC,GAAIF,EAAM,SAAW,UAA4B,OAAOA,EAExD,GAAM,CAAE,aAAAG,CAAa,EAAIH,EACnB,CAAE,YAAAI,CAAY,EAAIF,EAExB,MAAO,CACL,GAAGF,EACH,aAAcK,EACZF,EACAC,EACCE,GACCA,EAAE,YAAcF,EAAY,WAC5BE,EAAE,YAAcF,EAAY,UAC7BE,IACQ,CACL,GAAGA,EACH,SAAUA,EAAE,SAAWF,EAAY,QACrC,GAEF,IAAMA,CACR,CACF,CACF,CACA,IAAK,qCAAsC,CACzC,GAAIJ,EAAM,SAAW,UAA4B,OAAOA,EAExD,GAAM,CAAE,aAAAG,CAAa,EAAIH,EACnB,CAAE,YAAAI,CAAY,EAAIF,EACxB,MAAO,CACL,GAAGF,EACH,aAAcK,EACZF,EACAC,EACCE,GACCA,EAAE,YAAcF,EAAY,WAC5BE,EAAE,YAAcF,EAAY,UAC7BE,IACQ,CACL,GAAGA,EACH,SAAUA,EAAE,SAAWF,EAAY,QACrC,EAEJ,CACF,CACF,CACA,IAAK,wBACH,OAAIJ,EAAM,SAAW,UAAmCA,EAEjD,CACL,GAAGA,EACH,OAAQ,YACR,YAAaE,EAAM,WACrB,EACF,IAAK,uBACH,OAAIF,EAAM,SAAW,UAAmCA,EAEjD,CACL,GAAGA,EACH,OAAQ,WACR,WAAYE,EAAM,UACpB,CACJ,CACF,EAEaK,EAAmBC,GACvBA,EAAO,OAAqBT,EAAQD,CAAiB,EAG5CW,OAChBA,EAAA,uBAAyB,yBACzBA,EAAA,uBAAyB,yBACzBA,EAAA,cAAgB,gBAChBA,EAAA,mBAAqB,qBACrBA,EAAA,qBAAuB,uBALPA,OAAA","names":["ShoppingCartStatus","emptyShoppingCart","evolve","state","type","event","productItems","productItem","i","p","getShoppingCart","events","ShoppingCartErrors"]}
@@ -1,12 +1,16 @@
1
- import { ShoppingCart } from './shoppingCart.mjs';
1
+ import { ShoppingCart, ShoppingCartEvent } from './shoppingCart.mjs';
2
2
  import * as _event_driven_io_emmett from '@event-driven-io/emmett';
3
3
  import { EventStore } from '@event-driven-io/emmett';
4
4
  import { ShoppingCartCommand } from './businessLogic.mjs';
5
5
  import { FastifyInstance } from 'fastify';
6
6
 
7
- declare const handle: (eventStore: EventStore<bigint>, id: string, command: ShoppingCartCommand, options?: {
7
+ declare const handle: (eventStore: EventStore<bigint, Readonly<{
8
+ eventId: string;
9
+ streamPosition: bigint;
10
+ streamName: string;
11
+ }>>, id: string, command: ShoppingCartCommand, options?: {
8
12
  expectedStreamVersion?: _event_driven_io_emmett.ExpectedStreamVersion<bigint> | undefined;
9
- } | undefined) => Promise<_event_driven_io_emmett.CommandHandlerResult<ShoppingCart, bigint>>;
13
+ } | undefined) => Promise<_event_driven_io_emmett.CommandHandlerResult<ShoppingCart, ShoppingCartEvent, bigint>>;
10
14
  declare const RegisterRoutes: (eventStore: EventStore) => (app: FastifyInstance) => void;
11
15
 
12
16
  export { RegisterRoutes, handle };
@@ -1,12 +1,16 @@
1
- import { ShoppingCart } from './shoppingCart.js';
1
+ import { ShoppingCart, ShoppingCartEvent } from './shoppingCart.js';
2
2
  import * as _event_driven_io_emmett from '@event-driven-io/emmett';
3
3
  import { EventStore } from '@event-driven-io/emmett';
4
4
  import { ShoppingCartCommand } from './businessLogic.js';
5
5
  import { FastifyInstance } from 'fastify';
6
6
 
7
- declare const handle: (eventStore: EventStore<bigint>, id: string, command: ShoppingCartCommand, options?: {
7
+ declare const handle: (eventStore: EventStore<bigint, Readonly<{
8
+ eventId: string;
9
+ streamPosition: bigint;
10
+ streamName: string;
11
+ }>>, id: string, command: ShoppingCartCommand, options?: {
8
12
  expectedStreamVersion?: _event_driven_io_emmett.ExpectedStreamVersion<bigint> | undefined;
9
- } | undefined) => Promise<_event_driven_io_emmett.CommandHandlerResult<ShoppingCart, bigint>>;
13
+ } | undefined) => Promise<_event_driven_io_emmett.CommandHandlerResult<ShoppingCart, ShoppingCartEvent, bigint>>;
10
14
  declare const RegisterRoutes: (eventStore: EventStore) => (app: FastifyInstance) => void;
11
15
 
12
16
  export { RegisterRoutes, handle };
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkAI5EQ7AWjs = require('../../chunk-AI5EQ7AW.js');var _chunkFXSUJ5HPjs = require('../../chunk-FXSUJ5HP.js');require('fastify');var a=_chunkFXSUJ5HPjs.e.call(void 0, _chunkAI5EQ7AWjs.d),I=o=>100,P= exports.RegisterRoutes =o=>n=>{n.post("/clients/:clientId/shopping-carts",async(e,r)=>{let{clientId:t}=e.params;_chunkFXSUJ5HPjs.c.call(void 0, t);let s=t;return await a(o,s,{type:"OpenShoppingCart",data:{clientId:s,shoppingCartId:s,now:new Date}}),r.code(201).send({id:t})}),n.post("/clients/:clientId/shopping-carts/:shoppingCartId/product-items",async(e,r)=>{let{shoppingCartId:t}=e.params;_chunkFXSUJ5HPjs.c.call(void 0, t);let{productId:s,quantity:c}=e.body,d={productId:_chunkFXSUJ5HPjs.c.call(void 0, s),quantity:_chunkFXSUJ5HPjs.d.call(void 0, c)},m=I(d.productId);return await a(o,t,{type:"AddProductItemToShoppingCart",data:{shoppingCartId:t,productItem:{...d,unitPrice:m}}}),r.code(204).send()}),n.delete("/clients/:clientId/shopping-carts/:shoppingCartId/product-items",async(e,r)=>{let{shoppingCartId:t}=e.params;_chunkFXSUJ5HPjs.c.call(void 0, t);let{productId:s,quantity:c,unitPrice:d}=e.query,m={productId:_chunkFXSUJ5HPjs.c.call(void 0, s),quantity:_chunkFXSUJ5HPjs.d.call(void 0, Number(c)),unitPrice:_chunkFXSUJ5HPjs.d.call(void 0, Number(d))};return await a(o,t,{type:"RemoveProductItemFromShoppingCart",data:{shoppingCartId:t,productItem:m}}),r.code(204).send()}),n.post("/clients/:clientId/shopping-carts/:shoppingCartId/confirm",async(e,r)=>{let{shoppingCartId:t}=e.params;return _chunkFXSUJ5HPjs.c.call(void 0, t),await a(o,t,{type:"ConfirmShoppingCart",data:{shoppingCartId:t,now:new Date}}),r.code(204).send()}),n.delete("/clients/:clientId/shopping-carts/:shoppingCartId",async(e,r)=>{let{shoppingCartId:t}=e.params;_chunkFXSUJ5HPjs.c.call(void 0, t);try{await a(o,t,{type:"CancelShoppingCart",data:{shoppingCartId:t,now:new Date}})}catch(s){return s instanceof Error&&"message"in s?r.code(403).send({detail:s.message}):r.code(403)}return r.code(204).send()})};exports.RegisterRoutes = P; exports.handle = a;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkEMCVUR73js = require('../../chunk-EMCVUR73.js');require('../../chunk-UXU77SIW.js');var _chunkYTHGSSIVjs = require('../../chunk-YTHGSSIV.js');require('fastify');var a=_chunkYTHGSSIVjs.h.call(void 0, _chunkEMCVUR73js.d),I=o=>100,P= exports.RegisterRoutes =o=>n=>{n.post("/clients/:clientId/shopping-carts",async(e,r)=>{let{clientId:t}=e.params;_chunkYTHGSSIVjs.c.call(void 0, t);let s=t;return await a(o,s,{type:"OpenShoppingCart",data:{clientId:s,shoppingCartId:s,now:new Date}}),r.code(201).send({id:t})}),n.post("/clients/:clientId/shopping-carts/:shoppingCartId/product-items",async(e,r)=>{let{shoppingCartId:t}=e.params;_chunkYTHGSSIVjs.c.call(void 0, t);let{productId:s,quantity:c}=e.body,d={productId:_chunkYTHGSSIVjs.c.call(void 0, s),quantity:_chunkYTHGSSIVjs.d.call(void 0, c)},m=I(d.productId);return await a(o,t,{type:"AddProductItemToShoppingCart",data:{shoppingCartId:t,productItem:{...d,unitPrice:m}}}),r.code(204).send()}),n.delete("/clients/:clientId/shopping-carts/:shoppingCartId/product-items",async(e,r)=>{let{shoppingCartId:t}=e.params;_chunkYTHGSSIVjs.c.call(void 0, t);let{productId:s,quantity:c,unitPrice:d}=e.query,m={productId:_chunkYTHGSSIVjs.c.call(void 0, s),quantity:_chunkYTHGSSIVjs.d.call(void 0, Number(c)),unitPrice:_chunkYTHGSSIVjs.d.call(void 0, Number(d))};return await a(o,t,{type:"RemoveProductItemFromShoppingCart",data:{shoppingCartId:t,productItem:m}}),r.code(204).send()}),n.post("/clients/:clientId/shopping-carts/:shoppingCartId/confirm",async(e,r)=>{let{shoppingCartId:t}=e.params;return _chunkYTHGSSIVjs.c.call(void 0, t),await a(o,t,{type:"ConfirmShoppingCart",data:{shoppingCartId:t,now:new Date}}),r.code(204).send()}),n.delete("/clients/:clientId/shopping-carts/:shoppingCartId",async(e,r)=>{let{shoppingCartId:t}=e.params;_chunkYTHGSSIVjs.c.call(void 0, t);try{await a(o,t,{type:"CancelShoppingCart",data:{shoppingCartId:t,now:new Date}})}catch(s){return s instanceof Error&&"message"in s?r.code(403).send({detail:s.message}):r.code(403)}return r.code(204).send()})};exports.RegisterRoutes = P; exports.handle = a;
2
2
  //# sourceMappingURL=api.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/e2e/decider/api.ts"],"names":["handle","s","decider","dummyPriceProvider","_productId","RegisterRoutes","eventStore","app","request","reply","clientId","_","shoppingCartId","productId","quantity","productItem","b","unitPrice","error"],"mappings":"sGAMA,MAIO,UAIA,IAAMA,EAASC,EAAsBC,CAAO,EAC7CC,EAAsBC,GACnB,IAOIC,EACVC,GAA4BC,GAAyB,CACpDA,EAAI,KACF,oCACA,MAAOC,EAAyBC,IAAuC,CACrE,GAAM,CAAE,SAAAC,CAAS,EAAIF,EAAQ,OAC7BG,EAAqBD,CAAQ,EAC7B,IAAME,EAAiBF,EACvB,aAAMV,EAAOM,EAAYM,EAAgB,CACvC,KAAM,mBACN,KAAM,CAAE,SAAUA,EAAgB,eAAAA,EAAgB,IAAK,IAAI,IAAO,CACpE,CAAC,EACMH,EAAM,KAAK,GAAG,EAAE,KAAK,CAAE,GAAIC,CAAS,CAAC,CAC9C,CACF,EACAH,EAAI,KACF,kEACA,MAAOC,EAAyBC,IAAuC,CACrE,GAAM,CAAE,eAAAG,CAAe,EAAIJ,EAAQ,OACnCG,EAAqBC,CAAc,EACnC,GAAM,CAAE,UAAAC,EAAW,SAAAC,CAAS,EAAIN,EAAQ,KAClCO,EAA2B,CAC/B,UAAWJ,EAAqBE,CAAS,EACzC,SAAUG,EAAqBF,CAAQ,CACzC,EAEMG,EAAYd,EAAmBY,EAAY,SAAS,EAC1D,aAAMf,EAAOM,EAAYM,EAAgB,CACvC,KAAM,+BACN,KAAM,CACJ,eAAAA,EACA,YAAa,CAAE,GAAGG,EAAa,UAAAE,CA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AK,GAAG,EAAE,KAAK,CAC9B,CACF,CACF","sourcesContent":["import {\n DeciderCommandHandler,\n assertNotEmptyString,\n assertPositiveNumber,\n type EventStore,\n} from '@event-driven-io/emmett';\nimport {\n type FastifyInstance,\n type FastifyReply,\n type FastifyRequest,\n} from 'fastify';\nimport { decider } from './businessLogic';\nimport { type PricedProductItem, type ProductItem } from './shoppingCart';\n\nexport const handle = DeciderCommandHandler(decider);\nconst dummyPriceProvider = (_productId: string) => {\n return 100;\n};\n\ninterface ShoppingCartItem {\n shoppingCartId: string;\n}\n\nexport const RegisterRoutes =\n (eventStore: EventStore) => (app: FastifyInstance) => {\n app.post(\n '/clients/:clientId/shopping-carts',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { clientId } = request.params as { clientId: string };\n assertNotEmptyString(clientId);\n const shoppingCartId = clientId;\n await handle(eventStore, shoppingCartId, {\n type: 'OpenShoppingCart',\n data: { clientId: shoppingCartId, shoppingCartId, now: new Date() },\n });\n return reply.code(201).send({ id: clientId });\n },\n );\n app.post(\n '/clients/:clientId/shopping-carts/:shoppingCartId/product-items',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n const { productId, quantity } = request.body as PricedProductItem;\n const productItem: ProductItem = {\n productId: assertNotEmptyString(productId),\n quantity: assertPositiveNumber(quantity),\n };\n\n const unitPrice = dummyPriceProvider(productItem.productId);\n await handle(eventStore, shoppingCartId, {\n type: 'AddProductItemToShoppingCart',\n data: {\n shoppingCartId,\n productItem: { ...productItem, unitPrice },\n },\n });\n return reply.code(204).send();\n },\n );\n app.delete(\n '/clients/:clientId/shopping-carts/:shoppingCartId/product-items',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n const { productId, quantity, unitPrice } =\n request.query as PricedProductItem;\n const productItem: PricedProductItem = {\n productId: assertNotEmptyString(productId),\n quantity: assertPositiveNumber(Number(quantity)),\n unitPrice: assertPositiveNumber(Number(unitPrice)),\n };\n\n await handle(eventStore, shoppingCartId, {\n type: 'RemoveProductItemFromShoppingCart',\n data: { shoppingCartId, productItem },\n });\n return reply.code(204).send();\n },\n );\n app.post(\n '/clients/:clientId/shopping-carts/:shoppingCartId/confirm',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n\n await handle(eventStore, shoppingCartId, {\n type: 'ConfirmShoppingCart',\n data: { shoppingCartId, now: new Date() },\n });\n return reply.code(204).send();\n },\n );\n app.delete(\n '/clients/:clientId/shopping-carts/:shoppingCartId',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n try {\n await handle(eventStore, shoppingCartId, {\n type: 'CancelShoppingCart',\n data: { shoppingCartId, now: new Date() },\n });\n } catch (error) {\n return error instanceof Error && 'message' in error\n ? reply.code(403).send({ detail: error.message })\n : reply.code(403);\n }\n return reply.code(204).send();\n },\n );\n };\n"]}
1
+ {"version":3,"sources":["../../../src/e2e/decider/api.ts"],"names":["handle","s","decider","dummyPriceProvider","_productId","RegisterRoutes","eventStore","app","request","reply","clientId","y","shoppingCartId","productId","quantity","productItem","f","unitPrice","error"],"mappings":"sIAMA,MAIO,UAIA,IAAMA,EAASC,EAAsBC,CAAO,EAC7CC,EAAsBC,GACnB,IAOIC,EACVC,GAA4BC,GAAyB,CACpDA,EAAI,KACF,oCACA,MAAOC,EAAyBC,IAAuC,CACrE,GAAM,CAAE,SAAAC,CAAS,EAAIF,EAAQ,OAC7BG,EAAqBD,CAAQ,EAC7B,IAAME,EAAiBF,EACvB,aAAMV,EAAOM,EAAYM,EAAgB,CACvC,KAAM,mBACN,KAAM,CAAE,SAAUA,EAAgB,eAAAA,EAAgB,IAAK,IAAI,IAA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AAK,IAAI,IAAO,CAC1C,CAAC,EACMH,EAAM,KAAK,GAAG,EAAE,KAAK,CAC9B,CACF,EACAF,EAAI,OACF,oDACA,MAAOC,EAAyBC,IAAuC,CACrE,GAAM,CAAE,eAAAG,CAAe,EAAIJ,EAAQ,OACnCG,EAAqBC,CAAc,EACnC,GAAI,CACF,MAAMZ,EAAOM,EAAYM,EAAgB,CACvC,KAAM,qBACN,KAAM,CAAE,eAAAA,EAAgB,IAAK,IAAI,IAAO,CAC1C,CAAC,CACH,OAASM,EAAO,CACd,OAAOA,aAAiB,OAAS,YAAaA,EAC1CT,EAAM,KAAK,GAAG,EAAE,KAAK,CAAE,OAAQS,EAAM,OAAQ,CAAC,EAC9CT,EAAM,KAAK,GAAG,CACpB,CACA,OAAOA,EAAM,KAAK,GAAG,EAAE,KAAK,CAC9B,CACF,CACF","sourcesContent":["import {\n DeciderCommandHandler,\n assertNotEmptyString,\n assertPositiveNumber,\n type EventStore,\n} from '@event-driven-io/emmett';\nimport {\n type FastifyInstance,\n type FastifyReply,\n type FastifyRequest,\n} from 'fastify';\nimport { decider } from './businessLogic';\nimport { type PricedProductItem, type ProductItem } from './shoppingCart';\n\nexport const handle = DeciderCommandHandler(decider);\nconst dummyPriceProvider = (_productId: string) => {\n return 100;\n};\n\ninterface ShoppingCartItem {\n shoppingCartId: string;\n}\n\nexport const RegisterRoutes =\n (eventStore: EventStore) => (app: FastifyInstance) => {\n app.post(\n '/clients/:clientId/shopping-carts',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { clientId } = request.params as { clientId: string };\n assertNotEmptyString(clientId);\n const shoppingCartId = clientId;\n await handle(eventStore, shoppingCartId, {\n type: 'OpenShoppingCart',\n data: { clientId: shoppingCartId, shoppingCartId, now: new Date() },\n });\n return reply.code(201).send({ id: clientId });\n },\n );\n app.post(\n '/clients/:clientId/shopping-carts/:shoppingCartId/product-items',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n const { productId, quantity } = request.body as PricedProductItem;\n const productItem: ProductItem = {\n productId: assertNotEmptyString(productId),\n quantity: assertPositiveNumber(quantity),\n };\n\n const unitPrice = dummyPriceProvider(productItem.productId);\n await handle(eventStore, shoppingCartId, {\n type: 'AddProductItemToShoppingCart',\n data: {\n shoppingCartId,\n productItem: { ...productItem, unitPrice },\n },\n });\n return reply.code(204).send();\n },\n );\n app.delete(\n '/clients/:clientId/shopping-carts/:shoppingCartId/product-items',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n const { productId, quantity, unitPrice } =\n request.query as PricedProductItem;\n const productItem: PricedProductItem = {\n productId: assertNotEmptyString(productId),\n quantity: assertPositiveNumber(Number(quantity)),\n unitPrice: assertPositiveNumber(Number(unitPrice)),\n };\n\n await handle(eventStore, shoppingCartId, {\n type: 'RemoveProductItemFromShoppingCart',\n data: { shoppingCartId, productItem },\n });\n return reply.code(204).send();\n },\n );\n app.post(\n '/clients/:clientId/shopping-carts/:shoppingCartId/confirm',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n\n await handle(eventStore, shoppingCartId, {\n type: 'ConfirmShoppingCart',\n data: { shoppingCartId, now: new Date() },\n });\n return reply.code(204).send();\n },\n );\n app.delete(\n '/clients/:clientId/shopping-carts/:shoppingCartId',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n try {\n await handle(eventStore, shoppingCartId, {\n type: 'CancelShoppingCart',\n data: { shoppingCartId, now: new Date() },\n });\n } catch (error) {\n return error instanceof Error && 'message' in error\n ? reply.code(403).send({ detail: error.message })\n : reply.code(403);\n }\n return reply.code(204).send();\n },\n );\n };\n"]}
@@ -1,2 +1,2 @@
1
- import{d as y}from"../../chunk-QLVXJW5N.mjs";import{c as i,d as p,e as u}from"../../chunk-YY3STM5A.mjs";import"fastify";var a=u(y),I=o=>100,P=o=>n=>{n.post("/clients/:clientId/shopping-carts",async(e,r)=>{let{clientId:t}=e.params;i(t);let s=t;return await a(o,s,{type:"OpenShoppingCart",data:{clientId:s,shoppingCartId:s,now:new Date}}),r.code(201).send({id:t})}),n.post("/clients/:clientId/shopping-carts/:shoppingCartId/product-items",async(e,r)=>{let{shoppingCartId:t}=e.params;i(t);let{productId:s,quantity:c}=e.body,d={productId:i(s),quantity:p(c)},m=I(d.productId);return await a(o,t,{type:"AddProductItemToShoppingCart",data:{shoppingCartId:t,productItem:{...d,unitPrice:m}}}),r.code(204).send()}),n.delete("/clients/:clientId/shopping-carts/:shoppingCartId/product-items",async(e,r)=>{let{shoppingCartId:t}=e.params;i(t);let{productId:s,quantity:c,unitPrice:d}=e.query,m={productId:i(s),quantity:p(Number(c)),unitPrice:p(Number(d))};return await a(o,t,{type:"RemoveProductItemFromShoppingCart",data:{shoppingCartId:t,productItem:m}}),r.code(204).send()}),n.post("/clients/:clientId/shopping-carts/:shoppingCartId/confirm",async(e,r)=>{let{shoppingCartId:t}=e.params;return i(t),await a(o,t,{type:"ConfirmShoppingCart",data:{shoppingCartId:t,now:new Date}}),r.code(204).send()}),n.delete("/clients/:clientId/shopping-carts/:shoppingCartId",async(e,r)=>{let{shoppingCartId:t}=e.params;i(t);try{await a(o,t,{type:"CancelShoppingCart",data:{shoppingCartId:t,now:new Date}})}catch(s){return s instanceof Error&&"message"in s?r.code(403).send({detail:s.message}):r.code(403)}return r.code(204).send()})};export{P as RegisterRoutes,a as handle};
1
+ import{d as y}from"../../chunk-UQKUA465.mjs";import"../../chunk-ZSD2HWZE.mjs";import{c as i,d as p,h as u}from"../../chunk-IA2ESUCU.mjs";import"fastify";var a=u(y),I=o=>100,P=o=>n=>{n.post("/clients/:clientId/shopping-carts",async(e,r)=>{let{clientId:t}=e.params;i(t);let s=t;return await a(o,s,{type:"OpenShoppingCart",data:{clientId:s,shoppingCartId:s,now:new Date}}),r.code(201).send({id:t})}),n.post("/clients/:clientId/shopping-carts/:shoppingCartId/product-items",async(e,r)=>{let{shoppingCartId:t}=e.params;i(t);let{productId:s,quantity:c}=e.body,d={productId:i(s),quantity:p(c)},m=I(d.productId);return await a(o,t,{type:"AddProductItemToShoppingCart",data:{shoppingCartId:t,productItem:{...d,unitPrice:m}}}),r.code(204).send()}),n.delete("/clients/:clientId/shopping-carts/:shoppingCartId/product-items",async(e,r)=>{let{shoppingCartId:t}=e.params;i(t);let{productId:s,quantity:c,unitPrice:d}=e.query,m={productId:i(s),quantity:p(Number(c)),unitPrice:p(Number(d))};return await a(o,t,{type:"RemoveProductItemFromShoppingCart",data:{shoppingCartId:t,productItem:m}}),r.code(204).send()}),n.post("/clients/:clientId/shopping-carts/:shoppingCartId/confirm",async(e,r)=>{let{shoppingCartId:t}=e.params;return i(t),await a(o,t,{type:"ConfirmShoppingCart",data:{shoppingCartId:t,now:new Date}}),r.code(204).send()}),n.delete("/clients/:clientId/shopping-carts/:shoppingCartId",async(e,r)=>{let{shoppingCartId:t}=e.params;i(t);try{await a(o,t,{type:"CancelShoppingCart",data:{shoppingCartId:t,now:new Date}})}catch(s){return s instanceof Error&&"message"in s?r.code(403).send({detail:s.message}):r.code(403)}return r.code(204).send()})};export{P as RegisterRoutes,a as handle};
2
2
  //# sourceMappingURL=api.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/e2e/decider/api.ts"],"sourcesContent":["import {\n DeciderCommandHandler,\n assertNotEmptyString,\n assertPositiveNumber,\n type EventStore,\n} from '@event-driven-io/emmett';\nimport {\n type FastifyInstance,\n type FastifyReply,\n type FastifyRequest,\n} from 'fastify';\nimport { decider } from './businessLogic';\nimport { type PricedProductItem, type ProductItem } from './shoppingCart';\n\nexport const handle = DeciderCommandHandler(decider);\nconst dummyPriceProvider = (_productId: string) => {\n return 100;\n};\n\ninterface ShoppingCartItem {\n shoppingCartId: string;\n}\n\nexport const RegisterRoutes =\n (eventStore: EventStore) => (app: FastifyInstance) => {\n app.post(\n '/clients/:clientId/shopping-carts',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { clientId } = request.params as { clientId: string };\n assertNotEmptyString(clientId);\n const shoppingCartId = clientId;\n await handle(eventStore, shoppingCartId, {\n type: 'OpenShoppingCart',\n data: { clientId: shoppingCartId, shoppingCartId, now: new Date() },\n });\n return reply.code(201).send({ id: clientId });\n },\n );\n app.post(\n '/clients/:clientId/shopping-carts/:shoppingCartId/product-items',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n const { productId, quantity } = request.body as PricedProductItem;\n const productItem: ProductItem = {\n productId: assertNotEmptyString(productId),\n quantity: assertPositiveNumber(quantity),\n };\n\n const unitPrice = dummyPriceProvider(productItem.productId);\n await handle(eventStore, shoppingCartId, {\n type: 'AddProductItemToShoppingCart',\n data: {\n shoppingCartId,\n productItem: { ...productItem, unitPrice },\n },\n });\n return reply.code(204).send();\n },\n );\n app.delete(\n '/clients/:clientId/shopping-carts/:shoppingCartId/product-items',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n const { productId, quantity, unitPrice } =\n request.query as PricedProductItem;\n const productItem: PricedProductItem = {\n productId: assertNotEmptyString(productId),\n quantity: assertPositiveNumber(Number(quantity)),\n unitPrice: assertPositiveNumber(Number(unitPrice)),\n };\n\n await handle(eventStore, shoppingCartId, {\n type: 'RemoveProductItemFromShoppingCart',\n data: { shoppingCartId, productItem },\n });\n return reply.code(204).send();\n },\n );\n app.post(\n '/clients/:clientId/shopping-carts/:shoppingCartId/confirm',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n\n await handle(eventStore, shoppingCartId, {\n type: 'ConfirmShoppingCart',\n data: { shoppingCartId, now: new Date() },\n });\n return reply.code(204).send();\n },\n );\n app.delete(\n '/clients/:clientId/shopping-carts/:shoppingCartId',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n try {\n await handle(eventStore, shoppingCartId, {\n type: 'CancelShoppingCart',\n data: { shoppingCartId, now: new Date() },\n });\n } catch (error) {\n return error instanceof Error && 'message' in error\n ? reply.code(403).send({ detail: error.message })\n : reply.code(403);\n }\n return reply.code(204).send();\n },\n );\n };\n"],"mappings":"wGAMA,MAIO,UAIA,IAAMA,EAASC,EAAsBC,CAAO,EAC7CC,EAAsBC,GACnB,IAOIC,EACVC,GAA4BC,GAAyB,CACpDA,EAAI,KACF,oCACA,MAAOC,EAAyBC,IAAuC,CACrE,GAAM,CAAE,SAAAC,CAAS,EAAIF,EAAQ,OAC7BG,EAAqBD,CAAQ,EAC7B,IAAME,EAAiBF,EACvB,aAAMV,EAAOM,EAAYM,EAAgB,CACvC,KAAM,mBACN,KAAM,CAAE,SAAUA,EAAgB,eAAAA,EAAgB,IAAK,IAAI,IAAO,CACpE,CAAC,EACMH,EAAM,KAAK,GAAG,EAAE,KAAK,CAAE,GAAIC,CAAS,CAAC,CAC9C,CACF,EACAH,EAAI,KACF,kEACA,MAAOC,EAAyBC,IAAuC,CACrE,GAAM,CAAE,eAAAG,CAAe,EAAIJ,EAAQ,OACnCG,EAAqBC,CAAc,EACnC,GAAM,CAAE,UAAAC,EAAW,SAAAC,CAAS,EAAIN,EAAQ,KAClCO,EAA2B,CAC/B,UAAWJ,EAAqBE,CAAS,EACzC,SAAUG,EAAqBF,CAAQ,CACzC,EAEMG,EAAYd,EAAmBY,EAAY,SAAS,EAC1D,aAAMf,EAAOM,EAAYM,EAAgB,CACvC,KAAM,+BACN,KAAM,CACJ,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T,EAAM,KAAK,GAAG,CACpB,CACA,OAAOA,EAAM,KAAK,GAAG,EAAE,KAAK,CAC9B,CACF,CACF","names":["handle","s","decider","dummyPriceProvider","_productId","RegisterRoutes","eventStore","app","request","reply","clientId","_","shoppingCartId","productId","quantity","productItem","b","unitPrice","error"]}
1
+ {"version":3,"sources":["../../../src/e2e/decider/api.ts"],"sourcesContent":["import {\n DeciderCommandHandler,\n assertNotEmptyString,\n assertPositiveNumber,\n type EventStore,\n} from '@event-driven-io/emmett';\nimport {\n type FastifyInstance,\n type FastifyReply,\n type FastifyRequest,\n} from 'fastify';\nimport { decider } from './businessLogic';\nimport { type PricedProductItem, type ProductItem } from './shoppingCart';\n\nexport const handle = DeciderCommandHandler(decider);\nconst dummyPriceProvider = (_productId: string) => {\n return 100;\n};\n\ninterface ShoppingCartItem {\n shoppingCartId: string;\n}\n\nexport const RegisterRoutes =\n (eventStore: EventStore) => (app: FastifyInstance) => {\n app.post(\n '/clients/:clientId/shopping-carts',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { clientId } = request.params as { clientId: string };\n assertNotEmptyString(clientId);\n const shoppingCartId = clientId;\n await handle(eventStore, shoppingCartId, {\n type: 'OpenShoppingCart',\n data: { clientId: shoppingCartId, shoppingCartId, now: new Date() },\n });\n return reply.code(201).send({ id: clientId });\n },\n );\n app.post(\n '/clients/:clientId/shopping-carts/:shoppingCartId/product-items',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n const { productId, quantity } = request.body as PricedProductItem;\n const productItem: ProductItem = {\n productId: assertNotEmptyString(productId),\n quantity: assertPositiveNumber(quantity),\n };\n\n const unitPrice = dummyPriceProvider(productItem.productId);\n await handle(eventStore, shoppingCartId, {\n type: 'AddProductItemToShoppingCart',\n data: {\n shoppingCartId,\n productItem: { ...productItem, unitPrice },\n },\n });\n return reply.code(204).send();\n },\n );\n app.delete(\n '/clients/:clientId/shopping-carts/:shoppingCartId/product-items',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n const { productId, quantity, unitPrice } =\n request.query as PricedProductItem;\n const productItem: PricedProductItem = {\n productId: assertNotEmptyString(productId),\n quantity: assertPositiveNumber(Number(quantity)),\n unitPrice: assertPositiveNumber(Number(unitPrice)),\n };\n\n await handle(eventStore, shoppingCartId, {\n type: 'RemoveProductItemFromShoppingCart',\n data: { shoppingCartId, productItem },\n });\n return reply.code(204).send();\n },\n );\n app.post(\n '/clients/:clientId/shopping-carts/:shoppingCartId/confirm',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n\n await handle(eventStore, shoppingCartId, {\n type: 'ConfirmShoppingCart',\n data: { shoppingCartId, now: new Date() },\n });\n return reply.code(204).send();\n },\n );\n app.delete(\n '/clients/:clientId/shopping-carts/:shoppingCartId',\n async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const { shoppingCartId } = request.params as ShoppingCartItem;\n assertNotEmptyString(shoppingCartId);\n try {\n await handle(eventStore, shoppingCartId, {\n type: 'CancelShoppingCart',\n data: { shoppingCartId, now: new Date() },\n });\n } catch (error) {\n return error instanceof Error && 'message' in error\n ? reply.code(403).send({ detail: error.message })\n : reply.code(403);\n }\n return reply.code(204).send();\n },\n );\n };\n"],"mappings":"yIAMA,MAIO,UAIA,IAAMA,EAASC,EAAsBC,CAAO,EAC7CC,EAAsBC,GACnB,IAOIC,EACVC,GAA4BC,GAAyB,CACpDA,EAAI,KACF,oCACA,MAAOC,EAAyBC,IAAuC,CACrE,GAAM,CAAE,SAAAC,CAAS,EAAIF,EAAQ,OAC7BG,EAAqBD,CAAQ,EAC7B,IAAME,EAAiBF,EACvB,aAAMV,EAAOM,EAAYM,EAAgB,CACvC,KAAM,mBACN,KAAM,CAA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,CACvC,KAAM,sBACN,KAAM,CAAE,eAAAA,EAAgB,IAAK,IAAI,IAAO,CAC1C,CAAC,EACMH,EAAM,KAAK,GAAG,EAAE,KAAK,CAC9B,CACF,EACAF,EAAI,OACF,oDACA,MAAOC,EAAyBC,IAAuC,CACrE,GAAM,CAAE,eAAAG,CAAe,EAAIJ,EAAQ,OACnCG,EAAqBC,CAAc,EACnC,GAAI,CACF,MAAMZ,EAAOM,EAAYM,EAAgB,CACvC,KAAM,qBACN,KAAM,CAAE,eAAAA,EAAgB,IAAK,IAAI,IAAO,CAC1C,CAAC,CACH,OAASM,EAAO,CACd,OAAOA,aAAiB,OAAS,YAAaA,EAC1CT,EAAM,KAAK,GAAG,EAAE,KAAK,CAAE,OAAQS,EAAM,OAAQ,CAAC,EAC9CT,EAAM,KAAK,GAAG,CACpB,CACA,OAAOA,EAAM,KAAK,GAAG,EAAE,KAAK,CAC9B,CACF,CACF","names":["handle","s","decider","dummyPriceProvider","_productId","RegisterRoutes","eventStore","app","request","reply","clientId","y","shoppingCartId","productId","quantity","productItem","f","unitPrice","error"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkAI5EQ7AWjs = require('../../chunk-AI5EQ7AW.js');require('../../chunk-FXSUJ5HP.js');exports.ShoppingCartErrors = _chunkAI5EQ7AWjs.a; exports.assertProductItemExists = _chunkAI5EQ7AWjs.b; exports.decide = _chunkAI5EQ7AWjs.c; exports.decider = _chunkAI5EQ7AWjs.d;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkEMCVUR73js = require('../../chunk-EMCVUR73.js');require('../../chunk-UXU77SIW.js');require('../../chunk-YTHGSSIV.js');exports.ShoppingCartErrors = _chunkEMCVUR73js.a; exports.assertProductItemExists = _chunkEMCVUR73js.b; exports.decide = _chunkEMCVUR73js.c; exports.decider = _chunkEMCVUR73js.d;
2
2
  //# sourceMappingURL=businessLogic.js.map
@@ -1,2 +1,2 @@
1
- import{a,b,c,d}from"../../chunk-QLVXJW5N.mjs";import"../../chunk-YY3STM5A.mjs";export{a as ShoppingCartErrors,b as assertProductItemExists,c as decide,d as decider};
1
+ import{a,b,c,d}from"../../chunk-UQKUA465.mjs";import"../../chunk-ZSD2HWZE.mjs";import"../../chunk-IA2ESUCU.mjs";export{a as ShoppingCartErrors,b as assertProductItemExists,c as decide,d as decider};
2
2
  //# sourceMappingURL=businessLogic.mjs.map
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkFXSUJ5HPjs = require('../../chunk-FXSUJ5HP.js');exports.ShoppingCartErrors = _chunkFXSUJ5HPjs.j; exports.ShoppingCartStatus = _chunkFXSUJ5HPjs.f; exports.emptyShoppingCart = _chunkFXSUJ5HPjs.g; exports.evolve = _chunkFXSUJ5HPjs.h; exports.getShoppingCart = _chunkFXSUJ5HPjs.i;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkUXU77SIWjs = require('../../chunk-UXU77SIW.js');require('../../chunk-YTHGSSIV.js');exports.ShoppingCartErrors = _chunkUXU77SIWjs.e; exports.ShoppingCartStatus = _chunkUXU77SIWjs.a; exports.emptyShoppingCart = _chunkUXU77SIWjs.b; exports.evolve = _chunkUXU77SIWjs.c; exports.getShoppingCart = _chunkUXU77SIWjs.d;
2
2
  //# sourceMappingURL=shoppingCart.js.map
@@ -1,2 +1,2 @@
1
- import{f as a,g as b,h as c,i as d,j as e}from"../../chunk-YY3STM5A.mjs";export{e as ShoppingCartErrors,a as ShoppingCartStatus,b as emptyShoppingCart,c as evolve,d as getShoppingCart};
1
+ import{a,b,c,d,e}from"../../chunk-ZSD2HWZE.mjs";import"../../chunk-IA2ESUCU.mjs";export{e as ShoppingCartErrors,a as ShoppingCartStatus,b as emptyShoppingCart,c as evolve,d as getShoppingCart};
2
2
  //# sourceMappingURL=shoppingCart.mjs.map
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _strict = require('assert/strict'); var _strict2 = _interopRequireDefault(_strict);var c=e=>{let s=e.headers.etag;_strict2.default.ok(s),_strict2.default.match(s,/W\/"\d+.*"/)},a= exports.runTwice =e=>({expect:async t=>{let{first:r,second:n}=t,p=await r(await e());return await n(await e()),p}}),R= exports.statuses =(e,s)=>({first:t=>t.expect(e),second:t=>t.expect(s)});exports.expectNextRevisionInResponseEtag = c; exports.runTwice = a; exports.statuses = R;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkYTHGSSIVjs = require('../chunk-YTHGSSIV.js');var c=e=>{let s=e.headers.etag;_chunkYTHGSSIVjs.b.call(void 0, s),_chunkYTHGSSIVjs.a.call(void 0, s,/W\/"\d+.*"/)},R= exports.runTwice =e=>({expect:async t=>{let{first:n,second:p}=t,i=await n(await e());return await p(await e()),i}}),d= exports.statuses =(e,s)=>({first:t=>t.expect(e),second:t=>t.expect(s)});exports.expectNextRevisionInResponseEtag = c; exports.runTwice = R; exports.statuses = d;
2
2
  //# sourceMappingURL=testing.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/e2e/testing.ts"],"names":["assert","expectNextRevisionInResponseEtag","response","eTagValue","runTwice","test","firstExpect","secondExpect","result","statuses","first","second"],"mappings":"AACA,OAAOA,MAAY,gBAWZ,IAAMC,EACXC,GACG,CACH,IAAMC,EAAYD,EAAS,QAAQ,KACnCF,EAAO,GAAGG,CAAS,EACnBH,EAAO,MAAMG,EAAW,YAAY,CACtC,EAEaC,EAAYC,IAahB,CAAE,OAZM,MAAOL,GAGG,CACvB,GAAM,CAAE,MAAOM,EAAa,OAAQC,CAAa,EAAIP,EAE/CQ,EAAS,MAAMF,EAAY,MAAMD,EAAK,CAAC,EAC7C,aAAME,EAAa,MAAMF,EAAK,CAAC,EAExBG,CACT,CAEgB,GAGLC,EAAW,CAACC,EAAeC,KAC/B,CACL,MAAQN,GAAeA,EAAK,OAAOK,CAAK,EACxC,OAASL,GAAeA,EAAK,OAAOM,CAAM,CAC5C","sourcesContent":["import type { Response } from 'light-my-request';\nimport assert from 'node:assert/strict';\nimport type { Test } from 'supertest';\n\nexport type TestResponse<RequestBody> = Omit<\n Omit<Response, 'body'>,\n 'headers'\n> & {\n body: Partial<RequestBody>;\n headers: Record<string, string>;\n};\n\nexport const expectNextRevisionInResponseEtag = <RequestBody>(\n response: TestResponse<RequestBody>,\n) => {\n const eTagValue = response.headers['etag'];\n assert.ok(eTagValue);\n assert.match(eTagValue, /W\\/\"\\d+.*\"/);\n};\n\nexport const runTwice = (test: () => Promise<Response>) => {\n const expect = async (assert: {\n first: (test: Response) => Promise<Response>;\n second: (test: Response) => Promise<Response>;\n }): Promise<Response> => {\n const { first: firstExpect, second: secondExpect } = assert;\n\n const result = await firstExpect(await test());\n await secondExpect(await test());\n\n return result;\n };\n\n return { expect };\n};\n\nexport const statuses = (first: number, second: number) => {\n return {\n first: (test: Test) => test.expect(first),\n second: (test: Test) => test.expect(second),\n };\n};\n"]}
1
+ {"version":3,"sources":["../../src/e2e/testing.ts"],"names":["expectNextRevisionInResponseEtag","response","eTagValue","g","k","runTwice","test","assert","firstExpect","secondExpect","result","statuses","first","second"],"mappings":"gDAYO,IAAMA,EACXC,GACG,CACH,IAAMC,EAAYD,EAAS,QAAQ,KACnCE,EAASD,CAAS,EAClBE,EAAcF,EAAW,YAAY,CACvC,EAEaG,EAAYC,IAahB,CAAE,OAZM,MAAOC,GAGG,CACvB,GAAM,CAAE,MAAOC,EAAa,OAAQC,CAAa,EAAIF,EAE/CG,EAAS,MAAMF,EAAY,MAAMF,EAAK,CAAC,EAC7C,aAAMG,EAAa,MAAMH,EAAK,CAAC,EAExBI,CACT,CAEgB,GAGLC,EAAW,CAACC,EAAeC,KAC/B,CACL,MAAQP,GAAeA,EAAK,OAAOM,CAAK,EACxC,OAASN,GAAeA,EAAK,OAAOO,CAAM,CAC5C","sourcesContent":["import { assertMatches, assertOk } from '@event-driven-io/emmett';\nimport type { Response } from 'light-my-request';\nimport type { Test } from 'supertest';\n\nexport type TestResponse<RequestBody> = Omit<\n Omit<Response, 'body'>,\n 'headers'\n> & {\n body: Partial<RequestBody>;\n headers: Record<string, string>;\n};\n\nexport const expectNextRevisionInResponseEtag = <RequestBody>(\n response: TestResponse<RequestBody>,\n) => {\n const eTagValue = response.headers['etag'];\n assertOk(eTagValue);\n assertMatches(eTagValue, /W\\/\"\\d+.*\"/);\n};\n\nexport const runTwice = (test: () => Promise<Response>) => {\n const expect = async (assert: {\n first: (test: Response) => Promise<Response>;\n second: (test: Response) => Promise<Response>;\n }): Promise<Response> => {\n const { first: firstExpect, second: secondExpect } = assert;\n\n const result = await firstExpect(await test());\n await secondExpect(await test());\n\n return result;\n };\n\n return { expect };\n};\n\nexport const statuses = (first: number, second: number) => {\n return {\n first: (test: Test) => test.expect(first),\n second: (test: Test) => test.expect(second),\n };\n};\n"]}
@@ -1,2 +1,2 @@
1
- import o from"node:assert/strict";var c=e=>{let s=e.headers.etag;o.ok(s),o.match(s,/W\/"\d+.*"/)},a=e=>({expect:async t=>{let{first:r,second:n}=t,p=await r(await e());return await n(await e()),p}}),R=(e,s)=>({first:t=>t.expect(e),second:t=>t.expect(s)});export{c as expectNextRevisionInResponseEtag,a as runTwice,R as statuses};
1
+ import{a as o,b as r}from"../chunk-IA2ESUCU.mjs";var c=e=>{let s=e.headers.etag;r(s),o(s,/W\/"\d+.*"/)},R=e=>({expect:async t=>{let{first:n,second:p}=t,i=await n(await e());return await p(await e()),i}}),d=(e,s)=>({first:t=>t.expect(e),second:t=>t.expect(s)});export{c as expectNextRevisionInResponseEtag,R as runTwice,d as statuses};
2
2
  //# sourceMappingURL=testing.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/e2e/testing.ts"],"sourcesContent":["import type { Response } from 'light-my-request';\nimport assert from 'node:assert/strict';\nimport type { Test } from 'supertest';\n\nexport type TestResponse<RequestBody> = Omit<\n Omit<Response, 'body'>,\n 'headers'\n> & {\n body: Partial<RequestBody>;\n headers: Record<string, string>;\n};\n\nexport const expectNextRevisionInResponseEtag = <RequestBody>(\n response: TestResponse<RequestBody>,\n) => {\n const eTagValue = response.headers['etag'];\n assert.ok(eTagValue);\n assert.match(eTagValue, /W\\/\"\\d+.*\"/);\n};\n\nexport const runTwice = (test: () => Promise<Response>) => {\n const expect = async (assert: {\n first: (test: Response) => Promise<Response>;\n second: (test: Response) => Promise<Response>;\n }): Promise<Response> => {\n const { first: firstExpect, second: secondExpect } = assert;\n\n const result = await firstExpect(await test());\n await secondExpect(await test());\n\n return result;\n };\n\n return { expect };\n};\n\nexport const statuses = (first: number, second: number) => {\n return {\n first: (test: Test) => test.expect(first),\n second: (test: Test) => test.expect(second),\n };\n};\n"],"mappings":"AACA,OAAOA,MAAY,qBAWZ,IAAMC,EACXC,GACG,CACH,IAAMC,EAAYD,EAAS,QAAQ,KACnCF,EAAO,GAAGG,CAAS,EACnBH,EAAO,MAAMG,EAAW,YAAY,CACtC,EAEaC,EAAYC,IAahB,CAAE,OAZM,MAAOL,GAGG,CACvB,GAAM,CAAE,MAAOM,EAAa,OAAQC,CAAa,EAAIP,EAE/CQ,EAAS,MAAMF,EAAY,MAAMD,EAAK,CAAC,EAC7C,aAAME,EAAa,MAAMF,EAAK,CAAC,EAExBG,CACT,CAEgB,GAGLC,EAAW,CAACC,EAAeC,KAC/B,CACL,MAAQN,GAAeA,EAAK,OAAOK,CAAK,EACxC,OAASL,GAAeA,EAAK,OAAOM,CAAM,CAC5C","names":["assert","expectNextRevisionInResponseEtag","response","eTagValue","runTwice","test","firstExpect","secondExpect","result","statuses","first","second"]}
1
+ {"version":3,"sources":["../../src/e2e/testing.ts"],"sourcesContent":["import { assertMatches, assertOk } from '@event-driven-io/emmett';\nimport type { Response } from 'light-my-request';\nimport type { Test } from 'supertest';\n\nexport type TestResponse<RequestBody> = Omit<\n Omit<Response, 'body'>,\n 'headers'\n> & {\n body: Partial<RequestBody>;\n headers: Record<string, string>;\n};\n\nexport const expectNextRevisionInResponseEtag = <RequestBody>(\n response: TestResponse<RequestBody>,\n) => {\n const eTagValue = response.headers['etag'];\n assertOk(eTagValue);\n assertMatches(eTagValue, /W\\/\"\\d+.*\"/);\n};\n\nexport const runTwice = (test: () => Promise<Response>) => {\n const expect = async (assert: {\n first: (test: Response) => Promise<Response>;\n second: (test: Response) => Promise<Response>;\n }): Promise<Response> => {\n const { first: firstExpect, second: secondExpect } = assert;\n\n const result = await firstExpect(await test());\n await secondExpect(await test());\n\n return result;\n };\n\n return { expect };\n};\n\nexport const statuses = (first: number, second: number) => {\n return {\n first: (test: Test) => test.expect(first),\n second: (test: Test) => test.expect(second),\n };\n};\n"],"mappings":"iDAYO,IAAMA,EACXC,GACG,CACH,IAAMC,EAAYD,EAAS,QAAQ,KACnCE,EAASD,CAAS,EAClBE,EAAcF,EAAW,YAAY,CACvC,EAEaG,EAAYC,IAahB,CAAE,OAZM,MAAOC,GAGG,CACvB,GAAM,CAAE,MAAOC,EAAa,OAAQC,CAAa,EAAIF,EAE/CG,EAAS,MAAMF,EAAY,MAAMF,EAAK,CAAC,EAC7C,aAAMG,EAAa,MAAMH,EAAK,CAAC,EAExBI,CACT,CAEgB,GAGLC,EAAW,CAACC,EAAeC,KAC/B,CACL,MAAQP,GAAeA,EAAK,OAAOM,CAAK,EACxC,OAASN,GAAeA,EAAK,OAAOO,CAAM,CAC5C","names":["expectNextRevisionInResponseEtag","response","eTagValue","g","k","runTwice","test","assert","firstExpect","secondExpect","result","statuses","first","second"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@event-driven-io/emmett-fastify",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Emmett - Event Sourcing development made simple",
5
5
  "scripts": {
6
6
  "build": "tsup",
@@ -52,7 +52,7 @@
52
52
  "dependencies": {},
53
53
  "devDependencies": {},
54
54
  "peerDependencies": {
55
- "@event-driven-io/emmett": "^0.9.0",
55
+ "@event-driven-io/emmett": "^0.10.0",
56
56
  "fastify": "4.26.2",
57
57
  "@fastify/compress": "7.0.0",
58
58
  "@fastify/etag": "5.1.0",
@@ -1,2 +0,0 @@
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 _chunkFXSUJ5HPjs = require('./chunk-FXSUJ5HP.js');var S=(p=>(p.CART_ALREADY_EXISTS="CART_ALREADY_EXISTS",p.CART_IS_ALREADY_CLOSED="CART_IS_ALREADY_CLOSED",p.PRODUCT_ITEM_NOT_FOUND="PRODUCT_ITEM_NOT_FOUND",p.CART_IS_EMPTY="CART_IS_EMPTY",p.UNKNOWN_EVENT_TYPE="UNKNOWN_EVENT_TYPE",p.UNKNOWN_COMMAND_TYPE="UNKNOWN_COMMAND_TYPE",p))(S||{}),I= exports.b =(o,{productId:t,quantity:r,unitPrice:n})=>{if((_nullishCoalesce(_optionalChain([o, 'access', _ => _.find, 'call', _2 => _2(i=>i.productId===t&&i.unitPrice==n), 'optionalAccess', _3 => _3.quantity]), () => (0)))<r)throw new (0, _chunkFXSUJ5HPjs.b)("PRODUCT_ITEM_NOT_FOUND")},g= exports.c =({type:o,data:t},r)=>{switch(o){case"OpenShoppingCart":{if(r.status!=="Empty")throw new (0, _chunkFXSUJ5HPjs.b)("CART_ALREADY_EXISTS");return{type:"ShoppingCartOpened",data:{shoppingCartId:t.shoppingCartId,clientId:t.clientId,openedAt:t.now}}}case"AddProductItemToShoppingCart":{if(r.status!=="Pending")throw new (0, _chunkFXSUJ5HPjs.b)("CART_IS_ALREADY_CLOSED");return{type:"ProductItemAddedToShoppingCart",data:{shoppingCartId:t.shoppingCartId,productItem:t.productItem}}}case"RemoveProductItemFromShoppingCart":{if(r.status!=="Pending")throw new (0, _chunkFXSUJ5HPjs.b)("CART_IS_ALREADY_CLOSED");return I(r.productItems,t.productItem),{type:"ProductItemRemovedFromShoppingCart",data:{shoppingCartId:t.shoppingCartId,productItem:t.productItem}}}case"ConfirmShoppingCart":{if(r.status!=="Pending")throw new (0, _chunkFXSUJ5HPjs.b)("CART_IS_ALREADY_CLOSED");if(r.productItems.length===0)throw new (0, _chunkFXSUJ5HPjs.b)("CART_IS_EMPTY");return{type:"ShoppingCartConfirmed",data:{shoppingCartId:t.shoppingCartId,confirmedAt:t.now}}}case"CancelShoppingCart":{if(r.status!=="Pending")throw new (0, _chunkFXSUJ5HPjs.b)("CART_IS_ALREADY_CLOSED");return{type:"ShoppingCartCanceled",data:{shoppingCartId:t.shoppingCartId,canceledAt:t.now}}}default:{let n=t;throw new (0, _chunkFXSUJ5HPjs.a)("UNKNOWN_COMMAND_TYPE")}}},u= exports.d ={decide:g,evolve:_chunkFXSUJ5HPjs.h,getInitialState:()=>_chunkFXSUJ5HPjs.g};exports.a = S; exports.b = I; exports.c = g; exports.d = u;
2
- //# sourceMappingURL=chunk-AI5EQ7AW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/e2e/decider/businessLogic.ts"],"names":["ShoppingCartErrors","assertProductItemExists","productItems","productId","quantity","unitPrice","p","u","decide","type","command","shoppingCart","_","s","decider","evolve","emptyShoppingCart"],"mappings":"wDAuEO,IAAWA,OAChBA,EAAA,oBAAsB,sBACtBA,EAAA,uBAAyB,yBACzBA,EAAA,uBAAyB,yBACzBA,EAAA,cAAgB,gBAChBA,EAAA,mBAAqB,qBACrBA,EAAA,qBAAuB,uBANPA,OAAA,IASLC,EAA0B,CACrCC,EACA,CAAE,UAAAC,EAAW,SAAA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AAS,CACP,IAAME,EAAWF,EACjB,MAAM,IAAIG,EAAY,sBAAuC,CAC/D,CACF,CACF,EAEaC,EAIT,CACF,OAAAN,EACA,OAAAO,EACA,gBAAiB,IAAMC,CACzB","sourcesContent":["import {\n EmmettError,\n IllegalStateError,\n type Decider,\n} from '@event-driven-io/emmett';\n\nimport {\n ShoppingCartStatus,\n emptyShoppingCart,\n evolve,\n type PricedProductItem,\n type ShoppingCart,\n type ShoppingCartEvent,\n} from './shoppingCart';\n\n//////////////////////////////////////\n/// Commands\n//////////////////////////////////////\n\nexport type OpenShoppingCart = {\n type: 'OpenShoppingCart';\n data: {\n shoppingCartId: string;\n clientId: string;\n now: Date;\n };\n};\n\nexport type AddProductItemToShoppingCart = {\n type: 'AddProductItemToShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n};\n\nexport type RemoveProductItemFromShoppingCart = {\n type: 'RemoveProductItemFromShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n};\n\nexport type ConfirmShoppingCart = {\n type: 'ConfirmShoppingCart';\n data: {\n shoppingCartId: string;\n now: Date;\n };\n};\n\nexport type CancelShoppingCart = {\n type: 'CancelShoppingCart';\n data: {\n shoppingCartId: string;\n now: Date;\n };\n};\n\nexport type ShoppingCartCommand =\n | OpenShoppingCart\n | AddProductItemToShoppingCart\n | RemoveProductItemFromShoppingCart\n | ConfirmShoppingCart\n | CancelShoppingCart;\n\n//////////////////////////////////////\n/// Decide\n//////////////////////////////////////\n\nexport const enum ShoppingCartErrors {\n CART_ALREADY_EXISTS = 'CART_ALREADY_EXISTS',\n CART_IS_ALREADY_CLOSED = 'CART_IS_ALREADY_CLOSED',\n PRODUCT_ITEM_NOT_FOUND = 'PRODUCT_ITEM_NOT_FOUND',\n CART_IS_EMPTY = 'CART_IS_EMPTY',\n UNKNOWN_EVENT_TYPE = 'UNKNOWN_EVENT_TYPE',\n UNKNOWN_COMMAND_TYPE = 'UNKNOWN_COMMAND_TYPE',\n}\n\nexport const assertProductItemExists = (\n productItems: PricedProductItem[],\n { productId, quantity, unitPrice }: PricedProductItem,\n): void => {\n const currentQuantity =\n productItems.find(\n (p) => p.productId === productId && p.unitPrice == unitPrice,\n )?.quantity ?? 0;\n\n if (currentQuantity < quantity) {\n throw new IllegalStateError(ShoppingCartErrors.PRODUCT_ITEM_NOT_FOUND);\n }\n};\n\nexport const decide = (\n { type, data: command }: ShoppingCartCommand,\n shoppingCart: ShoppingCart,\n): ShoppingCartEvent => {\n switch (type) {\n case 'OpenShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Empty) {\n throw new IllegalStateError(ShoppingCartErrors.CART_ALREADY_EXISTS);\n }\n return {\n type: 'ShoppingCartOpened',\n data: {\n shoppingCartId: command.shoppingCartId,\n clientId: command.clientId,\n openedAt: command.now,\n },\n };\n }\n\n case 'AddProductItemToShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n return {\n type: 'ProductItemAddedToShoppingCart',\n data: {\n shoppingCartId: command.shoppingCartId,\n productItem: command.productItem,\n },\n };\n }\n\n case 'RemoveProductItemFromShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n assertProductItemExists(shoppingCart.productItems, command.productItem);\n\n return {\n type: 'ProductItemRemovedFromShoppingCart',\n data: {\n shoppingCartId: command.shoppingCartId,\n productItem: command.productItem,\n },\n };\n }\n\n case 'ConfirmShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n if (shoppingCart.productItems.length === 0) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_EMPTY);\n }\n\n return {\n type: 'ShoppingCartConfirmed',\n data: {\n shoppingCartId: command.shoppingCartId,\n confirmedAt: command.now,\n },\n };\n }\n\n case 'CancelShoppingCart': {\n if (shoppingCart.status !== ShoppingCartStatus.Pending) {\n throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);\n }\n\n return {\n type: 'ShoppingCartCanceled',\n data: {\n shoppingCartId: command.shoppingCartId,\n canceledAt: command.now,\n },\n };\n }\n default: {\n const _: never = command;\n throw new EmmettError(ShoppingCartErrors.UNKNOWN_COMMAND_TYPE);\n }\n }\n};\n\nexport const decider: Decider<\n ShoppingCart,\n ShoppingCartCommand,\n ShoppingCartEvent\n> = {\n decide,\n evolve,\n getInitialState: () => emptyShoppingCart,\n};\n"]}
@@ -1,2 +0,0 @@
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 d=(t,e,o,s,a=()=>{})=>{let r=!1,i=t.map(n=>o(n)?(r=!0,s(n)):n).filter(n=>n!==void 0).map(n=>{if(!n)throw Error("That should not happen");return n});return!r&&a()!==void 0?[...t,e]:i};var _assert = require('assert'); var _assert2 = _interopRequireDefault(_assert);var c=class E extends Error{constructor(e){let o=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:g(e)?e:500,s=e&&typeof e=="object"&&"message"in e?e.message:l(e)?e:`Error with status code '${o}' ocurred during Emmett processing`;super(s),this.errorCode=o,Object.setPrototypeOf(this,E.prototype)}};var u=class y extends c{constructor(e){super({errorCode:400,message:_nullishCoalesce(e, () => ("Validation Error ocurred during Emmett processing"))}),Object.setPrototypeOf(this,y.prototype)}},x= exports.b =class N extends c{constructor(e){super({errorCode:403,message:_nullishCoalesce(e, () => ("Illegal State ocurred during Emmett processing"))}),Object.setPrototypeOf(this,N.prototype)}};var P=(t=>(t.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",t.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",t.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",t))(P||{}),g=t=>typeof t=="number"&&t===t,l=t=>typeof t=="string",T= exports.c =t=>{if(!l(t)||t.length===0)throw new u("NOT_A_NONEMPTY_STRING");return t},A= exports.d =t=>{if(!g(t)||t<=0)throw new u("NOT_A_POSITIVE_NUMBER");return t};var S="STREAM_DOES_NOT_EXIST",I="NO_CONCURRENCY_CHECK";var h=(t,e,o=s=>s)=>async(s,a,r,i)=>{let n=o(a),p=await s.aggregateStream(n,{evolve:t,getInitialState:e,read:{expectedStreamVersion:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _2 => _2.expectedStreamVersion]), () => (I))}}),C=_nullishCoalesce(_optionalChain([p, 'optionalAccess', _3 => _3.state]), () => (e())),O=_optionalChain([p, 'optionalAccess', _4 => _4.currentStreamVersion]),m=r(C),f=Array.isArray(m)?m:[m],_=_nullishCoalesce(_nullishCoalesce(_optionalChain([i, 'optionalAccess', _5 => _5.expectedStreamVersion]), () => (O)), () => (S));return{...await s.appendToStream(n,f,{...i,expectedStreamVersion:_}),newState:f.reduce(t,C)}};var b=({decide:t,evolve:e,getInitialState:o},s=a=>a)=>async(a,r,i,n)=>h(e,o,s)(a,r,p=>t(i,p),n);var _uuid = require('uuid');var D=(a=>(a.Empty="Empty",a.Pending="Pending",a.Confirmed="Confirmed",a.Canceled="Canceled",a))(D||{}),R= exports.g ={status:"Empty"},M= exports.h =(t,{type:e,data:o})=>{switch(e){case"ShoppingCartOpened":return{id:o.shoppingCartId,clientId:o.clientId,openedAt:o.openedAt,productItems:[],status:"Pending"};case"ProductItemAddedToShoppingCart":{if(t.status!=="Pending")return t;let{productItems:s}=t,{productItem:a}=o;return{...t,productItems:d(s,a,r=>r.productId===a.productId&&r.unitPrice===a.unitPrice,r=>({...r,quantity:r.quantity+a.quantity}),()=>a)}}case"ProductItemRemovedFromShoppingCart":{if(t.status!=="Pending")return t;let{productItems:s}=t,{productItem:a}=o;return{...t,productItems:d(s,a,r=>r.productId===a.productId&&r.unitPrice===a.unitPrice,r=>({...r,quantity:r.quantity-a.quantity}))}}case"ShoppingCartConfirmed":return t.status!=="Pending"?t:{...t,status:"Confirmed",confirmedAt:o.confirmedAt};case"ShoppingCartCanceled":return t.status!=="Pending"?t:{...t,status:"Canceled",canceledAt:o.canceledAt}}},Ht= exports.i =t=>t.reduce(M,R),V= exports.j =(r=>(r.CART_IS_ALREADY_CLOSED="CART_IS_ALREADY_CLOSED",r.PRODUCT_ITEM_NOT_FOUND="PRODUCT_ITEM_NOT_FOUND",r.CART_IS_EMPTY="CART_IS_EMPTY",r.UNKNOWN_EVENT_TYPE="UNKNOWN_EVENT_TYPE",r.UNKNOWN_COMMAND_TYPE="UNKNOWN_COMMAND_TYPE",r))(V||{});exports.a = c; exports.b = x; exports.c = T; exports.d = A; exports.e = b; exports.f = D; exports.g = R; exports.h = M; exports.i = Ht; exports.j = V;
2
- //# sourceMappingURL=chunk-FXSUJ5HP.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../emmett/src/utils/merge.ts","../../emmett/src/testing/deciderSpecification.ts","../../emmett/src/errors/index.ts","../../emmett/src/validation/index.ts","../../emmett/src/eventStore/expectedVersion.ts","../../emmett/src/commandHandling/handleCommand.ts","../../emmett/src/commandHandling/handleCommandWithDecider.ts","../../emmett/src/eventStore/inMemoryEventStore.ts","../src/e2e/decider/shoppingCart.ts"],"names":["merge","array","item","where","onExisting","onNotFound","wasFound","result","p","assert","EmmettError","_EmmettError","options","errorCode","isNumber","message","isString","ValidationError","_ValidationError","IllegalStateError","_IllegalStateError","ValidationErrors","val","assertNotEmptyString","value","assertPositiveNumber","STREAM_DOES_NOT_EXIST","NO_CONCURRENCY_CHECK","CommandHandler","evolve","getInitialState","mapToStreamId","id","eventStore","handle","streamName","aggregationResult","state","currentStreamVersion","newEvents","expectedStreamVersion","DeciderCommandHandler","decide","command","randomUUID","ShoppingCartStatus","emptyShoppingCart","type","event","productItems","productItem","i","getShoppingCart","events","ShoppingCartErrors"],"mappings":"AAAO,IAAMA,EAAQ,CACnBC,EACAC,EACAC,EACAC,EACAC,EAAkC,IAAG,CAAA,IAClC,CACH,IAAIC,EAAW,GAETC,EAASN,EAEZ,IAAKO,GACCL,EAAMK,CAAC,GAEZF,EAAW,GACJF,EAAWI,CAAC,GAHGA,CAIvB,EAGA,OAAQA,GAAMA,IAAM,MAAS,EAE7B,IAAKA,GAAM,CACV,GAAI,CAACA,EAAG,MAAM,MAAM,wBAAwB,EAE5C,OAAOA,CACT,CAAC,EAIH,MAAI,CAACF,GACYD,EAAW,IAEX,OAAkB,CAAC,GAAGJ,EAAOC,CAAI,EAG3CK,CACT,ECpCA,OAAOE,MAAY,SCEZ,IAAMC,EAAN,MAAMC,UAAoB,KAAM,CAC9B,UAEP,YACEC,EACA,CACA,IAAMC,EACJD,GAAW,OAAOA,GAAY,UAAY,cAAeA,EACrDA,EAAQ,UACRE,EAASF,CAAO,EACdA,EACA,IACFG,EACJH,GAAW,OAAOA,GAAY,UAAY,YAAaA,EACnDA,EAAQ,QACRI,EAASJ,CAAO,EACdA,EACA,2BAA2BC,CAAS,qCAE5C,MAAME,CAAO,EACb,KAAK,UAAYF,EAGjB,OAAO,eAAe,KAAMF,EAAY,SAAS,CACnD,CACF,EAzBO,IA6CMM,EAAN,MAAMC,UAAwBR,CAAY,CAC/C,YAAYK,EAAkB,CAC5B,MAAM,CACJ,UAAW,IACX,QAASA,GAAW,mDACtB,CAAC,EAGD,OAAO,eAAe,KAAMG,EAAgB,SAAS,CACvD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QACrC,EAEJ,CACF,CACF,CACA,IAAK,wBACH,OAAIb,EAAM,SAAW,UAAmCA,EAEjD,CACL,GAAGA,EACH,OAAQ,YACR,YAAaW,EAAM,WACrB,EACF,IAAK,uBACH,OAAIX,EAAM,SAAW,UAAmCA,EAEjD,CACL,GAAGA,EACH,OAAQ,WACR,WAAYW,EAAM,UACpB,CACJ,CACF,EAEaI,GAAmBC,GACvBA,EAAO,OAAqBxB,EAAQiB,CAAiB,EAG5CQ,OAChBA,EAAA,uBAAyB,yBACzBA,EAAA,uBAAyB,yBACzBA,EAAA,cAAgB,gBAChBA,EAAA,mBAAqB,qBACrBA,EAAA,qBAAuB,uBALPA,OAAA","sourcesContent":["export const merge = <T>(\n array: T[],\n item: T,\n where: (current: T) => boolean,\n onExisting: (current: T) => T,\n onNotFound: () => T | undefined = () => undefined,\n) => {\n let wasFound = false;\n\n const result = array\n // merge the existing item if matches condition\n .map((p: T) => {\n if (!where(p)) return p;\n\n wasFound = true;\n return onExisting(p);\n })\n // filter out item if undefined was returned\n // for cases of removal\n .filter((p) => p !== undefined)\n // make TypeScript happy\n .map((p) => {\n if (!p) throw Error('That should not happen');\n\n return p;\n });\n\n // if item was not found and onNotFound action is defined\n // try to generate new item\n if (!wasFound) {\n const result = onNotFound();\n\n if (result !== undefined) return [...array, item];\n }\n\n return result;\n};\n","import assert from 'assert';\n\nexport type DeciderSpecfication<Command, Event> = (\n givenEvents: Event | Event[],\n) => {\n when: (command: Command) => {\n then: (expectedEvents: Event | Event[]) => void;\n thenThrows: <Error>(assert: (error: Error) => boolean) => void;\n };\n};\n\nexport const DeciderSpecification = {\n for: <Command, Event, State>(decider: {\n decide: (command: Command, state: State) => Event | Event[];\n evolve: (state: State, event: Event) => State;\n initialState: () => State;\n }): DeciderSpecfication<Command, Event> => {\n {\n return (givenEvents: Event | Event[]) => {\n return {\n when: (command: Command) => {\n const handle = () => {\n const existingEvents = Array.isArray(givenEvents)\n ? givenEvents\n : [givenEvents];\n\n const currentState = existingEvents.reduce<State>(\n decider.evolve,\n decider.initialState(),\n );\n\n return decider.decide(command, currentState);\n };\n\n return {\n then: (expectedEvents: Event | Event[]): void => {\n const resultEvents = handle();\n\n const resultEventsArray = Array.isArray(resultEvents)\n ? resultEvents\n : [resultEvents];\n\n const expectedEventsArray = Array.isArray(expectedEvents)\n ? expectedEvents\n : [expectedEvents];\n\n assert.deepEqual(resultEventsArray, expectedEventsArray);\n },\n thenThrows: <Error>(check?: (error: Error) => boolean): void => {\n try {\n handle();\n assert.fail('Handler did not fail as expected');\n } catch (error) {\n if (check) assert.ok(check(error as Error));\n }\n },\n };\n },\n };\n };\n }\n },\n};\n","import { isNumber, isString } from '../validation';\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 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","import { ConcurrencyError } from '../errors';\nimport type { Flavour } from '../typing';\nimport type { DefaultStreamVersionType } from './eventStore';\n\nexport type ExpectedStreamVersion<VersionType = DefaultStreamVersionType> =\n | ExpectedStreamVersionWithValue<VersionType>\n | ExpectedStreamVersionGeneral;\n\nexport type ExpectedStreamVersionWithValue<\n VersionType = DefaultStreamVersionType,\n> = Flavour<VersionType, 'StreamVersion'>;\n\nexport type ExpectedStreamVersionGeneral = Flavour<\n 'STREAM_EXISTS' | 'STREAM_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK',\n 'StreamVersion'\n>;\n\nexport const STREAM_EXISTS = 'STREAM_EXISTS' as ExpectedStreamVersionGeneral;\nexport const STREAM_DOES_NOT_EXIST =\n 'STREAM_DOES_NOT_EXIST' as ExpectedStreamVersionGeneral;\nexport const NO_CONCURRENCY_CHECK =\n 'NO_CONCURRENCY_CHECK' as ExpectedStreamVersionGeneral;\n\nexport const matchesExpectedVersion = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion | undefined,\n expected: ExpectedStreamVersion<StreamVersion>,\n): boolean => {\n if (expected === NO_CONCURRENCY_CHECK) return true;\n\n if (expected == STREAM_DOES_NOT_EXIST) return current === undefined;\n\n if (expected == STREAM_EXISTS) return current !== undefined;\n\n return current === expected;\n};\n\nexport const assertExpectedVersionMatchesCurrent = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion | undefined,\n expected: ExpectedStreamVersion<StreamVersion> | undefined,\n): void => {\n expected ??= NO_CONCURRENCY_CHECK;\n\n if (!matchesExpectedVersion(current, expected))\n throw new ExpectedVersionConflictError(current, expected);\n};\n\nexport class ExpectedVersionConflictError<\n VersionType = DefaultStreamVersionType,\n> extends ConcurrencyError {\n constructor(\n current: VersionType | undefined,\n expected: ExpectedStreamVersion<VersionType>,\n ) {\n super(current?.toString(), expected?.toString());\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ExpectedVersionConflictError.prototype);\n }\n}\n","import {\n NO_CONCURRENCY_CHECK,\n STREAM_DOES_NOT_EXIST,\n type AppendToStreamResult,\n type DefaultStreamVersionType,\n type EventStore,\n type ExpectedStreamVersion,\n} from '../eventStore';\nimport type { Event } from '../typing';\n\n// #region command-handler\nexport type CommandHandlerResult<\n State,\n StreamVersion = DefaultStreamVersionType,\n> = AppendToStreamResult<StreamVersion> & { newState: State };\n\nexport const CommandHandler =\n <State, StreamEvent extends Event, StreamVersion = DefaultStreamVersionType>(\n evolve: (state: State, event: StreamEvent) => State,\n getInitialState: () => State,\n mapToStreamId: (id: string) => string = (id) => id,\n ) =>\n async <Store extends EventStore<StreamVersion>>(\n eventStore: Store,\n id: string,\n handle: (state: State) => StreamEvent | StreamEvent[],\n options?: Parameters<Store['appendToStream']>[2] & {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n },\n ): Promise<CommandHandlerResult<State, StreamVersion>> => {\n const streamName = mapToStreamId(id);\n\n // 1. Aggregate the stream\n const aggregationResult = await eventStore.aggregateStream<\n State,\n StreamEvent\n >(streamName, {\n evolve,\n getInitialState,\n read: {\n // expected stream version is passed to fail fast\n // if stream is in the wrong state\n expectedStreamVersion:\n options?.expectedStreamVersion ?? NO_CONCURRENCY_CHECK,\n },\n });\n\n // 2. Use the aggregate state or the initial one (when e.g. stream does not exist)\n const state = aggregationResult?.state ?? getInitialState();\n const currentStreamVersion = aggregationResult?.currentStreamVersion;\n\n // 3. Run business logic\n const result = handle(state);\n\n const newEvents = Array.isArray(result) ? result : [result];\n\n // Either use:\n // - provided expected stream version,\n // - current stream version got from stream aggregation,\n // - or expect stream not to exists otherwise.\n const expectedStreamVersion: ExpectedStreamVersion<StreamVersion> =\n options?.expectedStreamVersion ??\n currentStreamVersion ??\n STREAM_DOES_NOT_EXIST;\n\n // 4. Append result to the stream\n const appendResult = await eventStore.appendToStream(\n streamName,\n newEvents,\n {\n ...options,\n expectedStreamVersion,\n },\n );\n\n // 5. Return result with updated state\n return { ...appendResult, newState: newEvents.reduce(evolve, state) };\n };\n// #endregion command-handler\n","import type {\n DefaultStreamVersionType,\n EventStore,\n ExpectedStreamVersion,\n} from '../eventStore';\nimport type { Command, Event } from '../typing';\nimport type { Decider } from '../typing/decider';\nimport { CommandHandler } from './handleCommand';\n\n// #region command-handler\nexport const DeciderCommandHandler =\n <\n State,\n CommandType extends Command,\n StreamEvent extends Event,\n StreamVersion = DefaultStreamVersionType,\n >(\n {\n decide,\n evolve,\n getInitialState,\n }: Decider<State, CommandType, StreamEvent>,\n mapToStreamId: (id: string) => string = (id) => id,\n ) =>\n async (\n eventStore: EventStore<StreamVersion>,\n id: string,\n command: CommandType,\n options?: {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n },\n ) =>\n CommandHandler<State, StreamEvent, StreamVersion>(\n evolve,\n getInitialState,\n mapToStreamId,\n )(eventStore, id, (state) => decide(command, state), options);\n// #endregion command-handler\n","import { v4 as randomUUID } from 'uuid';\nimport type { Event } from '../typing';\nimport {\n type AggregateStreamOptions,\n type AggregateStreamResult,\n type AppendToStreamOptions,\n type AppendToStreamResult,\n type EventStore,\n type ReadStreamOptions,\n type ReadStreamResult,\n} from './eventStore';\nimport { assertExpectedVersionMatchesCurrent } from './expectedVersion';\n\nexport type EventMetadata = Readonly<{\n eventId: string;\n streamPosition: number;\n logPosition: bigint;\n}>;\n\nexport type EventEnvelope<E extends Event = Event> = {\n event: E;\n metadata: EventMetadata;\n};\n\nexport type EventHandler<E extends Event = Event> = (\n eventEnvelope: EventEnvelope<E>,\n) => void;\n\nexport const getInMemoryEventStore = (): EventStore => {\n const streams = new Map<string, EventEnvelope[]>();\n\n const getAllEventsCount = () => {\n return Array.from<EventEnvelope[]>(streams.values())\n .map((s) => s.length)\n .reduce((p, c) => p + c, 0);\n };\n\n return {\n async aggregateStream<State, EventType extends Event>(\n streamName: string,\n options: AggregateStreamOptions<State, EventType>,\n ): Promise<AggregateStreamResult<State> | null> {\n const { evolve, getInitialState, read } = options;\n\n const result = await this.readStream<EventType>(streamName, read);\n\n if (!result) return null;\n\n const events = result?.events ?? [];\n\n return {\n currentStreamVersion: BigInt(events.length),\n state: events.reduce(evolve, getInitialState()),\n };\n },\n\n readStream: <EventType extends Event>(\n streamName: string,\n options?: ReadStreamOptions,\n ): Promise<ReadStreamResult<EventType>> => {\n const events = streams.get(streamName);\n const currentStreamVersion = events ? BigInt(events.length) : undefined;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n );\n\n const from = Number(options && 'from' in options ? options.from : 0);\n const to = Number(\n options && 'to' in options\n ? options.to\n : options && 'maxCount' in options && options.maxCount\n ? options.from + options.maxCount\n : events?.length ?? 1,\n );\n\n const resultEvents =\n events && events.length > 0\n ? events.map((e) => e.event as EventType).slice(from, to)\n : [];\n\n const result: ReadStreamResult<EventType> =\n events && events.length > 0\n ? {\n currentStreamVersion: currentStreamVersion!,\n events: resultEvents,\n }\n : null;\n\n return Promise.resolve(result);\n },\n\n appendToStream: <EventType extends Event>(\n streamName: string,\n events: EventType[],\n options?: AppendToStreamOptions,\n ): Promise<AppendToStreamResult> => {\n const currentEvents = streams.get(streamName) ?? [];\n const currentStreamVersion =\n currentEvents.length > 0 ? BigInt(currentEvents.length) : undefined;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n );\n\n const eventEnvelopes: EventEnvelope[] = events.map((event, index) => {\n return {\n event,\n metadata: {\n eventId: randomUUID(),\n streamPosition: currentEvents.length + index + 1,\n logPosition: BigInt(getAllEventsCount() + index + 1),\n },\n };\n });\n\n const positionOfLastEventInTheStream = BigInt(\n eventEnvelopes.slice(-1)[0]!.metadata.streamPosition,\n );\n\n streams.set(streamName, [...currentEvents, ...eventEnvelopes]);\n\n const result: AppendToStreamResult = {\n nextExpectedStreamVersion: positionOfLastEventInTheStream,\n };\n\n return Promise.resolve(result);\n },\n };\n};\n","import { merge } from '@event-driven-io/emmett';\n\nexport interface ProductItem {\n productId: string;\n quantity: number;\n}\n\nexport type PricedProductItem = ProductItem & {\n unitPrice: number;\n};\n\nexport type ShoppingCartEvent =\n | {\n type: 'ShoppingCartOpened';\n data: {\n shoppingCartId: string;\n clientId: string;\n openedAt: Date;\n };\n }\n | {\n type: 'ProductItemAddedToShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n }\n | {\n type: 'ProductItemRemovedFromShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n }\n | {\n type: 'ShoppingCartConfirmed';\n data: {\n shoppingCartId: string;\n confirmedAt: Date;\n };\n }\n | {\n type: 'ShoppingCartCanceled';\n data: {\n shoppingCartId: string;\n canceledAt: Date;\n };\n };\n\nexport enum ShoppingCartStatus {\n Empty = 'Empty',\n Pending = 'Pending',\n Confirmed = 'Confirmed',\n Canceled = 'Canceled',\n}\n\nexport type Empty = { status: ShoppingCartStatus.Empty };\n\nexport type Pending = {\n status: ShoppingCartStatus.Pending;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n openedAt: Date;\n};\n\nexport type Confirmed = {\n status: ShoppingCartStatus.Confirmed;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n confirmedAt: Date;\n};\n\nexport type Canceled = {\n status: ShoppingCartStatus.Canceled;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n canceledAt: Date;\n};\n\nexport type ShoppingCart = Empty | Pending | Confirmed | Canceled;\n\nexport const emptyShoppingCart: Empty = { status: ShoppingCartStatus.Empty };\n\nexport const evolve = (\n state: ShoppingCart,\n { type, data: event }: ShoppingCartEvent,\n): ShoppingCart => {\n switch (type) {\n case 'ShoppingCartOpened':\n return {\n id: event.shoppingCartId,\n clientId: event.clientId,\n openedAt: event.openedAt,\n productItems: [],\n status: ShoppingCartStatus.Pending,\n };\n case 'ProductItemAddedToShoppingCart': {\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n const { productItems } = state;\n const { productItem } = event;\n\n return {\n ...state,\n productItems: merge(\n productItems,\n productItem,\n (p) =>\n p.productId === productItem.productId &&\n p.unitPrice === productItem.unitPrice,\n (p) => {\n return {\n ...p,\n quantity: p.quantity + productItem.quantity,\n };\n },\n () => productItem,\n ),\n };\n }\n case 'ProductItemRemovedFromShoppingCart': {\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n const { productItems } = state;\n const { productItem } = event;\n return {\n ...state,\n productItems: merge(\n productItems,\n productItem,\n (p) =>\n p.productId === productItem.productId &&\n p.unitPrice === productItem.unitPrice,\n (p) => {\n return {\n ...p,\n quantity: p.quantity - productItem.quantity,\n };\n },\n ),\n };\n }\n case 'ShoppingCartConfirmed':\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n return {\n ...state,\n status: ShoppingCartStatus.Confirmed,\n confirmedAt: event.confirmedAt,\n };\n case 'ShoppingCartCanceled':\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n return {\n ...state,\n status: ShoppingCartStatus.Canceled,\n canceledAt: event.canceledAt,\n };\n }\n};\n\nexport const getShoppingCart = (events: ShoppingCartEvent[]): ShoppingCart => {\n return events.reduce<ShoppingCart>(evolve, emptyShoppingCart);\n};\n\nexport const enum ShoppingCartErrors {\n CART_IS_ALREADY_CLOSED = 'CART_IS_ALREADY_CLOSED',\n PRODUCT_ITEM_NOT_FOUND = 'PRODUCT_ITEM_NOT_FOUND',\n CART_IS_EMPTY = 'CART_IS_EMPTY',\n UNKNOWN_EVENT_TYPE = 'UNKNOWN_EVENT_TYPE',\n UNKNOWN_COMMAND_TYPE = 'UNKNOWN_COMMAND_TYPE',\n}\n"]}
@@ -1,2 +0,0 @@
1
- import{a,b as e,g as C,h as d}from"./chunk-YY3STM5A.mjs";var S=(p=>(p.CART_ALREADY_EXISTS="CART_ALREADY_EXISTS",p.CART_IS_ALREADY_CLOSED="CART_IS_ALREADY_CLOSED",p.PRODUCT_ITEM_NOT_FOUND="PRODUCT_ITEM_NOT_FOUND",p.CART_IS_EMPTY="CART_IS_EMPTY",p.UNKNOWN_EVENT_TYPE="UNKNOWN_EVENT_TYPE",p.UNKNOWN_COMMAND_TYPE="UNKNOWN_COMMAND_TYPE",p))(S||{}),I=(o,{productId:t,quantity:r,unitPrice:n})=>{if((o.find(i=>i.productId===t&&i.unitPrice==n)?.quantity??0)<r)throw new e("PRODUCT_ITEM_NOT_FOUND")},g=({type:o,data:t},r)=>{switch(o){case"OpenShoppingCart":{if(r.status!=="Empty")throw new e("CART_ALREADY_EXISTS");return{type:"ShoppingCartOpened",data:{shoppingCartId:t.shoppingCartId,clientId:t.clientId,openedAt:t.now}}}case"AddProductItemToShoppingCart":{if(r.status!=="Pending")throw new e("CART_IS_ALREADY_CLOSED");return{type:"ProductItemAddedToShoppingCart",data:{shoppingCartId:t.shoppingCartId,productItem:t.productItem}}}case"RemoveProductItemFromShoppingCart":{if(r.status!=="Pending")throw new e("CART_IS_ALREADY_CLOSED");return I(r.productItems,t.productItem),{type:"ProductItemRemovedFromShoppingCart",data:{shoppingCartId:t.shoppingCartId,productItem:t.productItem}}}case"ConfirmShoppingCart":{if(r.status!=="Pending")throw new e("CART_IS_ALREADY_CLOSED");if(r.productItems.length===0)throw new e("CART_IS_EMPTY");return{type:"ShoppingCartConfirmed",data:{shoppingCartId:t.shoppingCartId,confirmedAt:t.now}}}case"CancelShoppingCart":{if(r.status!=="Pending")throw new e("CART_IS_ALREADY_CLOSED");return{type:"ShoppingCartCanceled",data:{shoppingCartId:t.shoppingCartId,canceledAt:t.now}}}default:{let n=t;throw new a("UNKNOWN_COMMAND_TYPE")}}},u={decide:g,evolve:d,getInitialState:()=>C};export{S as a,I as b,g as c,u as d};
2
- //# sourceMappingURL=chunk-QLVXJW5N.mjs.map
@@ -1,2 +0,0 @@
1
- var d=(t,e,o,s,a=()=>{})=>{let r=!1,i=t.map(n=>o(n)?(r=!0,s(n)):n).filter(n=>n!==void 0).map(n=>{if(!n)throw Error("That should not happen");return n});return!r&&a()!==void 0?[...t,e]:i};import G from"assert";var c=class E extends Error{errorCode;constructor(e){let o=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:g(e)?e:500,s=e&&typeof e=="object"&&"message"in e?e.message:l(e)?e:`Error with status code '${o}' ocurred during Emmett processing`;super(s),this.errorCode=o,Object.setPrototypeOf(this,E.prototype)}};var u=class y extends c{constructor(e){super({errorCode:400,message:e??"Validation Error ocurred during Emmett processing"}),Object.setPrototypeOf(this,y.prototype)}},x=class N extends c{constructor(e){super({errorCode:403,message:e??"Illegal State ocurred during Emmett processing"}),Object.setPrototypeOf(this,N.prototype)}};var P=(t=>(t.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",t.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",t.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",t))(P||{}),g=t=>typeof t=="number"&&t===t,l=t=>typeof t=="string",T=t=>{if(!l(t)||t.length===0)throw new u("NOT_A_NONEMPTY_STRING");return t},A=t=>{if(!g(t)||t<=0)throw new u("NOT_A_POSITIVE_NUMBER");return t};var S="STREAM_DOES_NOT_EXIST",I="NO_CONCURRENCY_CHECK";var h=(t,e,o=s=>s)=>async(s,a,r,i)=>{let n=o(a),p=await s.aggregateStream(n,{evolve:t,getInitialState:e,read:{expectedStreamVersion:i?.expectedStreamVersion??I}}),C=p?.state??e(),O=p?.currentStreamVersion,m=r(C),f=Array.isArray(m)?m:[m],_=i?.expectedStreamVersion??O??S;return{...await s.appendToStream(n,f,{...i,expectedStreamVersion:_}),newState:f.reduce(t,C)}};var b=({decide:t,evolve:e,getInitialState:o},s=a=>a)=>async(a,r,i,n)=>h(e,o,s)(a,r,p=>t(i,p),n);import{v4 as at}from"uuid";var D=(a=>(a.Empty="Empty",a.Pending="Pending",a.Confirmed="Confirmed",a.Canceled="Canceled",a))(D||{}),R={status:"Empty"},M=(t,{type:e,data:o})=>{switch(e){case"ShoppingCartOpened":return{id:o.shoppingCartId,clientId:o.clientId,openedAt:o.openedAt,productItems:[],status:"Pending"};case"ProductItemAddedToShoppingCart":{if(t.status!=="Pending")return t;let{productItems:s}=t,{productItem:a}=o;return{...t,productItems:d(s,a,r=>r.productId===a.productId&&r.unitPrice===a.unitPrice,r=>({...r,quantity:r.quantity+a.quantity}),()=>a)}}case"ProductItemRemovedFromShoppingCart":{if(t.status!=="Pending")return t;let{productItems:s}=t,{productItem:a}=o;return{...t,productItems:d(s,a,r=>r.productId===a.productId&&r.unitPrice===a.unitPrice,r=>({...r,quantity:r.quantity-a.quantity}))}}case"ShoppingCartConfirmed":return t.status!=="Pending"?t:{...t,status:"Confirmed",confirmedAt:o.confirmedAt};case"ShoppingCartCanceled":return t.status!=="Pending"?t:{...t,status:"Canceled",canceledAt:o.canceledAt}}},Ht=t=>t.reduce(M,R),V=(r=>(r.CART_IS_ALREADY_CLOSED="CART_IS_ALREADY_CLOSED",r.PRODUCT_ITEM_NOT_FOUND="PRODUCT_ITEM_NOT_FOUND",r.CART_IS_EMPTY="CART_IS_EMPTY",r.UNKNOWN_EVENT_TYPE="UNKNOWN_EVENT_TYPE",r.UNKNOWN_COMMAND_TYPE="UNKNOWN_COMMAND_TYPE",r))(V||{});export{c as a,x as b,T as c,A as d,b as e,D as f,R as g,M as h,Ht as i,V as j};
2
- //# sourceMappingURL=chunk-YY3STM5A.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../emmett/src/utils/merge.ts","../../emmett/src/testing/deciderSpecification.ts","../../emmett/src/errors/index.ts","../../emmett/src/validation/index.ts","../../emmett/src/eventStore/expectedVersion.ts","../../emmett/src/commandHandling/handleCommand.ts","../../emmett/src/commandHandling/handleCommandWithDecider.ts","../../emmett/src/eventStore/inMemoryEventStore.ts","../src/e2e/decider/shoppingCart.ts"],"sourcesContent":["export const merge = <T>(\n array: T[],\n item: T,\n where: (current: T) => boolean,\n onExisting: (current: T) => T,\n onNotFound: () => T | undefined = () => undefined,\n) => {\n let wasFound = false;\n\n const result = array\n // merge the existing item if matches condition\n .map((p: T) => {\n if (!where(p)) return p;\n\n wasFound = true;\n return onExisting(p);\n })\n // filter out item if undefined was returned\n // for cases of removal\n .filter((p) => p !== undefined)\n // make TypeScript happy\n .map((p) => {\n if (!p) throw Error('That should not happen');\n\n return p;\n });\n\n // if item was not found and onNotFound action is defined\n // try to generate new item\n if (!wasFound) {\n const result = onNotFound();\n\n if (result !== undefined) return [...array, item];\n }\n\n return result;\n};\n","import assert from 'assert';\n\nexport type DeciderSpecfication<Command, Event> = (\n givenEvents: Event | Event[],\n) => {\n when: (command: Command) => {\n then: (expectedEvents: Event | Event[]) => void;\n thenThrows: <Error>(assert: (error: Error) => boolean) => void;\n };\n};\n\nexport const DeciderSpecification = {\n for: <Command, Event, State>(decider: {\n decide: (command: Command, state: State) => Event | Event[];\n evolve: (state: State, event: Event) => State;\n initialState: () => State;\n }): DeciderSpecfication<Command, Event> => {\n {\n return (givenEvents: Event | Event[]) => {\n return {\n when: (command: Command) => {\n const handle = () => {\n const existingEvents = Array.isArray(givenEvents)\n ? givenEvents\n : [givenEvents];\n\n const currentState = existingEvents.reduce<State>(\n decider.evolve,\n decider.initialState(),\n );\n\n return decider.decide(command, currentState);\n };\n\n return {\n then: (expectedEvents: Event | Event[]): void => {\n const resultEvents = handle();\n\n const resultEventsArray = Array.isArray(resultEvents)\n ? resultEvents\n : [resultEvents];\n\n const expectedEventsArray = Array.isArray(expectedEvents)\n ? expectedEvents\n : [expectedEvents];\n\n assert.deepEqual(resultEventsArray, expectedEventsArray);\n },\n thenThrows: <Error>(check?: (error: Error) => boolean): void => {\n try {\n handle();\n assert.fail('Handler did not fail as expected');\n } catch (error) {\n if (check) assert.ok(check(error as Error));\n }\n },\n };\n },\n };\n };\n }\n },\n};\n","import { isNumber, isString } from '../validation';\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 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","import { ConcurrencyError } from '../errors';\nimport type { Flavour } from '../typing';\nimport type { DefaultStreamVersionType } from './eventStore';\n\nexport type ExpectedStreamVersion<VersionType = DefaultStreamVersionType> =\n | ExpectedStreamVersionWithValue<VersionType>\n | ExpectedStreamVersionGeneral;\n\nexport type ExpectedStreamVersionWithValue<\n VersionType = DefaultStreamVersionType,\n> = Flavour<VersionType, 'StreamVersion'>;\n\nexport type ExpectedStreamVersionGeneral = Flavour<\n 'STREAM_EXISTS' | 'STREAM_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK',\n 'StreamVersion'\n>;\n\nexport const STREAM_EXISTS = 'STREAM_EXISTS' as ExpectedStreamVersionGeneral;\nexport const STREAM_DOES_NOT_EXIST =\n 'STREAM_DOES_NOT_EXIST' as ExpectedStreamVersionGeneral;\nexport const NO_CONCURRENCY_CHECK =\n 'NO_CONCURRENCY_CHECK' as ExpectedStreamVersionGeneral;\n\nexport const matchesExpectedVersion = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion | undefined,\n expected: ExpectedStreamVersion<StreamVersion>,\n): boolean => {\n if (expected === NO_CONCURRENCY_CHECK) return true;\n\n if (expected == STREAM_DOES_NOT_EXIST) return current === undefined;\n\n if (expected == STREAM_EXISTS) return current !== undefined;\n\n return current === expected;\n};\n\nexport const assertExpectedVersionMatchesCurrent = <\n StreamVersion = DefaultStreamVersionType,\n>(\n current: StreamVersion | undefined,\n expected: ExpectedStreamVersion<StreamVersion> | undefined,\n): void => {\n expected ??= NO_CONCURRENCY_CHECK;\n\n if (!matchesExpectedVersion(current, expected))\n throw new ExpectedVersionConflictError(current, expected);\n};\n\nexport class ExpectedVersionConflictError<\n VersionType = DefaultStreamVersionType,\n> extends ConcurrencyError {\n constructor(\n current: VersionType | undefined,\n expected: ExpectedStreamVersion<VersionType>,\n ) {\n super(current?.toString(), expected?.toString());\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ExpectedVersionConflictError.prototype);\n }\n}\n","import {\n NO_CONCURRENCY_CHECK,\n STREAM_DOES_NOT_EXIST,\n type AppendToStreamResult,\n type DefaultStreamVersionType,\n type EventStore,\n type ExpectedStreamVersion,\n} from '../eventStore';\nimport type { Event } from '../typing';\n\n// #region command-handler\nexport type CommandHandlerResult<\n State,\n StreamVersion = DefaultStreamVersionType,\n> = AppendToStreamResult<StreamVersion> & { newState: State };\n\nexport const CommandHandler =\n <State, StreamEvent extends Event, StreamVersion = DefaultStreamVersionType>(\n evolve: (state: State, event: StreamEvent) => State,\n getInitialState: () => State,\n mapToStreamId: (id: string) => string = (id) => id,\n ) =>\n async <Store extends EventStore<StreamVersion>>(\n eventStore: Store,\n id: string,\n handle: (state: State) => StreamEvent | StreamEvent[],\n options?: Parameters<Store['appendToStream']>[2] & {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n },\n ): Promise<CommandHandlerResult<State, StreamVersion>> => {\n const streamName = mapToStreamId(id);\n\n // 1. Aggregate the stream\n const aggregationResult = await eventStore.aggregateStream<\n State,\n StreamEvent\n >(streamName, {\n evolve,\n getInitialState,\n read: {\n // expected stream version is passed to fail fast\n // if stream is in the wrong state\n expectedStreamVersion:\n options?.expectedStreamVersion ?? NO_CONCURRENCY_CHECK,\n },\n });\n\n // 2. Use the aggregate state or the initial one (when e.g. stream does not exist)\n const state = aggregationResult?.state ?? getInitialState();\n const currentStreamVersion = aggregationResult?.currentStreamVersion;\n\n // 3. Run business logic\n const result = handle(state);\n\n const newEvents = Array.isArray(result) ? result : [result];\n\n // Either use:\n // - provided expected stream version,\n // - current stream version got from stream aggregation,\n // - or expect stream not to exists otherwise.\n const expectedStreamVersion: ExpectedStreamVersion<StreamVersion> =\n options?.expectedStreamVersion ??\n currentStreamVersion ??\n STREAM_DOES_NOT_EXIST;\n\n // 4. Append result to the stream\n const appendResult = await eventStore.appendToStream(\n streamName,\n newEvents,\n {\n ...options,\n expectedStreamVersion,\n },\n );\n\n // 5. Return result with updated state\n return { ...appendResult, newState: newEvents.reduce(evolve, state) };\n };\n// #endregion command-handler\n","import type {\n DefaultStreamVersionType,\n EventStore,\n ExpectedStreamVersion,\n} from '../eventStore';\nimport type { Command, Event } from '../typing';\nimport type { Decider } from '../typing/decider';\nimport { CommandHandler } from './handleCommand';\n\n// #region command-handler\nexport const DeciderCommandHandler =\n <\n State,\n CommandType extends Command,\n StreamEvent extends Event,\n StreamVersion = DefaultStreamVersionType,\n >(\n {\n decide,\n evolve,\n getInitialState,\n }: Decider<State, CommandType, StreamEvent>,\n mapToStreamId: (id: string) => string = (id) => id,\n ) =>\n async (\n eventStore: EventStore<StreamVersion>,\n id: string,\n command: CommandType,\n options?: {\n expectedStreamVersion?: ExpectedStreamVersion<StreamVersion>;\n },\n ) =>\n CommandHandler<State, StreamEvent, StreamVersion>(\n evolve,\n getInitialState,\n mapToStreamId,\n )(eventStore, id, (state) => decide(command, state), options);\n// #endregion command-handler\n","import { v4 as randomUUID } from 'uuid';\nimport type { Event } from '../typing';\nimport {\n type AggregateStreamOptions,\n type AggregateStreamResult,\n type AppendToStreamOptions,\n type AppendToStreamResult,\n type EventStore,\n type ReadStreamOptions,\n type ReadStreamResult,\n} from './eventStore';\nimport { assertExpectedVersionMatchesCurrent } from './expectedVersion';\n\nexport type EventMetadata = Readonly<{\n eventId: string;\n streamPosition: number;\n logPosition: bigint;\n}>;\n\nexport type EventEnvelope<E extends Event = Event> = {\n event: E;\n metadata: EventMetadata;\n};\n\nexport type EventHandler<E extends Event = Event> = (\n eventEnvelope: EventEnvelope<E>,\n) => void;\n\nexport const getInMemoryEventStore = (): EventStore => {\n const streams = new Map<string, EventEnvelope[]>();\n\n const getAllEventsCount = () => {\n return Array.from<EventEnvelope[]>(streams.values())\n .map((s) => s.length)\n .reduce((p, c) => p + c, 0);\n };\n\n return {\n async aggregateStream<State, EventType extends Event>(\n streamName: string,\n options: AggregateStreamOptions<State, EventType>,\n ): Promise<AggregateStreamResult<State> | null> {\n const { evolve, getInitialState, read } = options;\n\n const result = await this.readStream<EventType>(streamName, read);\n\n if (!result) return null;\n\n const events = result?.events ?? [];\n\n return {\n currentStreamVersion: BigInt(events.length),\n state: events.reduce(evolve, getInitialState()),\n };\n },\n\n readStream: <EventType extends Event>(\n streamName: string,\n options?: ReadStreamOptions,\n ): Promise<ReadStreamResult<EventType>> => {\n const events = streams.get(streamName);\n const currentStreamVersion = events ? BigInt(events.length) : undefined;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n );\n\n const from = Number(options && 'from' in options ? options.from : 0);\n const to = Number(\n options && 'to' in options\n ? options.to\n : options && 'maxCount' in options && options.maxCount\n ? options.from + options.maxCount\n : events?.length ?? 1,\n );\n\n const resultEvents =\n events && events.length > 0\n ? events.map((e) => e.event as EventType).slice(from, to)\n : [];\n\n const result: ReadStreamResult<EventType> =\n events && events.length > 0\n ? {\n currentStreamVersion: currentStreamVersion!,\n events: resultEvents,\n }\n : null;\n\n return Promise.resolve(result);\n },\n\n appendToStream: <EventType extends Event>(\n streamName: string,\n events: EventType[],\n options?: AppendToStreamOptions,\n ): Promise<AppendToStreamResult> => {\n const currentEvents = streams.get(streamName) ?? [];\n const currentStreamVersion =\n currentEvents.length > 0 ? BigInt(currentEvents.length) : undefined;\n\n assertExpectedVersionMatchesCurrent(\n currentStreamVersion,\n options?.expectedStreamVersion,\n );\n\n const eventEnvelopes: EventEnvelope[] = events.map((event, index) => {\n return {\n event,\n metadata: {\n eventId: randomUUID(),\n streamPosition: currentEvents.length + index + 1,\n logPosition: BigInt(getAllEventsCount() + index + 1),\n },\n };\n });\n\n const positionOfLastEventInTheStream = BigInt(\n eventEnvelopes.slice(-1)[0]!.metadata.streamPosition,\n );\n\n streams.set(streamName, [...currentEvents, ...eventEnvelopes]);\n\n const result: AppendToStreamResult = {\n nextExpectedStreamVersion: positionOfLastEventInTheStream,\n };\n\n return Promise.resolve(result);\n },\n };\n};\n","import { merge } from '@event-driven-io/emmett';\n\nexport interface ProductItem {\n productId: string;\n quantity: number;\n}\n\nexport type PricedProductItem = ProductItem & {\n unitPrice: number;\n};\n\nexport type ShoppingCartEvent =\n | {\n type: 'ShoppingCartOpened';\n data: {\n shoppingCartId: string;\n clientId: string;\n openedAt: Date;\n };\n }\n | {\n type: 'ProductItemAddedToShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n }\n | {\n type: 'ProductItemRemovedFromShoppingCart';\n data: {\n shoppingCartId: string;\n productItem: PricedProductItem;\n };\n }\n | {\n type: 'ShoppingCartConfirmed';\n data: {\n shoppingCartId: string;\n confirmedAt: Date;\n };\n }\n | {\n type: 'ShoppingCartCanceled';\n data: {\n shoppingCartId: string;\n canceledAt: Date;\n };\n };\n\nexport enum ShoppingCartStatus {\n Empty = 'Empty',\n Pending = 'Pending',\n Confirmed = 'Confirmed',\n Canceled = 'Canceled',\n}\n\nexport type Empty = { status: ShoppingCartStatus.Empty };\n\nexport type Pending = {\n status: ShoppingCartStatus.Pending;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n openedAt: Date;\n};\n\nexport type Confirmed = {\n status: ShoppingCartStatus.Confirmed;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n confirmedAt: Date;\n};\n\nexport type Canceled = {\n status: ShoppingCartStatus.Canceled;\n id: string;\n clientId: string;\n productItems: PricedProductItem[];\n canceledAt: Date;\n};\n\nexport type ShoppingCart = Empty | Pending | Confirmed | Canceled;\n\nexport const emptyShoppingCart: Empty = { status: ShoppingCartStatus.Empty };\n\nexport const evolve = (\n state: ShoppingCart,\n { type, data: event }: ShoppingCartEvent,\n): ShoppingCart => {\n switch (type) {\n case 'ShoppingCartOpened':\n return {\n id: event.shoppingCartId,\n clientId: event.clientId,\n openedAt: event.openedAt,\n productItems: [],\n status: ShoppingCartStatus.Pending,\n };\n case 'ProductItemAddedToShoppingCart': {\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n const { productItems } = state;\n const { productItem } = event;\n\n return {\n ...state,\n productItems: merge(\n productItems,\n productItem,\n (p) =>\n p.productId === productItem.productId &&\n p.unitPrice === productItem.unitPrice,\n (p) => {\n return {\n ...p,\n quantity: p.quantity + productItem.quantity,\n };\n },\n () => productItem,\n ),\n };\n }\n case 'ProductItemRemovedFromShoppingCart': {\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n const { productItems } = state;\n const { productItem } = event;\n return {\n ...state,\n productItems: merge(\n productItems,\n productItem,\n (p) =>\n p.productId === productItem.productId &&\n p.unitPrice === productItem.unitPrice,\n (p) => {\n return {\n ...p,\n quantity: p.quantity - productItem.quantity,\n };\n },\n ),\n };\n }\n case 'ShoppingCartConfirmed':\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n return {\n ...state,\n status: ShoppingCartStatus.Confirmed,\n confirmedAt: event.confirmedAt,\n };\n case 'ShoppingCartCanceled':\n if (state.status !== ShoppingCartStatus.Pending) return state;\n\n return {\n ...state,\n status: ShoppingCartStatus.Canceled,\n canceledAt: event.canceledAt,\n };\n }\n};\n\nexport const getShoppingCart = (events: ShoppingCartEvent[]): ShoppingCart => {\n return events.reduce<ShoppingCart>(evolve, emptyShoppingCart);\n};\n\nexport const enum ShoppingCartErrors {\n CART_IS_ALREADY_CLOSED = 'CART_IS_ALREADY_CLOSED',\n PRODUCT_ITEM_NOT_FOUND = 'PRODUCT_ITEM_NOT_FOUND',\n CART_IS_EMPTY = 'CART_IS_EMPTY',\n UNKNOWN_EVENT_TYPE = 'UNKNOWN_EVENT_TYPE',\n UNKNOWN_COMMAND_TYPE = 'UNKNOWN_COMMAND_TYPE',\n}\n"],"mappings":"AAAO,IAAMA,EAAQ,CACnBC,EACAC,EACAC,EACAC,EACAC,EAAkC,IAAG,CAAA,IAClC,CACH,IAAIC,EAAW,GAETC,EAASN,EAEZ,IAAKO,GAC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,IACH,CACjB,OAAQD,EAAM,CACZ,IAAK,qBACH,MAAO,CACL,GAAIC,EAAM,eACV,SAAUA,EAAM,SAChB,SAAUA,EAAM,SAChB,aAAc,CAAC,EACf,OAAQ,SACV,EACF,IAAK,iCAAkC,CACrC,GAAIF,EAAM,SAAW,UAA4B,OAAOA,EAExD,GAAM,CAAE,aAAAG,CAAa,EAAIH,EACnB,CAAE,YAAAI,CAAY,EAAIF,EAExB,MAAO,CACL,GAAGF,EACH,aAAcK,EACZF,EACAC,EACCE,GACCA,EAAE,YAAcF,EAAY,WAC5BE,EAAE,YAAcF,EAAY,UAC7BE,IACQ,CACL,GAAGA,EACH,SAAUA,EAAE,SAAWF,EAAY,QACrC,GAEF,IAAMA,CACR,CACF,CACF,CACA,IAAK,qCAAsC,CACzC,GAAIJ,EAAM,SAAW,UAA4B,OAAOA,EAExD,GAAM,CAAE,aAAAG,CAAa,EAAIH,EACnB,CAAE,YAAAI,CAAY,EAAIF,EACxB,MAAO,CACL,GAAGF,EACH,aAAcK,EACZF,EACAC,EACCE,GACCA,EAAE,YAAcF,EAAY,WAC5BE,EAAE,YAAcF,EAAY,UAC7BE,IACQ,CACL,GAAGA,EACH,SAAUA,EAAE,SAAWF,EAAY,QACrC,EAEJ,CACF,CACF,CACA,IAAK,wBACH,OAAIJ,EAAM,SAAW,UAAmCA,EAEjD,CACL,GAAGA,EACH,OAAQ,YACR,YAAaE,EAAM,WACrB,EACF,IAAK,uBACH,OAAIF,EAAM,SAAW,UAAmCA,EAEjD,CACL,GAAGA,EACH,OAAQ,WACR,WAAYE,EAAM,UACpB,CACJ,CACF,EAEaK,GAAmBC,GACvBA,EAAO,OAAqBT,EAAQD,CAAiB,EAG5CW,OAChBA,EAAA,uBAAyB,yBACzBA,EAAA,uBAAyB,yBACzBA,EAAA,cAAgB,gBAChBA,EAAA,mBAAqB,qBACrBA,EAAA,qBAAuB,uBALPA,OAAA","names":["merge","array","item","where","onExisting","onNotFound","wasFound","result","p","assert","EmmettError","_EmmettError","options","errorCode","isNumber","message","isString","ValidationError","_ValidationError","EmmettError","message","IllegalStateError","_IllegalStateError","ValidationErrors","isNumber","val","isString","assertNotEmptyString","value","ValidationError","assertPositiveNumber","STREAM_DOES_NOT_EXIST","NO_CONCURRENCY_CHECK","CommandHandler","evolve","getInitialState","mapToStreamId","id","eventStore","handle","options","streamName","aggregationResult","NO_CONCURRENCY_CHECK","state","currentStreamVersion","result","newEvents","expectedStreamVersion","STREAM_DOES_NOT_EXIST","DeciderCommandHandler","decide","evolve","getInitialState","mapToStreamId","id","eventStore","command","options","CommandHandler","state","randomUUID","ShoppingCartStatus","emptyShoppingCart","evolve","state","type","event","productItems","productItem","i","p","getShoppingCart","events","ShoppingCartErrors"]}