@cullet/erp-core 1.0.11 → 1.2.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 (118) hide show
  1. package/KIT_CONTEXT.md +1 -0
  2. package/README.md +128 -1
  3. package/dist/app-error.d.ts +108 -0
  4. package/dist/application/index.d.ts +2 -0
  5. package/dist/application/index.js +3 -0
  6. package/dist/domain/index.d.ts +3 -0
  7. package/dist/domain/index.js +3 -0
  8. package/dist/domain-event-contracts.d.ts +27 -0
  9. package/dist/domain-event-contracts.js +22 -0
  10. package/dist/domain-event-contracts.js.map +1 -0
  11. package/dist/domain-exception.d.ts +7 -0
  12. package/dist/domain-exception.js +12 -0
  13. package/dist/domain-exception.js.map +1 -0
  14. package/dist/errors/index.d.ts +2 -1
  15. package/dist/errors/index.js +4 -2
  16. package/dist/exceptions/index.d.ts +5 -0
  17. package/dist/exceptions/index.js +7 -0
  18. package/dist/gate-engine-registry.d.ts +81 -0
  19. package/dist/gate-engine-registry.js +2 -1
  20. package/dist/gate-engine-registry.js.map +1 -1
  21. package/dist/gate-types.d.ts +3 -139
  22. package/dist/gate-v1-payload.schema.js +3 -143
  23. package/dist/gate-v1-payload.schema.js.map +1 -1
  24. package/dist/hashing.js +49 -0
  25. package/dist/hashing.js.map +1 -0
  26. package/dist/immutable.d.ts +6 -0
  27. package/dist/immutable.js +54 -0
  28. package/dist/immutable.js.map +1 -0
  29. package/dist/index.d.ts +21 -200
  30. package/dist/index.js +21 -251
  31. package/dist/index.js.map +1 -1
  32. package/dist/invalid-state-transition-exception.js +30 -0
  33. package/dist/invalid-state-transition-exception.js.map +1 -0
  34. package/dist/invariant-violation-exception.js +11 -0
  35. package/dist/invariant-violation-exception.js.map +1 -0
  36. package/dist/not-found-error.js +54 -0
  37. package/dist/not-found-error.js.map +1 -0
  38. package/dist/outcome.d.ts +140 -0
  39. package/dist/outcome.js +1 -1
  40. package/dist/parse-gate-payload.d.ts +4 -78
  41. package/dist/path.d.ts +90 -0
  42. package/dist/plugin.d.ts +85 -0
  43. package/dist/plugin.js +74 -0
  44. package/dist/plugin.js.map +1 -0
  45. package/dist/plugins/index.d.ts +2 -0
  46. package/dist/plugins/index.js +2 -0
  47. package/dist/policies/engines/index.d.ts +3 -2
  48. package/dist/policies/engines/v1/gate/index.d.ts +2 -1
  49. package/dist/policies/engines/v1/gate/index.js +2 -1
  50. package/dist/policies/engines/v1/gate/index.js.map +1 -1
  51. package/dist/policies/index.d.ts +6 -3
  52. package/dist/policies/index.js +2 -1
  53. package/dist/policy-service.d.ts +4 -86
  54. package/dist/policy-service.js +8 -16
  55. package/dist/policy-service.js.map +1 -1
  56. package/dist/result/index.d.ts +2 -0
  57. package/dist/result/index.js +3 -0
  58. package/dist/result.js +118 -0
  59. package/dist/result.js.map +1 -0
  60. package/dist/ruleset-registry.js +42 -0
  61. package/dist/ruleset-registry.js.map +1 -0
  62. package/dist/rulesets/index.d.ts +2 -0
  63. package/dist/rulesets/index.js +2 -0
  64. package/dist/temporal-guards.js +15 -0
  65. package/dist/temporal-guards.js.map +1 -0
  66. package/dist/temporal-use-case.d.ts +304 -0
  67. package/dist/temporal-use-case.js +150 -0
  68. package/dist/temporal-use-case.js.map +1 -0
  69. package/dist/unexpected-error.js +179 -0
  70. package/dist/unexpected-error.js.map +1 -0
  71. package/dist/use-case.js +91 -0
  72. package/dist/use-case.js.map +1 -0
  73. package/dist/uuid-identifier.d.ts +230 -0
  74. package/dist/uuid-identifier.js +60 -0
  75. package/dist/uuid-identifier.js.map +1 -0
  76. package/dist/validation-code.d.ts +23 -0
  77. package/dist/validation-code.js +1 -223
  78. package/dist/validation-code.js.map +1 -1
  79. package/dist/validation-error.d.ts +3 -128
  80. package/dist/validation-error.js +2 -52
  81. package/dist/validation-error.js.map +1 -1
  82. package/dist/validation-exception.d.ts +50 -0
  83. package/dist/validation-exception.js +24 -0
  84. package/dist/validation-exception.js.map +1 -0
  85. package/dist/value-object-ruleset.contracts.d.ts +36 -0
  86. package/dist/value-object.js +191 -0
  87. package/dist/value-object.js.map +1 -0
  88. package/dist/version.d.ts +10 -0
  89. package/dist/versioning/index.d.ts +3 -0
  90. package/dist/versioning/index.js +3 -0
  91. package/meta.json +18 -3
  92. package/package.json +37 -4
  93. package/src/application/index.ts +1 -0
  94. package/src/core/application/commands/index.ts +1 -0
  95. package/src/core/application/index.ts +12 -3
  96. package/src/core/application/ports/index.ts +2 -2
  97. package/src/core/application/ports/policy-port.ts +13 -3
  98. package/src/core/application/ports/repository.port.ts +37 -1
  99. package/src/core/application/temporal/temporal-use-case.ts +14 -2
  100. package/src/core/application/use-case.ts +133 -2
  101. package/src/core/domain/rulesets/index.ts +7 -0
  102. package/src/core/domain/uuid-identifier.ts +72 -0
  103. package/src/core/domain/value-object.ts +37 -5
  104. package/src/core/exceptions/index.ts +13 -0
  105. package/src/core/index.ts +15 -12
  106. package/src/core/plugins/index.ts +7 -0
  107. package/src/core/plugins/plugin.ts +99 -0
  108. package/src/core/plugins/types.ts +53 -0
  109. package/src/core/versioning/index.ts +14 -0
  110. package/src/domain/index.ts +7 -0
  111. package/src/examples/application/cancel-order.example.ts +124 -0
  112. package/src/examples/application/in-memory-account-repository.example.ts +73 -0
  113. package/src/exceptions/index.ts +1 -0
  114. package/src/plugins/index.ts +1 -0
  115. package/src/result/index.ts +2 -0
  116. package/src/rulesets/index.ts +1 -0
  117. package/src/version.ts +1 -1
  118. package/src/versioning/index.ts +1 -0
@@ -0,0 +1,191 @@
1
+ import { t as InvariantViolationException } from "./invariant-violation-exception.js";
2
+ import { i as version, n as __decorate, t as makeImmutable } from "./immutable.js";
3
+ import { n as cloneDate, t as assertValidDate } from "./temporal-guards.js";
4
+ import { t as PluginManager } from "./plugin.js";
5
+ //#region src/core/shared/aggregate-version.ts
6
+ function assertValidAggregateVersion(aggregateVersion) {
7
+ if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) throw new InvariantViolationException(`aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`);
8
+ }
9
+ //#endregion
10
+ //#region src/core/domain/entity.ts
11
+ var _Entity;
12
+ /**
13
+ * Base class for domain entities — objects defined by a stable identity rather
14
+ * than by their attributes. Two entities are "the same" when their `id`
15
+ * matches, even if every other field differs; this is the opposite of a
16
+ * {@link ValueObject}, which is defined entirely by its contents.
17
+ *
18
+ * The class owns the bookkeeping common to every aggregate root: a creation
19
+ * timestamp that never changes, a last-modified timestamp, and an
20
+ * `aggregateVersion` counter used for optimistic concurrency control. All three
21
+ * are validated on construction and the dates are defensively cloned, so an
22
+ * entity can never be built into — or leak — an inconsistent temporal state.
23
+ *
24
+ * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
25
+ */
26
+ let Entity = class Entity {
27
+ static {
28
+ _Entity = this;
29
+ }
30
+ /**
31
+ * Reconstitutes an entity from its persisted {@link EntityState}.
32
+ *
33
+ * Validates the temporal invariants up front so an invalid entity is
34
+ * impossible to construct: both dates must be valid, the aggregate version
35
+ * must be a non-negative integer, and `updatedAt` may not predate
36
+ * `createdAt`. Both dates are cloned on the way in so a later mutation of
37
+ * the caller's `Date` objects cannot reach into the entity's internal state.
38
+ *
39
+ * Declared `protected` because entities are reconstituted through a
40
+ * subclass factory, never instantiated directly by application code.
41
+ *
42
+ * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
43
+ */
44
+ constructor(state) {
45
+ assertValidDate("createdAt", state.createdAt);
46
+ assertValidDate("updatedAt", state.updatedAt);
47
+ assertValidAggregateVersion(state.aggregateVersion);
48
+ if (state.updatedAt.getTime() < state.createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
49
+ this._id = state.id;
50
+ this._createdAt = cloneDate(state.createdAt);
51
+ this._updatedAt = cloneDate(state.updatedAt);
52
+ this._aggregateVersion = state.aggregateVersion;
53
+ }
54
+ /** The entity's stable identity — the basis for equality between entities. */
55
+ get id() {
56
+ return this._id;
57
+ }
58
+ /**
59
+ * When the entity was first created.
60
+ *
61
+ * Returns a clone so callers cannot mutate the entity's internal `Date`;
62
+ * the value is fixed at construction and never changes thereafter.
63
+ */
64
+ get createdAt() {
65
+ return cloneDate(this._createdAt);
66
+ }
67
+ /**
68
+ * When the entity was last modified.
69
+ *
70
+ * Returns a clone for the same encapsulation reason as {@link createdAt};
71
+ * the underlying value advances only through {@link markAsModified}.
72
+ */
73
+ get updatedAt() {
74
+ return cloneDate(this._updatedAt);
75
+ }
76
+ /**
77
+ * Monotonic counter incremented on every mutation, used for optimistic
78
+ * concurrency control: a writer reads this value, and the persistence layer
79
+ * rejects the write if the stored version has moved on in the meantime.
80
+ */
81
+ get aggregateVersion() {
82
+ return this._aggregateVersion;
83
+ }
84
+ /**
85
+ * The schema/contract version stamped on this entity type by the
86
+ * `@version` decorator — used to detect and migrate state persisted under
87
+ * an older shape.
88
+ */
89
+ get contractVersion() {
90
+ return _Entity.CONTRACT_VERSION;
91
+ }
92
+ /**
93
+ * The single seam through which an entity records a mutation: it advances
94
+ * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must
95
+ * call this from every state-changing method so the version counter stays
96
+ * an accurate optimistic-lock token.
97
+ *
98
+ * @param updatedAt - The modification instant; defaults to now. Validated
99
+ * and required not to predate `createdAt`, preserving the same invariant
100
+ * the constructor enforces.
101
+ * @returns The new aggregate version after the increment.
102
+ * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
103
+ */
104
+ markAsModified(updatedAt = /* @__PURE__ */ new Date()) {
105
+ assertValidDate("updatedAt", updatedAt);
106
+ if (updatedAt.getTime() < this._createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
107
+ this._updatedAt = cloneDate(updatedAt);
108
+ this._aggregateVersion += 1;
109
+ return this._aggregateVersion;
110
+ }
111
+ };
112
+ Entity = _Entity = __decorate([version("1.0")], Entity);
113
+ //#endregion
114
+ //#region src/core/domain/value-object.ts
115
+ var _ValueObject;
116
+ /**
117
+ * Base class for value objects — domain concepts defined entirely by their
118
+ * contents, with no identity of their own. Two value objects are
119
+ * interchangeable when they hold equal data, which is the opposite of an
120
+ * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one
121
+ * instance with an equal one changes nothing about the model.
122
+ *
123
+ * Immutability is the defining guarantee here. The wrapped `value` is
124
+ * deep-frozen on construction, so a value object can be shared freely without
125
+ * any risk of a consumer mutating shared state. Subclasses seal the instance
126
+ * itself with {@link finalize} once their own fields are set.
127
+ *
128
+ * @typeParam T - The shape of the wrapped data.
129
+ * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
130
+ */
131
+ let ValueObject = class ValueObject {
132
+ static {
133
+ _ValueObject = this;
134
+ }
135
+ static {
136
+ this.plugins = new PluginManager();
137
+ }
138
+ /**
139
+ * Wraps `value`, deep-freezing it so the value object is immutable from the
140
+ * moment it exists. Declared `protected` because value objects are built
141
+ * through a validating subclass factory, never instantiated directly.
142
+ */
143
+ constructor(value) {
144
+ this.value = makeImmutable(value);
145
+ }
146
+ /**
147
+ * The schema/contract version stamped on this value-object type by the
148
+ * `@version` decorator — used to detect state persisted under an older shape.
149
+ */
150
+ get contractVersion() {
151
+ return _ValueObject.CONTRACT_VERSION;
152
+ }
153
+ /**
154
+ * Freezes the instance shell, blocking reassignment of any own field.
155
+ *
156
+ * `value` is already deep-frozen by the constructor, so the wrapped data is
157
+ * immutable regardless. The instance itself is NOT frozen automatically
158
+ * because a subclass may still need to assign its own fields after
159
+ * `super(value)` runs. Call `finalize()` at the very end of the subclass
160
+ * constructor (after all fields are set) to make the whole value object
161
+ * immutable.
162
+ */
163
+ finalize() {
164
+ Object.freeze(this);
165
+ }
166
+ /**
167
+ * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value
168
+ * object serializes to its primitive form rather than exposing the internal
169
+ * `value` wrapper.
170
+ */
171
+ toJSON() {
172
+ return this.toPrimitive();
173
+ }
174
+ /**
175
+ * Compares this value object with another by content. Because value objects
176
+ * carry no identity, two independently constructed instances holding the
177
+ * same data are considered equal.
178
+ *
179
+ * Delegates to the registered equality {@link plugins}; with no plugin
180
+ * registered it falls back to comparing the serialized wrapped `value`.
181
+ * Subclasses may still override for a faster or domain-specific comparison.
182
+ */
183
+ equals(other) {
184
+ return _ValueObject.plugins.invoke("equals", [this, other], { fallback: (a, b) => JSON.stringify(a.value) === JSON.stringify(b.value) });
185
+ }
186
+ };
187
+ ValueObject = _ValueObject = __decorate([version("1.0")], ValueObject);
188
+ //#endregion
189
+ export { Entity as n, assertValidAggregateVersion as r, ValueObject as t };
190
+
191
+ //# sourceMappingURL=value-object.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"value-object.js","names":[],"sources":["../src/core/shared/aggregate-version.ts","../src/core/domain/entity.ts","../src/core/domain/value-object.ts"],"sourcesContent":["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 { PluginManager } from \"../plugins/index.js\";\nimport { type DeepReadonly, makeImmutable } from \"../shared/immutable.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * Extension point for value-object equality. A plugin implementing this\n * contract overrides how any two value objects are compared, letting the host\n * application swap in a structural comparator (e.g. `lodash.isEqual` over the\n * wrapped `value`) without every value object having to implement `equals` by\n * hand.\n */\ntype ValueObjectPluginContract = {\n equals: (\n a: ValueObject<unknown, unknown>,\n b: ValueObject<unknown, unknown>,\n ) => boolean;\n};\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 /**\n * Registry of equality plugins shared by every value object. Empty by\n * default — when nothing is registered, {@link equals} falls back to a\n * structural comparison of the wrapped `value`. Hosts register a plugin\n * (e.g. `lodash.isEqual`) once at startup to customise equality globally.\n */\n public static readonly plugins =\n new PluginManager<ValueObjectPluginContract>();\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, two independently constructed instances holding the\n * same data are considered equal.\n *\n * Delegates to the registered equality {@link plugins}; with no plugin\n * registered it falls back to comparing the serialized wrapped `value`.\n * Subclasses may still override for a faster or domain-specific comparison.\n */\n public equals(other: this): boolean {\n return ValueObject.plugins.invoke(\"equals\", [this, other], {\n fallback: (a, b) =>\n JSON.stringify(a.value) === JSON.stringify(b.value),\n });\n }\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, type ValueObjectPluginContract };\n"],"mappings":";;;;;AAEA,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;+BA7GC,QAAQ,KAAK,CAAA,GAAA,MAAA;;;;;;;;;;;;;;;;;;;ACDd,IAAA,cAAA,MACe,YAAkB;;;;;iBAUzB,IAAI,cAAyC;;;;;;;CAUjD,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;;;;;;;;;;CAWA,OAAc,OAAsB;EAChC,OAAA,aAAmB,QAAQ,OAAO,UAAU,CAAC,MAAM,KAAK,GAAG,EACvD,WAAW,GAAG,MACV,KAAK,UAAU,EAAE,KAAK,MAAM,KAAK,UAAU,EAAE,KAAK,EAC1D,CAAC;CACL;AAOJ;yCA7EC,QAAQ,KAAK,CAAA,GAAA,WAAA"}
@@ -0,0 +1,10 @@
1
+ //#region src/core/versioning/version.d.ts
2
+ type ContractVersion = `${number}.${number}`;
3
+ type VersionedTarget = {
4
+ readonly prototype: object;
5
+ };
6
+ declare const CONTRACT_VERSION_PROPERTY: "CONTRACT_VERSION";
7
+ declare function version<const TVersion extends ContractVersion>(contractVersion: TVersion): (target: VersionedTarget) => void;
8
+ //#endregion
9
+ export { version as i, ContractVersion as n, VersionedTarget as r, CONTRACT_VERSION_PROPERTY as t };
10
+ //# sourceMappingURL=version.d.ts.map
@@ -0,0 +1,3 @@
1
+ import { i as version, n as ContractVersion, r as VersionedTarget, t as CONTRACT_VERSION_PROPERTY } from "../version.js";
2
+ import { a as buildDomainEventContractVersions, i as DomainEventEnvelope, n as DomainEventContractSelection, o as createDomainEventEnvelope, r as DomainEventContractVersions, t as CreateDomainEventEnvelopeInput } from "../domain-event-contracts.js";
3
+ export { CONTRACT_VERSION_PROPERTY, ContractVersion, CreateDomainEventEnvelopeInput, DomainEventContractSelection, DomainEventContractVersions, DomainEventEnvelope, VersionedTarget, buildDomainEventContractVersions, createDomainEventEnvelope, version };
@@ -0,0 +1,3 @@
1
+ import { i as version, r as CONTRACT_VERSION_PROPERTY } from "../immutable.js";
2
+ import { n as createDomainEventEnvelope, t as buildDomainEventContractVersions } from "../domain-event-contracts.js";
3
+ export { CONTRACT_VERSION_PROPERTY, buildDomainEventContractVersions, createDomainEventEnvelope, version };
package/meta.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": "2",
3
3
  "name": "erp-core",
4
- "version": "1.0.11",
4
+ "version": "1.2.0",
5
5
  "description": "Núcleo arquitetural para ERP em TypeScript — entidades, value objects, erros tipados e policies declaráveis sobre clean architecture.",
6
6
  "compatibility": {
7
7
  "engines": {
@@ -12,7 +12,9 @@
12
12
  "peerDependencies": [
13
13
  {
14
14
  "name": "zod",
15
- "range": ">=3.22.0 <5"
15
+ "range": ">=3.22.0 <5",
16
+ "optional": true,
17
+ "notes": "Only required by the `./policies` subpath (gate/compute engines). The domain/result/errors/exceptions/rulesets/versioning/plugins subpaths are zod-free."
16
18
  }
17
19
  ]
18
20
  },
@@ -51,6 +53,17 @@
51
53
  "exports": [
52
54
  "Entity",
53
55
  "ValueObject",
56
+ "UuidIdentifier",
57
+ "PluginManager",
58
+ "Result",
59
+ "Outcome",
60
+ "RulesetRegistry",
61
+ "DomainException",
62
+ "InvariantViolationException",
63
+ "ValidationException",
64
+ "ValidationField",
65
+ "version",
66
+ "createDomainEventEnvelope",
54
67
  "AppError",
55
68
  "ValidationError",
56
69
  "NotFoundError",
@@ -75,7 +88,9 @@
75
88
  "1.0.8 - Align kit metadata with what the package actually ships and fix doc/packaging gaps. No runtime or public API changes.",
76
89
  "1.0.9 - Harden erp-core invariants and error serialization",
77
90
  "1.0.10 - Stop the `meta.json` `changelog` from drifting and clarify the `ValueObject` freeze contract.",
78
- "1.0.11 - Document the public API surface with TSDoc."
91
+ "1.0.11 - Document the public API surface with TSDoc.",
92
+ "1.1.0 - **New: `ResultRepository`, `UseCaseObservability`, and `./application` subpath**",
93
+ "1.2.0 - Add zod-free subpaths for the stable core primitives and a value-object equality plugin system."
79
94
  ],
80
95
  "deprecated": false
81
96
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cullet/erp-core",
3
- "version": "1.0.11",
3
+ "version": "1.2.0",
4
4
  "description": "Núcleo arquitetural para ERP em TypeScript — entidades, value objects, erros tipados e policies declaráveis sobre clean architecture.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -15,10 +15,30 @@
15
15
  "types": "./dist/index.d.ts",
16
16
  "import": "./dist/index.js"
17
17
  },
18
+ "./application": {
19
+ "types": "./dist/application/index.d.ts",
20
+ "import": "./dist/application/index.js"
21
+ },
22
+ "./domain": {
23
+ "types": "./dist/domain/index.d.ts",
24
+ "import": "./dist/domain/index.js"
25
+ },
18
26
  "./errors": {
19
27
  "types": "./dist/errors/index.d.ts",
20
28
  "import": "./dist/errors/index.js"
21
29
  },
30
+ "./exceptions": {
31
+ "types": "./dist/exceptions/index.d.ts",
32
+ "import": "./dist/exceptions/index.js"
33
+ },
34
+ "./exceptions/validation-field": {
35
+ "types": "./dist/exceptions/validation-field.d.ts",
36
+ "import": "./dist/exceptions/validation-field.js"
37
+ },
38
+ "./plugins": {
39
+ "types": "./dist/plugins/index.d.ts",
40
+ "import": "./dist/plugins/index.js"
41
+ },
22
42
  "./policies": {
23
43
  "types": "./dist/policies/index.d.ts",
24
44
  "import": "./dist/policies/index.js"
@@ -31,9 +51,17 @@
31
51
  "types": "./dist/policies/engines/v1/gate/index.d.ts",
32
52
  "import": "./dist/policies/engines/v1/gate/index.js"
33
53
  },
34
- "./exceptions/validation-field": {
35
- "types": "./dist/exceptions/validation-field.d.ts",
36
- "import": "./dist/exceptions/validation-field.js"
54
+ "./result": {
55
+ "types": "./dist/result/index.d.ts",
56
+ "import": "./dist/result/index.js"
57
+ },
58
+ "./rulesets": {
59
+ "types": "./dist/rulesets/index.d.ts",
60
+ "import": "./dist/rulesets/index.js"
61
+ },
62
+ "./versioning": {
63
+ "types": "./dist/versioning/index.d.ts",
64
+ "import": "./dist/versioning/index.js"
37
65
  },
38
66
  "./package.json": "./package.json"
39
67
  },
@@ -58,6 +86,11 @@
58
86
  "peerDependencies": {
59
87
  "zod": ">=3.22.0 <5"
60
88
  },
89
+ "peerDependenciesMeta": {
90
+ "zod": {
91
+ "optional": true
92
+ }
93
+ },
61
94
  "publishConfig": {
62
95
  "access": "public"
63
96
  },
@@ -0,0 +1 @@
1
+ export * from "../core/application/index.js";
@@ -1,2 +1,3 @@
1
1
  export type { CommandInput } from "./command.js";
2
2
  export { Command } from "./command.js";
3
+ export { RequestedBy, type RequestedByKind } from "./requested-by.js";
@@ -1,15 +1,20 @@
1
1
  export type { CommandInput } from "./commands/index.js";
2
- export { Command } from "./commands/index.js";
2
+ export {
3
+ Command,
4
+ RequestedBy,
5
+ type RequestedByKind,
6
+ } from "./commands/index.js";
3
7
  export type {
4
8
  LogPayload,
5
9
  LoggerPort,
6
10
  MetricLabels,
7
11
  MetricsPort,
8
- PolicyEvaluationError,
9
12
  PolicyEvaluationInput,
10
13
  PolicyEvaluationOutput,
11
14
  PolicyPort,
15
+ PolicyPortError,
12
16
  Repository,
17
+ ResultRepository,
13
18
  TraceAttributeValue,
14
19
  TraceSpan,
15
20
  TracerPort,
@@ -28,4 +33,8 @@ export {
28
33
  TemporalUseCase,
29
34
  type TemporalUseCaseInput,
30
35
  } from "./temporal/index.js";
31
- export { type MaybePromise, UseCase } from "./use-case.js";
36
+ export {
37
+ type MaybePromise,
38
+ UseCase,
39
+ type UseCaseObservability,
40
+ } from "./use-case.js";
@@ -1,12 +1,12 @@
1
1
  export type { LogPayload, LoggerPort } from "./logger.port.js";
2
2
  export type { MetricLabels, MetricsPort } from "./metrics.port.js";
3
3
  export type {
4
- PolicyEvaluationError,
5
4
  PolicyEvaluationInput,
6
5
  PolicyEvaluationOutput,
7
6
  PolicyPort,
7
+ PolicyPortError,
8
8
  } from "./policy-port.js";
9
- export type { Repository } from "./repository.port.js";
9
+ export type { Repository, ResultRepository } from "./repository.port.js";
10
10
  export type {
11
11
  TemporalHistory,
12
12
  TemporalRepository,
@@ -7,17 +7,27 @@ import type { Result } from "../../result/result.js";
7
7
 
8
8
  type PolicyEvaluationInput = EvaluateInput;
9
9
  type PolicyEvaluationOutput = PolicyEvaluationResult;
10
- type PolicyEvaluationError = AppError;
10
+
11
+ /**
12
+ * Failure surfaced by {@link PolicyPort.evaluate}.
13
+ *
14
+ * This is the *post-mapping* boundary: the structured `PolicyEvaluationError`
15
+ * union produced inside the policies module is expected to have already been
16
+ * translated into an {@link AppError} (e.g. via `mapPolicyEvaluationError`)
17
+ * before it reaches a use case. Named distinctly from the policies-layer
18
+ * `PolicyEvaluationError` to avoid a collision on the public surface.
19
+ */
20
+ type PolicyPortError = AppError;
11
21
 
12
22
  interface PolicyPort {
13
23
  evaluate(
14
24
  input: PolicyEvaluationInput,
15
- ): Promise<Result<PolicyEvaluationOutput, PolicyEvaluationError>>;
25
+ ): Promise<Result<PolicyEvaluationOutput, PolicyPortError>>;
16
26
  }
17
27
 
18
28
  export type {
19
- PolicyEvaluationError,
20
29
  PolicyEvaluationInput,
21
30
  PolicyEvaluationOutput,
22
31
  PolicyPort,
32
+ PolicyPortError,
23
33
  };
@@ -1,7 +1,43 @@
1
+ import type { AppError } from "../../errors/index.js";
2
+ import type { Result } from "../../result/result.js";
3
+
4
+ /**
5
+ * Persistence port for an aggregate in the imperative style: absence is
6
+ * modelled as `null`, and failures (missing row on delete, optimistic
7
+ * concurrency conflicts, infrastructure errors) surface as thrown exceptions.
8
+ *
9
+ * Prefer {@link ResultRepository} when you want those persistence outcomes to
10
+ * be explicit, recoverable values rather than exceptions.
11
+ */
1
12
  interface Repository<TEntity, TId> {
2
13
  findById(id: TId): Promise<TEntity | null>;
3
14
  save(entity: TEntity): Promise<void>;
4
15
  delete(id: TId): Promise<void>;
5
16
  }
6
17
 
7
- export type { Repository };
18
+ /**
19
+ * `Result`-returning counterpart of {@link Repository}, aligned with the
20
+ * "errors as values" philosophy used by `Command` / `UseCase`.
21
+ *
22
+ * Where {@link Repository} returns `Promise<void>` from `save`/`delete` and
23
+ * relies on thrown exceptions, this variant lets a repository *signal*
24
+ * recoverable persistence outcomes without breaking control flow — for
25
+ * example a `NotFoundError` when updating/deleting a missing aggregate, or a
26
+ * `ConflictError` on an optimistic-concurrency version mismatch. A successful
27
+ * write resolves to `Result.ok(undefined)`.
28
+ *
29
+ * `findById` keeps `null` as the "not present" answer to a lookup (not an
30
+ * error) while still wrapping the call in a `Result` so genuine failures
31
+ * (e.g. a connectivity error) stay in band.
32
+ *
33
+ * `TError` defaults to {@link AppError} to match the rest of the application
34
+ * boundary (see `PolicyPortError`); narrow it per repository when the failure
35
+ * set is known, e.g. `ResultRepository<Order, OrderId, NotFoundError | ConflictError>`.
36
+ */
37
+ interface ResultRepository<TEntity, TId, TError = AppError> {
38
+ findById(id: TId): Promise<Result<TEntity | null, TError>>;
39
+ save(entity: TEntity): Promise<Result<void, TError>>;
40
+ delete(id: TId): Promise<Result<void, TError>>;
41
+ }
42
+
43
+ export type { Repository, ResultRepository };
@@ -11,7 +11,19 @@ interface TemporalUseCaseInput {
11
11
  readonly temporalContext?: TemporalContext;
12
12
  }
13
13
 
14
- type TemporalizedContextSeed<TSeed extends ContextSeed> = TSeed;
14
+ /**
15
+ * A {@link ContextSeed} after temporal enrichment by
16
+ * {@link TemporalUseCase.buildPolicySeed}: structurally identical to `TSeed`,
17
+ * except `fields.now` is now guaranteed present as a `Date` (injected from the
18
+ * resolved {@link TemporalContext}). Downstream policies can therefore read
19
+ * `seed.fields.now` without a presence/type guard.
20
+ */
21
+ type TemporalizedContextSeed<TSeed extends ContextSeed> = Omit<
22
+ TSeed,
23
+ "fields"
24
+ > & {
25
+ readonly fields: TSeed["fields"] & { readonly now: Date };
26
+ };
15
27
 
16
28
  abstract class TemporalUseCase<
17
29
  Input extends object,
@@ -33,7 +45,7 @@ abstract class TemporalUseCase<
33
45
  ...seed.fields,
34
46
  now: new Date(temporalContext.requestedAt.getTime()),
35
47
  },
36
- }) as TSeed;
48
+ }) as TemporalizedContextSeed<TSeed>;
37
49
  }
38
50
  }
39
51