@shirudo/ddd-kit 0.15.0 → 1.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -84
- package/dist/index.d.ts +342 -313
- package/dist/index.js +881 -1
- package/dist/index.js.map +1 -1
- package/dist/result.js +297 -1
- package/dist/result.js.map +1 -1
- package/dist/utils-array.js +241 -1
- package/dist/utils-array.js.map +1 -1
- package/dist/utils.js +1 -0
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/aggregate/aggregate.ts","../src/utils/array/is-built-in.ts","../src/utils/array/deep-equal.ts","../src/entity/entity.ts","../src/aggregate/aggregate-root.ts","../src/core/result/result.ts","../src/aggregate/aggregate-event-sourced.ts","../src/app/command-bus.ts","../src/app/handler.ts","../src/app/query-bus.ts","../src/core/guard.ts","../src/events/event-bus.ts","../src/utils/array/deep-omit.ts","../src/utils/array/deep-equal-except.ts","../src/value-object/value-object.ts"],"names":["aggregate","state","version","__name","withEvent","agg","evt","bump","createDomainEvent","type","payload","options","createDomainEventWithMetadata","metadata","copyMetadata","sourceEvent","additionalMetadata","mergeMetadata","metadataObjects","sameAggregate","a","b","isBuiltInObject","obj","tag","objConstructor","constructorName","proto","objProto","objToString","objHasOwn","deepEqual","deepEqualInner","visited","typeA","typeB","objA","objB","cached","tagA","tagB","viewA","viewB","len","i","arrA","arrB","mapA","mapB","key","valA","valB","setA","setB","value","timeA","timeB","regA","regB","stringKeysA","stringKeysB","symbolKeysA","symbolKeysB","Entity","id","initialState","_state","newState","sameEntity","findEntityById","entities","entity","hasEntityId","removeEntityById","updateEntityById","updater","replaceEntityById","replacement","entityIds","AggregateRoot","config","event","bumpVersion","snapshot","ok","err","error","AggregateEventSourced","_event","isNew","validation","handler","history","result","events","eventsAfterSnapshot","CommandBus","commandType","command","withCommit","deps","fn","QueryBus","queryType","query","guard","cond","EventBusImpl","eventType","handlersForType","deepOmit","omitInternal","path","arr","clone","stringKeys","symbolKeys","keys","shouldIgnoreKey","deepEqualExcept","prunedA","prunedB","deepFreeze","propNames","name","vo","voEquals","voEqualsExcept","voWithValidation","validate","errorMessage","voWithValidationUnsafe","ValueObject","props","other","Constructor"],"mappings":"AA2FO,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,KAAA,CAAA,CAAA,CAAA,YAAA,CAAA,IAAA,CAAA,CAAA,CAAA,SAASA,CAAAA,CACfC,CAAAA,CACAC,CAAAA,CAAmB,CAAA,CACK,CACxB,OAAO,CAAE,KAAA,CAAAD,CAAAA,CAAO,OAAA,CAAAC,CAAAA,CAAS,aAAA,CAAe,EAAG,CAC5C,CALgBC,CAAAA,CAAAH,CAAAA,CAAA,WAAA,CAAA,CAOT,SAASI,EAAAA,CACfC,CAAAA,CACAC,CAAAA,CACkB,CAClB,OAAO,CAAE,GAAGD,CAAAA,CAAK,cAAe,CAAC,GAAGA,CAAAA,CAAI,aAAA,CAAeC,CAAG,CAAE,CAC7D,CALgBH,CAAAA,CAAAC,EAAAA,CAAA,WAAA,CAAA,CAOT,SAASG,EAAAA,CACfF,CAAAA,CACkB,CAClB,OAAO,CAAE,GAAGA,CAAAA,CAAK,OAAA,CAAUA,CAAAA,CAAI,OAAA,CAAU,CAAc,CACxD,CAJgBF,CAAAA,CAAAI,EAAAA,CAAA,MAAA,CAAA,CAoBT,SAASC,CAAAA,CACfC,CAAAA,CACAC,CAAAA,CACAC,EAKoB,CACpB,OAAO,CACN,IAAA,CAAAF,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,UAAA,CAAYC,CAAAA,EAAS,UAAA,EAAc,IAAI,IAAA,CACvC,OAAA,CAASA,CAAAA,EAAS,OAAA,EAAW,CAAA,CAC7B,QAAA,CAAUA,CAAAA,EAAS,QACpB,CAC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AASG,EAAAA,CACZ,EACAF,CAAAA,CACAC,CAAAA,CACK,CACL,GAAI,CAACD,CAAAA,CAAS,CAAC,CAAA,CACX,MAAM,IAAI,KAAA,CACNC,CAAAA,EAAgB,CAAA,oCAAA,EAAuC,IAAA,CAAK,SAAA,CAAU,CAAC,CAAC,CAAA,CAC5E,CAAA,CAEJ,OAAOL,CAAAA,CAAG,CAAC,CACf,CAXgB1H,CAAAA,CAAAgI,EAAAA,CAAA,wBAAA,CAAA,CA4DT,IAAeC,CAAAA,CAAf,KAAwE,CAzQ/E,OAyQ+EjI,CAAAA,CAAA,IAAA,CAAA,aAAA,EAAA,CAC3D,KAAA,CAoBhB,WAAA,CAAYkI,CAAAA,CAAU,CAClB,IAAA,CAAK,QAAA,CAASA,CAAK,CAAA,CACnB,IAAA,CAAK,KAAA,CAAQX,CAAAA,CAAW,CAAE,GAAGW,CAAM,CAAC,EACxC,CASU,QAAA,CAASA,CAAAA,CAAgB,CAEnC,CASO,MAAA,CAAOC,CAAAA,CAAgC,CAK1C,OAJIA,CAAAA,EAAU,IAAA,EAIV,IAAA,CAAK,WAAA,GAAgBA,CAAAA,CAAM,YACpB,KAAA,CAGJvG,CAAAA,CAAU,IAAA,CAAK,KAAA,CAAOuG,CAAAA,CAAM,KAAK,CAC5C,CAQO,KAAA,CAAMD,CAAAA,CAA0B,CACnC,IAAME,CAAAA,CAAc,IAAA,CAAK,WAAA,CACzB,OAAO,IAAIA,CAAAA,CAAY,CAAE,GAAG,IAAA,CAAK,KAAA,CAAO,GAAIF,CAAAA,EAAS,EAAI,CAAC,CAC9D,CAOO,MAAA,EAAsB,CACzB,OAAO,IAAA,CAAK,KAChB,CAGJ","file":"index.js","sourcesContent":["import type { Id } from \"../core/id\";\n\nexport type Version = number & { readonly __v: true };\n\n/**\n * Metadata associated with a domain event for traceability and correlation.\n * Used in event-driven architectures to track event flow across services.\n */\nexport interface EventMetadata {\n\t/**\n\t * Correlation ID for tracing events across multiple services/components.\n\t * Typically used to group related events in a distributed system.\n\t */\n\tcorrelationId?: string;\n\n\t/**\n\t * Causation ID referencing the event or command that caused this event.\n\t * Used to build event chains and understand causality.\n\t */\n\tcausationId?: string;\n\n\t/**\n\t * User ID of the person or system that triggered the event.\n\t */\n\tuserId?: string;\n\n\t/**\n\t * Source service or component that produced the event.\n\t */\n\tsource?: string;\n\n\t/**\n\t * Additional custom metadata fields.\n\t * Allows extensibility for domain-specific metadata.\n\t */\n\t[key: string]: unknown;\n}\n\n/**\n * Domain Event represents something meaningful that happened in the domain.\n * Events are immutable and carry information about what occurred.\n *\n * @template T - The event type name (e.g., \"OrderCreated\")\n * @template P - The event payload type\n */\nexport interface DomainEvent<T extends string, P> {\n\t/**\n\t * The type of the event, used for routing and handling.\n\t */\n\ttype: T;\n\n\t/**\n\t * The event payload containing the domain data.\n\t */\n\tpayload: P;\n\n\t/**\n\t * Timestamp when the event occurred.\n\t */\n\toccurredAt: Date;\n\n\t/**\n\t * Event schema version for handling schema evolution.\n\t * Defaults to 1 if not specified. Higher versions indicate schema changes.\n\t */\n\tversion?: number;\n\n\t/**\n\t * Optional metadata for traceability, correlation, and auditing.\n\t * Includes correlationId, causationId, userId, source, and custom fields.\n\t */\n\tmetadata?: EventMetadata;\n}\n\n// Re-export interfaces from their respective files for convenience\nexport type { IAggregateRoot } from \"./aggregate-root\";\nexport type { IAggregateEventSourced } from \"./aggregate-event-sourced\";\n\n/**\n * Structural interface representing an aggregate with state and events.\n * Used for type constraints in repositories and other infrastructure code.\n *\n * @template State - The type of the aggregate state\n * @template Evt - The union type of all domain events\n */\nexport interface Aggregate<State, Evt extends DomainEvent<string, unknown>> {\n\tstate: Readonly<State>;\n\tversion: Version;\n\tpendingEvents: ReadonlyArray<Evt>;\n}\n\nexport function aggregate<State, Evt extends DomainEvent<string, unknown>>(\n\tstate: State,\n\tversion: Version = 0 as Version,\n): Aggregate<State, Evt> {\n\treturn { state, version, pendingEvents: [] };\n}\n\nexport function withEvent<S, E extends DomainEvent<string, unknown>>(\n\tagg: Aggregate<S, E>,\n\tevt: E,\n): Aggregate<S, E> {\n\treturn { ...agg, pendingEvents: [...agg.pendingEvents, evt] };\n}\n\nexport function bump<S, E extends DomainEvent<string, unknown>>(\n\tagg: Aggregate<S, E>,\n): Aggregate<S, E> {\n\treturn { ...agg, version: (agg.version + 1) as Version };\n}\n\n/**\n * Creates a domain event with default values.\n * Sets occurredAt to current date and version to 1 if not provided.\n *\n * @param type - The event type\n * @param payload - The event payload\n * @param options - Optional event configuration\n * @returns A domain event\n *\n * @example\n * ```typescript\n * const event = createDomainEvent(\"OrderCreated\", { orderId: \"123\" });\n * ```\n */\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\toptions?: {\n\t\toccurredAt?: Date;\n\t\tversion?: number;\n\t\tmetadata?: EventMetadata;\n\t},\n): DomainEvent<T, P> {\n\treturn {\n\t\ttype,\n\t\tpayload,\n\t\toccurredAt: options?.occurredAt ?? new Date(),\n\t\tversion: options?.version ?? 1,\n\t\tmetadata: options?.metadata,\n\t};\n}\n\n/**\n * Creates a domain event with metadata for traceability.\n * Convenience function for creating events with correlation and causation IDs.\n *\n * @param type - The event type\n * @param payload - The event payload\n * @param metadata - Event metadata for traceability\n * @param options - Optional event configuration\n * @returns A domain event with metadata\n *\n * @example\n * ```typescript\n * const event = createDomainEventWithMetadata(\n * \"OrderCreated\",\n * { orderId: \"123\" },\n * {\n * correlationId: \"corr-123\",\n * causationId: \"cmd-456\",\n * userId: \"user-789\"\n * }\n * );\n * ```\n */\nexport function createDomainEventWithMetadata<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\tmetadata: EventMetadata,\n\toptions?: {\n\t\toccurredAt?: Date;\n\t\tversion?: number;\n\t},\n): DomainEvent<T, P> {\n\treturn createDomainEvent(type, payload, {\n\t\t...options,\n\t\tmetadata,\n\t});\n}\n\n/**\n * Copies metadata from a source event to a new event.\n * Useful for maintaining correlation chains in event-driven architectures.\n *\n * @param sourceEvent - The source event to copy metadata from\n * @param additionalMetadata - Additional metadata to merge in\n * @returns Event metadata with copied and merged values\n *\n * @example\n * ```typescript\n * const newEvent = createDomainEvent(\n * \"OrderShipped\",\n * { orderId: \"123\" },\n * {\n * metadata: copyMetadata(previousEvent, { causationId: previousEvent.type })\n * }\n * );\n * ```\n */\nexport function copyMetadata(\n\tsourceEvent: DomainEvent<string, unknown>,\n\tadditionalMetadata?: Partial<EventMetadata>,\n): EventMetadata {\n\treturn {\n\t\t...(sourceEvent.metadata ?? {}),\n\t\t...(additionalMetadata ?? {}),\n\t};\n}\n\n/**\n * Merges multiple metadata objects into one.\n * Later metadata objects override earlier ones for the same keys.\n *\n * @param metadataObjects - Array of metadata objects to merge\n * @returns Merged event metadata\n *\n * @example\n * ```typescript\n * const metadata = mergeMetadata(\n * { correlationId: \"corr-123\" },\n * { userId: \"user-456\" },\n * { source: \"order-service\" }\n * );\n * ```\n */\nexport function mergeMetadata(\n\t...metadataObjects: Array<EventMetadata | undefined>\n): EventMetadata {\n\treturn Object.assign({}, ...metadataObjects.filter(Boolean));\n}\n\n/**\n * Snapshot of an aggregate state at a specific point in time.\n * Used for optimizing event replay by starting from a snapshot\n * instead of replaying all events from the beginning.\n *\n * @template TState - The type of the aggregate state\n */\nexport interface AggregateSnapshot<TState> {\n\t/**\n\t * The state of the aggregate at the time of the snapshot.\n\t */\n\tstate: TState;\n\n\t/**\n\t * The version of the aggregate when the snapshot was taken.\n\t */\n\tversion: Version;\n\n\t/**\n\t * Timestamp when the snapshot was created.\n\t */\n\tsnapshotAt: Date;\n}\n\n/**\n * Checks if two aggregates are the same (same ID and version).\n * Useful for optimistic concurrency control checks.\n *\n * @param a - First aggregate\n * @param b - Second aggregate\n * @returns true if both aggregates have the same ID and version\n *\n * @example\n * ```typescript\n * const aggregate1 = await repository.getById(id);\n * // ... some operations ...\n * const aggregate2 = await repository.getById(id);\n *\n * if (!sameAggregate(aggregate1, aggregate2)) {\n * throw new Error(\"Aggregate was modified by another process\");\n * }\n * ```\n */\nexport function sameAggregate<TId extends Id<string>>(\n\ta: { id: TId; version: Version },\n\tb: { id: TId; version: Version },\n): boolean {\n\treturn a.id === b.id && a.version === b.version;\n}\n","/**\n * Checks if an object is a built-in JavaScript type that should be treated atomically.\n * This function automatically detects built-ins without requiring manual maintenance.\n *\n * Detection strategy:\n * 1. TypedArrays: Check if tag ends with \"Array]\" (covers all current and future TypedArrays)\n * 2. ArrayBuffer views: Use ArrayBuffer.isView() (covers DataView and all TypedArrays)\n * 3. Built-in constructors: Check if constructor exists in global scope and matches known patterns\n * 4. Tag-based: Fallback to tag matching for known built-ins\n *\n * @param obj - The object to check\n * @param tag - The result of `Object.prototype.toString.call(obj)`\n * @returns `true` if the object is a built-in type, `false` otherwise\n */\nexport function isBuiltInObject(obj: object, tag: string): boolean {\n\t// 1. TypedArrays: all end with \"Array]\" - future-proof for new TypedArrays\n\tif (tag.endsWith(\"Array]\")) {\n\t\treturn true;\n\t}\n\n\t// 2. ArrayBuffer views: covers DataView and all TypedArrays (future-proof)\n\tif (ArrayBuffer.isView(obj)) {\n\t\treturn true;\n\t}\n\n\t// 3. ArrayBuffer and SharedArrayBuffer\n\tif (tag === \"[object ArrayBuffer]\" || tag === \"[object SharedArrayBuffer]\") {\n\t\treturn true;\n\t}\n\n\t// 4. Check if constructor exists in global scope (future-proof for new globals)\n\tconst objConstructor = (obj as { constructor?: unknown }).constructor;\n\tif (objConstructor && typeof objConstructor === \"function\") {\n\t\tconst constructorName = objConstructor.name;\n\t\t// Check if it's a known global constructor\n\t\t// This covers: Date, RegExp, Map, Set, WeakMap, WeakSet, Promise, Error, etc.\n\t\tif (\n\t\t\tconstructorName &&\n\t\t\ttypeof globalThis !== \"undefined\" &&\n\t\t\tconstructorName in globalThis &&\n\t\t\t(globalThis as Record<string, unknown>)[constructorName] === objConstructor\n\t\t) {\n\t\t\t// Additional check: ensure it's not a user-defined class with same name\n\t\t\t// Built-ins typically have non-enumerable properties and specific prototypes\n\t\t\tconst proto = Object.getPrototypeOf(obj);\n\t\t\tif (proto !== Object.prototype && proto !== null) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// 5. Tag-based fallback for known built-ins (covers edge cases)\n\tconst knownBuiltInTags = new Set([\n\t\t\"[object Date]\",\n\t\t\"[object RegExp]\",\n\t\t\"[object Map]\",\n\t\t\"[object Set]\",\n\t\t\"[object WeakMap]\",\n\t\t\"[object WeakSet]\",\n\t\t\"[object Promise]\",\n\t\t\"[object Error]\",\n\t\t\"[object Boolean]\",\n\t\t\"[object Number]\",\n\t\t\"[object String]\",\n\t]);\n\n\treturn knownBuiltInTags.has(tag);\n}\n\n","import { isBuiltInObject } from \"./is-built-in\";\n\nconst objProto = Object.prototype;\nconst objToString = objProto.toString;\nconst objHasOwn = objProto.hasOwnProperty;\n\n/**\n * Performs a deep equality check between two values.\n *\n * This function compares values recursively, handling:\n * - Primitives (with special handling for NaN)\n * - Arrays (nested arrays supported)\n * - Objects (plain objects and class instances)\n * - TypedArrays (Uint8Array, Int32Array, etc.)\n * - DataView\n * - Maps and Sets\n * - Dates and RegExp\n * - Wrapper objects (Boolean, Number, String)\n * - Circular references (detected and handled)\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @returns `true` if the values are deeply equal, `false` otherwise\n *\n * @example\n * ```ts\n * deepEqual([1, 2, 3], [1, 2, 3]); // true\n * deepEqual({ a: 1, b: [2, 3] }, { a: 1, b: [2, 3] }); // true\n * deepEqual(NaN, NaN); // true\n * deepEqual([1, 2], [1, 2, 3]); // false\n * ```\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n\treturn deepEqualInner(a, b, new WeakMap<object, object>());\n}\n\n/**\n * Internal recursive function for deep equality comparison.\n * Tracks visited objects to detect and handle circular references.\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param visited - WeakMap to track visited object pairs and detect cycles\n * @returns `true` if the values are deeply equal, `false` otherwise\n * @internal\n */\nfunction deepEqualInner(\n\ta: unknown,\n\tb: unknown,\n\tvisited: WeakMap<object, object>\n): boolean {\n\t// 1. Fast path: reference equality\n\tif (a === b) return true;\n\n\tconst typeA = typeof a;\n\tconst typeB = typeof b;\n\n\t// 2. If one is not an object → primitive / function\n\tif (typeA !== \"object\" || a === null || typeB !== \"object\" || b === null) {\n\t\t// Special case: NaN should be equal\n\t\tif (typeA === \"number\" && typeB === \"number\") {\n\t\t\treturn Number.isNaN(a as number) && Number.isNaN(b as number);\n\t\t}\n\t\t// Everything else is directly unequal with !== (including functions)\n\t\treturn false;\n\t}\n\n\t// From here on: both are non-null objects\n\n\tconst objA = a as object;\n\tconst objB = b as object;\n\n\t// 3. Cycles: already seen pair?\n\tconst cached = visited.get(objA);\n\tif (cached !== undefined) {\n\t\t// If we already paired this A with a different B → unequal\n\t\treturn cached === objB;\n\t}\n\tvisited.set(objA, objB);\n\n\t// 4. Handle Typed Arrays / DataView first\n\tif (ArrayBuffer.isView(objA) || ArrayBuffer.isView(objB)) {\n\t\tif (!ArrayBuffer.isView(objA) || !ArrayBuffer.isView(objB)) return false;\n\n\t\tconst tagA = objToString.call(objA);\n\t\tconst tagB = objToString.call(objB);\n\t\tif (tagA !== tagB) return false;\n\n\t\t// DataView: compare byte by byte\n\t\tif (tagA === \"[object DataView]\") {\n\t\t\tconst viewA = objA as DataView;\n\t\t\tconst viewB = objB as DataView;\n\t\t\tif (viewA.byteLength !== viewB.byteLength) return false;\n\n\t\t\tconst len = viewA.byteLength;\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (viewA.getUint8(i) !== viewB.getUint8(i)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t// Typed Arrays: element by element\n\t\tconst arrA = objA as unknown as ArrayLike<unknown>;\n\t\tconst arrB = objB as unknown as ArrayLike<unknown>;\n\n\t\tconst len = arrA.length;\n\t\tif (len !== arrB.length) return false;\n\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tif ((arrA as any)[i] !== (arrB as any)[i]) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// 5. Tag-based type detection (robust across realms)\n\tconst tagA = objToString.call(objA);\n\tconst tagB = objToString.call(objB);\n\tif (tagA !== tagB) return false;\n\n\tswitch (tagA) {\n\t\tcase \"[object Array]\": {\n\t\t\tconst arrA = objA as unknown[];\n\t\t\tconst arrB = objB as unknown[];\n\t\t\tconst len = arrA.length;\n\t\t\tif (len !== arrB.length) return false;\n\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (!deepEqualInner(arrA[i], arrB[i], visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Map]\": {\n\t\t\tconst mapA = objA as Map<unknown, unknown>;\n\t\t\tconst mapB = objB as Map<unknown, unknown>;\n\n\t\t\tif (mapA.size !== mapB.size) return false;\n\n\t\t\tfor (const [key, valA] of mapA) {\n\t\t\t\t// Map keys according to JS semantics: reference / SameValueZero\n\t\t\t\tif (!mapB.has(key)) return false;\n\t\t\t\tconst valB = mapB.get(key);\n\t\t\t\tif (!deepEqualInner(valA, valB, visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Set]\": {\n\t\t\tconst setA = objA as Set<unknown>;\n\t\t\tconst setB = objB as Set<unknown>;\n\n\t\t\tif (setA.size !== setB.size) return false;\n\n\t\t\t// Set elements: same reference (JS semantics)\n\t\t\tfor (const value of setA) {\n\t\t\t\tif (!setB.has(value)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Date]\": {\n\t\t\tconst timeA = (objA as Date).getTime();\n\t\t\tconst timeB = (objB as Date).getTime();\n\t\t\treturn timeA === timeB;\n\t\t}\n\n\t\tcase \"[object RegExp]\": {\n\t\t\tconst regA = objA as RegExp;\n\t\t\tconst regB = objB as RegExp;\n\t\t\treturn regA.source === regB.source && regA.flags === regB.flags;\n\t\t}\n\n\t\tcase \"[object Boolean]\":\n\t\tcase \"[object Number]\":\n\t\tcase \"[object String]\": {\n\t\t\t// Wrapper objects (new Boolean/Number/String)\n\t\t\treturn (objA as any).valueOf() === (objB as any).valueOf();\n\t\t}\n\n\t\tdefault: {\n\t\t\t// 6. Check if this is an unhandled built-in type (future-proof)\n\t\t\t// If both are built-ins but not handled above, they should be compared by reference\n\t\t\t// (since we don't know their internal structure)\n\t\t\tif (isBuiltInObject(objA, tagA) && isBuiltInObject(objB, tagB)) {\n\t\t\t\t// Unhandled built-in types: compare by reference as fallback\n\t\t\t\t// This ensures new built-ins don't fall through to plain object comparison\n\t\t\t\treturn objA === objB;\n\t\t\t}\n\n\t\t\t// 7. Fallback: plain / custom objects → compare own enumerable keys + values\n\t\t\tconst stringKeysA = Object.keys(objA as any);\n\t\t\tconst stringKeysB = Object.keys(objB as any);\n\t\t\tconst symbolKeysA = Object.getOwnPropertySymbols(objA as any);\n\t\t\tconst symbolKeysB = Object.getOwnPropertySymbols(objB as any);\n\n\t\t\t// Compare string keys count\n\t\t\tif (stringKeysA.length !== stringKeysB.length) return false;\n\t\t\t// Compare symbol keys count\n\t\t\tif (symbolKeysA.length !== symbolKeysB.length) return false;\n\n\t\t\t// Check all string keys exist in both objects\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!objHasOwn.call(objB, key)) return false;\n\t\t\t}\n\n\t\t\t// Check all symbol keys exist in both objects\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!Object.getOwnPropertySymbols(objB as any).includes(key)) return false;\n\t\t\t}\n\n\t\t\t// Compare string key values\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!deepEqualInner((objA as any)[key], (objB as any)[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Compare symbol key values\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!deepEqualInner((objA as any)[key], (objB as any)[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n}\n","/**\n * Entity utilities and interfaces for Domain-Driven Design.\n *\n * In Domain-Driven Design, there are two types of entities:\n *\n * 1. **Aggregate Root Entity**: The parent Entity of an aggregate.\n * - Has identity (id), state, and version\n * - Implemented by classes extending `AggregateRoot` or `AggregateEventSourced`\n * - Represents the aggregate externally\n * - Loaded/saved through repositories\n *\n * 2. **Child Entities**: Entities within an aggregate.\n * - Have identity (id) and state, but no own version\n * - Can extend `EntityBase<TState, TId>` for class-based entities\n * - Or use functional style with `Identifiable<TId> & TProps`\n * - Exist only within the aggregate boundary\n * - Versioned through the Aggregate Root\n * - Cannot be referenced directly from outside the aggregate\n *\n * This module provides:\n * - `EntityBase<TState, TId>` - Base class for entities with state\n * - `Entity<TId>` - Simple class for entities without state management\n * - `Identifiable<TId>` - Minimal interface for objects with id\n * - Helper functions for working with collections of entities\n *\n * @example\n * ```typescript\n * // Class-based child entity with logic\n * class OrderItem extends EntityBase<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n *\n * calculateSubtotal(): number {\n * return this._state.price * this._state.quantity;\n * }\n * }\n *\n * // Functional-style child entity (simpler, no logic)\n * type OrderItem = Identifiable<ItemId> & {\n * productId: string;\n * quantity: number;\n * price: number;\n * };\n *\n * // Aggregate Root (Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * // Order is an Aggregate Root Entity\n * // OrderState contains OrderItem child entities\n * }\n * ```\n */\nimport { deepEqual } from \"../utils/array/deep-equal\";\n\nimport type { Id } from \"../core/id\";\n\n/**\n * Functional definition of an Entity via its capability.\n * An object is identifiable if it has an id.\n */\nexport type Identifiable<TId> = {\n\treadonly id: TId;\n};\n\n/**\n * Interface for Entities with state.\n *\n * In Domain-Driven Design, Entities have:\n * - Identity (id): Distinguishes one entity from another\n * - State: The attributes/properties of the entity\n *\n * Unlike Value Objects (which are immutable and compared by value),\n * Entities are compared by identity and can have mutable state.\n *\n * @template TId - The type of the entity identifier\n * @template TState - The type of the entity state\n */\nexport interface IEntity<TId extends Id<string>, TState> extends Identifiable<TId> {\n\t/**\n\t * Unique identifier of the entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * The current state of the entity.\n\t */\n\treadonly state: TState;\n}\n\n/**\n * Abstract base class for Entities with state.\n *\n * Provides:\n * - Identity management (id)\n * - State management\n * - State validation hook\n * - Immutable state access through getter\n *\n * This is the foundation for all Entities in DDD:\n * - Child Entities within aggregates can extend this\n * - Aggregate Roots extend this and add version + events\n *\n * @template TState - The type of the entity state\n * @template TId - The type of the entity identifier\n *\n * @example\n * ```typescript\n * // Child Entity within an aggregate\n * class OrderItem extends Entity<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n * }\n * ```\n */\nexport abstract class Entity<TState, TId extends Id<string>>\n\timplements IEntity<TId, TState> {\n\tpublic readonly id: TId;\n\n\t/**\n\t * Returns the current state of the entity.\n\t * State is readonly from outside to enforce encapsulation.\n\t */\n\tpublic get state(): TState {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * The state is 'protected' so that only the subclass can modify it.\n\t * Subclasses can mutate this directly or use helper methods.\n\t */\n\tprotected _state: TState;\n\n\tprotected constructor(id: TId, initialState: TState) {\n\t\tif (id === null || id === undefined) {\n\t\t\tthrow new Error(\"Entity ID cannot be null or undefined\");\n\t\t}\n\t\tthis.id = id;\n\t\tthis._state = initialState;\n\t\tthis.validateState(this._state);\n\t}\n\n\t/**\n\t * Optional validation hook to ensure state invariants.\n\t * Called during construction and whenever helpful.\n\t * Override this method to implement validation logic.\n\t *\n\t * @param state - The state to validate\n\t * @throws Error if validation fails\n\t */\n\tprotected validateState(_state: TState): void {\n\t\t// Default implementation does nothing\n\t}\n\n\t/**\n\t * Sets the state of the entity.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t *\n\t * @param newState - The new state\n\t */\n\tprotected setState(newState: TState): void {\n\t\tthis.validateState(newState);\n\t\tthis._state = newState;\n\t}\n}\n\n\n/**\n * Checks if two entities have the same ID.\n * Works with any object that has an 'id' property.\n *\n * @param a - First entity\n * @param b - Second entity\n * @returns true if both entities have the same ID, false otherwise\n *\n * @example\n * ```typescript\n * const item1: OrderItem = { id: itemId1, productId: \"prod-1\", quantity: 2 };\n * const item2: OrderItem = { id: itemId2, productId: \"prod-2\", quantity: 1 };\n *\n * sameEntity(item1, item2); // false\n * sameEntity(item1, item1); // true\n * ```\n */\nexport function sameEntity<TId>(a: Identifiable<TId>, b: Identifiable<TId>): boolean {\n\treturn deepEqual(a.id, b.id);\n}\n\n/**\n * Finds an entity by ID in a collection.\n * Returns undefined if not found.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to search for\n * @returns The entity if found, undefined otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const item = findEntityById(items, itemId1);\n * // item is { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ```\n */\nexport function findEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T | undefined {\n\treturn entities.find((entity) => deepEqual(entity.id, id));\n}\n\n/**\n * Checks if an entity with the given ID exists in the collection.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to check for\n * @returns true if an entity with the ID exists, false otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * hasEntityId(items, itemId1); // true\n * hasEntityId(items, itemId2); // false\n * ```\n */\nexport function hasEntityId<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): boolean {\n\treturn entities.some((entity) => deepEqual(entity.id, id));\n}\n\n/**\n * Removes an entity with the given ID from the collection.\n * Returns a new array without the entity.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to remove\n * @returns A new array without the entity with the given ID\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const updated = removeEntityById(items, itemId1);\n * // updated is [{ id: itemId2, productId: \"prod-2\", quantity: 1 }]\n * ```\n */\nexport function removeEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T[] {\n\treturn entities.filter((entity) => !deepEqual(entity.id, id));\n}\n\n/**\n * Updates an entity with the given ID in the collection.\n * Returns a new array with the updated entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to update\n * @param updater - Function that takes the entity and returns the updated entity\n * @returns A new array with the updated entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = updateEntityById(items, itemId1, (item) => ({\n * ...item,\n * quantity: item.quantity + 1\n * }));\n * // updated is [{ id: itemId1, productId: \"prod-1\", quantity: 3 }]\n * ```\n */\nexport function updateEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\tupdater: (entity: T) => T,\n): T[] {\n\treturn entities.map((entity) => (deepEqual(entity.id, id) ? updater(entity) : entity));\n}\n\n/**\n * Replaces an entity with the given ID in the collection.\n * Returns a new array with the replaced entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to replace\n * @param replacement - The replacement entity\n * @returns A new array with the replaced entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = replaceEntityById(items, itemId1, {\n * id: itemId1,\n * productId: \"prod-1\",\n * quantity: 5\n * });\n * ```\n */\nexport function replaceEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\treplacement: T,\n): T[] {\n\treturn entities.map((entity) => (deepEqual(entity.id, id) ? replacement : entity));\n}\n\n/**\n * Extracts all IDs from a collection of entities.\n *\n * @param entities - Array of entities\n * @returns Array of entity IDs\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const ids = entityIds(items);\n * // ids is [itemId1, itemId2]\n * ```\n */\nexport function entityIds<TId, T extends Identifiable<TId>>(entities: T[]): TId[] {\n\treturn entities.map((entity) => entity.id);\n}\n\n","import type { Id } from \"../core/id\";\nimport { Entity } from \"../entity/entity\";\nimport type {\n\tAggregateSnapshot,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Marker interface for Aggregate Roots.\n *\n * In Domain-Driven Design, an Aggregate Root is an Entity (the parent Entity of the aggregate).\n * It represents the aggregate externally and is the only object that external code\n * is allowed to hold references to. All access to child entities within the aggregate\n * must go through the Aggregate Root.\n *\n * An Aggregate consists of:\n * - One Aggregate Root (Entity with id + version)\n * - Optional child entities (Entities with id + state, but no own version)\n * - Optional value objects\n *\n * The Aggregate Root has identity (id), state, and version for optimistic concurrency control.\n * Child entities exist only within the aggregate boundary and are versioned through\n * the Aggregate Root.\n *\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * class Order extends AggregateRoot<OrderState, OrderId> implements IAggregateRoot<OrderId> {\n * // Order is an Aggregate Root (an Entity with version)\n * // OrderState contains child entities (e.g., OrderItem) and value objects\n * }\n * ```\n */\nexport interface IAggregateRoot<TId extends Id<string>> {\n\t/**\n\t * Unique identifier of the aggregate root entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * Version number for optimistic concurrency control.\n\t * Incremented on each state change to detect concurrent modifications.\n\t * This version applies to the entire aggregate, including all child entities.\n\t */\n\treadonly version: Version;\n}\n\n/**\n * Configuration options for AggregateRoot behavior.\n */\nexport interface AggregateConfig {\n\t/**\n\t * Whether to automatically bump the version when state changes.\n\t * Defaults to false. Set to true for automatic versioning.\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for creating Aggregate Roots (Entities) without Event Sourcing.\n *\n * This class creates an Entity that serves as the Aggregate Root. The Aggregate Root\n * is the parent Entity of the aggregate and represents it externally. It has identity\n * (id), state, and version for optimistic concurrency control.\n *\n * Extends `Entity<TState, TId>` to inherit:\n * - Identity (id)\n * - State management\n * - State validation\n *\n * Adds Aggregate Root specific functionality:\n * - Version management (for Optimistic Concurrency Control)\n * - Domain events tracking\n * - Snapshot support for performance optimization\n *\n * The aggregate state (`TState`) contains:\n * - Child entities (Entities with id + state, but no own version)\n * - Value objects (immutable objects)\n *\n * All changes to child entities are versioned through the Aggregate Root. The version\n * applies to the entire aggregate, including all child entities.\n *\n * Implements `IAggregateRoot<TId>` to mark this as an Aggregate Root Entity.\n *\n * Use this class when you don't need Event Sourcing but still want\n * aggregate patterns with versioning and state management.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * // Order is an Aggregate Root (an Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * constructor(id: OrderId, initialState: OrderState) {\n * super(id, initialState);\n * }\n *\n * confirm(): void {\n * this._state = { ...this._state, status: \"confirmed\" };\n * this.bumpVersion(); // Versions the entire aggregate\n * }\n * }\n * ```\n */\nexport abstract class AggregateRoot<TState, TId extends Id<string>>\n\textends Entity<TState, TId>\n\timplements IAggregateRoot<TId> {\n\tpublic version: Version = 0 as Version;\n\n\tprivate readonly _config: AggregateConfig;\n\tprivate readonly _autoVersionBump: boolean;\n\tprivate _domainEvents: unknown[] = [];\n\n\t/**\n\t * Returns a read-only list of domain events recorded by this aggregate.\n\t * These events are side-effects of state changes.\n\t */\n\tpublic get domainEvents(): ReadonlyArray<unknown> {\n\t\treturn this._domainEvents;\n\t}\n\n\t/**\n\t * Clears the list of recorded domain events.\n\t * Call this after dispatching the events.\n\t */\n\tpublic clearDomainEvents(): void {\n\t\tthis._domainEvents = [];\n\t}\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: AggregateConfig,\n\t) {\n\t\tsuper(id, initialState);\n\t\tthis._config = config ?? {};\n\t\tthis._autoVersionBump = this._config.autoVersionBump ?? false;\n\t}\n\n\t/**\n\t * Adds a domain event to the aggregate's list of changes.\n\t * Use this to record side-effects that should be published.\n\t *\n\t * @param event - The domain event to add\n\t */\n\tprotected addDomainEvent(event: unknown): void {\n\t\tthis._domainEvents.push(event);\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Call this after state changes for Optimistic Concurrency Control.\n\t *\n\t * If `autoVersionBump` is enabled, this is called automatically\n\t * when using `setState()`.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.version = (this.version + 1) as Version;\n\t}\n\n\t/**\n\t * Sets the state and optionally bumps the version automatically.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t * Overrides Entity.setState to add version bumping.\n\t *\n\t * @param newState - The new state\n\t * @param bumpVersion - Whether to bump the version (defaults to autoVersionBump config)\n\t */\n\tprotected setState(\n\t\tnewState: TState,\n\t\tbumpVersion?: boolean,\n\t): void {\n\t\tsuper.setState(newState);\n\t\tconst shouldBump = bumpVersion ?? this._autoVersionBump;\n\t\tif (shouldBump) {\n\t\t\tthis.bumpVersion();\n\t\t}\n\t}\n\n\t/**\n\t * Creates a snapshot of the current aggregate state.\n\t * Useful for performance optimization, backup/restore, and audit trails.\n\t *\n\t * @returns A snapshot containing the current state and version\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = aggregate.createSnapshot();\n\t * await snapshotRepository.save(aggregate.id, snapshot);\n\t * ```\n\t */\n\tpublic createSnapshot(): AggregateSnapshot<TState> {\n\t\treturn {\n\t\t\tstate: { ...this._state } as TState,\n\t\t\tversion: this.version,\n\t\t\tsnapshotAt: new Date(),\n\t\t};\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot.\n\t * This is useful for loading aggregates from snapshots instead of\n\t * rebuilding them from scratch.\n\t * Validates the restored state.\n\t *\n\t * @param snapshot - The snapshot to restore from\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = await snapshotRepository.getLatest(aggregateId);\n\t * aggregate.restoreFromSnapshot(snapshot);\n\t * ```\n\t */\n\tpublic restoreFromSnapshot(snapshot: AggregateSnapshot<TState>): void {\n\t\tthis.validateState(snapshot.state);\n\t\tthis._state = snapshot.state;\n\t\tthis.version = snapshot.version;\n\t}\n}\n","export type Ok<T> = { ok: true; value: T };\nexport type Err<E> = { ok: false; error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/**\n * Creates an Ok result with a value.\n *\n * @param value - The success value\n * @returns An Ok result containing the value\n *\n * @example\n * ```typescript\n * const result = ok(42);\n * // result is Ok<number>\n * ```\n */\nexport function ok<T>(value: T): Ok<T>;\n\n/**\n * Creates an Ok result with void (no value).\n *\n * @returns An Ok<void> result\n *\n * @example\n * ```typescript\n * const result = ok();\n * // result is Ok<void>\n * ```\n */\nexport function ok(): Ok<void>;\n\nexport function ok<T>(value?: T): Ok<T> {\n\treturn { ok: true, value: value as T };\n}\n\n/**\n * Creates an Err result with an error.\n *\n * @param error - The error value\n * @returns An Err result containing the error\n *\n * @example\n * ```typescript\n * const result = err(\"Something went wrong\");\n * // result is Err<string>\n * ```\n */\nexport function err<E>(error: E): Err<E>;\n\n/**\n * Creates an Err result with void (no error value).\n *\n * @returns An Err<void> result\n *\n * @example\n * ```typescript\n * const result = err();\n * // result is Err<void>\n * ```\n */\nexport function err(): Err<void>;\n\nexport function err<E>(error?: E): Err<E> {\n\treturn { ok: false, error: error as E };\n}\n\n/**\n * Type guard to check if a Result is Ok.\n * Narrows the type to Ok<T> when returning true.\n *\n * @param result - The result to check\n * @returns true if the result is Ok, false otherwise\n *\n * @example\n * ```typescript\n * const result = voWithValidation(data, validator);\n * if (isOk(result)) {\n * // TypeScript knows result is Ok<VO<T>>\n * console.log(result.value);\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is Ok<T> {\n\treturn result.ok === true;\n}\n\n/**\n * Type guard to check if a Result is Err.\n * Narrows the type to Err<E> when returning true.\n *\n * @param result - The result to check\n * @returns true if the result is Err, false otherwise\n *\n * @example\n * ```typescript\n * const result = voWithValidation(data, validator);\n * if (isErr(result)) {\n * // TypeScript knows result is Err<string>\n * console.error(result.error);\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is Err<E> {\n\treturn result.ok === false;\n}\n\n/**\n * Chains Result operations (flatMap/bind).\n * If the result is Ok, applies the function to the value.\n * If Err, returns the error unchanged.\n *\n * @param result - The result to chain\n * @param fn - Function that takes the Ok value and returns a new Result\n * @returns A new Result\n *\n * @example\n * ```typescript\n * const result = validateUserId(\"123\")\n * .andThen(userId => validateEmail(\"test@example.com\")\n * .map(email => ({ id: userId, email }))\n * );\n * ```\n */\nexport function andThen<T, E, U>(\n\tresult: Result<T, E>,\n\tfn: (value: T) => Result<U, E>,\n): Result<U, E> {\n\tif (result.ok) {\n\t\treturn fn(result.value);\n\t}\n\treturn result;\n}\n\n/**\n * Transforms the Ok value using a function.\n * If the result is Err, returns the error unchanged.\n *\n * @param result - The result to transform\n * @param fn - Function to transform the Ok value\n * @returns A new Result with transformed value\n *\n * @example\n * ```typescript\n * const result = ok(5);\n * const doubled = map(result, x => x * 2); // Ok<10>\n * ```\n */\nexport function map<T, E, U>(\n\tresult: Result<T, E>,\n\tfn: (value: T) => U,\n): Result<U, E> {\n\tif (result.ok) {\n\t\treturn ok(fn(result.value));\n\t}\n\treturn result;\n}\n\n/**\n * Transforms the Err value using a function.\n * If the result is Ok, returns the value unchanged.\n *\n * @param result - The result to transform\n * @param fn - Function to transform the Err value\n * @returns A new Result with transformed error\n *\n * @example\n * ```typescript\n * const result = err(\"not found\");\n * const mapped = mapErr(result, e => `Error: ${e}`); // Err<\"Error: not found\">\n * ```\n */\nexport function mapErr<T, E, F>(\n\tresult: Result<T, E>,\n\tfn: (error: E) => F,\n): Result<T, F> {\n\tif (result.ok) {\n\t\treturn result;\n\t}\n\treturn err(fn(result.error));\n}\n\n/**\n * Returns the value if Ok, otherwise returns the default value.\n *\n * @param result - The result to unwrap\n * @param defaultValue - Default value to return if Err\n * @returns The Ok value or the default value\n *\n * @example\n * ```typescript\n * const result = validateUserId(\"123\");\n * const userId = unwrapOr(result, \"default-id\");\n * ```\n */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n\treturn result.ok ? result.value : defaultValue;\n}\n\n/**\n * Returns the value if Ok, otherwise computes default from error.\n *\n * @param result - The result to unwrap\n * @param fn - Function to compute default from error\n * @returns The Ok value or computed default\n *\n * @example\n * ```typescript\n * const result = validateUserId(\"\");\n * const userId = unwrapOrElse(result, err => `fallback-${Date.now()}`);\n * ```\n */\nexport function unwrapOrElse<T, E>(\n\tresult: Result<T, E>,\n\tfn: (error: E) => T,\n): T {\n\treturn result.ok ? result.value : fn(result.error);\n}\n\n/**\n * Pattern matching for Result.\n * Applies one function if Ok, another if Err.\n *\n * @param result - The result to match\n * @param onOk - Function to apply if Ok\n * @param onErr - Function to apply if Err\n * @returns The result of applying the appropriate function\n *\n * @example\n * ```typescript\n * const message = match(result,\n * value => `Success: ${value}`,\n * error => `Error: ${error}`\n * );\n * ```\n *\n * @example Using object syntax\n * ```typescript\n * const message = match(result, {\n * ok: value => `Success: ${value}`,\n * err: error => `Error: ${error}`\n * });\n * ```\n */\nexport function match<T, E, R>(\n\tresult: Result<T, E>,\n\tonOk: (value: T) => R,\n\tonErr: (error: E) => R,\n): R;\nexport function match<T, E, R>(\n\tresult: Result<T, E>,\n\thandlers: { ok: (value: T) => R; err: (error: E) => R },\n): R;\nexport function match<T, E, R>(\n\tresult: Result<T, E>,\n\tonOkOrHandlers: ((value: T) => R) | { ok: (value: T) => R; err: (error: E) => R },\n\tonErr?: (error: E) => R,\n): R {\n\tif (typeof onOkOrHandlers === \"function\") {\n\t\t// Function syntax: match(result, onOk, onErr)\n\t\treturn result.ok ? onOkOrHandlers(result.value) : onErr!(result.error);\n\t}\n\t// Object syntax: match(result, { ok: ..., err: ... })\n\treturn result.ok\n\t\t? onOkOrHandlers.ok(result.value)\n\t\t: onOkOrHandlers.err(result.error);\n}\n\n/**\n * Async pattern matching for Result.\n * Applies one async function if Ok, another if Err.\n * Both handlers must return Promises.\n *\n * @param result - The result to match\n * @param onOk - Async function to apply if Ok\n * @param onErr - Async function to apply if Err\n * @returns Promise resolving to the result of applying the appropriate function\n *\n * @example\n * ```typescript\n * const message = await matchAsync(result,\n * async (value) => `Success: ${value}`,\n * async (error) => `Error: ${error}`\n * );\n * ```\n *\n * @example Using object syntax\n * ```typescript\n * const message = await matchAsync(result, {\n * ok: async (value) => `Success: ${value}`,\n * err: async (error) => `Error: ${error}`\n * });\n * ```\n */\nexport async function matchAsync<T, E, R>(\n\tresult: Result<T, E>,\n\tonOk: (value: T) => Promise<R>,\n\tonErr: (error: E) => Promise<R>,\n): Promise<R>;\nexport async function matchAsync<T, E, R>(\n\tresult: Result<T, E>,\n\thandlers: { ok: (value: T) => Promise<R>; err: (error: E) => Promise<R> },\n): Promise<R>;\nexport async function matchAsync<T, E, R>(\n\tresult: Result<T, E>,\n\tonOkOrHandlers:\n\t\t| ((value: T) => Promise<R>)\n\t\t| { ok: (value: T) => Promise<R>; err: (error: E) => Promise<R> },\n\tonErr?: (error: E) => Promise<R>,\n): Promise<R> {\n\tif (typeof onOkOrHandlers === \"function\") {\n\t\t// Function syntax: matchAsync(result, onOk, onErr)\n\t\treturn result.ok\n\t\t\t? onOkOrHandlers(result.value)\n\t\t\t: onErr!(result.error);\n\t}\n\t// Object syntax: matchAsync(result, { ok: ..., err: ... })\n\treturn result.ok\n\t\t? onOkOrHandlers.ok(result.value)\n\t\t: onOkOrHandlers.err(result.error);\n}\n\n/**\n * Pattern matching for Result that returns a Result.\n * Both handlers must return a Result, allowing you to transform\n * both the success and error cases while staying in Result context.\n *\n * @param result - The result to match\n * @param handlers - Object with ok and err handlers, both returning Result\n * @returns A new Result from the appropriate handler\n *\n * @example\n * ```typescript\n * const result = await fetchUser(id);\n * return matchResult(result, {\n * ok: (user) => ok(transformUser(user)),\n * err: (error) => err(mapToAppError(error))\n * });\n * ```\n */\nexport function matchResult<T, E, U, F>(\n\tresult: Result<T, E>,\n\thandlers: {\n\t\tok: (value: T) => Result<U, F>;\n\t\terr: (error: E) => Result<U, F>;\n\t},\n): Result<U, F>;\nexport function matchResult<T, E, U, F>(\n\tresult: Result<T, E>,\n\tonOk: (value: T) => Result<U, F>,\n\tonErr: (error: E) => Result<U, F>,\n): Result<U, F>;\nexport function matchResult<T, E, U, F>(\n\tresult: Result<T, E>,\n\tonOkOrHandlers:\n\t\t| ((value: T) => Result<U, F>)\n\t\t| { ok: (value: T) => Result<U, F>; err: (error: E) => Result<U, F> },\n\tonErr?: (error: E) => Result<U, F>,\n): Result<U, F> {\n\tif (typeof onOkOrHandlers === \"function\") {\n\t\treturn result.ok ? onOkOrHandlers(result.value) : onErr!(result.error);\n\t}\n\treturn result.ok\n\t\t? onOkOrHandlers.ok(result.value)\n\t\t: onOkOrHandlers.err(result.error);\n}\n\n/**\n * Pipes a Result through multiple operations.\n * Each function receives the previous Result and returns a new Result.\n * Stops on first error.\n *\n * @param initial - The initial Result value\n * @param fns - Array of functions that take the previous Result and return a new Result\n * @returns The final Result after all operations\n *\n * @example\n * ```typescript\n * // Instead of nested andThen calls:\n * andThen(\n * updateCountryCode(code),\n * () => andThen(updateCurrencyCode(currency), () => updateLanguageCode(lang))\n * )\n *\n * // Use pipe (cleaner and more readable):\n * pipe(\n * updateCountryCode(code),\n * () => updateCurrencyCode(currency),\n * () => updateLanguageCode(lang)\n * )\n * ```\n *\n * @example With void results\n * ```typescript\n * setInitialData(initialData: JobConfigProps[\"initialData\"]): Result<void, JobDomainError> {\n * return pipe(\n * this.updateCountryCode(initialData.countryCode),\n * () => this.updateCurrencyCode(initialData.currencyCode),\n * () => this.updateLanguageCode(initialData.languageCode)\n * );\n * }\n * ```\n */\nexport function pipe<T, E>(\n\tinitial: Result<T, E>,\n\t...fns: Array<(prev: Result<T, E>) => Result<T, E>>\n): Result<T, E> {\n\tlet current = initial;\n\tfor (const fn of fns) {\n\t\tcurrent = fn(current);\n\t\tif (!current.ok) {\n\t\t\treturn current;\n\t\t}\n\t}\n\treturn current;\n}\n\n/**\n * Wraps a function that may throw exceptions into a Result type.\n * Catches any thrown exceptions and converts them to Err results.\n *\n * @param fn - Function that may throw exceptions\n * @param errorMapper - Optional function to transform the caught error\n * @returns A Result containing the function's return value or error\n *\n * @example\n * ```typescript\n * function riskyOperation(): string {\n * if (Math.random() > 0.5) {\n * throw new Error(\"Something went wrong\");\n * }\n * return \"success\";\n * }\n *\n * const result = tryCatch(() => riskyOperation());\n * if (result.ok) {\n * console.log(result.value); // \"success\"\n * } else {\n * console.error(result.error.message); // \"Something went wrong\"\n * }\n * ```\n *\n * @example With custom error mapper\n * ```typescript\n * const result = tryCatch(\n * () => riskyOperation(),\n * (error) => `Custom: ${error instanceof Error ? error.message : String(error)}`\n * );\n * ```\n */\nexport function tryCatch<T, E = Error>(\n\tfn: () => T,\n\terrorMapper?: (error: unknown) => E,\n): Result<T, E> {\n\ttry {\n\t\treturn ok(fn());\n\t} catch (error) {\n\t\tif (errorMapper) {\n\t\t\treturn err(errorMapper(error));\n\t\t}\n\t\treturn err((error instanceof Error ? error : new Error(String(error))) as E);\n\t}\n}\n\n/**\n * Wraps an async function that may throw exceptions into a Promise<Result>.\n * Catches any thrown exceptions and converts them to Err results.\n *\n * @param fn - Async function that may throw exceptions\n * @param errorMapper - Optional function to transform the caught error\n * @returns A Promise resolving to a Result containing the function's return value or error\n *\n * @example\n * ```typescript\n * async function riskyAsyncOperation(): Promise<string> {\n * if (Math.random() > 0.5) {\n * throw new Error(\"Something went wrong\");\n * }\n * return \"success\";\n * }\n *\n * const result = await tryCatchAsync(() => riskyAsyncOperation());\n * if (result.ok) {\n * console.log(result.value); // \"success\"\n * } else {\n * console.error(result.error.message); // \"Something went wrong\"\n * }\n * ```\n */\nexport async function tryCatchAsync<T, E = Error>(\n\tfn: () => Promise<T>,\n\terrorMapper?: (error: unknown) => E,\n): Promise<Result<T, E>> {\n\ttry {\n\t\tconst value = await fn();\n\t\treturn ok(value);\n\t} catch (error) {\n\t\tif (errorMapper) {\n\t\t\treturn err(errorMapper(error));\n\t\t}\n\t\treturn err((error instanceof Error ? error : new Error(String(error))) as E);\n\t}\n}\n\n","import { err, ok, type Result } from \"../core/result\";\nimport type { Id } from \"../core/id\";\nimport { AggregateRoot, type AggregateConfig, type IAggregateRoot } from \"./aggregate-root\";\nimport type {\n\tAggregateSnapshot,\n\tDomainEvent,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Interface for Event-Sourced Aggregate Roots.\n * Defines the contract for aggregates that manage state changes via event sourcing.\n *\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The union type of all domain events\n */\nexport interface IAggregateEventSourced<\n\tTId extends Id<string>,\n\tTEvent extends DomainEvent<string, unknown>,\n> extends IAggregateRoot<TId> {\n\t/**\n\t * Returns a read-only list of new, not-yet-persisted events.\n\t */\n\treadonly pendingEvents: ReadonlyArray<TEvent>;\n\n\t/**\n\t * Reconstitutes the aggregate from an event history.\n\t *\n\t * @param history - An ordered list of past events\n\t */\n\tloadFromHistory(history: TEvent[]): Result<void, string>;\n\n\t/**\n\t * Clears the list of pending events.\n\t */\n\tclearPendingEvents(): void;\n\n\t/**\n\t * Checks if the aggregate has any pending events.\n\t */\n\thasPendingEvents(): boolean;\n\n\t/**\n\t * Returns the number of pending events.\n\t */\n\tgetEventCount(): number;\n\n\t/**\n\t * Returns the latest pending event, if any.\n\t */\n\tgetLatestEvent(): TEvent | undefined;\n}\n\ntype Handler<TState, TEvent> = (state: TState, event: TEvent) => TState;\n\n/**\n * Extended configuration options for AggregateEventSourced behavior.\n */\nexport interface AggregateEventSourcedConfig extends AggregateConfig {\n\t/**\n\t * Whether to automatically bump the version when applying new events.\n\t * Defaults to true. Set to false to manually control versioning.\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for Event-Sourced Aggregate Roots (Entities).\n * \n * Extends `AggregateRoot` to create an Aggregate Root Entity with Event Sourcing capabilities.\n * The Aggregate Root is the parent Entity of the aggregate and represents it externally.\n * \n * The aggregate state (`TState`) contains:\n * - Child entities (Entities with id, but no own version)\n * - Value objects (immutable objects)\n * \n * All changes to child entities are versioned through the Aggregate Root. The version\n * applies to the entire aggregate, including all child entities.\n * \n * Extends `AggregateRoot` with Event Sourcing capabilities:\n * - Event tracking (pendingEvents)\n * - Event handlers for state transitions\n * - Event validation\n * - History replay\n *\n * Use this class when you want Event Sourcing with full event tracking\n * and replay capabilities.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TEvent - The union type of all domain events\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * // Order is an Aggregate Root (an Entity) with Event Sourcing\n * class Order extends AggregateEventSourced<OrderState, OrderEvent, OrderId> {\n * confirm(): void {\n * this.apply(createDomainEvent(\"OrderConfirmed\", {}));\n * }\n *\n * protected readonly handlers = {\n * OrderConfirmed: (state: OrderState): OrderState => ({\n * ...state,\n * status: \"confirmed\",\n * }),\n * };\n * }\n * ```\n */\nexport abstract class AggregateEventSourced<\n\tTState,\n\tTEvent extends DomainEvent<string, unknown>,\n\tTId extends Id<string>,\n> extends AggregateRoot<TState, TId>\n\timplements IAggregateEventSourced<TId, TEvent> {\n\tprivate readonly _eventConfig: AggregateEventSourcedConfig;\n\tprivate readonly _eventAutoVersionBump: boolean;\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: AggregateEventSourcedConfig,\n\t) {\n\t\tsuper(id, initialState, config);\n\t\tthis._eventConfig = config ?? {};\n\t\tthis._eventAutoVersionBump = this._eventConfig.autoVersionBump ?? true;\n\t}\n\n\t/**\n\t * Returns a read-only list of new, not-yet-persisted events.\n\t */\n\tpublic get pendingEvents(): ReadonlyArray<TEvent> {\n\t\treturn this.domainEvents as ReadonlyArray<TEvent>;\n\t}\n\n\t/**\n\t * Clears the list of pending events.\n\t * Typically called after the events have been persisted.\n\t */\n\tpublic clearPendingEvents(): void {\n\t\tthis.clearDomainEvents();\n\t}\n\n\t/**\n\t * Validates an event before it is applied.\n\t * Override this method to add custom validation logic.\n\t * Return `ok(true)` if the event is valid, `err(message)` otherwise.\n\t *\n\t * @param event - The event to validate\n\t * @returns Result indicating if the event is valid\n\t *\n\t * @example\n\t * ```typescript\n\t * protected validateEvent(event: OrderEvent): Result<true, string> {\n\t * if (event.type === \"OrderShipped\" && this.state.status !== \"confirmed\") {\n\t * return err(\"Order must be confirmed before shipping\");\n\t * }\n\t * return ok(true);\n\t * }\n\t * ```\n\t */\n\tprotected validateEvent(_event: TEvent): Result<true, string> {\n\t\treturn ok(true);\n\t}\n\n\t/**\n\t * Applies an event to change the state and adds it\n\t * to the list of pending events.\n\t * Returns a Result type instead of throwing an error.\n\t *\n\t * @param event - The domain event to apply\n\t * @param isNew - Indicates whether the event is new (and needs to be persisted)\n\t * or if it is being loaded from history\n\t * @returns Result<void, string> - ok if successful, err with error message if validation fails or handler is missing\n\t */\n\tprotected apply(event: TEvent, isNew = true): Result<void, string> {\n\t\t// Validate event before applying\n\t\tconst validation = this.validateEvent(event);\n\t\tif (!validation.ok) {\n\t\t\treturn err(\n\t\t\t\t`Event validation failed for ${event.type}: ${validation.error}`,\n\t\t\t);\n\t\t}\n\n\t\tconst handler = this.handlers[event.type as keyof typeof this.handlers];\n\t\tif (!handler) {\n\t\t\treturn err(`Missing handler for event type: ${event.type}`);\n\t\t}\n\n\t\t// First, change the state\n\t\tthis._state = handler(\n\t\t\tthis._state,\n\t\t\tevent as Extract<TEvent, { type: TEvent[\"type\"] }>,\n\t\t);\n\n\t\t// Then (if new) add the event to the list and bump version\n\t\tif (isNew) {\n\t\t\tthis.addDomainEvent(event);\n\t\t\tif (this._eventAutoVersionBump) {\n\t\t\t\tthis.version = (this.version + 1) as Version;\n\t\t\t}\n\t\t}\n\n\t\treturn ok();\n\t}\n\n\t/**\n\t * Applies an event to change the state and adds it\n\t * to the list of pending events.\n\t * Throws an error if validation fails or handler is missing.\n\t *\n\t * @param event - The domain event to apply\n\t * @param isNew - Indicates whether the event is new (and needs to be persisted)\n\t * or if it is being loaded from history\n\t * @throws Error if event validation fails or handler is missing\n\t */\n\tprotected applyUnsafe(event: TEvent, isNew = true): void {\n\t\t// Validate event before applying\n\t\tconst validation = this.validateEvent(event);\n\t\tif (!validation.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Event validation failed for ${event.type}: ${validation.error}`,\n\t\t\t);\n\t\t}\n\n\t\tconst handler = this.handlers[event.type as keyof typeof this.handlers];\n\t\tif (!handler) {\n\t\t\tthrow new Error(`Missing handler for event type: ${event.type}`);\n\t\t}\n\n\t\t// First, change the state\n\t\tthis._state = handler(\n\t\t\tthis._state,\n\t\t\tevent as Extract<TEvent, { type: TEvent[\"type\"] }>,\n\t\t);\n\n\t\t// Then (if new) add the event to the list and bump version\n\t\tif (isNew) {\n\t\t\tthis.addDomainEvent(event);\n\t\t\tif (this._eventAutoVersionBump) {\n\t\t\t\tthis.version = (this.version + 1) as Version;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Only needed if `autoVersionBump` is disabled.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.version = (this.version + 1) as Version;\n\t}\n\n\t/**\n\t * Reconstitutes the aggregate from an event history.\n\t * Sets the version to the number of events in the history.\n\t *\n\t * @param history - An ordered list of past events\n\t */\n\tpublic loadFromHistory(history: TEvent[]): Result<void, string> {\n\t\tfor (const event of history) {\n\t\t\tconst result = this.apply(event, false); // 'false' as it's not a new event\n\t\t\tif (!result.ok) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\t// Set version to the number of events in history\n\t\tthis.version = history.length as Version;\n\t\treturn ok();\n\t}\n\n\t/**\n\t * Checks if the aggregate has any pending events.\n\t *\n\t * @returns true if there are pending events, false otherwise\n\t */\n\tpublic hasPendingEvents(): boolean {\n\t\treturn this.domainEvents.length > 0;\n\t}\n\n\t/**\n\t * Returns the number of pending events.\n\t *\n\t * @returns The count of pending events\n\t */\n\tpublic getEventCount(): number {\n\t\treturn this.domainEvents.length;\n\t}\n\n\t/**\n\t * Returns the latest pending event, if any.\n\t *\n\t * @returns The most recent event or undefined if no events exist\n\t */\n\tpublic getLatestEvent(): TEvent | undefined {\n\t\tconst events = this.domainEvents;\n\t\treturn events[events.length - 1] as TEvent | undefined;\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot and applies events that occurred after the snapshot.\n\t * This is more efficient than replaying all events from the beginning.\n\t *\n\t * @param snapshot - The snapshot to restore from\n\t * @param eventsAfterSnapshot - Events that occurred after the snapshot was taken\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = await snapshotRepository.getLatest(aggregateId);\n\t * const eventsAfter = await eventStore.getEventsAfter(aggregateId, snapshot.version);\n\t * aggregate.restoreFromSnapshotWithEvents(snapshot, eventsAfter);\n\t * ```\n\t */\n\tpublic restoreFromSnapshotWithEvents(\n\t\tsnapshot: AggregateSnapshot<TState>,\n\t\teventsAfterSnapshot: TEvent[],\n\t): Result<void, string> {\n\t\tthis._state = snapshot.state;\n\t\tthis.version = snapshot.version;\n\n\t\t// Apply events that occurred after the snapshot\n\t\tfor (const event of eventsAfterSnapshot) {\n\t\t\tconst result = this.apply(event, false);\n\t\t\tif (!result.ok) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\n\t\t// Set version to snapshot version + events after snapshot\n\t\tthis.version = (snapshot.version + eventsAfterSnapshot.length) as Version;\n\t\treturn ok();\n\t}\n\n\t/**\n\t * A map of event types to their corresponding handlers.\n\t * Subclasses MUST implement this property.\n\t */\n\tprotected abstract readonly handlers: {\n\t\t[K in TEvent[\"type\"]]: Handler<TState, Extract<TEvent, { type: K }>>;\n\t};\n}\n\n","import type { Result } from \"../core/result\";\nimport { err } from \"../core/result\";\nimport type { Command, CommandHandler } from \"./command\";\n\n/**\n * Command Bus interface for dispatching commands to their handlers.\n * Provides a centralized way to execute commands with handler registration.\n *\n * @example\n * ```typescript\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", createOrderHandler);\n *\n * const result = await bus.execute({\n * type: \"CreateOrder\",\n * customerId: \"123\",\n * items: [...]\n * });\n * ```\n */\nexport interface ICommandBus {\n\t/**\n\t * Executes a command by dispatching it to the registered handler.\n\t *\n\t * @param command - The command to execute\n\t * @returns Result containing the success value or error message\n\t */\n\texecute<C extends Command, R>(command: C): Promise<Result<R, string>>;\n\n\t/**\n\t * Registers a handler for a specific command type.\n\t *\n\t * @param commandType - The command type to register the handler for\n\t * @param handler - The handler function for this command type\n\t */\n\tregister<C extends Command, R>(\n\t\tcommandType: C[\"type\"],\n\t\thandler: CommandHandler<C, R>,\n\t): void;\n}\n\n/**\n * Simple in-memory command bus implementation.\n * Handlers are stored in a Map and dispatched based on command type.\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, validation, authorization)\n * - Error handling and retry logic\n * - Timeout handling\n * - Metrics and observability\n * - Transaction management\n * - Dead letter queue support\n *\n * The `CommandHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @example\n * ```typescript\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", async (cmd) => {\n * // ... handler logic\n * return ok(orderId);\n * });\n *\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * ```\n */\nexport class CommandBus implements ICommandBus {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, CommandHandler<any, any>>();\n\n\tregister<C extends Command, R>(\n\t\tcommandType: C[\"type\"],\n\t\thandler: CommandHandler<C, R>,\n\t): void {\n\t\tthis.handlers.set(commandType, handler);\n\t}\n\n\tasync execute<C extends Command, R>(\n\t\tcommand: C,\n\t): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(command.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for command type: ${command.type}`);\n\t\t}\n\t\treturn handler(command);\n\t}\n}\n\n","import type { EventBus, Outbox } from \"../events/ports\";\nimport type { UnitOfWork } from \"../repo/uow\";\n\n/**\n * Helper function for executing commands within a transaction.\n * Handles event persistence via outbox and optional event bus publishing.\n *\n * @param deps - Dependencies including outbox, optional event bus, and unit of work\n * @param fn - Function that returns result and events\n * @returns The result wrapped in a transaction\n *\n * @example\n * ```typescript\n * const result = await withCommit(\n * { outbox, bus, uow },\n * async () => {\n * const order = Order.create(customerId, items);\n * await repository.save(order);\n * return {\n * result: order.id,\n * events: order.pendingEvents\n * };\n * }\n * );\n * ```\n */\nexport function withCommit<Evt, R>(\n\tdeps: {\n\t\toutbox: Outbox<Evt>;\n\t\tbus?: EventBus<Evt>;\n\t\tuow: UnitOfWork;\n\t},\n\tfn: () => Promise<{ result: R; events: ReadonlyArray<Evt> }>,\n) {\n\treturn deps.uow.transactional(async () => {\n\t\tconst { result, events } = await fn();\n\t\tawait deps.outbox.add(events);\n\t\tif (deps.bus) await deps.bus.publish(events);\n\t\treturn result;\n\t});\n}\n","import { err, ok, type Result } from \"../core/result\";\nimport type { Query, QueryHandler } from \"./query\";\n\n/**\n * Query Bus interface for dispatching queries to their handlers.\n * Provides a centralized way to execute queries with handler registration.\n *\n * @example\n * ```typescript\n * const bus = new QueryBus();\n * bus.register(\"GetOrder\", getOrderHandler);\n *\n * const order = await bus.execute({\n * type: \"GetOrder\",\n * orderId: \"123\"\n * });\n * ```\n */\nexport interface IQueryBus {\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * Returns a Result type instead of throwing an error.\n\t *\n\t * @param query - The query to execute\n\t * @returns Result containing the query result if successful, or an error message if no handler is registered\n\t */\n\texecute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * Throws an error if no handler is registered.\n\t *\n\t * @param query - The query to execute\n\t * @returns The query result\n\t * @throws Error if no handler is registered for the query type\n\t */\n\texecuteUnsafe<Q extends Query, R>(query: Q): Promise<R>;\n\n\t/**\n\t * Registers a handler for a specific query type.\n\t *\n\t * @param queryType - The query type to register the handler for\n\t * @param handler - The handler function for this query type\n\t */\n\tregister<Q extends Query, R>(\n\t\tqueryType: Q[\"type\"],\n\t\thandler: QueryHandler<Q, R>,\n\t): void;\n}\n\n/**\n * Type map for query types to their return types.\n * Used to improve type inference in QueryBus.\n */\ntype QueryTypeMap = Record<string, unknown>;\n\n/**\n * Simple in-memory query bus implementation.\n * Handlers are stored in a Map and dispatched based on query type.\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, caching, rate limiting)\n * - Error handling\n * - Timeout handling\n * - Metrics and observability\n * - Query result caching\n * - Rate limiting\n *\n * The `QueryHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @example\n * ```typescript\n * const bus = new QueryBus();\n * bus.register(\"GetOrder\", async (query) => {\n * return await repository.getById(query.orderId);\n * });\n *\n * const order = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * ```\n */\nexport class QueryBus<TMap extends QueryTypeMap = QueryTypeMap>\n\timplements IQueryBus\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, QueryHandler<any, any>>();\n\n\tregister<Q extends Query, R>(\n\t\tqueryType: Q[\"type\"],\n\t\thandler: QueryHandler<Q, R>,\n\t): void {\n\t\tthis.handlers.set(queryType, handler);\n\t}\n\n\tasync execute<Q extends Query & { type: keyof TMap }>(\n\t\tquery: Q,\n\t): Promise<Result<TMap[Q[\"type\"]], string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await handler(query);\n\t\t\treturn ok(result);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n\n\tasync executeUnsafe<Q extends Query, R>(query: Q): Promise<R> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\tthrow new Error(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\treturn handler(query);\n\t}\n}\n\n","import { err, ok, type Result } from \"./result\";\n\n/**\n * Guard function that validates a condition and returns a Result.\n * Returns `ok(true)` if the condition is met, otherwise `err(error)`.\n *\n * @param cond - The condition to check\n * @param error - Error message if condition fails\n * @returns Result<true, string>\n *\n * @example\n * ```typescript\n * const result = guard(id.length > 0, \"ID cannot be empty\");\n * if (!result.ok) {\n * return err(result.error);\n * }\n * ```\n */\nexport function guard(cond: boolean, error: string): Result<true, string> {\n\treturn cond ? ok(true) : err(error);\n}\n","import type { DomainEvent } from \"../aggregate/aggregate\";\nimport type { EventBus, EventHandler } from \"./ports\";\n\n/**\n * Simple in-memory event bus implementation.\n * Supports multiple subscribers per event type (pub/sub pattern).\n *\n * @template Evt - The type of domain events (must extend DomainEvent)\n *\n * @example\n * ```typescript\n * const bus = new EventBusImpl<OrderEvent>();\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await sendEmail(event.payload.customerId);\n * });\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await logEvent(event);\n * });\n *\n * await bus.publish([orderCreatedEvent]);\n * // Both handlers will be called\n * ```\n */\nexport class EventBusImpl<Evt extends DomainEvent<string, unknown>>\n\timplements EventBus<Evt>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, Set<EventHandler<any>>>();\n\n\tsubscribe<T extends Evt>(\n\t\teventType: string,\n\t\thandler: EventHandler<T>,\n\t): () => void {\n\t\tconst type = eventType;\n\t\tif (!this.handlers.has(type)) {\n\t\t\tthis.handlers.set(type, new Set());\n\t\t}\n\t\tconst handlersForType = this.handlers.get(type)!;\n\t\thandlersForType.add(handler);\n\n\t\t// Return unsubscribe function\n\t\treturn () => {\n\t\t\thandlersForType.delete(handler);\n\t\t\tif (handlersForType.size === 0) {\n\t\t\t\tthis.handlers.delete(type);\n\t\t\t}\n\t\t};\n\t}\n\n\tasync publish(events: ReadonlyArray<Evt>): Promise<void> {\n\t\tfor (const event of events) {\n\t\t\tconst handlersForType = this.handlers.get(event.type);\n\t\t\tif (handlersForType) {\n\t\t\t\t// Call all handlers for this event type\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tArray.from(handlersForType).map((handler) => handler(event)),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n\n","import { isBuiltInObject } from \"./is-built-in\";\n\nexport type Key = string | symbol;\nexport type PathSegment = string | number | symbol;\n\nexport interface DeepOmitOptions {\n\t/**\n\t * Keys to ignore everywhere in the object tree.\n\t * Only applies to object properties, not Map/Set/TypedArray contents.\n\t */\n\treadonly ignoreKeys?: readonly Key[];\n\n\t/**\n\t * Fine-grained control: Key + path (without current key).\n\t * Example path: [\"user\", \"meta\", 0, \"data\"]\n\t */\n\treadonly ignoreKeyPredicate?: (\n\t\tkey: Key,\n\t\tpath: readonly PathSegment[],\n\t) => boolean;\n}\n\n/**\n * Creates a deep copy of `value` with certain keys removed according to the provided rules.\n *\n * This function recursively traverses the object tree and removes keys that match\n * the criteria specified in `options`. Built-in types (Date, Map, Set, TypedArrays, etc.)\n * are treated atomically and not modified.\n *\n * @param value - The value to create a deep copy from\n * @param options - Options specifying which keys to ignore\n * @returns A deep copy of `value` with specified keys removed\n *\n * @example\n * ```ts\n * const obj = { a: 1, b: { c: 2, d: 3 } };\n * const result = deepOmit(obj, { ignoreKeys: ['d'] });\n * // result: { a: 1, b: { c: 2 } }\n * ```\n */\nexport function deepOmit<T>(value: T, options: DeepOmitOptions): T {\n\tconst visited = new WeakMap<object, unknown>();\n\treturn omitInternal(value, options, [], visited) as T;\n}\n\nfunction omitInternal(\n\tvalue: unknown,\n\toptions: DeepOmitOptions,\n\tpath: PathSegment[],\n\tvisited: WeakMap<object, unknown>,\n): unknown {\n\tif (value === null) return value;\n\tconst type = typeof value;\n\n\t// Primitives and functions are passed through unchanged\n\tif (type !== \"object\") return value;\n\n\tconst obj = value as object;\n\n\t// Cycles: return cached value if already visited\n\tconst cached = visited.get(obj);\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\tconst tag = Object.prototype.toString.call(obj);\n\n\t// Arrays: recursively process elements\n\tif (tag === \"[object Array]\") {\n\t\tconst arr = obj as unknown[];\n\t\tconst clone: unknown[] = new Array(arr.length);\n\t\tvisited.set(obj, clone);\n\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tpath.push(i);\n\t\t\tclone[i] = omitInternal(arr[i], options, path, visited);\n\t\t\tpath.pop();\n\t\t}\n\t\treturn clone;\n\t}\n\n\t// Built-ins: treat atomically, no key filtering inside\n\t// Future-proof detection: check if object is a built-in type\n\tif (isBuiltInObject(obj, tag)) {\n\t\treturn value;\n\t}\n\n\t// Plain / Custom Objects: filter keys, recursively process values\n\tconst clone = Object.create(Object.getPrototypeOf(obj));\n\tvisited.set(obj, clone);\n\n\tconst stringKeys = Object.keys(obj);\n\tconst symbolKeys = Object.getOwnPropertySymbols(obj);\n\tconst keys: Key[] = [...stringKeys, ...symbolKeys];\n\n\tfor (const key of keys) {\n\t\tif (shouldIgnoreKey(key, path, options)) continue;\n\n\t\tpath.push(key);\n\t\t(clone as Record<PropertyKey, unknown>)[key] = omitInternal(\n\t\t\t(obj as Record<PropertyKey, unknown>)[key],\n\t\t\toptions,\n\t\t\tpath,\n\t\t\tvisited,\n\t\t);\n\t\tpath.pop();\n\t}\n\n\treturn clone;\n}\n\nfunction shouldIgnoreKey(\n\tkey: Key,\n\tpath: readonly PathSegment[],\n\toptions: DeepOmitOptions,\n): boolean {\n\tif (options.ignoreKeys?.includes(key)) {\n\t\treturn true;\n\t}\n\tif (options.ignoreKeyPredicate?.(key, path)) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n","import { deepEqual } from \"./deep-equal\";\nimport { type DeepOmitOptions, deepOmit } from \"./deep-omit\";\n\nexport type DeepEqualExceptOptions = DeepOmitOptions;\n\n/**\n * Performs a deep equality comparison between two values after omitting specified keys.\n * \n * This function first removes the specified keys from both values using `deepOmit`,\n * then performs a deep equality check using `deepEqual`.\n * \n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param options - Options specifying which keys to omit before comparison\n * @returns `true` if the values are deeply equal after omitting specified keys, `false` otherwise\n * \n * @example\n * ```ts\n * const obj1 = { id: 1, name: \"Alice\", updatedAt: \"2024-01-01\" };\n * const obj2 = { id: 2, name: \"Alice\", updatedAt: \"2024-01-02\" };\n * \n * deepEqualExcept(obj1, obj2, { ignoreKeys: [\"id\", \"updatedAt\"] }); // true\n * ```\n */\nexport function deepEqualExcept(\n\ta: unknown,\n\tb: unknown,\n\toptions: DeepEqualExceptOptions,\n): boolean {\n\tconst prunedA = deepOmit(a, options);\n\tconst prunedB = deepOmit(b, options);\n\treturn deepEqual(prunedA, prunedB);\n}\n","import { deepEqual } from \"../utils/array/deep-equal\";\nimport {\n deepEqualExcept,\n type DeepEqualExceptOptions,\n} from \"../utils/array/deep-equal-except\";\nimport { err, ok, type Result } from \"../core/result\";\n\n// ============================================================================\n// Functional Value Object API\n// ============================================================================\n\nexport type VO<T> = Readonly<T>;\n\n/**\n * Deep freezes an object and all its nested properties recursively.\n * This ensures true immutability for value objects with nested structures.\n * Handles circular references by tracking visited objects.\n */\nexport function deepFreeze<T>(obj: T, visited = new WeakSet<object>()): Readonly<T> {\n // Handle null and non-objects\n if (obj === null || typeof obj !== \"object\") {\n return obj as Readonly<T>;\n }\n\n // Handle circular references\n if (visited.has(obj as object)) {\n return obj as Readonly<T>;\n }\n\n // Mark as visited\n visited.add(obj as object);\n\n // Retrieve the property names defined on obj\n const propNames = Object.getOwnPropertyNames(obj);\n\n // Freeze properties before freezing self\n for (const name of propNames) {\n const value = (obj as Record<string, unknown>)[name];\n\n // Freeze value if it is an object or array\n if (value && (typeof value === \"object\" || Array.isArray(value))) {\n deepFreeze(value, visited);\n }\n }\n\n return Object.freeze(obj) as Readonly<T>;\n}\n\n/**\n * Creates a deeply immutable value object from the given data.\n * All nested objects and arrays are frozen recursively.\n *\n * @param t - The data to convert into a value object\n * @returns A deeply frozen, immutable value object\n *\n * @example\n * ```typescript\n * const address = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * // address.coordinates.lat = 99; // ❌ Error: Cannot assign to read-only property\n * ```\n */\nexport function vo<T>(t: T): VO<T> {\n return deepFreeze({ ...t });\n}\n\n/**\n * Compares two value objects for equality based on their values.\n * Uses deep equality comparison that handles:\n * - Nested objects and arrays\n * - Primitives (including NaN)\n * - Dates, Maps, Sets, RegExp\n * - TypedArrays and DataView\n * - Symbol keys\n * - Circular references\n *\n * @param a - First value object\n * @param b - Second value object\n * @returns true if both objects have the same values, false otherwise\n *\n * @example\n * ```typescript\n * const money1 = vo({ amount: 100, currency: \"USD\" });\n * const money2 = vo({ amount: 100, currency: \"USD\" });\n * voEquals(money1, money2); // true\n *\n * const address1 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * const address2 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * voEquals(address1, address2); // true\n * ```\n */\nexport function voEquals<T>(a: VO<T>, b: VO<T>): boolean {\n return deepEqual(a, b);\n}\n\n/**\n * Compares two value objects for equality while ignoring specified keys.\n * Useful for comparing value objects that contain metadata or optional fields\n * that should not affect equality comparison.\n *\n * @param a - First value object\n * @param b - Second value object\n * @param options - Options specifying which keys to ignore during comparison\n * @returns true if both objects have the same values (after ignoring specified keys), false otherwise\n *\n * @example\n * ```typescript\n * // Value object with metadata\n * const address1 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-02\" }\n * });\n *\n * const address2 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-03\" }\n * });\n *\n * // Compare ignoring metadata timestamps\n * voEqualsExcept(address1, address2, {\n * ignoreKeys: [\"updatedAt\"],\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n *\n * // Compare ignoring all metadata\n * voEqualsExcept(address1, address2, {\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n * ```\n */\nexport function voEqualsExcept<T>(\n a: VO<T>,\n b: VO<T>,\n options: DeepEqualExceptOptions,\n): boolean {\n return deepEqualExcept(a, b, options);\n}\n\n/**\n * Creates a value object with optional validation.\n * Returns a Result type instead of throwing an error.\n *\n * @param t - The data to convert into a value object\n * @param validate - Validation function that returns true if valid\n * @param errorMessage - Optional custom error message if validation fails\n * @returns Result containing the value object if valid, or an error message if validation fails\n *\n * @example\n * ```typescript\n * const result = voWithValidation(\n * { amount: 100, currency: \"USD\" },\n * (m) => m.amount >= 0 && m.currency.length === 3,\n * \"Invalid money: amount must be non-negative and currency must be 3 characters\"\n * );\n *\n * if (result.ok) {\n * console.log(result.value); // Use the value object\n * } else {\n * console.error(result.error); // Handle validation error\n * }\n * ```\n */\nexport function voWithValidation<T>(\n t: T,\n validate: (value: T) => boolean,\n errorMessage?: string,\n): Result<VO<T>, string> {\n if (!validate(t)) {\n return err(\n errorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n );\n }\n return ok(vo(t));\n}\n\n/**\n * Creates a value object with optional validation.\n * Throws an error if validation fails.\n *\n * @param t - The data to convert into a value object\n * @param validate - Validation function that returns true if valid\n * @param errorMessage - Optional custom error message if validation fails\n * @returns A deeply frozen, immutable value object\n * @throws Error if validation fails\n *\n * @example\n * ```typescript\n * const money = voWithValidationUnsafe(\n * { amount: 100, currency: \"USD\" },\n * (m) => m.amount >= 0 && m.currency.length === 3,\n * \"Invalid money: amount must be non-negative and currency must be 3 characters\"\n * );\n * ```\n */\nexport function voWithValidationUnsafe<T>(\n t: T,\n validate: (value: T) => boolean,\n errorMessage?: string,\n): VO<T> {\n if (!validate(t)) {\n throw new Error(\n errorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n );\n }\n return vo(t);\n}\n\n// ============================================================================\n// Class-based Value Object API\n// ============================================================================\n\n/**\n * Interface for Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport interface IValueObject<T extends object> {\n /**\n * The immutable properties of the value object.\n */\n readonly props: Readonly<T>;\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal\n */\n equals(other: IValueObject<T>): boolean;\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n clone(props?: Partial<T>): IValueObject<T>;\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n toJSON(): Readonly<T>;\n}\n\n/**\n * Abstract base class for creating Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport abstract class ValueObject<T extends object> implements IValueObject<T> {\n public readonly props: Readonly<T>;\n\n /**\n * Creates a new ValueObject.\n * The properties are deeply frozen to ensure immutability.\n *\n * @param props - The properties of the value object\n * @example\n * ```ts\n * class Money extends ValueObject<{ amount: number; currency: string }> {\n * constructor(props: { amount: number; currency: string }) {\n * super(props);\n * }\n *\n * protected validate(props: { amount: number; currency: string }): void {\n * if (props.amount < 0) throw new Error(\"Amount cannot be negative\");\n * }\n * }\n * ```\n */\n constructor(props: T) {\n this.validate(props);\n this.props = deepFreeze({ ...props });\n }\n\n /**\n * Optional validation hook that can be overridden by subclasses.\n * Should throw an error if validation fails.\n *\n * @param props - The properties to validate\n * @throws Error if validation fails\n */\n protected validate(props: T): void {\n // Default implementation does nothing\n }\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties and checks for constructor equality.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal and constructors match\n */\n public equals(other: ValueObject<T>): boolean {\n if (other === null || other === undefined) {\n return false;\n }\n\n if (this.constructor !== other.constructor) {\n return false;\n }\n\n return deepEqual(this.props, other.props);\n }\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n public clone(props?: Partial<T>): this {\n const Constructor = this.constructor as new (props: T) => this;\n return new Constructor({ ...this.props, ...(props || {}) });\n }\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n public toJSON(): Readonly<T> {\n return this.props;\n }\n\n\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/aggregate/domain-event.ts","../src/aggregate/aggregate.ts","../src/utils/array/is-built-in.ts","../src/utils/array/deep-equal.ts","../src/entity/entity.ts","../src/aggregate/aggregate-root.ts","../src/core/result/result.ts","../src/aggregate/event-sourced-aggregate.ts","../src/app/command-bus.ts","../src/app/handler.ts","../src/app/query-bus.ts","../src/core/guard.ts","../src/events/event-bus.ts","../src/utils/array/deep-omit.ts","../src/utils/array/deep-equal-except.ts","../src/value-object/value-object.ts"],"names":["tagA","tagB","len","clone"],"mappings":";;;;AAwGO,SAAS,iBAAA,CACf,IAAA,EACA,OAAA,EACA,OAAA,EAKoB;AACpB,EAAA,OAAO;AAAA,IACN,IAAA;AAAA,IACA,O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IAAA,OAAO,IAAA,CAAK,KAAA;AAAA,EAChB;AAGJ","file":"index.js","sourcesContent":["/**\n * Metadata associated with a domain event for traceability and correlation.\n * Used in event-driven architectures to track event flow across services.\n */\nexport interface EventMetadata {\n\t/**\n\t * Correlation ID for tracing events across multiple services/components.\n\t * Typically used to group related events in a distributed system.\n\t */\n\tcorrelationId?: string;\n\n\t/**\n\t * Causation ID referencing the event or command that caused this event.\n\t * Used to build event chains and understand causality.\n\t */\n\tcausationId?: string;\n\n\t/**\n\t * User ID of the person or system that triggered the event.\n\t */\n\tuserId?: string;\n\n\t/**\n\t * Source service or component that produced the event.\n\t */\n\tsource?: string;\n\n\t/**\n\t * Additional custom metadata fields.\n\t * Allows extensibility for domain-specific metadata.\n\t */\n\t[key: string]: unknown;\n}\n\n/**\n * Domain Event represents something meaningful that happened in the domain.\n * Events are immutable and carry information about what occurred.\n *\n * @template T - The event type name (e.g., \"OrderCreated\")\n * @template P - The event payload type\n */\nexport interface DomainEvent<T extends string, P = void> {\n\t/**\n\t * The type of the event, used for routing and handling.\n\t */\n\ttype: T;\n\n\t/**\n\t * The event payload containing the domain data.\n\t * Omitted when P is void (events without payload).\n\t */\n\tpayload: P;\n\n\t/**\n\t * Timestamp when the event occurred.\n\t */\n\toccurredAt: Date;\n\n\t/**\n\t * Event schema version for handling schema evolution.\n\t * Required for safe schema migration in event-sourced systems.\n\t * Use 1 for the initial schema version.\n\t */\n\tversion: number;\n\n\t/**\n\t * Optional metadata for traceability, correlation, and auditing.\n\t * Includes correlationId, causationId, userId, source, and custom fields.\n\t */\n\tmetadata?: EventMetadata;\n}\n\n/**\n * Creates a domain event with default values.\n * Sets occurredAt to current date and version to 1 if not provided.\n *\n * @param type - The event type\n * @param payload - The event payload\n * @param options - Optional event configuration\n * @returns A domain event\n *\n * @example\n * ```typescript\n * const event = createDomainEvent(\"OrderCreated\", { orderId: \"123\" });\n * ```\n */\nexport function createDomainEvent<T extends string>(\n\ttype: T,\n\tpayload?: undefined,\n\toptions?: {\n\t\toccurredAt?: Date;\n\t\tversion?: number;\n\t\tmetadata?: EventMetadata;\n\t},\n): DomainEvent<T, void>;\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\toptions?: {\n\t\toccurredAt?: Date;\n\t\tversion?: number;\n\t\tmetadata?: EventMetadata;\n\t},\n): DomainEvent<T, P>;\nexport function createDomainEvent<T extends string, P>(\n\ttype: T,\n\tpayload?: P,\n\toptions?: {\n\t\toccurredAt?: Date;\n\t\tversion?: number;\n\t\tmetadata?: EventMetadata;\n\t},\n): DomainEvent<T, P> {\n\treturn {\n\t\ttype,\n\t\tpayload: payload as P,\n\t\toccurredAt: options?.occurredAt ?? new Date(),\n\t\tversion: options?.version ?? 1,\n\t\tmetadata: options?.metadata,\n\t};\n}\n\n/**\n * Creates a domain event with metadata for traceability.\n * Convenience function for creating events with correlation and causation IDs.\n *\n * @example\n * ```typescript\n * const event = createDomainEventWithMetadata(\n * \"OrderCreated\",\n * { orderId: \"123\" },\n * { correlationId: \"corr-123\", causationId: \"cmd-456\", userId: \"user-789\" }\n * );\n * ```\n */\nexport function createDomainEventWithMetadata<T extends string, P>(\n\ttype: T,\n\tpayload: P,\n\tmetadata: EventMetadata,\n\toptions?: {\n\t\toccurredAt?: Date;\n\t\tversion?: number;\n\t},\n): DomainEvent<T, P> {\n\treturn createDomainEvent(type, payload, {\n\t\t...options,\n\t\tmetadata,\n\t});\n}\n\n/**\n * Copies metadata from a source event to a new event.\n * Useful for maintaining correlation chains in event-driven architectures.\n *\n * @example\n * ```typescript\n * const newEvent = createDomainEvent(\n * \"OrderShipped\",\n * { orderId: \"123\" },\n * { metadata: copyMetadata(previousEvent, { causationId: previousEvent.type }) }\n * );\n * ```\n */\nexport function copyMetadata(\n\tsourceEvent: DomainEvent<string, unknown>,\n\tadditionalMetadata?: Partial<EventMetadata>,\n): EventMetadata {\n\treturn {\n\t\t...(sourceEvent.metadata ?? {}),\n\t\t...(additionalMetadata ?? {}),\n\t};\n}\n\n/**\n * Merges multiple metadata objects into one.\n * Later metadata objects override earlier ones for the same keys.\n *\n * @example\n * ```typescript\n * const metadata = mergeMetadata(\n * { correlationId: \"corr-123\" },\n * { userId: \"user-456\" },\n * { source: \"order-service\" }\n * );\n * ```\n */\nexport function mergeMetadata(\n\t...metadataObjects: Array<EventMetadata | undefined>\n): EventMetadata {\n\treturn Object.assign({}, ...metadataObjects.filter(Boolean));\n}\n","import type { Id } from \"../core/id\";\n\n// Re-export domain event types for convenience\nexport * from \"./domain-event\";\n\n// Re-export interfaces from their respective files\nexport type { IAggregateRoot } from \"./aggregate-root\";\nexport type { IEventSourcedAggregate } from \"./event-sourced-aggregate\";\n\n// --- Aggregate types ---\n\nexport type Version = number & { readonly __v: true };\n\n/**\n * Lightweight functional aggregate state — state + version, no event sourcing.\n * This is a data projection, not a full Aggregate (which requires identity via IAggregateRoot).\n *\n * For event sourcing, use the class-based `EventSourcedAggregate` which enforces\n * that state changes happen through event handlers.\n *\n * @template State - The type of the aggregate state\n */\nexport interface AggregateState<State> {\n\tstate: Readonly<State>;\n\tversion: Version;\n}\n\n/**\n * Creates a lightweight functional aggregate state.\n *\n * @example\n * ```typescript\n * const order = aggregate<OrderState>({ status: \"draft\", items: [] });\n * ```\n */\nexport function aggregate<State>(\n\tstate: State,\n\tversion: Version = 0 as Version,\n): AggregateState<State> {\n\treturn { state, version };\n}\n\n/**\n * Bumps the version of a functional aggregate state.\n * Returns a new aggregate state with incremented version.\n */\nexport function bump<S>(\n\tagg: AggregateState<S>,\n): AggregateState<S> {\n\treturn { ...agg, version: (agg.version + 1) as Version };\n}\n\n/**\n * Snapshot of an aggregate state at a specific point in time.\n * Used for optimizing event replay by starting from a snapshot\n * instead of replaying all events from the beginning.\n *\n * @template TState - The type of the aggregate state\n */\nexport interface AggregateSnapshot<TState> {\n\t/**\n\t * The state of the aggregate at the time of the snapshot.\n\t */\n\tstate: TState;\n\n\t/**\n\t * The version of the aggregate when the snapshot was taken.\n\t */\n\tversion: Version;\n\n\t/**\n\t * Timestamp when the snapshot was created.\n\t */\n\tsnapshotAt: Date;\n}\n\n/**\n * Checks if two aggregates are at the same version (same ID and version).\n * Useful for optimistic concurrency control checks.\n *\n * Note: Two aggregates with the same ID ARE the same aggregate (identity).\n * This function checks if they are at the same version — i.e., no concurrent modification.\n *\n * @example\n * ```typescript\n * const before = await repository.getById(id);\n * // ... some operations ...\n * const after = await repository.getById(id);\n *\n * if (!sameVersion(before, after)) {\n * throw new Error(\"Aggregate was modified by another process\");\n * }\n * ```\n */\nexport function sameVersion<TId extends Id<string>>(\n\ta: { id: TId; version: Version },\n\tb: { id: TId; version: Version },\n): boolean {\n\treturn a.id === b.id && a.version === b.version;\n}\n","/**\n * Checks if an object is a built-in JavaScript type that should be treated atomically.\n * This function automatically detects built-ins without requiring manual maintenance.\n *\n * Detection strategy:\n * 1. TypedArrays: Check if tag ends with \"Array]\" (covers all current and future TypedArrays)\n * 2. ArrayBuffer views: Use ArrayBuffer.isView() (covers DataView and all TypedArrays)\n * 3. Built-in constructors: Check if constructor exists in global scope and matches known patterns\n * 4. Tag-based: Fallback to tag matching for known built-ins\n *\n * @param obj - The object to check\n * @param tag - The result of `Object.prototype.toString.call(obj)`\n * @returns `true` if the object is a built-in type, `false` otherwise\n */\nexport function isBuiltInObject(obj: object, tag: string): boolean {\n\t// 1. TypedArrays: all end with \"Array]\" - future-proof for new TypedArrays\n\tif (tag.endsWith(\"Array]\")) {\n\t\treturn true;\n\t}\n\n\t// 2. ArrayBuffer views: covers DataView and all TypedArrays (future-proof)\n\tif (ArrayBuffer.isView(obj)) {\n\t\treturn true;\n\t}\n\n\t// 3. ArrayBuffer and SharedArrayBuffer\n\tif (tag === \"[object ArrayBuffer]\" || tag === \"[object SharedArrayBuffer]\") {\n\t\treturn true;\n\t}\n\n\t// 4. Check if constructor exists in global scope (future-proof for new globals)\n\tconst objConstructor = (obj as { constructor?: unknown }).constructor;\n\tif (objConstructor && typeof objConstructor === \"function\") {\n\t\tconst constructorName = objConstructor.name;\n\t\t// Check if it's a known global constructor\n\t\t// This covers: Date, RegExp, Map, Set, WeakMap, WeakSet, Promise, Error, etc.\n\t\tif (\n\t\t\tconstructorName &&\n\t\t\ttypeof globalThis !== \"undefined\" &&\n\t\t\tconstructorName in globalThis &&\n\t\t\t(globalThis as Record<string, unknown>)[constructorName] === objConstructor\n\t\t) {\n\t\t\t// Additional check: ensure it's not a user-defined class with same name\n\t\t\t// Built-ins typically have non-enumerable properties and specific prototypes\n\t\t\tconst proto = Object.getPrototypeOf(obj);\n\t\t\tif (proto !== Object.prototype && proto !== null) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// 5. Tag-based fallback for known built-ins (covers edge cases)\n\tconst knownBuiltInTags = new Set([\n\t\t\"[object Date]\",\n\t\t\"[object RegExp]\",\n\t\t\"[object Map]\",\n\t\t\"[object Set]\",\n\t\t\"[object WeakMap]\",\n\t\t\"[object WeakSet]\",\n\t\t\"[object Promise]\",\n\t\t\"[object Error]\",\n\t\t\"[object Boolean]\",\n\t\t\"[object Number]\",\n\t\t\"[object String]\",\n\t]);\n\n\treturn knownBuiltInTags.has(tag);\n}\n\n","import { isBuiltInObject } from \"./is-built-in\";\n\nconst objProto = Object.prototype;\nconst objToString = objProto.toString;\nconst objHasOwn = objProto.hasOwnProperty;\n\n/**\n * Performs a deep equality check between two values.\n *\n * This function compares values recursively, handling:\n * - Primitives (with special handling for NaN)\n * - Arrays (nested arrays supported)\n * - Objects (plain objects and class instances)\n * - TypedArrays (Uint8Array, Int32Array, etc.)\n * - DataView\n * - Maps and Sets\n * - Dates and RegExp\n * - Wrapper objects (Boolean, Number, String)\n * - Circular references (detected and handled)\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @returns `true` if the values are deeply equal, `false` otherwise\n *\n * @example\n * ```ts\n * deepEqual([1, 2, 3], [1, 2, 3]); // true\n * deepEqual({ a: 1, b: [2, 3] }, { a: 1, b: [2, 3] }); // true\n * deepEqual(NaN, NaN); // true\n * deepEqual([1, 2], [1, 2, 3]); // false\n * ```\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n\treturn deepEqualInner(a, b, new WeakMap<object, object>());\n}\n\n/**\n * Internal recursive function for deep equality comparison.\n * Tracks visited objects to detect and handle circular references.\n *\n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param visited - WeakMap to track visited object pairs and detect cycles\n * @returns `true` if the values are deeply equal, `false` otherwise\n * @internal\n */\nfunction deepEqualInner(\n\ta: unknown,\n\tb: unknown,\n\tvisited: WeakMap<object, object>\n): boolean {\n\t// 1. Fast path: reference equality\n\tif (a === b) return true;\n\n\tconst typeA = typeof a;\n\tconst typeB = typeof b;\n\n\t// 2. If one is not an object → primitive / function\n\tif (typeA !== \"object\" || a === null || typeB !== \"object\" || b === null) {\n\t\t// Special case: NaN should be equal\n\t\tif (typeA === \"number\" && typeB === \"number\") {\n\t\t\treturn Number.isNaN(a as number) && Number.isNaN(b as number);\n\t\t}\n\t\t// Everything else is directly unequal with !== (including functions)\n\t\treturn false;\n\t}\n\n\t// From here on: both are non-null objects\n\n\tconst objA = a as object;\n\tconst objB = b as object;\n\n\t// 3. Cycles: already seen pair?\n\tconst cached = visited.get(objA);\n\tif (cached !== undefined) {\n\t\t// If we already paired this A with a different B → unequal\n\t\treturn cached === objB;\n\t}\n\tvisited.set(objA, objB);\n\n\t// 4. Handle Typed Arrays / DataView first\n\tif (ArrayBuffer.isView(objA) || ArrayBuffer.isView(objB)) {\n\t\tif (!ArrayBuffer.isView(objA) || !ArrayBuffer.isView(objB)) return false;\n\n\t\tconst tagA = objToString.call(objA);\n\t\tconst tagB = objToString.call(objB);\n\t\tif (tagA !== tagB) return false;\n\n\t\t// DataView: compare byte by byte\n\t\tif (tagA === \"[object DataView]\") {\n\t\t\tconst viewA = objA as DataView;\n\t\t\tconst viewB = objB as DataView;\n\t\t\tif (viewA.byteLength !== viewB.byteLength) return false;\n\n\t\t\tconst len = viewA.byteLength;\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (viewA.getUint8(i) !== viewB.getUint8(i)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t// Typed Arrays: element by element\n\t\tconst arrA = objA as unknown as ArrayLike<unknown>;\n\t\tconst arrB = objB as unknown as ArrayLike<unknown>;\n\n\t\tconst len = arrA.length;\n\t\tif (len !== arrB.length) return false;\n\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tif ((arrA as any)[i] !== (arrB as any)[i]) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// 5. Tag-based type detection (robust across realms)\n\tconst tagA = objToString.call(objA);\n\tconst tagB = objToString.call(objB);\n\tif (tagA !== tagB) return false;\n\n\tswitch (tagA) {\n\t\tcase \"[object Array]\": {\n\t\t\tconst arrA = objA as unknown[];\n\t\t\tconst arrB = objB as unknown[];\n\t\t\tconst len = arrA.length;\n\t\t\tif (len !== arrB.length) return false;\n\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tif (!deepEqualInner(arrA[i], arrB[i], visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Map]\": {\n\t\t\tconst mapA = objA as Map<unknown, unknown>;\n\t\t\tconst mapB = objB as Map<unknown, unknown>;\n\n\t\t\tif (mapA.size !== mapB.size) return false;\n\n\t\t\tfor (const [key, valA] of mapA) {\n\t\t\t\t// Map keys according to JS semantics: reference / SameValueZero\n\t\t\t\tif (!mapB.has(key)) return false;\n\t\t\t\tconst valB = mapB.get(key);\n\t\t\t\tif (!deepEqualInner(valA, valB, visited)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Set]\": {\n\t\t\tconst setA = objA as Set<unknown>;\n\t\t\tconst setB = objB as Set<unknown>;\n\n\t\t\tif (setA.size !== setB.size) return false;\n\n\t\t\t// Set elements: same reference (JS semantics)\n\t\t\tfor (const value of setA) {\n\t\t\t\tif (!setB.has(value)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tcase \"[object Date]\": {\n\t\t\tconst timeA = (objA as Date).getTime();\n\t\t\tconst timeB = (objB as Date).getTime();\n\t\t\treturn timeA === timeB;\n\t\t}\n\n\t\tcase \"[object RegExp]\": {\n\t\t\tconst regA = objA as RegExp;\n\t\t\tconst regB = objB as RegExp;\n\t\t\treturn regA.source === regB.source && regA.flags === regB.flags;\n\t\t}\n\n\t\tcase \"[object Boolean]\":\n\t\tcase \"[object Number]\":\n\t\tcase \"[object String]\": {\n\t\t\t// Wrapper objects (new Boolean/Number/String)\n\t\t\treturn (objA as any).valueOf() === (objB as any).valueOf();\n\t\t}\n\n\t\tdefault: {\n\t\t\t// 6. Check if this is an unhandled built-in type (future-proof)\n\t\t\t// If both are built-ins but not handled above, they should be compared by reference\n\t\t\t// (since we don't know their internal structure)\n\t\t\tif (isBuiltInObject(objA, tagA) && isBuiltInObject(objB, tagB)) {\n\t\t\t\t// Unhandled built-in types: compare by reference as fallback\n\t\t\t\t// This ensures new built-ins don't fall through to plain object comparison\n\t\t\t\treturn objA === objB;\n\t\t\t}\n\n\t\t\t// 7. Fallback: plain / custom objects → compare own enumerable keys + values\n\t\t\tconst stringKeysA = Object.keys(objA as any);\n\t\t\tconst stringKeysB = Object.keys(objB as any);\n\t\t\tconst symbolKeysA = Object.getOwnPropertySymbols(objA as any);\n\t\t\tconst symbolKeysB = Object.getOwnPropertySymbols(objB as any);\n\n\t\t\t// Compare string keys count\n\t\t\tif (stringKeysA.length !== stringKeysB.length) return false;\n\t\t\t// Compare symbol keys count\n\t\t\tif (symbolKeysA.length !== symbolKeysB.length) return false;\n\n\t\t\t// Check all string keys exist in both objects\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!objHasOwn.call(objB, key)) return false;\n\t\t\t}\n\n\t\t\t// Check all symbol keys exist in both objects\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!Object.getOwnPropertySymbols(objB as any).includes(key)) return false;\n\t\t\t}\n\n\t\t\t// Compare string key values\n\t\t\tfor (const key of stringKeysA) {\n\t\t\t\tif (!deepEqualInner((objA as any)[key], (objB as any)[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Compare symbol key values\n\t\t\tfor (const key of symbolKeysA) {\n\t\t\t\tif (!deepEqualInner((objA as any)[key], (objB as any)[key], visited)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n}\n","/**\n * Entity utilities and interfaces for Domain-Driven Design.\n *\n * In Domain-Driven Design, there are two types of entities:\n *\n * 1. **Aggregate Root Entity**: The parent Entity of an aggregate.\n * - Has identity (id), state, and version\n * - Implemented by classes extending `AggregateRoot` or `EventSourcedAggregate`\n * - Represents the aggregate externally\n * - Loaded/saved through repositories\n *\n * 2. **Child Entities**: Entities within an aggregate.\n * - Have identity (id) and state, but no own version\n * - Can extend `EntityBase<TState, TId>` for class-based entities\n * - Or use functional style with `Identifiable<TId> & TProps`\n * - Exist only within the aggregate boundary\n * - Versioned through the Aggregate Root\n * - Cannot be referenced directly from outside the aggregate\n *\n * This module provides:\n * - `EntityBase<TState, TId>` - Base class for entities with state\n * - `Entity<TId>` - Simple class for entities without state management\n * - `Identifiable<TId>` - Minimal interface for objects with id\n * - Helper functions for working with collections of entities\n *\n * @example\n * ```typescript\n * // Class-based child entity with logic\n * class OrderItem extends EntityBase<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n *\n * calculateSubtotal(): number {\n * return this._state.price * this._state.quantity;\n * }\n * }\n *\n * // Functional-style child entity (simpler, no logic)\n * type OrderItem = Identifiable<ItemId> & {\n * productId: string;\n * quantity: number;\n * price: number;\n * };\n *\n * // Aggregate Root (Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * // Order is an Aggregate Root Entity\n * // OrderState contains OrderItem child entities\n * }\n * ```\n */\nimport { deepEqual } from \"../utils/array/deep-equal\";\n\nimport type { Id } from \"../core/id\";\n\n/**\n * Functional definition of an Entity via its capability.\n * An object is identifiable if it has an id.\n */\nexport type Identifiable<TId> = {\n\treadonly id: TId;\n};\n\n/**\n * Interface for Entities with state.\n *\n * In Domain-Driven Design, Entities have:\n * - Identity (id): Distinguishes one entity from another\n * - State: The attributes/properties of the entity\n *\n * Unlike Value Objects (which are immutable and compared by value),\n * Entities are compared by identity and can have mutable state.\n *\n * @template TId - The type of the entity identifier\n * @template TState - The type of the entity state\n */\nexport interface IEntity<TId extends Id<string>, TState> extends Identifiable<TId> {\n\t/**\n\t * Unique identifier of the entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * The current state of the entity.\n\t */\n\treadonly state: TState;\n}\n\n/**\n * Abstract base class for Entities with state.\n *\n * Provides:\n * - Identity management (id)\n * - State management\n * - State validation hook\n * - Immutable state access through getter\n *\n * This is the foundation for all Entities in DDD:\n * - Child Entities within aggregates can extend this\n * - Aggregate Roots extend this and add version + events\n *\n * @template TState - The type of the entity state\n * @template TId - The type of the entity identifier\n *\n * @example\n * ```typescript\n * // Child Entity within an aggregate\n * class OrderItem extends Entity<OrderItemState, ItemId> {\n * constructor(id: ItemId, initialState: OrderItemState) {\n * super(id, initialState);\n * }\n *\n * updateQuantity(quantity: number): void {\n * this._state = { ...this._state, quantity };\n * }\n * }\n * ```\n */\nexport abstract class Entity<TState, TId extends Id<string>>\n\timplements IEntity<TId, TState> {\n\tpublic readonly id: TId;\n\n\t/**\n\t * Returns the current state of the entity.\n\t * State is readonly from outside to enforce encapsulation.\n\t */\n\tpublic get state(): TState {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * The state is 'protected' so that only the subclass can modify it.\n\t * Subclasses can mutate this directly or use helper methods.\n\t */\n\tprotected _state: TState;\n\n\tprotected constructor(id: TId, initialState: TState) {\n\t\tif (id === null || id === undefined) {\n\t\t\tthrow new Error(\"Entity ID cannot be null or undefined\");\n\t\t}\n\t\tthis.id = id;\n\t\tthis._state = initialState;\n\t\tthis.validateState(this._state);\n\t}\n\n\t/**\n\t * Optional validation hook to ensure state invariants.\n\t * Called during construction and whenever helpful.\n\t * Override this method to implement validation logic.\n\t *\n\t * @param state - The state to validate\n\t * @throws Error if validation fails\n\t */\n\tprotected validateState(_state: TState): void {\n\t\t// Default implementation does nothing\n\t}\n\n\t/**\n\t * Sets the state of the entity.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t *\n\t * @param newState - The new state\n\t */\n\tprotected setState(newState: TState): void {\n\t\tthis.validateState(newState);\n\t\tthis._state = newState;\n\t}\n}\n\n\n/**\n * Checks if two entities have the same ID.\n * Works with any object that has an 'id' property.\n *\n * @param a - First entity\n * @param b - Second entity\n * @returns true if both entities have the same ID, false otherwise\n *\n * @example\n * ```typescript\n * const item1: OrderItem = { id: itemId1, productId: \"prod-1\", quantity: 2 };\n * const item2: OrderItem = { id: itemId2, productId: \"prod-2\", quantity: 1 };\n *\n * sameEntity(item1, item2); // false\n * sameEntity(item1, item1); // true\n * ```\n */\nexport function sameEntity<TId>(a: Identifiable<TId>, b: Identifiable<TId>): boolean {\n\treturn deepEqual(a.id, b.id);\n}\n\n/**\n * Finds an entity by ID in a collection.\n * Returns undefined if not found.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to search for\n * @returns The entity if found, undefined otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const item = findEntityById(items, itemId1);\n * // item is { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ```\n */\nexport function findEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T | undefined {\n\treturn entities.find((entity) => deepEqual(entity.id, id));\n}\n\n/**\n * Checks if an entity with the given ID exists in the collection.\n *\n * @param entities - Array of entities to search\n * @param id - The ID to check for\n * @returns true if an entity with the ID exists, false otherwise\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * hasEntityId(items, itemId1); // true\n * hasEntityId(items, itemId2); // false\n * ```\n */\nexport function hasEntityId<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): boolean {\n\treturn entities.some((entity) => deepEqual(entity.id, id));\n}\n\n/**\n * Removes an entity with the given ID from the collection.\n * Returns a new array without the entity.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to remove\n * @returns A new array without the entity with the given ID\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const updated = removeEntityById(items, itemId1);\n * // updated is [{ id: itemId2, productId: \"prod-2\", quantity: 1 }]\n * ```\n */\nexport function removeEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n): T[] {\n\treturn entities.filter((entity) => !deepEqual(entity.id, id));\n}\n\n/**\n * Updates an entity with the given ID in the collection.\n * Returns a new array with the updated entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to update\n * @param updater - Function that takes the entity and returns the updated entity\n * @returns A new array with the updated entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = updateEntityById(items, itemId1, (item) => ({\n * ...item,\n * quantity: item.quantity + 1\n * }));\n * // updated is [{ id: itemId1, productId: \"prod-1\", quantity: 3 }]\n * ```\n */\nexport function updateEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\tupdater: (entity: T) => T,\n): T[] {\n\treturn entities.map((entity) => (deepEqual(entity.id, id) ? updater(entity) : entity));\n}\n\n/**\n * Replaces an entity with the given ID in the collection.\n * Returns a new array with the replaced entity.\n * If the entity is not found, returns the original array unchanged.\n *\n * @param entities - Array of entities\n * @param id - The ID of the entity to replace\n * @param replacement - The replacement entity\n * @returns A new array with the replaced entity\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 }\n * ];\n *\n * const updated = replaceEntityById(items, itemId1, {\n * id: itemId1,\n * productId: \"prod-1\",\n * quantity: 5\n * });\n * ```\n */\nexport function replaceEntityById<TId, T extends Identifiable<TId>>(\n\tentities: T[],\n\tid: TId,\n\treplacement: T,\n): T[] {\n\treturn entities.map((entity) => (deepEqual(entity.id, id) ? replacement : entity));\n}\n\n/**\n * Extracts all IDs from a collection of entities.\n *\n * @param entities - Array of entities\n * @returns Array of entity IDs\n *\n * @example\n * ```typescript\n * const items: OrderItem[] = [\n * { id: itemId1, productId: \"prod-1\", quantity: 2 },\n * { id: itemId2, productId: \"prod-2\", quantity: 1 }\n * ];\n *\n * const ids = entityIds(items);\n * // ids is [itemId1, itemId2]\n * ```\n */\nexport function entityIds<TId, T extends Identifiable<TId>>(entities: T[]): TId[] {\n\treturn entities.map((entity) => entity.id);\n}\n\n","import type { Id } from \"../core/id\";\nimport { Entity } from \"../entity/entity\";\nimport type {\n\tAggregateSnapshot,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Marker interface for Aggregate Roots.\n *\n * In Domain-Driven Design, an Aggregate Root is an Entity (the parent Entity of the aggregate).\n * It represents the aggregate externally and is the only object that external code\n * is allowed to hold references to. All access to child entities within the aggregate\n * must go through the Aggregate Root.\n *\n * An Aggregate consists of:\n * - One Aggregate Root (Entity with id + version)\n * - Optional child entities (Entities with id + state, but no own version)\n * - Optional value objects\n *\n * The Aggregate Root has identity (id), state, and version for optimistic concurrency control.\n * Child entities exist only within the aggregate boundary and are versioned through\n * the Aggregate Root.\n *\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * class Order extends AggregateRoot<OrderState, OrderId> implements IAggregateRoot<OrderId> {\n * // Order is an Aggregate Root (an Entity with version)\n * // OrderState contains child entities (e.g., OrderItem) and value objects\n * }\n * ```\n */\nexport interface IAggregateRoot<TId extends Id<string>> {\n\t/**\n\t * Unique identifier of the aggregate root entity.\n\t */\n\treadonly id: TId;\n\n\t/**\n\t * Version number for optimistic concurrency control.\n\t * Incremented on each state change to detect concurrent modifications.\n\t * This version applies to the entire aggregate, including all child entities.\n\t */\n\treadonly version: Version;\n}\n\n/**\n * Configuration options for AggregateRoot behavior.\n */\nexport interface AggregateConfig {\n\t/**\n\t * Whether to automatically bump the version when state changes.\n\t * Defaults to false. Set to true for automatic versioning.\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for Aggregate Roots without Event Sourcing.\n *\n * In DDD (Evans), an Aggregate is a cluster of objects — root entity, child entities,\n * and value objects — treated as a unit for consistency. The **Aggregate Root** is the\n * root entity that represents the aggregate externally and is the only entry point\n * for external code. This class serves as both: it IS the root entity and it contains\n * the aggregate state (`TState`) which holds child entities and value objects.\n *\n * Provides:\n * - Identity (id) and state management (via `Entity`)\n * - Version management for optimistic concurrency control\n * - Domain event tracking for side-effects\n * - Snapshot support for performance optimization\n *\n * All changes to child entities within `TState` are versioned through this root.\n * Use `setState()` for state mutations to ensure invariant validation.\n *\n * For event sourcing, use `EventSourcedAggregate` instead.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The type of domain events recorded by this aggregate (defaults to unknown)\n *\n * @example\n * ```typescript\n * // Order is an Aggregate Root (an Entity with version)\n * class Order extends AggregateRoot<OrderState, OrderId> {\n * constructor(id: OrderId, initialState: OrderState) {\n * super(id, initialState);\n * }\n *\n * confirm(): void {\n * this.setState({ ...this.state, status: \"confirmed\" }, true);\n * }\n * }\n * ```\n */\nexport abstract class AggregateRoot<TState, TId extends Id<string>, TEvent = unknown>\n\textends Entity<TState, TId>\n\timplements IAggregateRoot<TId> {\n\tprivate _version: Version = 0 as Version;\n\n\tpublic get version(): Version {\n\t\treturn this._version;\n\t}\n\n\tprotected setVersion(version: Version): void {\n\t\tthis._version = version;\n\t}\n\n\tprivate readonly _config: AggregateConfig;\n\tprivate readonly _autoVersionBump: boolean;\n\tprivate _domainEvents: TEvent[] = [];\n\n\t/**\n\t * Returns a read-only list of domain events recorded by this aggregate.\n\t * These events are side-effects of state changes.\n\t */\n\tpublic get domainEvents(): ReadonlyArray<TEvent> {\n\t\treturn this._domainEvents;\n\t}\n\n\t/**\n\t * Clears the list of recorded domain events.\n\t * Call this after dispatching the events.\n\t */\n\tpublic clearDomainEvents(): void {\n\t\tthis._domainEvents = [];\n\t}\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: AggregateConfig,\n\t) {\n\t\tsuper(id, initialState);\n\t\tthis._config = config ?? {};\n\t\tthis._autoVersionBump = this._config.autoVersionBump ?? false;\n\t}\n\n\t/**\n\t * Adds a domain event to the aggregate's list of changes.\n\t * Use this to record side-effects that should be published.\n\t *\n\t * @param event - The domain event to add\n\t */\n\tprotected addDomainEvent(event: TEvent): void {\n\t\tthis._domainEvents.push(event);\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Call this after state changes for Optimistic Concurrency Control.\n\t *\n\t * If `autoVersionBump` is enabled, this is called automatically\n\t * when using `setState()`.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.setVersion((this._version + 1) as Version);\n\t}\n\n\t/**\n\t * Sets the state and optionally bumps the version automatically.\n\t * This is a convenience method for state mutations.\n\t * Automatically validates the newState using `validateState()`.\n\t * Overrides Entity.setState to add version bumping.\n\t *\n\t * @param newState - The new state\n\t * @param bumpVersion - Whether to bump the version (defaults to autoVersionBump config)\n\t */\n\tprotected setState(\n\t\tnewState: TState,\n\t\tbumpVersion?: boolean,\n\t): void {\n\t\tsuper.setState(newState);\n\t\tconst shouldBump = bumpVersion ?? this._autoVersionBump;\n\t\tif (shouldBump) {\n\t\t\tthis.bumpVersion();\n\t\t}\n\t}\n\n\t/**\n\t * Creates a snapshot of the current aggregate state.\n\t * Useful for performance optimization, backup/restore, and audit trails.\n\t *\n\t * @returns A snapshot containing the current state and version\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = aggregate.createSnapshot();\n\t * await snapshotRepository.save(aggregate.id, snapshot);\n\t * ```\n\t */\n\tpublic createSnapshot(): AggregateSnapshot<TState> {\n\t\treturn {\n\t\t\tstate: structuredClone(this._state),\n\t\t\tversion: this.version,\n\t\t\tsnapshotAt: new Date(),\n\t\t};\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot.\n\t * This is useful for loading aggregates from snapshots instead of\n\t * rebuilding them from scratch.\n\t * Validates the restored state.\n\t *\n\t * @param snapshot - The snapshot to restore from\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = await snapshotRepository.getLatest(aggregateId);\n\t * aggregate.restoreFromSnapshot(snapshot);\n\t * ```\n\t */\n\tpublic restoreFromSnapshot(snapshot: AggregateSnapshot<TState>): void {\n\t\tthis.validateState(snapshot.state);\n\t\tthis._state = snapshot.state;\n\t\tthis.setVersion(snapshot.version);\n\t}\n}\n","export type Ok<T> = { ok: true; value: T };\nexport type Err<E> = { ok: false; error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/**\n * Creates an Ok result with a value.\n *\n * @param value - The success value\n * @returns An Ok result containing the value\n *\n * @example\n * ```typescript\n * const result = ok(42);\n * // result is Ok<number>\n * ```\n */\nexport function ok<T>(value: T): Ok<T>;\n\n/**\n * Creates an Ok result with void (no value).\n *\n * @returns An Ok<void> result\n *\n * @example\n * ```typescript\n * const result = ok();\n * // result is Ok<void>\n * ```\n */\nexport function ok(): Ok<void>;\n\nexport function ok<T>(value?: T): Ok<T> {\n\treturn { ok: true, value: value as T };\n}\n\n/**\n * Creates an Err result with an error.\n *\n * @param error - The error value\n * @returns An Err result containing the error\n *\n * @example\n * ```typescript\n * const result = err(\"Something went wrong\");\n * // result is Err<string>\n * ```\n */\nexport function err<E>(error: E): Err<E>;\n\n/**\n * Creates an Err result with void (no error value).\n *\n * @returns An Err<void> result\n *\n * @example\n * ```typescript\n * const result = err();\n * // result is Err<void>\n * ```\n */\nexport function err(): Err<void>;\n\nexport function err<E>(error?: E): Err<E> {\n\treturn { ok: false, error: error as E };\n}\n\n/**\n * Type guard to check if a Result is Ok.\n * Narrows the type to Ok<T> when returning true.\n *\n * @param result - The result to check\n * @returns true if the result is Ok, false otherwise\n *\n * @example\n * ```typescript\n * const result = voWithValidation(data, validator);\n * if (isOk(result)) {\n * // TypeScript knows result is Ok<VO<T>>\n * console.log(result.value);\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is Ok<T> {\n\treturn result.ok === true;\n}\n\n/**\n * Type guard to check if a Result is Err.\n * Narrows the type to Err<E> when returning true.\n *\n * @param result - The result to check\n * @returns true if the result is Err, false otherwise\n *\n * @example\n * ```typescript\n * const result = voWithValidation(data, validator);\n * if (isErr(result)) {\n * // TypeScript knows result is Err<string>\n * console.error(result.error);\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is Err<E> {\n\treturn result.ok === false;\n}\n\n/**\n * Chains Result operations (flatMap/bind).\n * If the result is Ok, applies the function to the value.\n * If Err, returns the error unchanged.\n *\n * @param result - The result to chain\n * @param fn - Function that takes the Ok value and returns a new Result\n * @returns A new Result\n *\n * @example\n * ```typescript\n * const result = validateUserId(\"123\")\n * .andThen(userId => validateEmail(\"test@example.com\")\n * .map(email => ({ id: userId, email }))\n * );\n * ```\n */\nexport function andThen<T, E, U>(\n\tresult: Result<T, E>,\n\tfn: (value: T) => Result<U, E>,\n): Result<U, E> {\n\tif (result.ok) {\n\t\treturn fn(result.value);\n\t}\n\treturn result;\n}\n\n/**\n * Transforms the Ok value using a function.\n * If the result is Err, returns the error unchanged.\n *\n * @param result - The result to transform\n * @param fn - Function to transform the Ok value\n * @returns A new Result with transformed value\n *\n * @example\n * ```typescript\n * const result = ok(5);\n * const doubled = map(result, x => x * 2); // Ok<10>\n * ```\n */\nexport function map<T, E, U>(\n\tresult: Result<T, E>,\n\tfn: (value: T) => U,\n): Result<U, E> {\n\tif (result.ok) {\n\t\treturn ok(fn(result.value));\n\t}\n\treturn result;\n}\n\n/**\n * Transforms the Err value using a function.\n * If the result is Ok, returns the value unchanged.\n *\n * @param result - The result to transform\n * @param fn - Function to transform the Err value\n * @returns A new Result with transformed error\n *\n * @example\n * ```typescript\n * const result = err(\"not found\");\n * const mapped = mapErr(result, e => `Error: ${e}`); // Err<\"Error: not found\">\n * ```\n */\nexport function mapErr<T, E, F>(\n\tresult: Result<T, E>,\n\tfn: (error: E) => F,\n): Result<T, F> {\n\tif (result.ok) {\n\t\treturn result;\n\t}\n\treturn err(fn(result.error));\n}\n\n/**\n * Returns the value if Ok, otherwise returns the default value.\n *\n * @param result - The result to unwrap\n * @param defaultValue - Default value to return if Err\n * @returns The Ok value or the default value\n *\n * @example\n * ```typescript\n * const result = validateUserId(\"123\");\n * const userId = unwrapOr(result, \"default-id\");\n * ```\n */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n\treturn result.ok ? result.value : defaultValue;\n}\n\n/**\n * Returns the value if Ok, otherwise computes default from error.\n *\n * @param result - The result to unwrap\n * @param fn - Function to compute default from error\n * @returns The Ok value or computed default\n *\n * @example\n * ```typescript\n * const result = validateUserId(\"\");\n * const userId = unwrapOrElse(result, err => `fallback-${Date.now()}`);\n * ```\n */\nexport function unwrapOrElse<T, E>(\n\tresult: Result<T, E>,\n\tfn: (error: E) => T,\n): T {\n\treturn result.ok ? result.value : fn(result.error);\n}\n\n/**\n * Pattern matching for Result.\n * Applies one function if Ok, another if Err.\n *\n * @param result - The result to match\n * @param onOk - Function to apply if Ok\n * @param onErr - Function to apply if Err\n * @returns The result of applying the appropriate function\n *\n * @example\n * ```typescript\n * const message = match(result,\n * value => `Success: ${value}`,\n * error => `Error: ${error}`\n * );\n * ```\n *\n * @example Using object syntax\n * ```typescript\n * const message = match(result, {\n * ok: value => `Success: ${value}`,\n * err: error => `Error: ${error}`\n * });\n * ```\n */\nexport function match<T, E, R>(\n\tresult: Result<T, E>,\n\tonOk: (value: T) => R,\n\tonErr: (error: E) => R,\n): R;\nexport function match<T, E, R>(\n\tresult: Result<T, E>,\n\thandlers: { ok: (value: T) => R; err: (error: E) => R },\n): R;\nexport function match<T, E, R>(\n\tresult: Result<T, E>,\n\tonOkOrHandlers: ((value: T) => R) | { ok: (value: T) => R; err: (error: E) => R },\n\tonErr?: (error: E) => R,\n): R {\n\tif (typeof onOkOrHandlers === \"function\") {\n\t\t// Function syntax: match(result, onOk, onErr)\n\t\treturn result.ok ? onOkOrHandlers(result.value) : onErr!(result.error);\n\t}\n\t// Object syntax: match(result, { ok: ..., err: ... })\n\treturn result.ok\n\t\t? onOkOrHandlers.ok(result.value)\n\t\t: onOkOrHandlers.err(result.error);\n}\n\n/**\n * Async pattern matching for Result.\n * Applies one async function if Ok, another if Err.\n * Both handlers must return Promises.\n *\n * @param result - The result to match\n * @param onOk - Async function to apply if Ok\n * @param onErr - Async function to apply if Err\n * @returns Promise resolving to the result of applying the appropriate function\n *\n * @example\n * ```typescript\n * const message = await matchAsync(result,\n * async (value) => `Success: ${value}`,\n * async (error) => `Error: ${error}`\n * );\n * ```\n *\n * @example Using object syntax\n * ```typescript\n * const message = await matchAsync(result, {\n * ok: async (value) => `Success: ${value}`,\n * err: async (error) => `Error: ${error}`\n * });\n * ```\n */\nexport async function matchAsync<T, E, R>(\n\tresult: Result<T, E>,\n\tonOk: (value: T) => Promise<R>,\n\tonErr: (error: E) => Promise<R>,\n): Promise<R>;\nexport async function matchAsync<T, E, R>(\n\tresult: Result<T, E>,\n\thandlers: { ok: (value: T) => Promise<R>; err: (error: E) => Promise<R> },\n): Promise<R>;\nexport async function matchAsync<T, E, R>(\n\tresult: Result<T, E>,\n\tonOkOrHandlers:\n\t\t| ((value: T) => Promise<R>)\n\t\t| { ok: (value: T) => Promise<R>; err: (error: E) => Promise<R> },\n\tonErr?: (error: E) => Promise<R>,\n): Promise<R> {\n\tif (typeof onOkOrHandlers === \"function\") {\n\t\t// Function syntax: matchAsync(result, onOk, onErr)\n\t\treturn result.ok\n\t\t\t? onOkOrHandlers(result.value)\n\t\t\t: onErr!(result.error);\n\t}\n\t// Object syntax: matchAsync(result, { ok: ..., err: ... })\n\treturn result.ok\n\t\t? onOkOrHandlers.ok(result.value)\n\t\t: onOkOrHandlers.err(result.error);\n}\n\n/**\n * Pattern matching for Result that returns a Result.\n * Both handlers must return a Result, allowing you to transform\n * both the success and error cases while staying in Result context.\n *\n * @param result - The result to match\n * @param handlers - Object with ok and err handlers, both returning Result\n * @returns A new Result from the appropriate handler\n *\n * @example\n * ```typescript\n * const result = await fetchUser(id);\n * return matchResult(result, {\n * ok: (user) => ok(transformUser(user)),\n * err: (error) => err(mapToAppError(error))\n * });\n * ```\n */\nexport function matchResult<T, E, U, F>(\n\tresult: Result<T, E>,\n\thandlers: {\n\t\tok: (value: T) => Result<U, F>;\n\t\terr: (error: E) => Result<U, F>;\n\t},\n): Result<U, F>;\nexport function matchResult<T, E, U, F>(\n\tresult: Result<T, E>,\n\tonOk: (value: T) => Result<U, F>,\n\tonErr: (error: E) => Result<U, F>,\n): Result<U, F>;\nexport function matchResult<T, E, U, F>(\n\tresult: Result<T, E>,\n\tonOkOrHandlers:\n\t\t| ((value: T) => Result<U, F>)\n\t\t| { ok: (value: T) => Result<U, F>; err: (error: E) => Result<U, F> },\n\tonErr?: (error: E) => Result<U, F>,\n): Result<U, F> {\n\tif (typeof onOkOrHandlers === \"function\") {\n\t\treturn result.ok ? onOkOrHandlers(result.value) : onErr!(result.error);\n\t}\n\treturn result.ok\n\t\t? onOkOrHandlers.ok(result.value)\n\t\t: onOkOrHandlers.err(result.error);\n}\n\n/**\n * Pipes a Result through multiple operations.\n * Each function receives the previous Result and returns a new Result.\n * Stops on first error.\n *\n * @param initial - The initial Result value\n * @param fns - Array of functions that take the previous Result and return a new Result\n * @returns The final Result after all operations\n *\n * @example\n * ```typescript\n * // Instead of nested andThen calls:\n * andThen(\n * updateCountryCode(code),\n * () => andThen(updateCurrencyCode(currency), () => updateLanguageCode(lang))\n * )\n *\n * // Use pipe (cleaner and more readable):\n * pipe(\n * updateCountryCode(code),\n * () => updateCurrencyCode(currency),\n * () => updateLanguageCode(lang)\n * )\n * ```\n *\n * @example With void results\n * ```typescript\n * setInitialData(initialData: JobConfigProps[\"initialData\"]): Result<void, JobDomainError> {\n * return pipe(\n * this.updateCountryCode(initialData.countryCode),\n * () => this.updateCurrencyCode(initialData.currencyCode),\n * () => this.updateLanguageCode(initialData.languageCode)\n * );\n * }\n * ```\n */\nexport function pipe<T, E>(\n\tinitial: Result<T, E>,\n\t...fns: Array<(prev: Result<T, E>) => Result<T, E>>\n): Result<T, E> {\n\tlet current = initial;\n\tfor (const fn of fns) {\n\t\tcurrent = fn(current);\n\t\tif (!current.ok) {\n\t\t\treturn current;\n\t\t}\n\t}\n\treturn current;\n}\n\n/**\n * Wraps a function that may throw exceptions into a Result type.\n * Catches any thrown exceptions and converts them to Err results.\n *\n * @param fn - Function that may throw exceptions\n * @param errorMapper - Optional function to transform the caught error\n * @returns A Result containing the function's return value or error\n *\n * @example\n * ```typescript\n * function riskyOperation(): string {\n * if (Math.random() > 0.5) {\n * throw new Error(\"Something went wrong\");\n * }\n * return \"success\";\n * }\n *\n * const result = tryCatch(() => riskyOperation());\n * if (result.ok) {\n * console.log(result.value); // \"success\"\n * } else {\n * console.error(result.error.message); // \"Something went wrong\"\n * }\n * ```\n *\n * @example With custom error mapper\n * ```typescript\n * const result = tryCatch(\n * () => riskyOperation(),\n * (error) => `Custom: ${error instanceof Error ? error.message : String(error)}`\n * );\n * ```\n */\nexport function tryCatch<T, E = Error>(\n\tfn: () => T,\n\terrorMapper?: (error: unknown) => E,\n): Result<T, E> {\n\ttry {\n\t\treturn ok(fn());\n\t} catch (error) {\n\t\tif (errorMapper) {\n\t\t\treturn err(errorMapper(error));\n\t\t}\n\t\treturn err((error instanceof Error ? error : new Error(String(error))) as E);\n\t}\n}\n\n/**\n * Wraps an async function that may throw exceptions into a Promise<Result>.\n * Catches any thrown exceptions and converts them to Err results.\n *\n * @param fn - Async function that may throw exceptions\n * @param errorMapper - Optional function to transform the caught error\n * @returns A Promise resolving to a Result containing the function's return value or error\n *\n * @example\n * ```typescript\n * async function riskyAsyncOperation(): Promise<string> {\n * if (Math.random() > 0.5) {\n * throw new Error(\"Something went wrong\");\n * }\n * return \"success\";\n * }\n *\n * const result = await tryCatchAsync(() => riskyAsyncOperation());\n * if (result.ok) {\n * console.log(result.value); // \"success\"\n * } else {\n * console.error(result.error.message); // \"Something went wrong\"\n * }\n * ```\n */\nexport async function tryCatchAsync<T, E = Error>(\n\tfn: () => Promise<T>,\n\terrorMapper?: (error: unknown) => E,\n): Promise<Result<T, E>> {\n\ttry {\n\t\tconst value = await fn();\n\t\treturn ok(value);\n\t} catch (error) {\n\t\tif (errorMapper) {\n\t\t\treturn err(errorMapper(error));\n\t\t}\n\t\treturn err((error instanceof Error ? error : new Error(String(error))) as E);\n\t}\n}\n\n","import { err, ok, type Result } from \"../core/result\";\nimport type { Id } from \"../core/id\";\nimport { Entity } from \"../entity/entity\";\nimport type { IAggregateRoot } from \"./aggregate-root\";\nimport type { DomainEvent } from \"./domain-event\";\nimport type {\n\tAggregateSnapshot,\n\tVersion,\n} from \"./aggregate\";\n\n/**\n * Interface for Event-Sourced Aggregate Roots.\n * Defines the contract for aggregates that manage state changes via event sourcing.\n *\n * @template TId - The type of the aggregate root identifier\n * @template TEvent - The union type of all domain events\n */\nexport interface IEventSourcedAggregate<\n\tTId extends Id<string>,\n\tTEvent extends DomainEvent<string, unknown>,\n> extends IAggregateRoot<TId> {\n\t/**\n\t * Returns a read-only list of new, not-yet-persisted events.\n\t */\n\treadonly pendingEvents: ReadonlyArray<TEvent>;\n\n\t/**\n\t * Reconstitutes the aggregate from an event history.\n\t *\n\t * @param history - An ordered list of past events\n\t */\n\tloadFromHistory(history: TEvent[]): Result<void, string>;\n\n\t/**\n\t * Clears the list of pending events.\n\t */\n\tclearPendingEvents(): void;\n\n\t/**\n\t * Checks if the aggregate has any pending events.\n\t */\n\thasPendingEvents(): boolean;\n\n\t/**\n\t * Returns the number of pending events.\n\t */\n\tgetEventCount(): number;\n\n\t/**\n\t * Returns the latest pending event, if any.\n\t */\n\tgetLatestEvent(): TEvent | undefined;\n}\n\ntype Handler<TState, TEvent> = (state: TState, event: TEvent) => TState;\n\n/**\n * Configuration options for EventSourcedAggregate behavior.\n */\nexport interface EventSourcedAggregateConfig {\n\t/**\n\t * Whether to automatically bump the version when applying new events.\n\t * Defaults to true. Set to false to manually control versioning.\n\t */\n\tautoVersionBump?: boolean;\n}\n\n/**\n * Base class for Event-Sourced Aggregate Roots (Vernon, IDDD Chapter 8).\n *\n * Like `AggregateRoot`, this is both the root entity and the aggregate boundary.\n * The difference is persistence: state is derived from events, not stored directly.\n * Events are the single source of truth — all state changes go through `apply()` → handler.\n *\n * Extends `Entity` directly (not `AggregateRoot`) so that `setState()` and\n * `addDomainEvent()` are not available. This enforces the event sourcing pattern\n * at the type level — there is no way to mutate state without going through an event handler.\n *\n * @template TState - The type of the aggregate state (contains child entities and value objects)\n * @template TEvent - The union type of all domain events\n * @template TId - The type of the aggregate root identifier\n *\n * @example\n * ```typescript\n * class Order extends EventSourcedAggregate<OrderState, OrderEvent, OrderId> {\n * confirm(): void {\n * this.apply(createDomainEvent(\"OrderConfirmed\", {}));\n * }\n *\n * protected readonly handlers = {\n * OrderConfirmed: (state: OrderState): OrderState => ({\n * ...state,\n * status: \"confirmed\",\n * }),\n * };\n * }\n * ```\n */\nexport abstract class EventSourcedAggregate<\n\tTState,\n\tTEvent extends DomainEvent<string, unknown>,\n\tTId extends Id<string>,\n> extends Entity<TState, TId>\n\timplements IEventSourcedAggregate<TId, TEvent> {\n\n\t// --- Version management (own, not inherited from AggregateRoot) ---\n\n\tprivate _version: Version = 0 as Version;\n\n\tpublic get version(): Version {\n\t\treturn this._version;\n\t}\n\n\tprivate setVersion(version: Version): void {\n\t\tthis._version = version;\n\t}\n\n\t// --- Event tracking ---\n\n\tprivate _pendingEvents: TEvent[] = [];\n\tprivate readonly _autoVersionBump: boolean;\n\n\tpublic get pendingEvents(): ReadonlyArray<TEvent> {\n\t\treturn this._pendingEvents;\n\t}\n\n\tpublic clearPendingEvents(): void {\n\t\tthis._pendingEvents = [];\n\t}\n\n\tprotected constructor(\n\t\tid: TId,\n\t\tinitialState: TState,\n\t\tconfig?: EventSourcedAggregateConfig,\n\t) {\n\t\tsuper(id, initialState);\n\t\tthis._autoVersionBump = config?.autoVersionBump ?? true;\n\t}\n\n\t// --- Event application ---\n\n\t/**\n\t * Validates an event before it is applied.\n\t * Override this method to add custom validation logic.\n\t * Return `ok(true)` if the event is valid, `err(message)` otherwise.\n\t */\n\tprotected validateEvent(_event: TEvent): Result<true, string> {\n\t\treturn ok(true);\n\t}\n\n\t/**\n\t * Applies an event to change the state and adds it to pending events.\n\t * Returns a Result type instead of throwing an error.\n\t *\n\t * @param event - The domain event to apply\n\t * @param isNew - Whether the event is new (needs persisting) or from history replay\n\t */\n\tprotected apply(event: TEvent, isNew = true): Result<void, string> {\n\t\tconst validation = this.validateEvent(event);\n\t\tif (!validation.ok) {\n\t\t\treturn err(\n\t\t\t\t`Event validation failed for ${event.type}: ${validation.error}`,\n\t\t\t);\n\t\t}\n\n\t\tconst handler = this.handlers[event.type as keyof typeof this.handlers];\n\t\tif (!handler) {\n\t\t\treturn err(`Missing handler for event type: ${event.type}`);\n\t\t}\n\n\t\tthis._state = handler(\n\t\t\tthis._state,\n\t\t\tevent as Extract<TEvent, { type: TEvent[\"type\"] }>,\n\t\t);\n\n\t\tif (isNew) {\n\t\t\tthis._pendingEvents.push(event);\n\t\t\tif (this._autoVersionBump) {\n\t\t\t\tthis.setVersion((this._version + 1) as Version);\n\t\t\t}\n\t\t}\n\n\t\treturn ok();\n\t}\n\n\t/**\n\t * Applies an event to change the state and adds it to pending events.\n\t * Throws an error if validation fails or handler is missing.\n\t */\n\tprotected applyUnsafe(event: TEvent, isNew = true): void {\n\t\tconst validation = this.validateEvent(event);\n\t\tif (!validation.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Event validation failed for ${event.type}: ${validation.error}`,\n\t\t\t);\n\t\t}\n\n\t\tconst handler = this.handlers[event.type as keyof typeof this.handlers];\n\t\tif (!handler) {\n\t\t\tthrow new Error(`Missing handler for event type: ${event.type}`);\n\t\t}\n\n\t\tthis._state = handler(\n\t\t\tthis._state,\n\t\t\tevent as Extract<TEvent, { type: TEvent[\"type\"] }>,\n\t\t);\n\n\t\tif (isNew) {\n\t\t\tthis._pendingEvents.push(event);\n\t\t\tif (this._autoVersionBump) {\n\t\t\t\tthis.setVersion((this._version + 1) as Version);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Manually bumps the aggregate version.\n\t * Only needed if `autoVersionBump` is disabled.\n\t */\n\tprotected bumpVersion(): void {\n\t\tthis.setVersion((this._version + 1) as Version);\n\t}\n\n\t// --- History & Snapshots ---\n\n\t/**\n\t * Reconstitutes the aggregate from an event history.\n\t * Sets the version to the number of events in the history.\n\t */\n\tpublic loadFromHistory(history: TEvent[]): Result<void, string> {\n\t\tfor (const event of history) {\n\t\t\tconst result = this.apply(event, false);\n\t\t\tif (!result.ok) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\tthis.setVersion(history.length as Version);\n\t\treturn ok();\n\t}\n\n\tpublic hasPendingEvents(): boolean {\n\t\treturn this._pendingEvents.length > 0;\n\t}\n\n\tpublic getEventCount(): number {\n\t\treturn this._pendingEvents.length;\n\t}\n\n\tpublic getLatestEvent(): TEvent | undefined {\n\t\treturn this._pendingEvents[this._pendingEvents.length - 1];\n\t}\n\n\t/**\n\t * Creates a snapshot of the current aggregate state.\n\t */\n\tpublic createSnapshot(): AggregateSnapshot<TState> {\n\t\treturn {\n\t\t\tstate: structuredClone(this._state),\n\t\t\tversion: this._version,\n\t\t\tsnapshotAt: new Date(),\n\t\t};\n\t}\n\n\t/**\n\t * Restores the aggregate from a snapshot and applies events that occurred after.\n\t */\n\tpublic restoreFromSnapshotWithEvents(\n\t\tsnapshot: AggregateSnapshot<TState>,\n\t\teventsAfterSnapshot: TEvent[],\n\t): Result<void, string> {\n\t\tthis._state = snapshot.state;\n\t\tthis.setVersion(snapshot.version);\n\n\t\tfor (const event of eventsAfterSnapshot) {\n\t\t\tconst result = this.apply(event, false);\n\t\t\tif (!result.ok) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\n\t\tthis.setVersion((snapshot.version + eventsAfterSnapshot.length) as Version);\n\t\treturn ok();\n\t}\n\n\t/**\n\t * A map of event types to their corresponding handlers.\n\t * Subclasses MUST implement this property.\n\t */\n\tprotected abstract readonly handlers: {\n\t\t[K in TEvent[\"type\"]]: Handler<TState, Extract<TEvent, { type: K }>>;\n\t};\n}\n","import type { Result } from \"../core/result\";\nimport { err } from \"../core/result\";\nimport type { Command, CommandHandler } from \"./command\";\n\n/**\n * Type map for command types to their return types.\n * Used to improve type inference in CommandBus.\n *\n * @example\n * ```typescript\n * type MyCommandMap = {\n * CreateOrder: OrderId;\n * CancelOrder: void;\n * };\n *\n * const bus = new CommandBus<MyCommandMap>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string> ← automatically inferred\n * ```\n */\ntype CommandTypeMap = Record<string, unknown>;\n\n/**\n * Command Bus interface for dispatching commands to their handlers.\n * Provides a centralized way to execute commands with handler registration.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * Without a type map, the return type must be specified manually or defaults to `unknown`.\n *\n * @template TMap - Optional mapping from command type strings to return types\n *\n * @example\n * ```typescript\n * // With type map (recommended) – return type is inferred\n * type MyCommands = { CreateOrder: OrderId; CancelOrder: void };\n * const bus = new CommandBus<MyCommands>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string>\n *\n * // Without type map – works like before\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", createOrderHandler);\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<unknown, string>\n * ```\n */\nexport interface ICommandBus<TMap extends CommandTypeMap = CommandTypeMap> {\n\t/**\n\t * Executes a command by dispatching it to the registered handler.\n\t * When a type map is provided, the return type is inferred from the command type.\n\t *\n\t * @param command - The command to execute\n\t * @returns Result containing the success value or error message\n\t */\n\texecute<C extends Command & { type: keyof TMap & string }>(\n\t\tcommand: C,\n\t): Promise<Result<TMap[C[\"type\"]], string>>;\n\texecute<C extends Command, R>(command: C): Promise<Result<R, string>>;\n\n\t/**\n\t * Registers a handler for a specific command type.\n\t *\n\t * @param commandType - The command type to register the handler for\n\t * @param handler - The handler function for this command type\n\t */\n\tregister<C extends Command, R>(\n\t\tcommandType: C[\"type\"],\n\t\thandler: CommandHandler<C, R>,\n\t): void;\n}\n\n/**\n * Simple in-memory command bus implementation.\n * Handlers are stored in a Map and dispatched based on command type.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * When `TMap` is provided, `execute()` infers the result type from the command type.\n * Without `TMap`, it works like before (return type defaults to `unknown` or can be specified manually).\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, validation, authorization)\n * - Error handling and retry logic\n * - Timeout handling\n * - Metrics and observability\n * - Transaction management\n * - Dead letter queue support\n *\n * The `CommandHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @template TMap - Optional mapping from command type strings to return types\n *\n * @example\n * ```typescript\n * // With type map – full inference\n * type Commands = { CreateOrder: OrderId; CancelOrder: void };\n * const bus = new CommandBus<Commands>();\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * // result: Result<OrderId, string>\n *\n * // Without type map – same as before\n * const bus = new CommandBus();\n * bus.register(\"CreateOrder\", async (cmd) => ok(orderId));\n * const result = await bus.execute({ type: \"CreateOrder\", ... });\n * ```\n */\nexport class CommandBus<TMap extends CommandTypeMap = CommandTypeMap>\n\timplements ICommandBus<TMap>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, CommandHandler<any, any>>();\n\n\tregister<C extends Command, R>(\n\t\tcommandType: C[\"type\"],\n\t\thandler: CommandHandler<C, R>,\n\t): void {\n\t\tthis.handlers.set(commandType, handler);\n\t}\n\n\tasync execute<C extends Command & { type: keyof TMap & string }>(\n\t\tcommand: C,\n\t): Promise<Result<TMap[C[\"type\"]], string>>;\n\tasync execute<C extends Command, R>(\n\t\tcommand: C,\n\t): Promise<Result<R, string>>;\n\tasync execute<C extends Command, R>(\n\t\tcommand: C,\n\t): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(command.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for command type: ${command.type}`);\n\t\t}\n\t\ttry {\n\t\t\treturn await handler(command);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n}\n","import type { EventBus, Outbox } from \"../events/ports\";\nimport type { UnitOfWork } from \"../repo/uow\";\n\n/**\n * Helper function for executing commands within a transaction.\n * Handles event persistence via outbox and optional event bus publishing.\n *\n * @param deps - Dependencies including outbox, optional event bus, and unit of work\n * @param fn - Function that returns result and events\n * @returns The result wrapped in a transaction\n *\n * @example\n * ```typescript\n * const result = await withCommit(\n * { outbox, bus, uow },\n * async () => {\n * const order = Order.create(customerId, items);\n * await repository.save(order);\n * return {\n * result: order.id,\n * events: order.pendingEvents\n * };\n * }\n * );\n * ```\n */\nexport function withCommit<Evt extends { type: string }, R>(\n\tdeps: {\n\t\toutbox: Outbox<Evt>;\n\t\tbus?: EventBus<Evt>;\n\t\tuow: UnitOfWork;\n\t},\n\tfn: () => Promise<{ result: R; events: ReadonlyArray<Evt> }>,\n) {\n\treturn deps.uow.transactional(async () => {\n\t\tconst { result, events } = await fn();\n\t\tawait deps.outbox.add(events);\n\t\tif (deps.bus) await deps.bus.publish(events);\n\t\treturn result;\n\t});\n}\n","import { err, ok, type Result } from \"../core/result\";\nimport type { Query, QueryHandler } from \"./query\";\n\n/**\n * Type map for query types to their return types.\n * Used to improve type inference in QueryBus.\n *\n * @example\n * ```typescript\n * type MyQueryMap = {\n * GetOrder: Order | null;\n * ListOrders: Order[];\n * };\n *\n * const bus = new QueryBus<MyQueryMap>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string> ← automatically inferred\n * ```\n */\ntype QueryTypeMap = Record<string, unknown>;\n\n/**\n * Query Bus interface for dispatching queries to their handlers.\n * Provides a centralized way to execute queries with handler registration.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * Without a type map, the return type must be specified manually or defaults to `unknown`.\n *\n * @template TMap - Optional mapping from query type strings to return types\n *\n * @example\n * ```typescript\n * // With type map (recommended) – return type is inferred\n * type MyQueries = { GetOrder: Order | null; ListOrders: Order[] };\n * const bus = new QueryBus<MyQueries>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string>\n *\n * // Without type map – works like before\n * const bus = new QueryBus();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<unknown, string>\n * ```\n */\nexport interface IQueryBus<TMap extends QueryTypeMap = QueryTypeMap> {\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * When a type map is provided, the return type is inferred from the query type.\n\t *\n\t * @param query - The query to execute\n\t * @returns Result containing the query result if successful, or an error message\n\t */\n\texecute<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<Result<TMap[Q[\"type\"]], string>>;\n\texecute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\n\t/**\n\t * Executes a query by dispatching it to the registered handler.\n\t * Throws an error if no handler is registered.\n\t *\n\t * @param query - The query to execute\n\t * @returns The query result\n\t * @throws Error if no handler is registered for the query type\n\t */\n\texecuteUnsafe<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<TMap[Q[\"type\"]]>;\n\texecuteUnsafe<Q extends Query, R>(query: Q): Promise<R>;\n\n\t/**\n\t * Registers a handler for a specific query type.\n\t *\n\t * @param queryType - The query type to register the handler for\n\t * @param handler - The handler function for this query type\n\t */\n\tregister<Q extends Query, R>(\n\t\tqueryType: Q[\"type\"],\n\t\thandler: QueryHandler<Q, R>,\n\t): void;\n}\n\n/**\n * Simple in-memory query bus implementation.\n * Handlers are stored in a Map and dispatched based on query type.\n *\n * Supports an optional type map (`TMap`) for automatic return type inference.\n * When `TMap` is provided, `execute()` and `executeUnsafe()` infer the result type from the query type.\n * Without `TMap`, it works like before (return type defaults to `unknown` or can be specified manually).\n *\n * **Note:** This is a basic implementation suitable for development and simple use cases.\n * For production environments, consider implementing or using a more feature-rich bus that includes:\n * - Middleware/Pipeline support (logging, caching, rate limiting)\n * - Error handling\n * - Timeout handling\n * - Metrics and observability\n * - Query result caching\n * - Rate limiting\n *\n * The `QueryHandler` type can still be used with external production-grade buses\n * (e.g., RabbitMQ, AWS SQS) while maintaining type safety.\n *\n * @template TMap - Optional mapping from query type strings to return types\n *\n * @example\n * ```typescript\n * // With type map – full inference\n * type Queries = { GetOrder: Order | null; ListOrders: Order[] };\n * const bus = new QueryBus<Queries>();\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * // result: Result<Order | null, string>\n *\n * // Without type map – same as before\n * const bus = new QueryBus();\n * bus.register(\"GetOrder\", async (query) => repository.getById(query.orderId));\n * const result = await bus.execute({ type: \"GetOrder\", orderId: \"123\" });\n * ```\n */\nexport class QueryBus<TMap extends QueryTypeMap = QueryTypeMap>\n\timplements IQueryBus<TMap>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, QueryHandler<any, any>>();\n\n\tregister<Q extends Query, R>(\n\t\tqueryType: Q[\"type\"],\n\t\thandler: QueryHandler<Q, R>,\n\t): void {\n\t\tthis.handlers.set(queryType, handler);\n\t}\n\n\tasync execute<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<Result<TMap[Q[\"type\"]], string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>>;\n\tasync execute<Q extends Query, R>(query: Q): Promise<Result<R, string>> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\treturn err(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await handler(query);\n\t\t\treturn ok(result);\n\t\t} catch (error) {\n\t\t\treturn err(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n\n\tasync executeUnsafe<Q extends Query & { type: keyof TMap & string }>(\n\t\tquery: Q,\n\t): Promise<TMap[Q[\"type\"]]>;\n\tasync executeUnsafe<Q extends Query, R>(query: Q): Promise<R>;\n\tasync executeUnsafe<Q extends Query, R>(query: Q): Promise<R> {\n\t\tconst handler = this.handlers.get(query.type);\n\t\tif (!handler) {\n\t\t\tthrow new Error(`No handler registered for query type: ${query.type}`);\n\t\t}\n\t\treturn handler(query);\n\t}\n}\n","import { err, ok, type Result } from \"./result\";\n\n/**\n * Guard function that validates a condition and returns a Result.\n * Returns `ok(true)` if the condition is met, otherwise `err(error)`.\n *\n * @param cond - The condition to check\n * @param error - Error message if condition fails\n * @returns Result<true, string>\n *\n * @example\n * ```typescript\n * const result = guard(id.length > 0, \"ID cannot be empty\");\n * if (!result.ok) {\n * return err(result.error);\n * }\n * ```\n */\nexport function guard(cond: boolean, error: string): Result<true, string> {\n\treturn cond ? ok(true) : err(error);\n}\n","import type { DomainEvent } from \"../aggregate/domain-event\";\nimport type { EventBus, EventHandler } from \"./ports\";\n\n/**\n * Simple in-memory event bus implementation.\n * Supports multiple subscribers per event type (pub/sub pattern).\n *\n * @template Evt - The type of domain events (must extend DomainEvent)\n *\n * @example\n * ```typescript\n * const bus = new EventBusImpl<OrderEvent>();\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await sendEmail(event.payload.customerId);\n * });\n *\n * bus.subscribe(\"OrderCreated\", async (event) => {\n * await logEvent(event);\n * });\n *\n * await bus.publish([orderCreatedEvent]);\n * // Both handlers will be called\n * ```\n */\nexport class EventBusImpl<Evt extends DomainEvent<string, unknown>>\n\timplements EventBus<Evt>\n{\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tprivate readonly handlers = new Map<string, Set<EventHandler<any>>>();\n\n\tsubscribe<T extends Evt>(\n\t\teventType: Evt[\"type\"],\n\t\thandler: EventHandler<T>,\n\t): () => void {\n\t\tconst type = eventType;\n\t\tif (!this.handlers.has(type)) {\n\t\t\tthis.handlers.set(type, new Set());\n\t\t}\n\t\tconst handlersForType = this.handlers.get(type)!;\n\t\thandlersForType.add(handler);\n\n\t\t// Return unsubscribe function\n\t\treturn () => {\n\t\t\thandlersForType.delete(handler);\n\t\t\tif (handlersForType.size === 0) {\n\t\t\t\tthis.handlers.delete(type);\n\t\t\t}\n\t\t};\n\t}\n\n\tonce<T extends Evt>(eventType: Evt[\"type\"]): Promise<T> {\n\t\treturn new Promise<T>((resolve) => {\n\t\t\tconst unsubscribe = this.subscribe<T>(eventType, ((event: T) => {\n\t\t\t\tunsubscribe();\n\t\t\t\tresolve(event);\n\t\t\t}) as EventHandler<T>);\n\t\t});\n\t}\n\n\tasync publish(events: ReadonlyArray<Evt>): Promise<void> {\n\t\tconst errors: Error[] = [];\n\n\t\tfor (const event of events) {\n\t\t\tconst handlersForType = this.handlers.get(event.type);\n\t\t\tif (handlersForType) {\n\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\tArray.from(handlersForType).map((handler) => handler(event)),\n\t\t\t\t);\n\t\t\t\tfor (const result of results) {\n\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\tresult.reason instanceof Error\n\t\t\t\t\t\t\t\t? result.reason\n\t\t\t\t\t\t\t\t: new Error(String(result.reason)),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (errors.length === 1) {\n\t\t\tthrow errors[0];\n\t\t}\n\t\tif (errors.length > 1) {\n\t\t\tthrow new AggregateError(errors, \"Multiple event handlers failed\");\n\t\t}\n\t}\n}\n\n","import { isBuiltInObject } from \"./is-built-in\";\n\nexport type Key = string | symbol;\nexport type PathSegment = string | number | symbol;\n\nexport interface DeepOmitOptions {\n\t/**\n\t * Keys to ignore everywhere in the object tree.\n\t * Only applies to object properties, not Map/Set/TypedArray contents.\n\t */\n\treadonly ignoreKeys?: readonly Key[];\n\n\t/**\n\t * Fine-grained control: Key + path (without current key).\n\t * Example path: [\"user\", \"meta\", 0, \"data\"]\n\t */\n\treadonly ignoreKeyPredicate?: (\n\t\tkey: Key,\n\t\tpath: readonly PathSegment[],\n\t) => boolean;\n}\n\n/**\n * Creates a deep copy of `value` with certain keys removed according to the provided rules.\n *\n * This function recursively traverses the object tree and removes keys that match\n * the criteria specified in `options`. Built-in types (Date, Map, Set, TypedArrays, etc.)\n * are treated atomically and not modified.\n *\n * @param value - The value to create a deep copy from\n * @param options - Options specifying which keys to ignore\n * @returns A deep copy of `value` with specified keys removed\n *\n * @example\n * ```ts\n * const obj = { a: 1, b: { c: 2, d: 3 } };\n * const result = deepOmit(obj, { ignoreKeys: ['d'] });\n * // result: { a: 1, b: { c: 2 } }\n * ```\n */\nexport function deepOmit<T>(value: T, options: DeepOmitOptions): T {\n\tconst visited = new WeakMap<object, unknown>();\n\treturn omitInternal(value, options, [], visited) as T;\n}\n\nfunction omitInternal(\n\tvalue: unknown,\n\toptions: DeepOmitOptions,\n\tpath: PathSegment[],\n\tvisited: WeakMap<object, unknown>,\n): unknown {\n\tif (value === null) return value;\n\tconst type = typeof value;\n\n\t// Primitives and functions are passed through unchanged\n\tif (type !== \"object\") return value;\n\n\tconst obj = value as object;\n\n\t// Cycles: return cached value if already visited\n\tconst cached = visited.get(obj);\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\tconst tag = Object.prototype.toString.call(obj);\n\n\t// Arrays: recursively process elements\n\tif (tag === \"[object Array]\") {\n\t\tconst arr = obj as unknown[];\n\t\tconst clone: unknown[] = new Array(arr.length);\n\t\tvisited.set(obj, clone);\n\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tpath.push(i);\n\t\t\tclone[i] = omitInternal(arr[i], options, path, visited);\n\t\t\tpath.pop();\n\t\t}\n\t\treturn clone;\n\t}\n\n\t// Built-ins: treat atomically, no key filtering inside\n\t// Future-proof detection: check if object is a built-in type\n\tif (isBuiltInObject(obj, tag)) {\n\t\treturn value;\n\t}\n\n\t// Plain / Custom Objects: filter keys, recursively process values\n\tconst clone = Object.create(Object.getPrototypeOf(obj));\n\tvisited.set(obj, clone);\n\n\tconst stringKeys = Object.keys(obj);\n\tconst symbolKeys = Object.getOwnPropertySymbols(obj);\n\tconst keys: Key[] = [...stringKeys, ...symbolKeys];\n\n\tfor (const key of keys) {\n\t\tif (shouldIgnoreKey(key, path, options)) continue;\n\n\t\tpath.push(key);\n\t\t(clone as Record<PropertyKey, unknown>)[key] = omitInternal(\n\t\t\t(obj as Record<PropertyKey, unknown>)[key],\n\t\t\toptions,\n\t\t\tpath,\n\t\t\tvisited,\n\t\t);\n\t\tpath.pop();\n\t}\n\n\treturn clone;\n}\n\nfunction shouldIgnoreKey(\n\tkey: Key,\n\tpath: readonly PathSegment[],\n\toptions: DeepOmitOptions,\n): boolean {\n\tif (options.ignoreKeys?.includes(key)) {\n\t\treturn true;\n\t}\n\tif (options.ignoreKeyPredicate?.(key, path)) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n","import { deepEqual } from \"./deep-equal\";\nimport { type DeepOmitOptions, deepOmit } from \"./deep-omit\";\n\nexport type DeepEqualExceptOptions = DeepOmitOptions;\n\n/**\n * Performs a deep equality comparison between two values after omitting specified keys.\n * \n * This function first removes the specified keys from both values using `deepOmit`,\n * then performs a deep equality check using `deepEqual`.\n * \n * @param a - The first value to compare\n * @param b - The second value to compare\n * @param options - Options specifying which keys to omit before comparison\n * @returns `true` if the values are deeply equal after omitting specified keys, `false` otherwise\n * \n * @example\n * ```ts\n * const obj1 = { id: 1, name: \"Alice\", updatedAt: \"2024-01-01\" };\n * const obj2 = { id: 2, name: \"Alice\", updatedAt: \"2024-01-02\" };\n * \n * deepEqualExcept(obj1, obj2, { ignoreKeys: [\"id\", \"updatedAt\"] }); // true\n * ```\n */\nexport function deepEqualExcept(\n\ta: unknown,\n\tb: unknown,\n\toptions: DeepEqualExceptOptions,\n): boolean {\n\tconst prunedA = deepOmit(a, options);\n\tconst prunedB = deepOmit(b, options);\n\treturn deepEqual(prunedA, prunedB);\n}\n","import { deepEqual } from \"../utils/array/deep-equal\";\nimport {\n deepEqualExcept,\n type DeepEqualExceptOptions,\n} from \"../utils/array/deep-equal-except\";\nimport { err, ok, type Result } from \"../core/result\";\n\n// ============================================================================\n// Functional Value Object API\n// ============================================================================\n\nexport type VO<T> = Readonly<T>;\n\n/**\n * Deep freezes an object and all its nested properties recursively.\n * This ensures true immutability for value objects with nested structures.\n * Handles circular references by tracking visited objects.\n */\nexport function deepFreeze<T>(obj: T, visited = new WeakSet<object>()): Readonly<T> {\n // Handle null and non-objects\n if (obj === null || typeof obj !== \"object\") {\n return obj as Readonly<T>;\n }\n\n // Handle circular references\n if (visited.has(obj as object)) {\n return obj as Readonly<T>;\n }\n\n // Mark as visited\n visited.add(obj as object);\n\n // Retrieve the property names defined on obj\n const propNames = Object.getOwnPropertyNames(obj);\n\n // Freeze properties before freezing self\n for (const name of propNames) {\n const value = (obj as Record<string, unknown>)[name];\n\n // Freeze value if it is an object or array\n if (value && (typeof value === \"object\" || Array.isArray(value))) {\n deepFreeze(value, visited);\n }\n }\n\n return Object.freeze(obj) as Readonly<T>;\n}\n\n/**\n * Creates a deeply immutable value object from the given data.\n * All nested objects and arrays are frozen recursively.\n *\n * @param t - The data to convert into a value object\n * @returns A deeply frozen, immutable value object\n *\n * @example\n * ```typescript\n * const address = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * // address.coordinates.lat = 99; // ❌ Error: Cannot assign to read-only property\n * ```\n */\nexport function vo<T>(t: T): VO<T> {\n return deepFreeze({ ...t });\n}\n\n/**\n * Compares two value objects for equality based on their values.\n * Uses deep equality comparison that handles:\n * - Nested objects and arrays\n * - Primitives (including NaN)\n * - Dates, Maps, Sets, RegExp\n * - TypedArrays and DataView\n * - Symbol keys\n * - Circular references\n *\n * @param a - First value object\n * @param b - Second value object\n * @returns true if both objects have the same values, false otherwise\n *\n * @example\n * ```typescript\n * const money1 = vo({ amount: 100, currency: \"USD\" });\n * const money2 = vo({ amount: 100, currency: \"USD\" });\n * voEquals(money1, money2); // true\n *\n * const address1 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * const address2 = vo({\n * street: \"Main St\",\n * coordinates: { lat: 52.5, lng: 13.4 }\n * });\n * voEquals(address1, address2); // true\n * ```\n */\nexport function voEquals<T>(a: VO<T>, b: VO<T>): boolean {\n return deepEqual(a, b);\n}\n\n/**\n * Compares two value objects for equality while ignoring specified keys.\n * Useful for comparing value objects that contain metadata or optional fields\n * that should not affect equality comparison.\n *\n * @param a - First value object\n * @param b - Second value object\n * @param options - Options specifying which keys to ignore during comparison\n * @returns true if both objects have the same values (after ignoring specified keys), false otherwise\n *\n * @example\n * ```typescript\n * // Value object with metadata\n * const address1 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-02\" }\n * });\n *\n * const address2 = vo({\n * street: \"Main St\",\n * city: \"Berlin\",\n * metadata: { createdAt: \"2024-01-01\", updatedAt: \"2024-01-03\" }\n * });\n *\n * // Compare ignoring metadata timestamps\n * voEqualsExcept(address1, address2, {\n * ignoreKeys: [\"updatedAt\"],\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n *\n * // Compare ignoring all metadata\n * voEqualsExcept(address1, address2, {\n * ignoreKeyPredicate: (key, path) => path.includes(\"metadata\")\n * }); // true\n * ```\n */\nexport function voEqualsExcept<T>(\n a: VO<T>,\n b: VO<T>,\n options: DeepEqualExceptOptions,\n): boolean {\n return deepEqualExcept(a, b, options);\n}\n\n/**\n * Creates a value object with optional validation.\n * Returns a Result type instead of throwing an error.\n *\n * @param t - The data to convert into a value object\n * @param validate - Validation function that returns true if valid\n * @param errorMessage - Optional custom error message if validation fails\n * @returns Result containing the value object if valid, or an error message if validation fails\n *\n * @example\n * ```typescript\n * const result = voWithValidation(\n * { amount: 100, currency: \"USD\" },\n * (m) => m.amount >= 0 && m.currency.length === 3,\n * \"Invalid money: amount must be non-negative and currency must be 3 characters\"\n * );\n *\n * if (result.ok) {\n * console.log(result.value); // Use the value object\n * } else {\n * console.error(result.error); // Handle validation error\n * }\n * ```\n */\nexport function voWithValidation<T>(\n t: T,\n validate: (value: T) => boolean,\n errorMessage?: string,\n): Result<VO<T>, string> {\n if (!validate(t)) {\n return err(\n errorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n );\n }\n return ok(vo(t));\n}\n\n/**\n * Creates a value object with optional validation.\n * Throws an error if validation fails.\n *\n * @param t - The data to convert into a value object\n * @param validate - Validation function that returns true if valid\n * @param errorMessage - Optional custom error message if validation fails\n * @returns A deeply frozen, immutable value object\n * @throws Error if validation fails\n *\n * @example\n * ```typescript\n * const money = voWithValidationUnsafe(\n * { amount: 100, currency: \"USD\" },\n * (m) => m.amount >= 0 && m.currency.length === 3,\n * \"Invalid money: amount must be non-negative and currency must be 3 characters\"\n * );\n * ```\n */\nexport function voWithValidationUnsafe<T>(\n t: T,\n validate: (value: T) => boolean,\n errorMessage?: string,\n): VO<T> {\n if (!validate(t)) {\n throw new Error(\n errorMessage ?? `Validation failed for value object: ${JSON.stringify(t)}`,\n );\n }\n return vo(t);\n}\n\n// ============================================================================\n// Class-based Value Object API\n// ============================================================================\n\n/**\n * Interface for Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport interface IValueObject<T extends object> {\n /**\n * The immutable properties of the value object.\n */\n readonly props: Readonly<T>;\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal\n */\n equals(other: IValueObject<T>): boolean;\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n clone(props?: Partial<T>): IValueObject<T>;\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n toJSON(): Readonly<T>;\n}\n\n/**\n * Abstract base class for creating Value Objects.\n * Value Objects are immutable and defined by their properties.\n *\n * @template T - The shape of the value object's properties\n */\nexport abstract class ValueObject<T extends object> implements IValueObject<T> {\n public readonly props: Readonly<T>;\n\n /**\n * Creates a new ValueObject.\n * The properties are deeply frozen to ensure immutability.\n *\n * @param props - The properties of the value object\n * @example\n * ```ts\n * class Money extends ValueObject<{ amount: number; currency: string }> {\n * constructor(props: { amount: number; currency: string }) {\n * super(props);\n * }\n *\n * protected validate(props: { amount: number; currency: string }): void {\n * if (props.amount < 0) throw new Error(\"Amount cannot be negative\");\n * }\n * }\n * ```\n */\n constructor(props: T) {\n this.validate(props);\n this.props = deepFreeze({ ...props });\n }\n\n /**\n * Optional validation hook that can be overridden by subclasses.\n * Should throw an error if validation fails.\n *\n * @param props - The properties to validate\n * @throws Error if validation fails\n */\n protected validate(props: T): void {\n // Default implementation does nothing\n }\n\n /**\n * Checks if this value object is equal to another.\n * Uses deep equality comparison on the properties and checks for constructor equality.\n *\n * @param other - The other value object to compare\n * @returns true if the properties are deeply equal and constructors match\n */\n public equals(other: ValueObject<T>): boolean {\n if (other === null || other === undefined) {\n return false;\n }\n\n if (this.constructor !== other.constructor) {\n return false;\n }\n\n return deepEqual(this.props, other.props);\n }\n\n /**\n * Creates a clone of the value object with optional property overrides.\n *\n * @param props - Optional properties to override\n * @returns A new instance of the value object\n */\n public clone(props?: Partial<T>): this {\n const Constructor = this.constructor as new (props: T) => this;\n return new Constructor({ ...this.props, ...(props || {}) });\n }\n\n /**\n * Serializes the value object to its raw properties for JSON operations.\n *\n * @returns The raw properties object\n */\n public toJSON(): Readonly<T> {\n return this.props;\n }\n\n\n}\n"]}
|