@cullet/erp-core 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/KIT_CONTEXT.md +1 -67
  2. package/dist/app-error.d.cts +108 -0
  3. package/dist/application/index.cjs +26 -0
  4. package/dist/application/index.d.cts +2 -0
  5. package/dist/application/index.d.ts +1 -1
  6. package/dist/application/index.js +2 -1
  7. package/dist/domain/index.cjs +16 -0
  8. package/dist/domain/index.d.cts +3 -0
  9. package/dist/domain/index.d.ts +3 -0
  10. package/dist/domain/index.js +3 -0
  11. package/dist/domain-event-contracts.cjs +33 -0
  12. package/dist/domain-event-contracts.cjs.map +1 -0
  13. package/dist/domain-event-contracts.d.cts +27 -0
  14. package/dist/domain-event-contracts.d.ts +27 -0
  15. package/dist/domain-event-contracts.js +22 -0
  16. package/dist/domain-event-contracts.js.map +1 -0
  17. package/dist/domain-exception.cjs +17 -0
  18. package/dist/domain-exception.cjs.map +1 -0
  19. package/dist/domain-exception.d.cts +7 -0
  20. package/dist/domain-exception.d.ts +7 -0
  21. package/dist/domain-exception.js +12 -0
  22. package/dist/domain-exception.js.map +1 -0
  23. package/dist/errors/index.cjs +41 -0
  24. package/dist/errors/index.d.cts +3 -0
  25. package/dist/errors/index.js +1 -1
  26. package/dist/exceptions/index.cjs +17 -0
  27. package/dist/exceptions/index.d.cts +5 -0
  28. package/dist/exceptions/index.d.ts +5 -0
  29. package/dist/exceptions/index.js +7 -0
  30. package/dist/exceptions/validation-field.cjs +3 -0
  31. package/dist/exceptions/validation-field.d.cts +2 -0
  32. package/dist/gate-engine-registry.cjs +308 -0
  33. package/dist/gate-engine-registry.cjs.map +1 -0
  34. package/dist/gate-engine-registry.d.cts +81 -0
  35. package/dist/gate-engine-registry.d.ts +2 -1
  36. package/dist/gate-engine-registry.js +2 -1
  37. package/dist/gate-engine-registry.js.map +1 -1
  38. package/dist/gate-types.d.cts +171 -0
  39. package/dist/gate-types.d.ts +3 -139
  40. package/dist/gate-v1-payload.schema.cjs +638 -0
  41. package/dist/gate-v1-payload.schema.cjs.map +1 -0
  42. package/dist/gate-v1-payload.schema.js +2 -116
  43. package/dist/gate-v1-payload.schema.js.map +1 -1
  44. package/dist/hashing.cjs +66 -0
  45. package/dist/hashing.cjs.map +1 -0
  46. package/dist/immutable.cjs +77 -0
  47. package/dist/immutable.cjs.map +1 -0
  48. package/dist/immutable.d.cts +6 -0
  49. package/dist/immutable.d.ts +6 -0
  50. package/dist/immutable.js +54 -0
  51. package/dist/immutable.js.map +1 -0
  52. package/dist/index.cjs +163 -0
  53. package/dist/index.cjs.map +1 -0
  54. package/dist/index.d.cts +30 -0
  55. package/dist/index.d.ts +15 -160
  56. package/dist/index.js +19 -176
  57. package/dist/index.js.map +1 -1
  58. package/dist/invalid-state-transition-exception.cjs +47 -0
  59. package/dist/invalid-state-transition-exception.cjs.map +1 -0
  60. package/dist/invalid-state-transition-exception.js +30 -0
  61. package/dist/invalid-state-transition-exception.js.map +1 -0
  62. package/dist/invariant-violation-exception.cjs +16 -0
  63. package/dist/invariant-violation-exception.cjs.map +1 -0
  64. package/dist/invariant-violation-exception.js +11 -0
  65. package/dist/invariant-violation-exception.js.map +1 -0
  66. package/dist/not-found-error.cjs +65 -0
  67. package/dist/not-found-error.cjs.map +1 -0
  68. package/dist/not-found-error.js +1 -1
  69. package/dist/outcome.cjs +97 -0
  70. package/dist/outcome.cjs.map +1 -0
  71. package/dist/outcome.d.cts +140 -0
  72. package/dist/outcome.d.ts +140 -0
  73. package/dist/outcome.js +1 -1
  74. package/dist/parse-gate-payload.d.cts +62 -0
  75. package/dist/parse-gate-payload.d.ts +2 -1
  76. package/dist/path.d.cts +90 -0
  77. package/dist/path.d.ts +2 -1
  78. package/dist/plugin.cjs +79 -0
  79. package/dist/plugin.cjs.map +1 -0
  80. package/dist/plugin.d.cts +85 -0
  81. package/dist/plugin.d.ts +85 -0
  82. package/dist/plugin.js +74 -0
  83. package/dist/plugin.js.map +1 -0
  84. package/dist/plugins/index.cjs +3 -0
  85. package/dist/plugins/index.d.cts +2 -0
  86. package/dist/plugins/index.d.ts +2 -0
  87. package/dist/plugins/index.js +2 -0
  88. package/dist/policies/engines/index.cjs +10 -0
  89. package/dist/policies/engines/index.d.cts +4 -0
  90. package/dist/policies/engines/index.d.ts +1 -1
  91. package/dist/policies/engines/v1/gate/index.cjs +91 -0
  92. package/dist/policies/engines/v1/gate/index.cjs.map +1 -0
  93. package/dist/policies/engines/v1/gate/index.d.cts +121 -0
  94. package/dist/policies/engines/v1/gate/index.d.ts +2 -1
  95. package/dist/policies/engines/v1/gate/index.js +2 -1
  96. package/dist/policies/engines/v1/gate/index.js.map +1 -1
  97. package/dist/policies/index.cjs +41 -0
  98. package/dist/policies/index.d.cts +7 -0
  99. package/dist/policies/index.d.ts +2 -1
  100. package/dist/policies/index.js +2 -1
  101. package/dist/policy-service.cjs +1190 -0
  102. package/dist/policy-service.cjs.map +1 -0
  103. package/dist/policy-service.d.cts +559 -0
  104. package/dist/policy-service.d.ts +2 -1
  105. package/dist/policy-service.js +6 -3
  106. package/dist/policy-service.js.map +1 -1
  107. package/dist/result/index.cjs +7 -0
  108. package/dist/result/index.d.cts +2 -0
  109. package/dist/result/index.d.ts +2 -0
  110. package/dist/result/index.js +3 -0
  111. package/dist/result.cjs +135 -0
  112. package/dist/result.cjs.map +1 -0
  113. package/dist/result.js +118 -0
  114. package/dist/result.js.map +1 -0
  115. package/dist/ruleset-registry.cjs +47 -0
  116. package/dist/ruleset-registry.cjs.map +1 -0
  117. package/dist/ruleset-registry.js +42 -0
  118. package/dist/ruleset-registry.js.map +1 -0
  119. package/dist/rulesets/index.cjs +3 -0
  120. package/dist/rulesets/index.d.cts +2 -0
  121. package/dist/rulesets/index.d.ts +2 -0
  122. package/dist/rulesets/index.js +2 -0
  123. package/dist/temporal-guards.cjs +32 -0
  124. package/dist/temporal-guards.cjs.map +1 -0
  125. package/dist/temporal-guards.js +2 -17
  126. package/dist/temporal-guards.js.map +1 -1
  127. package/dist/temporal-use-case.cjs +191 -0
  128. package/dist/temporal-use-case.cjs.map +1 -0
  129. package/dist/temporal-use-case.d.cts +304 -0
  130. package/dist/temporal-use-case.d.ts +4 -9
  131. package/dist/temporal-use-case.js +6 -140
  132. package/dist/temporal-use-case.js.map +1 -1
  133. package/dist/unexpected-error.cjs +208 -0
  134. package/dist/unexpected-error.cjs.map +1 -0
  135. package/dist/unexpected-error.js +179 -0
  136. package/dist/unexpected-error.js.map +1 -0
  137. package/dist/use-case.cjs +96 -0
  138. package/dist/use-case.cjs.map +1 -0
  139. package/dist/use-case.js +91 -0
  140. package/dist/use-case.js.map +1 -0
  141. package/dist/uuid-identifier.cjs +65 -0
  142. package/dist/uuid-identifier.cjs.map +1 -0
  143. package/dist/uuid-identifier.d.cts +230 -0
  144. package/dist/uuid-identifier.d.ts +230 -0
  145. package/dist/uuid-identifier.js +60 -0
  146. package/dist/uuid-identifier.js.map +1 -0
  147. package/dist/validation-code.cjs +60 -0
  148. package/dist/validation-code.cjs.map +1 -0
  149. package/dist/validation-code.d.cts +23 -0
  150. package/dist/validation-code.d.ts +23 -0
  151. package/dist/validation-code.js +1 -177
  152. package/dist/validation-code.js.map +1 -1
  153. package/dist/validation-error.cjs +1020 -0
  154. package/dist/validation-error.cjs.map +1 -0
  155. package/dist/validation-error.d.cts +777 -0
  156. package/dist/validation-error.d.ts +1 -21
  157. package/dist/validation-error.js +1 -1
  158. package/dist/validation-exception.cjs +41 -0
  159. package/dist/validation-exception.cjs.map +1 -0
  160. package/dist/validation-exception.d.cts +50 -0
  161. package/dist/validation-exception.d.ts +50 -0
  162. package/dist/validation-exception.js +8 -2
  163. package/dist/validation-exception.js.map +1 -1
  164. package/dist/validation-field.cjs +28 -0
  165. package/dist/validation-field.cjs.map +1 -0
  166. package/dist/validation-field.d.cts +12 -0
  167. package/dist/value-object-ruleset.contracts.d.cts +36 -0
  168. package/dist/value-object-ruleset.contracts.d.ts +36 -0
  169. package/dist/value-object.cjs +208 -0
  170. package/dist/value-object.cjs.map +1 -0
  171. package/dist/value-object.js +191 -0
  172. package/dist/value-object.js.map +1 -0
  173. package/dist/version.d.cts +10 -0
  174. package/dist/version.d.ts +10 -0
  175. package/dist/versioning/index.cjs +7 -0
  176. package/dist/versioning/index.d.cts +3 -0
  177. package/dist/versioning/index.d.ts +3 -0
  178. package/dist/versioning/index.js +3 -0
  179. package/meta.json +18 -3
  180. package/package.json +165 -17
  181. package/src/core/domain/rulesets/index.ts +7 -0
  182. package/src/core/domain/uuid-identifier.ts +72 -0
  183. package/src/core/domain/value-object.ts +37 -5
  184. package/src/core/exceptions/index.ts +13 -0
  185. package/src/core/index.ts +14 -2
  186. package/src/core/plugins/index.ts +7 -0
  187. package/src/core/plugins/plugin.ts +99 -0
  188. package/src/core/plugins/types.ts +53 -0
  189. package/src/core/versioning/index.ts +14 -0
  190. package/src/domain/index.ts +7 -0
  191. package/src/exceptions/index.ts +1 -0
  192. package/src/plugins/index.ts +1 -0
  193. package/src/result/index.ts +2 -0
  194. package/src/rulesets/index.ts +1 -0
  195. package/src/version.ts +1 -1
  196. package/src/versioning/index.ts +1 -0
package/dist/index.js CHANGED
@@ -1,194 +1,37 @@
1
- import { a as ErrorCodes, i as assertJsonSafeMetadata, n as UnexpectedError, o as serializationErrorCode, r as AppError } from "./validation-code.js";
1
+ import { a as serializationErrorCode, i as ErrorCodes, n as AppError, r as assertJsonSafeMetadata, t as UnexpectedError } from "./unexpected-error.js";
2
2
  import { C as translateUniqueViolationToDuplicate, S as UniqueConstraintViolationError, T as AuthenticationError, _ as IdempotencyPayloadMismatchError, a as evaluateTemporalWindow, b as ConflictError, c as SerializationInError, d as safePreview, f as LegacyIncompatibleError, g as IdempotencyKeyMissingError, h as IdempotencyInProgressError, i as TemporalError, l as SerializationMessages, m as IdempotencyError, n as ExpiredError, o as SerializationCodes, p as IntegrationError, r as NotYetValidError, s as SerializationError, t as ValidationError, u as SerializationOutError, v as IdempotencyReplayNotSupportedError, w as AuthorizationError, x as DuplicateError, y as AlreadyExistsError } from "./validation-error.js";
3
3
  import { n as BusinessRuleViolationError, t as NotFoundError } from "./not-found-error.js";
4
4
  import { n as sha256Hex, r as stableStringify, t as payloadHash } from "./hashing.js";
5
+ import { t as ValidationCode } from "./validation-code.js";
5
6
  import { t as ValidationField } from "./validation-field.js";
6
- import { a as Query, c as RequestedBy, d as version$1, i as makeImmutable, l as UseCase, n as assertTemporalContext, o as mapPolicyEvaluationError, r as createTemporalContext, s as Command, t as TemporalUseCase, u as __decorate } from "./temporal-use-case.js";
7
- import { i as InvariantViolationException, n as cloneDate, t as assertValidDate } from "./temporal-guards.js";
8
- import { c as Ok, d as CoreConfig, l as Result, o as PolicyContextPath, s as Err, u as coreConfig } from "./gate-v1-payload.schema.js";
7
+ import { t as DomainException } from "./domain-exception.js";
8
+ import { n as EntityNotFoundException, r as BusinessRuleViolationException, t as InvalidStateTransitionException } from "./invalid-state-transition-exception.js";
9
+ import { t as InvariantViolationException } from "./invariant-violation-exception.js";
10
+ import { n as MultipleValidationException, r as ValidationException, t as InvalidValueException } from "./validation-exception.js";
11
+ import { i as version, r as CONTRACT_VERSION_PROPERTY } from "./immutable.js";
12
+ import { t as UseCase } from "./use-case.js";
13
+ import { a as mapPolicyEvaluationError, i as Query, n as assertTemporalContext, o as Command, r as createTemporalContext, s as RequestedBy, t as TemporalUseCase } from "./temporal-use-case.js";
14
+ import { n as Entity, t as ValueObject } from "./value-object.js";
15
+ import { t as PluginManager } from "./plugin.js";
16
+ import { t as UuidIdentifier } from "./uuid-identifier.js";
17
+ import { t as RulesetRegistry } from "./ruleset-registry.js";
18
+ import { n as createDomainEventEnvelope, t as buildDomainEventContractVersions } from "./domain-event-contracts.js";
19
+ import { c as CoreConfig, o as PolicyContextPath, s as coreConfig } from "./gate-v1-payload.schema.js";
20
+ import { n as Ok, r as Result, t as Err } from "./result.js";
9
21
  import { t as Outcome } from "./outcome.js";
10
22
  import { _ as asPolicyDecisionId, a as ContextSeedValidator, b as asTenantId, c as ContextResolverRegistry, d as PolicyDefinition, f as InMemoryPolicyDefinitionRepository, g as PolicyCatalog, h as PolicyCatalogFactory, i as PolicyAsOfResolver, l as registerNamespacedContextResolversIn, m as PolicyKey, n as PolicyEvaluationErrors, o as contextResolverRegistry, p as PolicyScopeMatcher, r as PolicyResolver, s as registerNamespacedContextResolvers, t as PolicyService, u as PolicyContextBuilder, v as asPolicyDefinitionId, x as PolicyHashing, y as asSchoolId } from "./policy-service.js";
11
23
  import { a as ComputeEvaluatorRegistry, c as ComputePayloadParsers, i as ComputeRegistry, o as ComputeEngineRegistry, r as GatePayloadParsers, s as ComputePayloadParserRegistry, t as GateEngineRegistry } from "./gate-engine-registry.js";
12
24
  //#region src/version.ts
13
- const version = "1.1.0";
14
- //#endregion
15
- //#region src/core/shared/aggregate-version.ts
16
- function assertValidAggregateVersion(aggregateVersion) {
17
- if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) throw new InvariantViolationException(`aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`);
18
- }
19
- //#endregion
20
- //#region src/core/domain/entity.ts
21
- var _Entity;
22
- /**
23
- * Base class for domain entities — objects defined by a stable identity rather
24
- * than by their attributes. Two entities are "the same" when their `id`
25
- * matches, even if every other field differs; this is the opposite of a
26
- * {@link ValueObject}, which is defined entirely by its contents.
27
- *
28
- * The class owns the bookkeeping common to every aggregate root: a creation
29
- * timestamp that never changes, a last-modified timestamp, and an
30
- * `aggregateVersion` counter used for optimistic concurrency control. All three
31
- * are validated on construction and the dates are defensively cloned, so an
32
- * entity can never be built into — or leak — an inconsistent temporal state.
33
- *
34
- * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
35
- */
36
- let Entity = class Entity {
37
- static {
38
- _Entity = this;
39
- }
40
- /**
41
- * Reconstitutes an entity from its persisted {@link EntityState}.
42
- *
43
- * Validates the temporal invariants up front so an invalid entity is
44
- * impossible to construct: both dates must be valid, the aggregate version
45
- * must be a non-negative integer, and `updatedAt` may not predate
46
- * `createdAt`. Both dates are cloned on the way in so a later mutation of
47
- * the caller's `Date` objects cannot reach into the entity's internal state.
48
- *
49
- * Declared `protected` because entities are reconstituted through a
50
- * subclass factory, never instantiated directly by application code.
51
- *
52
- * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
53
- */
54
- constructor(state) {
55
- assertValidDate("createdAt", state.createdAt);
56
- assertValidDate("updatedAt", state.updatedAt);
57
- assertValidAggregateVersion(state.aggregateVersion);
58
- if (state.updatedAt.getTime() < state.createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
59
- this._id = state.id;
60
- this._createdAt = cloneDate(state.createdAt);
61
- this._updatedAt = cloneDate(state.updatedAt);
62
- this._aggregateVersion = state.aggregateVersion;
63
- }
64
- /** The entity's stable identity — the basis for equality between entities. */
65
- get id() {
66
- return this._id;
67
- }
68
- /**
69
- * When the entity was first created.
70
- *
71
- * Returns a clone so callers cannot mutate the entity's internal `Date`;
72
- * the value is fixed at construction and never changes thereafter.
73
- */
74
- get createdAt() {
75
- return cloneDate(this._createdAt);
76
- }
77
- /**
78
- * When the entity was last modified.
79
- *
80
- * Returns a clone for the same encapsulation reason as {@link createdAt};
81
- * the underlying value advances only through {@link markAsModified}.
82
- */
83
- get updatedAt() {
84
- return cloneDate(this._updatedAt);
85
- }
86
- /**
87
- * Monotonic counter incremented on every mutation, used for optimistic
88
- * concurrency control: a writer reads this value, and the persistence layer
89
- * rejects the write if the stored version has moved on in the meantime.
90
- */
91
- get aggregateVersion() {
92
- return this._aggregateVersion;
93
- }
94
- /**
95
- * The schema/contract version stamped on this entity type by the
96
- * `@version` decorator — used to detect and migrate state persisted under
97
- * an older shape.
98
- */
99
- get contractVersion() {
100
- return _Entity.CONTRACT_VERSION;
101
- }
102
- /**
103
- * The single seam through which an entity records a mutation: it advances
104
- * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must
105
- * call this from every state-changing method so the version counter stays
106
- * an accurate optimistic-lock token.
107
- *
108
- * @param updatedAt - The modification instant; defaults to now. Validated
109
- * and required not to predate `createdAt`, preserving the same invariant
110
- * the constructor enforces.
111
- * @returns The new aggregate version after the increment.
112
- * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
113
- */
114
- markAsModified(updatedAt = /* @__PURE__ */ new Date()) {
115
- assertValidDate("updatedAt", updatedAt);
116
- if (updatedAt.getTime() < this._createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
117
- this._updatedAt = cloneDate(updatedAt);
118
- this._aggregateVersion += 1;
119
- return this._aggregateVersion;
120
- }
121
- };
122
- Entity = _Entity = __decorate([version$1("1.0")], Entity);
123
- //#endregion
124
- //#region src/core/domain/value-object.ts
125
- var _ValueObject;
126
- /**
127
- * Base class for value objects — domain concepts defined entirely by their
128
- * contents, with no identity of their own. Two value objects are
129
- * interchangeable when they hold equal data, which is the opposite of an
130
- * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one
131
- * instance with an equal one changes nothing about the model.
132
- *
133
- * Immutability is the defining guarantee here. The wrapped `value` is
134
- * deep-frozen on construction, so a value object can be shared freely without
135
- * any risk of a consumer mutating shared state. Subclasses seal the instance
136
- * itself with {@link finalize} once their own fields are set.
137
- *
138
- * @typeParam T - The shape of the wrapped data.
139
- * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
140
- */
141
- let ValueObject = class ValueObject {
142
- static {
143
- _ValueObject = this;
144
- }
145
- /**
146
- * Wraps `value`, deep-freezing it so the value object is immutable from the
147
- * moment it exists. Declared `protected` because value objects are built
148
- * through a validating subclass factory, never instantiated directly.
149
- */
150
- constructor(value) {
151
- this.value = makeImmutable(value);
152
- }
153
- /**
154
- * The schema/contract version stamped on this value-object type by the
155
- * `@version` decorator — used to detect state persisted under an older shape.
156
- */
157
- get contractVersion() {
158
- return _ValueObject.CONTRACT_VERSION;
159
- }
160
- /**
161
- * Freezes the instance shell, blocking reassignment of any own field.
162
- *
163
- * `value` is already deep-frozen by the constructor, so the wrapped data is
164
- * immutable regardless. The instance itself is NOT frozen automatically
165
- * because a subclass may still need to assign its own fields after
166
- * `super(value)` runs. Call `finalize()` at the very end of the subclass
167
- * constructor (after all fields are set) to make the whole value object
168
- * immutable.
169
- */
170
- finalize() {
171
- Object.freeze(this);
172
- }
173
- /**
174
- * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value
175
- * object serializes to its primitive form rather than exposing the internal
176
- * `value` wrapper.
177
- */
178
- toJSON() {
179
- return this.toPrimitive();
180
- }
181
- };
182
- ValueObject = _ValueObject = __decorate([version$1("1.0")], ValueObject);
25
+ const version$1 = "1.3.0";
183
26
  //#endregion
184
27
  //#region src/index.ts
185
28
  const ERP_CORE_NAME = "erp-core";
186
- const ERP_CORE_VERSION = version;
29
+ const ERP_CORE_VERSION = version$1;
187
30
  const erpCoreRelease = {
188
31
  name: ERP_CORE_NAME,
189
32
  version: ERP_CORE_VERSION
190
33
  };
191
34
  //#endregion
192
- export { AlreadyExistsError, AppError, AuthenticationError, AuthorizationError, BusinessRuleViolationError, Command, ComputeEngineRegistry, ComputeEvaluatorRegistry, ComputePayloadParserRegistry, ComputePayloadParsers, ComputeRegistry, ConflictError, ContextResolverRegistry, ContextSeedValidator, CoreConfig, SerializationInError as DeserializationError, SerializationInError, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, Err, ErrorCodes, ExpiredError, GateEngineRegistry, GatePayloadParsers, IdempotencyError, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, InMemoryPolicyDefinitionRepository, IntegrationError, LegacyIncompatibleError, NotFoundError, NotYetValidError, Ok, Outcome, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogFactory, PolicyContextBuilder, PolicyContextPath, PolicyDefinition, PolicyEvaluationErrors, PolicyHashing, PolicyKey, PolicyResolver, PolicyScopeMatcher, PolicyService, Query, RequestedBy, Result, SerializationCodes, SerializationError, SerializationMessages, SerializationOutError, TemporalError, TemporalUseCase, UnexpectedError, UniqueConstraintViolationError, UseCase, ValidationError, ValidationField, ValueObject, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, assertTemporalContext, contextResolverRegistry, coreConfig, createTemporalContext, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate };
35
+ export { AlreadyExistsError, AppError, AuthenticationError, AuthorizationError, BusinessRuleViolationError, BusinessRuleViolationException, CONTRACT_VERSION_PROPERTY, Command, ComputeEngineRegistry, ComputeEvaluatorRegistry, ComputePayloadParserRegistry, ComputePayloadParsers, ComputeRegistry, ConflictError, ContextResolverRegistry, ContextSeedValidator, CoreConfig, SerializationInError as DeserializationError, SerializationInError, DomainException, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, EntityNotFoundException, Err, ErrorCodes, ExpiredError, GateEngineRegistry, GatePayloadParsers, IdempotencyError, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, InMemoryPolicyDefinitionRepository, IntegrationError, InvalidStateTransitionException, InvalidValueException, InvariantViolationException, LegacyIncompatibleError, MultipleValidationException, NotFoundError, NotYetValidError, Ok, Outcome, PluginManager, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogFactory, PolicyContextBuilder, PolicyContextPath, PolicyDefinition, PolicyEvaluationErrors, PolicyHashing, PolicyKey, PolicyResolver, PolicyScopeMatcher, PolicyService, Query, RequestedBy, Result, RulesetRegistry, SerializationCodes, SerializationError, SerializationMessages, SerializationOutError, TemporalError, TemporalUseCase, UnexpectedError, UniqueConstraintViolationError, UseCase, UuidIdentifier, ValidationCode, ValidationError, ValidationException, ValidationField, ValueObject, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, assertTemporalContext, buildDomainEventContractVersions, contextResolverRegistry, coreConfig, createDomainEventEnvelope, createTemporalContext, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate, version };
193
36
 
194
37
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["version","version"],"sources":["../src/version.ts","../src/core/shared/aggregate-version.ts","../src/core/domain/entity.ts","../src/core/domain/value-object.ts","../src/index.ts"],"sourcesContent":["// Versao do kit, sincronizada com package.json por scripts/sync-kit-version.mjs.\n// Nao edite a mao: rode `npm run sync-kit-version` (ou e regenerado no release).\n//\n// Mantemos a versao aqui, dentro de src/, para que a copia full-control seja\n// auto-contida: ao copiar so o conteudo de src/, o entry nao depende de um\n// `../package.json` que deixaria de existir no projeto consumidor.\nexport const version = \"1.1.0\";\n","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\nfunction assertValidAggregateVersion(aggregateVersion: number): void {\n if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) {\n throw new InvariantViolationException(\n `aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`,\n );\n }\n}\n\nexport { assertValidAggregateVersion };\n","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\nimport { assertValidAggregateVersion } from \"../shared/aggregate-version.js\";\nimport { assertValidDate, cloneDate } from \"../shared/temporal-guards.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * The minimal persisted shape needed to reconstitute an {@link Entity}.\n *\n * This is the contract between storage and the domain: a repository maps a row\n * (or document) onto these four fields and hands them to a subclass constructor.\n * `aggregateVersion` travels with the state so optimistic-concurrency checks\n * survive a round-trip through the database.\n */\ninterface EntityState<TIdentifier> {\n readonly id: TIdentifier;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly aggregateVersion: number;\n}\n\n/**\n * Base class for domain entities — objects defined by a stable identity rather\n * than by their attributes. Two entities are \"the same\" when their `id`\n * matches, even if every other field differs; this is the opposite of a\n * {@link ValueObject}, which is defined entirely by its contents.\n *\n * The class owns the bookkeeping common to every aggregate root: a creation\n * timestamp that never changes, a last-modified timestamp, and an\n * `aggregateVersion` counter used for optimistic concurrency control. All three\n * are validated on construction and the dates are defensively cloned, so an\n * entity can never be built into — or leak — an inconsistent temporal state.\n *\n * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).\n */\n@version(\"1.0\")\nabstract class Entity<TIdentifier> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n private readonly _id: TIdentifier;\n private readonly _createdAt: Date;\n private _updatedAt: Date;\n private _aggregateVersion: number;\n\n /**\n * Reconstitutes an entity from its persisted {@link EntityState}.\n *\n * Validates the temporal invariants up front so an invalid entity is\n * impossible to construct: both dates must be valid, the aggregate version\n * must be a non-negative integer, and `updatedAt` may not predate\n * `createdAt`. Both dates are cloned on the way in so a later mutation of\n * the caller's `Date` objects cannot reach into the entity's internal state.\n *\n * Declared `protected` because entities are reconstituted through a\n * subclass factory, never instantiated directly by application code.\n *\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\n */\n protected constructor(state: EntityState<TIdentifier>) {\n assertValidDate(\"createdAt\", state.createdAt);\n assertValidDate(\"updatedAt\", state.updatedAt);\n assertValidAggregateVersion(state.aggregateVersion);\n\n if (state.updatedAt.getTime() < state.createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._id = state.id;\n this._createdAt = cloneDate(state.createdAt);\n this._updatedAt = cloneDate(state.updatedAt);\n this._aggregateVersion = state.aggregateVersion;\n }\n\n /** The entity's stable identity — the basis for equality between entities. */\n public get id(): TIdentifier {\n return this._id;\n }\n\n /**\n * When the entity was first created.\n *\n * Returns a clone so callers cannot mutate the entity's internal `Date`;\n * the value is fixed at construction and never changes thereafter.\n */\n public get createdAt(): Date {\n return cloneDate(this._createdAt);\n }\n\n /**\n * When the entity was last modified.\n *\n * Returns a clone for the same encapsulation reason as {@link createdAt};\n * the underlying value advances only through {@link markAsModified}.\n */\n public get updatedAt(): Date {\n return cloneDate(this._updatedAt);\n }\n\n /**\n * Monotonic counter incremented on every mutation, used for optimistic\n * concurrency control: a writer reads this value, and the persistence layer\n * rejects the write if the stored version has moved on in the meantime.\n */\n public get aggregateVersion(): number {\n return this._aggregateVersion;\n }\n\n /**\n * The schema/contract version stamped on this entity type by the\n * `@version` decorator — used to detect and migrate state persisted under\n * an older shape.\n */\n public get contractVersion(): ContractVersion {\n return Entity.CONTRACT_VERSION;\n }\n\n /**\n * The single seam through which an entity records a mutation: it advances\n * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must\n * call this from every state-changing method so the version counter stays\n * an accurate optimistic-lock token.\n *\n * @param updatedAt - The modification instant; defaults to now. Validated\n * and required not to predate `createdAt`, preserving the same invariant\n * the constructor enforces.\n * @returns The new aggregate version after the increment.\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\n */\n protected markAsModified(updatedAt: Date = new Date()): number {\n assertValidDate(\"updatedAt\", updatedAt);\n\n if (updatedAt.getTime() < this._createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._updatedAt = cloneDate(updatedAt);\n this._aggregateVersion += 1;\n\n return this._aggregateVersion;\n }\n}\n\nexport { Entity, type EntityState };\n","import { type DeepReadonly, makeImmutable } from \"../shared/immutable.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * Base class for value objects — domain concepts defined entirely by their\n * contents, with no identity of their own. Two value objects are\n * interchangeable when they hold equal data, which is the opposite of an\n * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one\n * instance with an equal one changes nothing about the model.\n *\n * Immutability is the defining guarantee here. The wrapped `value` is\n * deep-frozen on construction, so a value object can be shared freely without\n * any risk of a consumer mutating shared state. Subclasses seal the instance\n * itself with {@link finalize} once their own fields are set.\n *\n * @typeParam T - The shape of the wrapped data.\n * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.\n */\n@version(\"1.0\")\nabstract class ValueObject<T, P> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n /** The wrapped data, deep-frozen so it can never be mutated after construction. */\n public readonly value: DeepReadonly<T>;\n\n /**\n * Wraps `value`, deep-freezing it so the value object is immutable from the\n * moment it exists. Declared `protected` because value objects are built\n * through a validating subclass factory, never instantiated directly.\n */\n protected constructor(value: T) {\n this.value = makeImmutable(value);\n }\n\n /**\n * The schema/contract version stamped on this value-object type by the\n * `@version` decorator — used to detect state persisted under an older shape.\n */\n public get contractVersion(): ContractVersion {\n return ValueObject.CONTRACT_VERSION;\n }\n\n /**\n * Freezes the instance shell, blocking reassignment of any own field.\n *\n * `value` is already deep-frozen by the constructor, so the wrapped data is\n * immutable regardless. The instance itself is NOT frozen automatically\n * because a subclass may still need to assign its own fields after\n * `super(value)` runs. Call `finalize()` at the very end of the subclass\n * constructor (after all fields are set) to make the whole value object\n * immutable.\n */\n protected finalize(): void {\n Object.freeze(this);\n }\n\n /**\n * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value\n * object serializes to its primitive form rather than exposing the internal\n * `value` wrapper.\n */\n public toJSON(): P {\n return this.toPrimitive();\n }\n\n /**\n * Compares this value object with another by content. Because value objects\n * carry no identity, subclasses implement equality over the wrapped data\n * (typically the primitive form), so two independently constructed instances\n * holding the same data are considered equal.\n */\n public abstract equals(other: this): boolean;\n\n /**\n * Projects the value object down to a plain, serializable primitive form —\n * the representation suitable for persistence, transport, or comparison.\n */\n public abstract toPrimitive(): P;\n}\n\nexport { type DeepReadonly, ValueObject };\n","import { version } from \"./version.js\";\n\nexport * from \"./core/index.js\";\n\nexport const ERP_CORE_NAME = \"erp-core\";\nexport const ERP_CORE_VERSION = version;\n\nexport const erpCoreRelease = {\n name: ERP_CORE_NAME,\n version: ERP_CORE_VERSION,\n} as const;\n"],"mappings":";;;;;;;;;;;;AAMA,MAAa,UAAU;;;ACJvB,SAAS,4BAA4B,kBAAgC;CACjE,IAAI,CAAC,OAAO,UAAU,gBAAgB,KAAK,mBAAmB,GAC1D,MAAM,IAAI,4BACN,8DAA8D,kBAClE;AAER;;;;;;;;;;;;;;;;;;AC0BA,IAAA,SAAA,MACe,OAAoB;;;;;;;;;;;;;;;;;;CAsB/B,YAAsB,OAAiC;EACnD,gBAAgB,aAAa,MAAM,SAAS;EAC5C,gBAAgB,aAAa,MAAM,SAAS;EAC5C,4BAA4B,MAAM,gBAAgB;EAElD,IAAI,MAAM,UAAU,QAAQ,IAAI,MAAM,UAAU,QAAQ,GACpD,MAAM,IAAI,4BACN,4CACJ;EAGJ,KAAK,MAAM,MAAM;EACjB,KAAK,aAAa,UAAU,MAAM,SAAS;EAC3C,KAAK,aAAa,UAAU,MAAM,SAAS;EAC3C,KAAK,oBAAoB,MAAM;CACnC;;CAGA,IAAW,KAAkB;EACzB,OAAO,KAAK;CAChB;;;;;;;CAQA,IAAW,YAAkB;EACzB,OAAO,UAAU,KAAK,UAAU;CACpC;;;;;;;CAQA,IAAW,YAAkB;EACzB,OAAO,UAAU,KAAK,UAAU;CACpC;;;;;;CAOA,IAAW,mBAA2B;EAClC,OAAO,KAAK;CAChB;;;;;;CAOA,IAAW,kBAAmC;EAC1C,OAAA,QAAc;CAClB;;;;;;;;;;;;;CAcA,eAAyB,4BAAkB,IAAI,KAAK,GAAW;EAC3D,gBAAgB,aAAa,SAAS;EAEtC,IAAI,UAAU,QAAQ,IAAI,KAAK,WAAW,QAAQ,GAC9C,MAAM,IAAI,4BACN,4CACJ;EAGJ,KAAK,aAAa,UAAU,SAAS;EACrC,KAAK,qBAAqB;EAE1B,OAAO,KAAK;CAChB;AACJ;+BA7GCA,UAAQ,KAAK,CAAA,GAAA,MAAA;;;;;;;;;;;;;;;;;;;AChBd,IAAA,cAAA,MACe,YAAkB;;;;;;;;;CAW7B,YAAsB,OAAU;EAC5B,KAAK,QAAQ,cAAc,KAAK;CACpC;;;;;CAMA,IAAW,kBAAmC;EAC1C,OAAA,aAAmB;CACvB;;;;;;;;;;;CAYA,WAA2B;EACvB,OAAO,OAAO,IAAI;CACtB;;;;;;CAOA,SAAmB;EACf,OAAO,KAAK,YAAY;CAC5B;AAeJ;yCA5DCC,UAAQ,KAAK,CAAA,GAAA,WAAA;;;ACdd,MAAa,gBAAgB;AAC7B,MAAa,mBAAmB;AAEhC,MAAa,iBAAiB;CAC1B,MAAM;CACN,SAAS;AACb"}
1
+ {"version":3,"file":"index.js","names":["version","version"],"sources":["../src/version.ts","../src/index.ts"],"sourcesContent":["// Versao do kit, sincronizada com package.json por scripts/sync-kit-version.mjs.\n// Nao edite a mao: rode `npm run sync-kit-version` (ou e regenerado no release).\n//\n// Mantemos a versao aqui, dentro de src/, para que a copia full-control seja\n// auto-contida: ao copiar so o conteudo de src/, o entry nao depende de um\n// `../package.json` que deixaria de existir no projeto consumidor.\nexport const version = \"1.3.0\";\n","import { version } from \"./version.js\";\n\nexport * from \"./core/index.js\";\n\nexport const ERP_CORE_NAME = \"erp-core\";\nexport const ERP_CORE_VERSION = version;\n\nexport const erpCoreRelease = {\n name: ERP_CORE_NAME,\n version: ERP_CORE_VERSION,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAaA,YAAU;;;ACFvB,MAAa,gBAAgB;AAC7B,MAAa,mBAAmBC;AAEhC,MAAa,iBAAiB;CAC1B,MAAM;CACN,SAAS;AACb"}
@@ -0,0 +1,47 @@
1
+ const require_domain_exception = require("./domain-exception.cjs");
2
+ //#region src/core/exceptions/business-rule-violation-exception.ts
3
+ var BusinessRuleViolationException = class extends require_domain_exception.DomainException {
4
+ constructor(rule, message) {
5
+ super(message);
6
+ this.rule = rule;
7
+ }
8
+ };
9
+ //#endregion
10
+ //#region src/core/exceptions/entity-not-found-exception.ts
11
+ var EntityNotFoundException = class extends require_domain_exception.DomainException {
12
+ constructor(entityName, identifier) {
13
+ super(`${entityName} with identifier ${identifier} was not found.`);
14
+ this.entityName = entityName;
15
+ this.identifier = identifier;
16
+ }
17
+ };
18
+ //#endregion
19
+ //#region src/core/exceptions/invalid-state-transition-exception.ts
20
+ var InvalidStateTransitionException = class extends require_domain_exception.DomainException {
21
+ constructor(from, to, message) {
22
+ super(message);
23
+ this.from = from;
24
+ this.to = to;
25
+ }
26
+ };
27
+ //#endregion
28
+ Object.defineProperty(exports, "BusinessRuleViolationException", {
29
+ enumerable: true,
30
+ get: function() {
31
+ return BusinessRuleViolationException;
32
+ }
33
+ });
34
+ Object.defineProperty(exports, "EntityNotFoundException", {
35
+ enumerable: true,
36
+ get: function() {
37
+ return EntityNotFoundException;
38
+ }
39
+ });
40
+ Object.defineProperty(exports, "InvalidStateTransitionException", {
41
+ enumerable: true,
42
+ get: function() {
43
+ return InvalidStateTransitionException;
44
+ }
45
+ });
46
+
47
+ //# sourceMappingURL=invalid-state-transition-exception.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invalid-state-transition-exception.cjs","names":["DomainException","DomainException","DomainException"],"sources":["../src/core/exceptions/business-rule-violation-exception.ts","../src/core/exceptions/entity-not-found-exception.ts","../src/core/exceptions/invalid-state-transition-exception.ts"],"sourcesContent":["import { DomainException } from \"./domain-exception.js\";\n\nclass BusinessRuleViolationException extends DomainException {\n constructor(\n public readonly rule: string,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport { BusinessRuleViolationException };\n","import { DomainException } from \"./domain-exception.js\";\n\nclass EntityNotFoundException extends DomainException {\n constructor(\n public readonly entityName: string,\n public readonly identifier: string,\n ) {\n super(`${entityName} with identifier ${identifier} was not found.`);\n }\n}\n\nexport { EntityNotFoundException };\n","import { DomainException } from \"./domain-exception.js\";\n\nclass InvalidStateTransitionException<\n TState extends string = string,\n> extends DomainException {\n constructor(\n public readonly from: TState,\n public readonly to: TState,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport { InvalidStateTransitionException };\n"],"mappings":";;AAEA,IAAM,iCAAN,cAA6CA,yBAAAA,gBAAgB;CACzD,YACI,MACA,SACF;EACE,MAAM,OAAO;EAHG,KAAA,OAAA;CAIpB;AACJ;;;ACPA,IAAM,0BAAN,cAAsCC,yBAAAA,gBAAgB;CAClD,YACI,YACA,YACF;EACE,MAAM,GAAG,WAAW,mBAAmB,WAAW,gBAAgB;EAHlD,KAAA,aAAA;EACA,KAAA,aAAA;CAGpB;AACJ;;;ACPA,IAAM,kCAAN,cAEUC,yBAAAA,gBAAgB;CACtB,YACI,MACA,IACA,SACF;EACE,MAAM,OAAO;EAJG,KAAA,OAAA;EACA,KAAA,KAAA;CAIpB;AACJ"}
@@ -0,0 +1,30 @@
1
+ import { t as DomainException } from "./domain-exception.js";
2
+ //#region src/core/exceptions/business-rule-violation-exception.ts
3
+ var BusinessRuleViolationException = class extends DomainException {
4
+ constructor(rule, message) {
5
+ super(message);
6
+ this.rule = rule;
7
+ }
8
+ };
9
+ //#endregion
10
+ //#region src/core/exceptions/entity-not-found-exception.ts
11
+ var EntityNotFoundException = class extends DomainException {
12
+ constructor(entityName, identifier) {
13
+ super(`${entityName} with identifier ${identifier} was not found.`);
14
+ this.entityName = entityName;
15
+ this.identifier = identifier;
16
+ }
17
+ };
18
+ //#endregion
19
+ //#region src/core/exceptions/invalid-state-transition-exception.ts
20
+ var InvalidStateTransitionException = class extends DomainException {
21
+ constructor(from, to, message) {
22
+ super(message);
23
+ this.from = from;
24
+ this.to = to;
25
+ }
26
+ };
27
+ //#endregion
28
+ export { EntityNotFoundException as n, BusinessRuleViolationException as r, InvalidStateTransitionException as t };
29
+
30
+ //# sourceMappingURL=invalid-state-transition-exception.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invalid-state-transition-exception.js","names":[],"sources":["../src/core/exceptions/business-rule-violation-exception.ts","../src/core/exceptions/entity-not-found-exception.ts","../src/core/exceptions/invalid-state-transition-exception.ts"],"sourcesContent":["import { DomainException } from \"./domain-exception.js\";\n\nclass BusinessRuleViolationException extends DomainException {\n constructor(\n public readonly rule: string,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport { BusinessRuleViolationException };\n","import { DomainException } from \"./domain-exception.js\";\n\nclass EntityNotFoundException extends DomainException {\n constructor(\n public readonly entityName: string,\n public readonly identifier: string,\n ) {\n super(`${entityName} with identifier ${identifier} was not found.`);\n }\n}\n\nexport { EntityNotFoundException };\n","import { DomainException } from \"./domain-exception.js\";\n\nclass InvalidStateTransitionException<\n TState extends string = string,\n> extends DomainException {\n constructor(\n public readonly from: TState,\n public readonly to: TState,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport { InvalidStateTransitionException };\n"],"mappings":";;AAEA,IAAM,iCAAN,cAA6C,gBAAgB;CACzD,YACI,MACA,SACF;EACE,MAAM,OAAO;EAHG,KAAA,OAAA;CAIpB;AACJ;;;ACPA,IAAM,0BAAN,cAAsC,gBAAgB;CAClD,YACI,YACA,YACF;EACE,MAAM,GAAG,WAAW,mBAAmB,WAAW,gBAAgB;EAHlD,KAAA,aAAA;EACA,KAAA,aAAA;CAGpB;AACJ;;;ACPA,IAAM,kCAAN,cAEU,gBAAgB;CACtB,YACI,MACA,IACA,SACF;EACE,MAAM,OAAO;EAJG,KAAA,OAAA;EACA,KAAA,KAAA;CAIpB;AACJ"}
@@ -0,0 +1,16 @@
1
+ const require_domain_exception = require("./domain-exception.cjs");
2
+ //#region src/core/exceptions/invariant-violation-exception.ts
3
+ var InvariantViolationException = class extends require_domain_exception.DomainException {
4
+ constructor(message) {
5
+ super(message);
6
+ }
7
+ };
8
+ //#endregion
9
+ Object.defineProperty(exports, "InvariantViolationException", {
10
+ enumerable: true,
11
+ get: function() {
12
+ return InvariantViolationException;
13
+ }
14
+ });
15
+
16
+ //# sourceMappingURL=invariant-violation-exception.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invariant-violation-exception.cjs","names":["DomainException"],"sources":["../src/core/exceptions/invariant-violation-exception.ts"],"sourcesContent":["import { DomainException } from \"./domain-exception.js\";\n\nclass InvariantViolationException extends DomainException {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport { InvariantViolationException };\n"],"mappings":";;AAEA,IAAM,8BAAN,cAA0CA,yBAAAA,gBAAgB;CACtD,YAAY,SAAiB;EACzB,MAAM,OAAO;CACjB;AACJ"}
@@ -0,0 +1,11 @@
1
+ import { t as DomainException } from "./domain-exception.js";
2
+ //#region src/core/exceptions/invariant-violation-exception.ts
3
+ var InvariantViolationException = class extends DomainException {
4
+ constructor(message) {
5
+ super(message);
6
+ }
7
+ };
8
+ //#endregion
9
+ export { InvariantViolationException as t };
10
+
11
+ //# sourceMappingURL=invariant-violation-exception.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invariant-violation-exception.js","names":[],"sources":["../src/core/exceptions/invariant-violation-exception.ts"],"sourcesContent":["import { DomainException } from \"./domain-exception.js\";\n\nclass InvariantViolationException extends DomainException {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport { InvariantViolationException };\n"],"mappings":";;AAEA,IAAM,8BAAN,cAA0C,gBAAgB;CACtD,YAAY,SAAiB;EACzB,MAAM,OAAO;CACjB;AACJ"}
@@ -0,0 +1,65 @@
1
+ const require_unexpected_error = require("./unexpected-error.cjs");
2
+ //#region src/core/errors/business-rule-violation-error.ts
3
+ var BusinessRuleViolationError = class extends require_unexpected_error.AppError {
4
+ constructor(rule, message, detail, options) {
5
+ const baseMetadata = detail ? {
6
+ rule,
7
+ detail
8
+ } : { rule };
9
+ const mergedMetadata = options?.metadata ? {
10
+ ...baseMetadata,
11
+ ...options.metadata
12
+ } : baseMetadata;
13
+ super(message, require_unexpected_error.ErrorCodes.businessRuleViolation, {
14
+ ...options,
15
+ metadata: mergedMetadata
16
+ });
17
+ }
18
+ };
19
+ //#endregion
20
+ //#region src/core/errors/not-found-error.ts
21
+ /**
22
+ * Raised when a requested resource does not exist. Maps naturally onto an HTTP
23
+ * 404 at the edge, but stays transport-agnostic here.
24
+ *
25
+ * The `resource` name builds the message (`"<resource> not found"`) and, with
26
+ * the optional lookup `criteria`, lands in the metadata so logs show *what* was
27
+ * searched for without the caller having to restate it in the message.
28
+ */
29
+ var NotFoundError = class extends require_unexpected_error.AppError {
30
+ /**
31
+ * @param resource - Human-readable name of the missing resource (e.g. `"Order"`).
32
+ * @param criteria - Optional lookup keys used in the search; recorded in
33
+ * metadata to aid debugging. Avoid putting sensitive values here.
34
+ * @param options - Optional cause, correlation ids, and extra metadata.
35
+ */
36
+ constructor(resource, criteria, options) {
37
+ const baseMetadata = criteria ? {
38
+ resource,
39
+ criteria
40
+ } : { resource };
41
+ const mergedMetadata = options?.metadata ? {
42
+ ...baseMetadata,
43
+ ...options.metadata
44
+ } : baseMetadata;
45
+ super(`${resource} not found`, require_unexpected_error.ErrorCodes.notFound, {
46
+ ...options,
47
+ metadata: mergedMetadata
48
+ });
49
+ }
50
+ };
51
+ //#endregion
52
+ Object.defineProperty(exports, "BusinessRuleViolationError", {
53
+ enumerable: true,
54
+ get: function() {
55
+ return BusinessRuleViolationError;
56
+ }
57
+ });
58
+ Object.defineProperty(exports, "NotFoundError", {
59
+ enumerable: true,
60
+ get: function() {
61
+ return NotFoundError;
62
+ }
63
+ });
64
+
65
+ //# sourceMappingURL=not-found-error.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"not-found-error.cjs","names":["AppError","ErrorCodes","AppError","ErrorCodes"],"sources":["../src/core/errors/business-rule-violation-error.ts","../src/core/errors/not-found-error.ts"],"sourcesContent":["import { AppError } from \"./app-error.js\";\nimport { ErrorCodes } from \"./error-codes.js\";\nimport type { AppErrorOptions } from \"./types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// BusinessRuleViolationError\n// ─────────────────────────────────────────────────────────────────────────────\n\nclass BusinessRuleViolationError extends AppError {\n constructor(\n rule: string,\n message: string,\n detail?: Record<string, unknown>,\n options?: AppErrorOptions,\n ) {\n const baseMetadata = detail ? { rule, detail } : { rule };\n const mergedMetadata = options?.metadata\n ? { ...baseMetadata, ...options.metadata }\n : baseMetadata;\n\n super(message, ErrorCodes.businessRuleViolation, {\n ...options,\n metadata: mergedMetadata,\n });\n }\n}\n\nexport { BusinessRuleViolationError };\n","import { AppError } from \"./app-error.js\";\nimport { ErrorCodes } from \"./error-codes.js\";\nimport type { AppErrorOptions } from \"./types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// NotFoundError\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Raised when a requested resource does not exist. Maps naturally onto an HTTP\n * 404 at the edge, but stays transport-agnostic here.\n *\n * The `resource` name builds the message (`\"<resource> not found\"`) and, with\n * the optional lookup `criteria`, lands in the metadata so logs show *what* was\n * searched for without the caller having to restate it in the message.\n */\nclass NotFoundError extends AppError {\n /**\n * @param resource - Human-readable name of the missing resource (e.g. `\"Order\"`).\n * @param criteria - Optional lookup keys used in the search; recorded in\n * metadata to aid debugging. Avoid putting sensitive values here.\n * @param options - Optional cause, correlation ids, and extra metadata.\n */\n constructor(\n resource: string,\n criteria?: Record<string, unknown>,\n options?: AppErrorOptions,\n ) {\n const baseMetadata = criteria ? { resource, criteria } : { resource };\n const mergedMetadata = options?.metadata\n ? { ...baseMetadata, ...options.metadata }\n : baseMetadata;\n\n super(`${resource} not found`, ErrorCodes.notFound, {\n ...options,\n metadata: mergedMetadata,\n });\n }\n}\n\nexport { NotFoundError };\n"],"mappings":";;AAQA,IAAM,6BAAN,cAAyCA,yBAAAA,SAAS;CAC9C,YACI,MACA,SACA,QACA,SACF;EACE,MAAM,eAAe,SAAS;GAAE;GAAM;EAAO,IAAI,EAAE,KAAK;EACxD,MAAM,iBAAiB,SAAS,WAC1B;GAAE,GAAG;GAAc,GAAG,QAAQ;EAAS,IACvC;EAEN,MAAM,SAASC,yBAAAA,WAAW,uBAAuB;GAC7C,GAAG;GACH,UAAU;EACd,CAAC;CACL;AACJ;;;;;;;;;;;ACTA,IAAM,gBAAN,cAA4BC,yBAAAA,SAAS;;;;;;;CAOjC,YACI,UACA,UACA,SACF;EACE,MAAM,eAAe,WAAW;GAAE;GAAU;EAAS,IAAI,EAAE,SAAS;EACpE,MAAM,iBAAiB,SAAS,WAC1B;GAAE,GAAG;GAAc,GAAG,QAAQ;EAAS,IACvC;EAEN,MAAM,GAAG,SAAS,aAAaC,yBAAAA,WAAW,UAAU;GAChD,GAAG;GACH,UAAU;EACd,CAAC;CACL;AACJ"}
@@ -1,4 +1,4 @@
1
- import { a as ErrorCodes, r as AppError } from "./validation-code.js";
1
+ import { i as ErrorCodes, n as AppError } from "./unexpected-error.js";
2
2
  //#region src/core/errors/business-rule-violation-error.ts
3
3
  var BusinessRuleViolationError = class extends AppError {
4
4
  constructor(rule, message, detail, options) {
@@ -0,0 +1,97 @@
1
+ const require_invariant_violation_exception = require("./invariant-violation-exception.cjs");
2
+ //#region src/core/result/outcome.ts
3
+ /**
4
+ * Outcome — Business decision abstraction.
5
+ *
6
+ * Represents the semantic result of a domain decision, policy evaluation,
7
+ * or business rule. NOT for technical success/failure — use Result for that.
8
+ *
9
+ * Mental model:
10
+ * "What was the business decision?"
11
+ * NOT "Did the operation succeed?"
12
+ *
13
+ * The status axis represents valid business outcomes (APPROVED, REJECTED,
14
+ * ALLOW, DENY, NO_OP, etc.), never technical Ok/Err.
15
+ *
16
+ * @typeParam S - Union of valid status literals for this outcome
17
+ * @typeParam D - Shape of the decision data carried by this outcome
18
+ */
19
+ var Outcome = class Outcome {
20
+ constructor(status, data, reason, metadata) {
21
+ this.status = status;
22
+ this.data = data;
23
+ this.reason = reason;
24
+ this.metadata = metadata;
25
+ Object.freeze(this);
26
+ }
27
+ static of(status, data, reason, metadata) {
28
+ return new Outcome(status, data, reason, Object.freeze({ ...metadata }));
29
+ }
30
+ static approved(data, reason) {
31
+ return new Outcome("APPROVED", data, reason, Object.freeze({}));
32
+ }
33
+ static rejected(data, reason) {
34
+ return new Outcome("REJECTED", data, reason, Object.freeze({}));
35
+ }
36
+ static noOp(data, reason) {
37
+ return new Outcome("NO_OP", data, reason, Object.freeze({}));
38
+ }
39
+ static deferred(data, reason) {
40
+ return new Outcome("DEFERRED", data, reason, Object.freeze({}));
41
+ }
42
+ static requiresReview(data, reason) {
43
+ return new Outcome("REQUIRES_REVIEW", data, reason, Object.freeze({}));
44
+ }
45
+ /**
46
+ * Narrows this Outcome to a specific status.
47
+ *
48
+ * @example
49
+ * if (outcome.is('DENY')) {
50
+ * outcome.data.violations // TS knows status is 'DENY'
51
+ * }
52
+ */
53
+ is(status) {
54
+ return this.status === status;
55
+ }
56
+ /**
57
+ * Exhaustive pattern match over all possible statuses.
58
+ * TypeScript enforces that every status has a handler.
59
+ *
60
+ * @example
61
+ * outcome.match({
62
+ * ALLOW: (o) => handleAllow(o.data),
63
+ * DENY: (o) => handleDeny(o.data.violations),
64
+ * })
65
+ */
66
+ match(handlers) {
67
+ const handler = handlers[this.status];
68
+ if (typeof handler !== "function") {
69
+ const availableStatuses = Object.keys(handlers);
70
+ throw new require_invariant_violation_exception.InvariantViolationException(`Outcome.match is missing a handler for runtime status "${this.status}". Available handlers: ${availableStatuses.join(", ") || "(none)"}`);
71
+ }
72
+ return handler(this);
73
+ }
74
+ withMetadata(extra) {
75
+ return new Outcome(this.status, this.data, this.reason, Object.freeze({
76
+ ...this.metadata,
77
+ ...extra
78
+ }));
79
+ }
80
+ withReason(reason) {
81
+ return new Outcome(this.status, this.data, reason, this.metadata);
82
+ }
83
+ toString() {
84
+ const parts = [this.status];
85
+ if (this.reason) parts.push(`reason="${this.reason}"`);
86
+ return `Outcome(${parts.join(", ")})`;
87
+ }
88
+ };
89
+ //#endregion
90
+ Object.defineProperty(exports, "Outcome", {
91
+ enumerable: true,
92
+ get: function() {
93
+ return Outcome;
94
+ }
95
+ });
96
+
97
+ //# sourceMappingURL=outcome.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outcome.cjs","names":["InvariantViolationException"],"sources":["../src/core/result/outcome.ts"],"sourcesContent":["// core/domain/outcome.ts\n\nimport { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\n/**\n * Outcome — Business decision abstraction.\n *\n * Represents the semantic result of a domain decision, policy evaluation,\n * or business rule. NOT for technical success/failure — use Result for that.\n *\n * Mental model:\n * \"What was the business decision?\"\n * NOT \"Did the operation succeed?\"\n *\n * The status axis represents valid business outcomes (APPROVED, REJECTED,\n * ALLOW, DENY, NO_OP, etc.), never technical Ok/Err.\n *\n * @typeParam S - Union of valid status literals for this outcome\n * @typeParam D - Shape of the decision data carried by this outcome\n */\nexport class Outcome<S extends string, D = undefined> {\n readonly status: S;\n readonly data: D;\n readonly reason: string | undefined;\n readonly metadata: Readonly<Record<string, unknown>>;\n\n private constructor(\n status: S,\n data: D,\n reason: string | undefined,\n metadata: Readonly<Record<string, unknown>>,\n ) {\n this.status = status;\n this.data = data;\n this.reason = reason;\n this.metadata = metadata;\n Object.freeze(this);\n }\n\n // ─── Generic factory ────────────────────────────────────────────────\n\n static of<S extends string, D = undefined>(\n status: S,\n data: D,\n reason?: string,\n metadata?: Record<string, unknown>,\n ): Outcome<S, D> {\n return new Outcome(\n status,\n data,\n reason,\n Object.freeze({ ...metadata }),\n );\n }\n\n // ─── Convenience factories for common business statuses ─────────────\n\n static approved<D = undefined>(\n data: D,\n reason?: string,\n ): Outcome<\"APPROVED\", D> {\n return new Outcome(\"APPROVED\", data, reason, Object.freeze({}));\n }\n\n static rejected<D = undefined>(\n data: D,\n reason: string,\n ): Outcome<\"REJECTED\", D> {\n return new Outcome(\"REJECTED\", data, reason, Object.freeze({}));\n }\n\n static noOp<D = undefined>(data: D, reason?: string): Outcome<\"NO_OP\", D> {\n return new Outcome(\"NO_OP\", data, reason, Object.freeze({}));\n }\n\n static deferred<D = undefined>(\n data: D,\n reason: string,\n ): Outcome<\"DEFERRED\", D> {\n return new Outcome(\"DEFERRED\", data, reason, Object.freeze({}));\n }\n\n static requiresReview<D = undefined>(\n data: D,\n reason: string,\n ): Outcome<\"REQUIRES_REVIEW\", D> {\n return new Outcome(\"REQUIRES_REVIEW\", data, reason, Object.freeze({}));\n }\n\n // ─── Type narrowing ────────────────────────────────────────────────\n\n /**\n * Narrows this Outcome to a specific status.\n *\n * @example\n * if (outcome.is('DENY')) {\n * outcome.data.violations // TS knows status is 'DENY'\n * }\n */\n is<T extends S>(status: T): this is Outcome<T, D> {\n return (this.status as string) === status;\n }\n\n // ─── Exhaustive match ──────────────────────────────────────────────\n\n /**\n * Exhaustive pattern match over all possible statuses.\n * TypeScript enforces that every status has a handler.\n *\n * @example\n * outcome.match({\n * ALLOW: (o) => handleAllow(o.data),\n * DENY: (o) => handleDeny(o.data.violations),\n * })\n */\n match<THandlers extends { [K in S]: (outcome: Outcome<K, D>) => unknown }>(\n handlers: THandlers,\n ): ReturnType<THandlers[S]> {\n const handler = (\n handlers as Partial<Record<string, (o: unknown) => unknown>>\n )[this.status];\n\n if (typeof handler !== \"function\") {\n const availableStatuses = Object.keys(handlers);\n throw new InvariantViolationException(\n `Outcome.match is missing a handler for runtime status \"${this.status}\". Available handlers: ${availableStatuses.join(\", \") || \"(none)\"}`,\n );\n }\n\n return handler(this) as ReturnType<THandlers[S]>;\n }\n\n // ─── Derived copies ────────────────────────────────────────────────\n\n withMetadata(extra: Record<string, unknown>): Outcome<S, D> {\n return new Outcome(\n this.status,\n this.data,\n this.reason,\n Object.freeze({ ...this.metadata, ...extra }),\n );\n }\n\n withReason(reason: string): Outcome<S, D> {\n return new Outcome(this.status, this.data, reason, this.metadata);\n }\n\n // ─── Debug ─────────────────────────────────────────────────────────\n\n toString(): string {\n const parts: string[] = [this.status];\n if (this.reason) parts.push(`reason=\"${this.reason}\"`);\n return `Outcome(${parts.join(\", \")})`;\n }\n}\n\n/** Common business outcome statuses. Extend per domain as needed. */\nexport type CommonOutcomeStatus =\n | \"APPROVED\"\n | \"REJECTED\"\n | \"NO_OP\"\n | \"DEFERRED\"\n | \"REQUIRES_REVIEW\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,IAAa,UAAb,MAAa,QAAyC;CAMlD,YACI,QACA,MACA,QACA,UACF;EACE,KAAK,SAAS;EACd,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,OAAO,OAAO,IAAI;CACtB;CAIA,OAAO,GACH,QACA,MACA,QACA,UACa;EACb,OAAO,IAAI,QACP,QACA,MACA,QACA,OAAO,OAAO,EAAE,GAAG,SAAS,CAAC,CACjC;CACJ;CAIA,OAAO,SACH,MACA,QACsB;EACtB,OAAO,IAAI,QAAQ,YAAY,MAAM,QAAQ,OAAO,OAAO,CAAC,CAAC,CAAC;CAClE;CAEA,OAAO,SACH,MACA,QACsB;EACtB,OAAO,IAAI,QAAQ,YAAY,MAAM,QAAQ,OAAO,OAAO,CAAC,CAAC,CAAC;CAClE;CAEA,OAAO,KAAoB,MAAS,QAAsC;EACtE,OAAO,IAAI,QAAQ,SAAS,MAAM,QAAQ,OAAO,OAAO,CAAC,CAAC,CAAC;CAC/D;CAEA,OAAO,SACH,MACA,QACsB;EACtB,OAAO,IAAI,QAAQ,YAAY,MAAM,QAAQ,OAAO,OAAO,CAAC,CAAC,CAAC;CAClE;CAEA,OAAO,eACH,MACA,QAC6B;EAC7B,OAAO,IAAI,QAAQ,mBAAmB,MAAM,QAAQ,OAAO,OAAO,CAAC,CAAC,CAAC;CACzE;;;;;;;;;CAYA,GAAgB,QAAkC;EAC9C,OAAQ,KAAK,WAAsB;CACvC;;;;;;;;;;;CAcA,MACI,UACwB;EACxB,MAAM,UACF,SACF,KAAK;EAEP,IAAI,OAAO,YAAY,YAAY;GAC/B,MAAM,oBAAoB,OAAO,KAAK,QAAQ;GAC9C,MAAM,IAAIA,sCAAAA,4BACN,0DAA0D,KAAK,OAAO,yBAAyB,kBAAkB,KAAK,IAAI,KAAK,UACnI;EACJ;EAEA,OAAO,QAAQ,IAAI;CACvB;CAIA,aAAa,OAA+C;EACxD,OAAO,IAAI,QACP,KAAK,QACL,KAAK,MACL,KAAK,QACL,OAAO,OAAO;GAAE,GAAG,KAAK;GAAU,GAAG;EAAM,CAAC,CAChD;CACJ;CAEA,WAAW,QAA+B;EACtC,OAAO,IAAI,QAAQ,KAAK,QAAQ,KAAK,MAAM,QAAQ,KAAK,QAAQ;CACpE;CAIA,WAAmB;EACf,MAAM,QAAkB,CAAC,KAAK,MAAM;EACpC,IAAI,KAAK,QAAQ,MAAM,KAAK,WAAW,KAAK,OAAO,EAAE;EACrD,OAAO,WAAW,MAAM,KAAK,IAAI,EAAE;CACvC;AACJ"}