@cullet/erp-core 1.0.9 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -43,45 +43,166 @@ interface TracerPort {
43
43
  declare function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError;
44
44
  //#endregion
45
45
  //#region src/core/domain/entity.d.ts
46
+ /**
47
+ * The minimal persisted shape needed to reconstitute an {@link Entity}.
48
+ *
49
+ * This is the contract between storage and the domain: a repository maps a row
50
+ * (or document) onto these four fields and hands them to a subclass constructor.
51
+ * `aggregateVersion` travels with the state so optimistic-concurrency checks
52
+ * survive a round-trip through the database.
53
+ */
46
54
  interface EntityState<TIdentifier> {
47
55
  readonly id: TIdentifier;
48
56
  readonly createdAt: Date;
49
57
  readonly updatedAt: Date;
50
58
  readonly aggregateVersion: number;
51
59
  }
60
+ /**
61
+ * Base class for domain entities — objects defined by a stable identity rather
62
+ * than by their attributes. Two entities are "the same" when their `id`
63
+ * matches, even if every other field differs; this is the opposite of a
64
+ * {@link ValueObject}, which is defined entirely by its contents.
65
+ *
66
+ * The class owns the bookkeeping common to every aggregate root: a creation
67
+ * timestamp that never changes, a last-modified timestamp, and an
68
+ * `aggregateVersion` counter used for optimistic concurrency control. All three
69
+ * are validated on construction and the dates are defensively cloned, so an
70
+ * entity can never be built into — or leak — an inconsistent temporal state.
71
+ *
72
+ * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
73
+ */
52
74
  declare abstract class Entity<TIdentifier> {
53
75
  static readonly CONTRACT_VERSION: ContractVersion;
54
76
  private readonly _id;
55
77
  private readonly _createdAt;
56
78
  private _updatedAt;
57
79
  private _aggregateVersion;
80
+ /**
81
+ * Reconstitutes an entity from its persisted {@link EntityState}.
82
+ *
83
+ * Validates the temporal invariants up front so an invalid entity is
84
+ * impossible to construct: both dates must be valid, the aggregate version
85
+ * must be a non-negative integer, and `updatedAt` may not predate
86
+ * `createdAt`. Both dates are cloned on the way in so a later mutation of
87
+ * the caller's `Date` objects cannot reach into the entity's internal state.
88
+ *
89
+ * Declared `protected` because entities are reconstituted through a
90
+ * subclass factory, never instantiated directly by application code.
91
+ *
92
+ * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
93
+ */
58
94
  protected constructor(state: EntityState<TIdentifier>);
95
+ /** The entity's stable identity — the basis for equality between entities. */
59
96
  get id(): TIdentifier;
97
+ /**
98
+ * When the entity was first created.
99
+ *
100
+ * Returns a clone so callers cannot mutate the entity's internal `Date`;
101
+ * the value is fixed at construction and never changes thereafter.
102
+ */
60
103
  get createdAt(): Date;
104
+ /**
105
+ * When the entity was last modified.
106
+ *
107
+ * Returns a clone for the same encapsulation reason as {@link createdAt};
108
+ * the underlying value advances only through {@link markAsModified}.
109
+ */
61
110
  get updatedAt(): Date;
111
+ /**
112
+ * Monotonic counter incremented on every mutation, used for optimistic
113
+ * concurrency control: a writer reads this value, and the persistence layer
114
+ * rejects the write if the stored version has moved on in the meantime.
115
+ */
62
116
  get aggregateVersion(): number;
117
+ /**
118
+ * The schema/contract version stamped on this entity type by the
119
+ * `@version` decorator — used to detect and migrate state persisted under
120
+ * an older shape.
121
+ */
63
122
  get contractVersion(): ContractVersion;
123
+ /**
124
+ * The single seam through which an entity records a mutation: it advances
125
+ * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must
126
+ * call this from every state-changing method so the version counter stays
127
+ * an accurate optimistic-lock token.
128
+ *
129
+ * @param updatedAt - The modification instant; defaults to now. Validated
130
+ * and required not to predate `createdAt`, preserving the same invariant
131
+ * the constructor enforces.
132
+ * @returns The new aggregate version after the increment.
133
+ * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
134
+ */
64
135
  protected markAsModified(updatedAt?: Date): number;
65
136
  }
66
137
  //#endregion
67
138
  //#region src/core/domain/value-object.d.ts
139
+ /**
140
+ * Base class for value objects — domain concepts defined entirely by their
141
+ * contents, with no identity of their own. Two value objects are
142
+ * interchangeable when they hold equal data, which is the opposite of an
143
+ * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one
144
+ * instance with an equal one changes nothing about the model.
145
+ *
146
+ * Immutability is the defining guarantee here. The wrapped `value` is
147
+ * deep-frozen on construction, so a value object can be shared freely without
148
+ * any risk of a consumer mutating shared state. Subclasses seal the instance
149
+ * itself with {@link finalize} once their own fields are set.
150
+ *
151
+ * @typeParam T - The shape of the wrapped data.
152
+ * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
153
+ */
68
154
  declare abstract class ValueObject<T, P> {
69
155
  static readonly CONTRACT_VERSION: ContractVersion;
156
+ /** The wrapped data, deep-frozen so it can never be mutated after construction. */
70
157
  readonly value: DeepReadonly<T>;
158
+ /**
159
+ * Wraps `value`, deep-freezing it so the value object is immutable from the
160
+ * moment it exists. Declared `protected` because value objects are built
161
+ * through a validating subclass factory, never instantiated directly.
162
+ */
71
163
  protected constructor(value: T);
164
+ /**
165
+ * The schema/contract version stamped on this value-object type by the
166
+ * `@version` decorator — used to detect state persisted under an older shape.
167
+ */
72
168
  get contractVersion(): ContractVersion;
169
+ /**
170
+ * Freezes the instance shell, blocking reassignment of any own field.
171
+ *
172
+ * `value` is already deep-frozen by the constructor, so the wrapped data is
173
+ * immutable regardless. The instance itself is NOT frozen automatically
174
+ * because a subclass may still need to assign its own fields after
175
+ * `super(value)` runs. Call `finalize()` at the very end of the subclass
176
+ * constructor (after all fields are set) to make the whole value object
177
+ * immutable.
178
+ */
73
179
  protected finalize(): void;
180
+ /**
181
+ * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value
182
+ * object serializes to its primitive form rather than exposing the internal
183
+ * `value` wrapper.
184
+ */
74
185
  toJSON(): P;
186
+ /**
187
+ * Compares this value object with another by content. Because value objects
188
+ * carry no identity, subclasses implement equality over the wrapped data
189
+ * (typically the primitive form), so two independently constructed instances
190
+ * holding the same data are considered equal.
191
+ */
75
192
  abstract equals(other: this): boolean;
193
+ /**
194
+ * Projects the value object down to a plain, serializable primitive form —
195
+ * the representation suitable for persistence, transport, or comparison.
196
+ */
76
197
  abstract toPrimitive(): P;
77
198
  }
78
199
  //#endregion
79
200
  //#region src/index.d.ts
80
201
  declare const ERP_CORE_NAME = "erp-core";
81
- declare const ERP_CORE_VERSION = "1.0.9";
202
+ declare const ERP_CORE_VERSION = "1.0.11";
82
203
  declare const erpCoreRelease: {
83
204
  readonly name: "erp-core";
84
- readonly version: "1.0.9";
205
+ readonly version: "1.0.11";
85
206
  };
86
207
  //#endregion
87
208
  export { AlreadyExistsError, AppError, AppErrorOptions, AsOfSource, AuthenticationError, AuthenticationErrorMetadata, AuthenticationErrorReason, AuthorizationError, AuthorizationErrorMetadata, AuthorizationErrorReason, AuthorizationRequirement, BasePolicyDefinitionProps, BusinessRuleViolationError, CommonOutcomeStatus, ComputeEngineRegistry, ComputeEvaluator, ComputeEvaluatorRegistration, ComputeEvaluatorRegistry, ComputeOutcome, ComputeOutcomeData, ComputePayloadParserRegistry, ComputePayloadParsers, ComputePolicyDefinitionProps, ComputeRegistry, ComputeStatus, ConditionEvaluationCause, ConditionEvaluationOptions, ConditionEvaluationReport, ConditionEvaluationReportLevel, ConditionEvaluationReportTag, ConditionEvaluatorReporter, ConflictError, ConflictErrorMetadata, ConflictKind, ContextResolverCircuitBreakerOptions, ContextResolverRegistry, ContextResolverResilienceOptions, ContextResolverRetryOptions, ContextSeed, ContextSeedValidator, ContextValueResolver, CoreConfig, CoreConfigOptions, CoreObservabilityConfig, type DeepReadonly, DeriveAsOfOptions, SerializationInError as DeserializationError, SerializationInError, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, type EntityState, Err, ErrorCodes, ErrorSeverity, EvaluateInput, ExpiredError, TemporalErrorMetadata as ExpiredErrorMetadata, TemporalErrorMetadata, TemporalPrecision as ExpiredErrorPrecision, TemporalPrecision, FindCandidatesParams, GateEngineRegistry, GateOutcome, GateOutcomeData, GatePayload, GatePayloadParsers, GatePolicyDefinitionProps, GateStatus, GateTraceLeafSnapshot, GateTraceNodeSnapshot, GateViolationTrace, IdempotencyError, IdempotencyErrorMetadata, IdempotencyFailureKind, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, InMemoryPolicyDefinitionRepository, IntegrationError, IntegrationErrorMetadata, IntegrationErrorReason, JsonSafePrimitive, JsonSafeRecord, JsonSafeValue, LegacyIncompatibleError, type LogPayload, type LoggerPort, type MetricLabels, type MetricsPort, NotFoundError, NotYetValidError, Ok, Outcome, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogEntryProps, PolicyCatalogFactory, PolicyContext, PolicyContextBuilder, PolicyContextBuilderOptions, PolicyContextPath, PolicyDecision, PolicyDecisionId, PolicyDefinition, PolicyDefinitionId, PolicyDefinitionProps, PolicyDefinitionStatus, PolicyEvaluationError, PolicyEvaluationErrors, PolicyEvaluationResult, PolicyHashing, PolicyKey, PolicyKind, PolicyOwner, PolicyPackage, PolicyResolver, PolicyScope, PolicyScopeLevel, PolicyScopeMatcher, PolicyService, PolicyServiceOptions, PolicyServiceParams, PolicyViolation, Result, SchoolId, ScopeChain, SerializationBoundary, SerializationCodes, SerializationDirection, SerializationError, SerializationErrorMetadata, SerializationFailureCategory, SerializationMessages, SerializationOutError, TemporalError, TemporalKind, TenantId, type TraceAttributeValue, type TraceSpan, type TracerPort, UnexpectedError, UniqueConstraintViolation, UniqueConstraintViolationError, ValidationError, ValidationField, ValueObject, VersionedComputeEngine, VersionedGateEngine, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, contextResolverRegistry, coreConfig, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate };
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { t as Outcome } from "./outcome.js";
6
6
  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";
7
7
  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";
8
8
  //#region src/version.ts
9
- const version$1 = "1.0.9";
9
+ const version$1 = "1.0.11";
10
10
  //#endregion
11
11
  //#region src/core/application/policy-error-mapper.ts
12
12
  function mapPolicyEvaluationError(err) {
@@ -65,10 +65,38 @@ function __decorate(decorators, target, key, desc) {
65
65
  //#endregion
66
66
  //#region src/core/domain/entity.ts
67
67
  var _Entity;
68
+ /**
69
+ * Base class for domain entities — objects defined by a stable identity rather
70
+ * than by their attributes. Two entities are "the same" when their `id`
71
+ * matches, even if every other field differs; this is the opposite of a
72
+ * {@link ValueObject}, which is defined entirely by its contents.
73
+ *
74
+ * The class owns the bookkeeping common to every aggregate root: a creation
75
+ * timestamp that never changes, a last-modified timestamp, and an
76
+ * `aggregateVersion` counter used for optimistic concurrency control. All three
77
+ * are validated on construction and the dates are defensively cloned, so an
78
+ * entity can never be built into — or leak — an inconsistent temporal state.
79
+ *
80
+ * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
81
+ */
68
82
  let Entity = class Entity {
69
83
  static {
70
84
  _Entity = this;
71
85
  }
86
+ /**
87
+ * Reconstitutes an entity from its persisted {@link EntityState}.
88
+ *
89
+ * Validates the temporal invariants up front so an invalid entity is
90
+ * impossible to construct: both dates must be valid, the aggregate version
91
+ * must be a non-negative integer, and `updatedAt` may not predate
92
+ * `createdAt`. Both dates are cloned on the way in so a later mutation of
93
+ * the caller's `Date` objects cannot reach into the entity's internal state.
94
+ *
95
+ * Declared `protected` because entities are reconstituted through a
96
+ * subclass factory, never instantiated directly by application code.
97
+ *
98
+ * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
99
+ */
72
100
  constructor(state) {
73
101
  assertValidDate("createdAt", state.createdAt);
74
102
  assertValidDate("updatedAt", state.updatedAt);
@@ -79,21 +107,56 @@ let Entity = class Entity {
79
107
  this._updatedAt = cloneDate(state.updatedAt);
80
108
  this._aggregateVersion = state.aggregateVersion;
81
109
  }
110
+ /** The entity's stable identity — the basis for equality between entities. */
82
111
  get id() {
83
112
  return this._id;
84
113
  }
114
+ /**
115
+ * When the entity was first created.
116
+ *
117
+ * Returns a clone so callers cannot mutate the entity's internal `Date`;
118
+ * the value is fixed at construction and never changes thereafter.
119
+ */
85
120
  get createdAt() {
86
121
  return cloneDate(this._createdAt);
87
122
  }
123
+ /**
124
+ * When the entity was last modified.
125
+ *
126
+ * Returns a clone for the same encapsulation reason as {@link createdAt};
127
+ * the underlying value advances only through {@link markAsModified}.
128
+ */
88
129
  get updatedAt() {
89
130
  return cloneDate(this._updatedAt);
90
131
  }
132
+ /**
133
+ * Monotonic counter incremented on every mutation, used for optimistic
134
+ * concurrency control: a writer reads this value, and the persistence layer
135
+ * rejects the write if the stored version has moved on in the meantime.
136
+ */
91
137
  get aggregateVersion() {
92
138
  return this._aggregateVersion;
93
139
  }
140
+ /**
141
+ * The schema/contract version stamped on this entity type by the
142
+ * `@version` decorator — used to detect and migrate state persisted under
143
+ * an older shape.
144
+ */
94
145
  get contractVersion() {
95
146
  return _Entity.CONTRACT_VERSION;
96
147
  }
148
+ /**
149
+ * The single seam through which an entity records a mutation: it advances
150
+ * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must
151
+ * call this from every state-changing method so the version counter stays
152
+ * an accurate optimistic-lock token.
153
+ *
154
+ * @param updatedAt - The modification instant; defaults to now. Validated
155
+ * and required not to predate `createdAt`, preserving the same invariant
156
+ * the constructor enforces.
157
+ * @returns The new aggregate version after the increment.
158
+ * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
159
+ */
97
160
  markAsModified(updatedAt = /* @__PURE__ */ new Date()) {
98
161
  assertValidDate("updatedAt", updatedAt);
99
162
  if (updatedAt.getTime() < this._createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
@@ -133,19 +196,58 @@ function makeImmutable(value) {
133
196
  //#endregion
134
197
  //#region src/core/domain/value-object.ts
135
198
  var _ValueObject;
199
+ /**
200
+ * Base class for value objects — domain concepts defined entirely by their
201
+ * contents, with no identity of their own. Two value objects are
202
+ * interchangeable when they hold equal data, which is the opposite of an
203
+ * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one
204
+ * instance with an equal one changes nothing about the model.
205
+ *
206
+ * Immutability is the defining guarantee here. The wrapped `value` is
207
+ * deep-frozen on construction, so a value object can be shared freely without
208
+ * any risk of a consumer mutating shared state. Subclasses seal the instance
209
+ * itself with {@link finalize} once their own fields are set.
210
+ *
211
+ * @typeParam T - The shape of the wrapped data.
212
+ * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
213
+ */
136
214
  let ValueObject = class ValueObject {
137
215
  static {
138
216
  _ValueObject = this;
139
217
  }
218
+ /**
219
+ * Wraps `value`, deep-freezing it so the value object is immutable from the
220
+ * moment it exists. Declared `protected` because value objects are built
221
+ * through a validating subclass factory, never instantiated directly.
222
+ */
140
223
  constructor(value) {
141
224
  this.value = makeImmutable(value);
142
225
  }
226
+ /**
227
+ * The schema/contract version stamped on this value-object type by the
228
+ * `@version` decorator — used to detect state persisted under an older shape.
229
+ */
143
230
  get contractVersion() {
144
231
  return _ValueObject.CONTRACT_VERSION;
145
232
  }
233
+ /**
234
+ * Freezes the instance shell, blocking reassignment of any own field.
235
+ *
236
+ * `value` is already deep-frozen by the constructor, so the wrapped data is
237
+ * immutable regardless. The instance itself is NOT frozen automatically
238
+ * because a subclass may still need to assign its own fields after
239
+ * `super(value)` runs. Call `finalize()` at the very end of the subclass
240
+ * constructor (after all fields are set) to make the whole value object
241
+ * immutable.
242
+ */
146
243
  finalize() {
147
244
  Object.freeze(this);
148
245
  }
246
+ /**
247
+ * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value
248
+ * object serializes to its primitive form rather than exposing the internal
249
+ * `value` wrapper.
250
+ */
149
251
  toJSON() {
150
252
  return this.toPrimitive();
151
253
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["version","version"],"sources":["../src/version.ts","../src/core/application/policy-error-mapper.ts","../src/core/shared/aggregate-version.ts","../src/core/versioning/version.ts","../src/core/domain/entity.ts","../src/core/shared/immutable.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.0.9\";\n","import {\n type AppError,\n BusinessRuleViolationError,\n NotFoundError,\n UnexpectedError,\n} from \"../errors/index.js\";\nimport type { PolicyEvaluationError } from \"../policies/index.js\";\n\nexport function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError {\n switch (err.kind) {\n case \"INVALID_CONTEXT\":\n return new BusinessRuleViolationError(\n `policy.${err.stage.toLowerCase()}`,\n err.message,\n { policyKey: err.policyKey, stage: err.stage },\n { cause: err.cause },\n );\n case \"INVALID_POLICY_KEY\":\n return new BusinessRuleViolationError(\n \"policy.invalid_key\",\n err.message,\n { rawPolicyKey: err.rawPolicyKey },\n { cause: err.cause },\n );\n case \"POLICY_NOT_FOUND\":\n return new NotFoundError(\n \"Policy\",\n { policyKey: err.policyKey },\n { cause: err.cause },\n );\n case \"POLICY_DEFINITION_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyDefinition\",\n {\n policyKey: err.policyKey,\n contextVersion: err.contextVersion,\n asOf: err.asOf.toISOString(),\n },\n { cause: err.cause },\n );\n case \"POLICY_VARIANT_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyVariant\",\n {\n policyKey: err.policyKey,\n policyKind: err.policyKind,\n payloadSchemaVersion: err.payloadSchemaVersion,\n },\n { cause: err.cause },\n );\n case \"ENGINE_FAILURE\":\n return new UnexpectedError(err.message, err.cause, {\n metadata: {\n policyKey: err.policyKey,\n engine: err.engine,\n engineVersion: err.engineVersion,\n },\n });\n }\n}\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","type ContractVersion = `${number}.${number}`;\n\ntype VersionedTarget = {\n readonly prototype: object;\n};\n\nconst CONTRACT_VERSION_PROPERTY = \"CONTRACT_VERSION\" as const;\nconst CONTRACT_VERSION_PATTERN = /^\\d+\\.\\d+$/;\n\nfunction version<const TVersion extends ContractVersion>(\n contractVersion: TVersion,\n) {\n if (!CONTRACT_VERSION_PATTERN.test(contractVersion)) {\n throw new TypeError(\n `Invalid contract version \"${contractVersion}\". Expected MAJOR.MINOR.`,\n );\n }\n\n return (target: VersionedTarget): void => {\n Object.defineProperty(target, CONTRACT_VERSION_PROPERTY, {\n value: contractVersion,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n };\n}\n\nexport {\n CONTRACT_VERSION_PROPERTY,\n type ContractVersion,\n version,\n type VersionedTarget,\n};\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\ninterface EntityState<TIdentifier> {\n readonly id: TIdentifier;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly aggregateVersion: number;\n}\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 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 public get id(): TIdentifier {\n return this._id;\n }\n\n public get createdAt(): Date {\n return cloneDate(this._createdAt);\n }\n\n public get updatedAt(): Date {\n return cloneDate(this._updatedAt);\n }\n\n public get aggregateVersion(): number {\n return this._aggregateVersion;\n }\n\n public get contractVersion(): ContractVersion {\n return Entity.CONTRACT_VERSION;\n }\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 { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\ntype PrimitiveValue =\n | bigint\n | boolean\n | null\n | number\n | string\n | symbol\n | undefined;\n\ntype DeepReadonly<T> = T extends PrimitiveValue | Date\n ? T\n : T extends readonly (infer TItem)[]\n ? readonly DeepReadonly<TItem>[]\n : { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> };\n\nfunction deepFreeze<T>(value: T): T {\n return deepFreezeInternal(value, new WeakSet<object>());\n}\n\nfunction deepFreezeInternal<T>(value: T, seen: WeakSet<object>): T {\n // Primitives and `null` need no freezing. `Date` is intentionally returned\n // as-is: `Object.freeze` cannot stop a Date's mutators (`setTime`,\n // `setFullYear`, …) because they write an internal slot, not an own\n // property — freezing it is a no-op against mutation. `makeImmutable`\n // already hands us a `structuredClone` copy, so the caller's original Date\n // is never aliased; deep-freezing of nested Dates is deliberately skipped.\n if (typeof value !== \"object\" || value === null || value instanceof Date) {\n return value;\n }\n\n // A value already on `seen` has been visited on this pass (cyclic graph or a\n // shared reference); revisiting it would recurse forever.\n if (seen.has(value)) {\n return value;\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) {\n deepFreezeInternal(item, seen);\n }\n\n return Object.freeze(value);\n }\n\n const objectValue = value as Record<PropertyKey, object | PrimitiveValue>;\n\n for (const propertyKey of Reflect.ownKeys(objectValue)) {\n deepFreezeInternal(objectValue[propertyKey], seen);\n }\n\n return Object.freeze(value);\n}\n\nfunction makeImmutable<T>(value: T): DeepReadonly<T> {\n if (typeof value !== \"object\" || value === null) {\n return value as DeepReadonly<T>;\n }\n\n let snapshot: T;\n try {\n snapshot = structuredClone(value);\n } catch (error) {\n // `structuredClone` throws `DataCloneError` for functions, symbols and\n // class instances. Surface it as a domain invariant instead of leaking\n // a host-specific runtime error to callers building value objects.\n throw new InvariantViolationException(\n `makeImmutable requires a structured-cloneable value: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n return deepFreeze(snapshot) as DeepReadonly<T>;\n}\n\nexport { deepFreeze, makeImmutable, type DeepReadonly };\n","import { type DeepReadonly, makeImmutable } from \"../shared/immutable.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n@version(\"1.0\")\nabstract class ValueObject<T, P> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n public readonly value: DeepReadonly<T>;\n\n protected constructor(value: T) {\n this.value = makeImmutable(value);\n }\n\n public get contractVersion(): ContractVersion {\n return ValueObject.CONTRACT_VERSION;\n }\n\n protected finalize(): void {\n Object.freeze(this);\n }\n\n public toJSON(): P {\n return this.toPrimitive();\n }\n\n public abstract equals(other: this): boolean;\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,MAAaA,YAAU;;;ACEvB,SAAgB,yBAAyB,KAAsC;CAC3E,QAAQ,IAAI,MAAZ;EACI,KAAK,mBACD,OAAO,IAAI,2BACP,UAAU,IAAI,MAAM,YAAY,KAChC,IAAI,SACJ;GAAE,WAAW,IAAI;GAAW,OAAO,IAAI;EAAM,GAC7C,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,sBACD,OAAO,IAAI,2BACP,sBACA,IAAI,SACJ,EAAE,cAAc,IAAI,aAAa,GACjC,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,oBACD,OAAO,IAAI,cACP,UACA,EAAE,WAAW,IAAI,UAAU,GAC3B,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,+BACD,OAAO,IAAI,cACP,oBACA;GACI,WAAW,IAAI;GACf,gBAAgB,IAAI;GACpB,MAAM,IAAI,KAAK,YAAY;EAC/B,GACA,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,4BACD,OAAO,IAAI,cACP,iBACA;GACI,WAAW,IAAI;GACf,YAAY,IAAI;GAChB,sBAAsB,IAAI;EAC9B,GACA,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,k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C,QAAQ,KAAK,CAAA,GAAA,WAAA;;;ACCd,MAAa,gBAAgB;AAC7B,MAAa,mBAAmBC;AAEhC,MAAa,iBAAiB;CAC1B,MAAM;CACN,SAAS;AACb"}
1
+ {"version":3,"file":"index.js","names":["version","version"],"sources":["../src/version.ts","../src/core/application/policy-error-mapper.ts","../src/core/shared/aggregate-version.ts","../src/core/versioning/version.ts","../src/core/domain/entity.ts","../src/core/shared/immutable.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.0.11\";\n","import {\n type AppError,\n BusinessRuleViolationError,\n NotFoundError,\n UnexpectedError,\n} from \"../errors/index.js\";\nimport type { PolicyEvaluationError } from \"../policies/index.js\";\n\nexport function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError {\n switch (err.kind) {\n case \"INVALID_CONTEXT\":\n return new BusinessRuleViolationError(\n `policy.${err.stage.toLowerCase()}`,\n err.message,\n { policyKey: err.policyKey, stage: err.stage },\n { cause: err.cause },\n );\n case \"INVALID_POLICY_KEY\":\n return new BusinessRuleViolationError(\n \"policy.invalid_key\",\n err.message,\n { rawPolicyKey: err.rawPolicyKey },\n { cause: err.cause },\n );\n case \"POLICY_NOT_FOUND\":\n return new NotFoundError(\n \"Policy\",\n { policyKey: err.policyKey },\n { cause: err.cause },\n );\n case \"POLICY_DEFINITION_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyDefinition\",\n {\n policyKey: err.policyKey,\n contextVersion: err.contextVersion,\n asOf: err.asOf.toISOString(),\n },\n { cause: err.cause },\n );\n case \"POLICY_VARIANT_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyVariant\",\n {\n policyKey: err.policyKey,\n policyKind: err.policyKind,\n payloadSchemaVersion: err.payloadSchemaVersion,\n },\n { cause: err.cause },\n );\n case \"ENGINE_FAILURE\":\n return new UnexpectedError(err.message, err.cause, {\n metadata: {\n policyKey: err.policyKey,\n engine: err.engine,\n engineVersion: err.engineVersion,\n },\n });\n }\n}\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","type ContractVersion = `${number}.${number}`;\n\ntype VersionedTarget = {\n readonly prototype: object;\n};\n\nconst CONTRACT_VERSION_PROPERTY = \"CONTRACT_VERSION\" as const;\nconst CONTRACT_VERSION_PATTERN = /^\\d+\\.\\d+$/;\n\nfunction version<const TVersion extends ContractVersion>(\n contractVersion: TVersion,\n) {\n if (!CONTRACT_VERSION_PATTERN.test(contractVersion)) {\n throw new TypeError(\n `Invalid contract version \"${contractVersion}\". Expected MAJOR.MINOR.`,\n );\n }\n\n return (target: VersionedTarget): void => {\n Object.defineProperty(target, CONTRACT_VERSION_PROPERTY, {\n value: contractVersion,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n };\n}\n\nexport {\n CONTRACT_VERSION_PROPERTY,\n type ContractVersion,\n version,\n type VersionedTarget,\n};\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 { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\ntype PrimitiveValue =\n | bigint\n | boolean\n | null\n | number\n | string\n | symbol\n | undefined;\n\ntype DeepReadonly<T> = T extends PrimitiveValue | Date\n ? T\n : T extends readonly (infer TItem)[]\n ? readonly DeepReadonly<TItem>[]\n : { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> };\n\nfunction deepFreeze<T>(value: T): T {\n return deepFreezeInternal(value, new WeakSet<object>());\n}\n\nfunction deepFreezeInternal<T>(value: T, seen: WeakSet<object>): T {\n // Primitives and `null` need no freezing. `Date` is intentionally returned\n // as-is: `Object.freeze` cannot stop a Date's mutators (`setTime`,\n // `setFullYear`, …) because they write an internal slot, not an own\n // property — freezing it is a no-op against mutation. `makeImmutable`\n // already hands us a `structuredClone` copy, so the caller's original Date\n // is never aliased; deep-freezing of nested Dates is deliberately skipped.\n if (typeof value !== \"object\" || value === null || value instanceof Date) {\n return value;\n }\n\n // A value already on `seen` has been visited on this pass (cyclic graph or a\n // shared reference); revisiting it would recurse forever.\n if (seen.has(value)) {\n return value;\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) {\n deepFreezeInternal(item, seen);\n }\n\n return Object.freeze(value);\n }\n\n const objectValue = value as Record<PropertyKey, object | PrimitiveValue>;\n\n for (const propertyKey of Reflect.ownKeys(objectValue)) {\n deepFreezeInternal(objectValue[propertyKey], seen);\n }\n\n return Object.freeze(value);\n}\n\nfunction makeImmutable<T>(value: T): DeepReadonly<T> {\n if (typeof value !== \"object\" || value === null) {\n return value as DeepReadonly<T>;\n }\n\n let snapshot: T;\n try {\n snapshot = structuredClone(value);\n } catch (error) {\n // `structuredClone` throws `DataCloneError` for functions, symbols and\n // class instances. Surface it as a domain invariant instead of leaking\n // a host-specific runtime error to callers building value objects.\n throw new InvariantViolationException(\n `makeImmutable requires a structured-cloneable value: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n return deepFreeze(snapshot) as DeepReadonly<T>;\n}\n\nexport { deepFreeze, makeImmutable, type DeepReadonly };\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,MAAaA,YAAU;;;ACEvB,SAAgB,yBAAyB,KAAsC;CAC3E,QAAQ,IAAI,MAAZ;EACI,KAAK,mBACD,OAAO,IAAI,2BACP,UAAU,IAAI,MAAM,YAAY,KAChC,IAAI,SACJ;GAAE,WAAW,IAAI;GAAW,OAAO,IAAI;EAAM,GAC7C,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,sBACD,OAAO,IAAI,2BACP,sBACA,IAAI,SACJ,EAAE,cAAc,IAAI,aAAa,GACjC,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,oBACD,OAAO,IAAI,cACP,UACA,EAAE,WAAW,IAAI,UAAU,GAC3B,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,+BACD,OAAO,IAAI,cACP,oBACA;GACI,WAAW,IAAI;GACf,gBAAgB,IAAI;GACpB,MAAM,IAAI,KAAK,YAAY;EAC/B,GACA,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,4BACD,OAAO,IAAI,cACP,iBACA;GACI,WAAW,IAAI;GACf,YAAY,IAAI;GAChB,sBAAsB,IAAI;EAC9B,GACA,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,kBACD,OAAO,IAAI,gBAAgB,IAAI,SAAS,IAAI,OAAO,EAC/C,UAAU;GACN,WAAW,IAAI;GACf,QAAQ,IAAI;GACZ,eAAe,IAAI;EACvB,EACJ,CAAC;CACT;AACJ;;;ACzDA,SAAS,4BAA4B,kBAAgC;CACjE,IAAI,CAAC,OAAO,UAAU,gBAAgB,KAAK,mBAAmB,GAC1D,MAAM,IAAI,4BACN,8DAA8D,kBAClE;AAER;;;ACFA,MAAM,4BAA4B;AAClC,MAAM,2BAA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
117
117
  private readonly versionedEntries;
118
118
  private readonly entriesByKey;
119
+ /**
120
+ * Indexes the given entries up front into two lookups — one per exact
121
+ * variant, one per policy key (the "family") — and validates them eagerly:
122
+ * a duplicate variant or an internally inconsistent family throws here, at
123
+ * wiring time, so a malformed catalog fails fast at startup rather than on
124
+ * the first evaluation.
125
+ *
126
+ * @throws {UnexpectedError} When two entries resolve to the same variant key.
127
+ */
119
128
  constructor(entries: readonly PolicyCatalogEntry[]);
129
+ /**
130
+ * Returns the single entry for a key. Deliberately strict: if the key has
131
+ * more than one variant it errs rather than guessing, steering the caller to
132
+ * {@link getVersioned} or {@link getFamily}. Use this only when a key is
133
+ * known to be unambiguous.
134
+ *
135
+ * @returns `ok` with the entry, or `err` when the key is unknown or ambiguous.
136
+ */
120
137
  get(key: string): Result<PolicyCatalogEntry, string>;
138
+ /**
139
+ * Returns every variant registered under a key — the whole "family". This is
140
+ * the lookup the evaluation pipeline uses, since a single key may host
141
+ * several engine/schema variants that the resolver then chooses between.
142
+ *
143
+ * @returns `ok` with the family (always non-empty), or `err` when the key is unknown.
144
+ */
121
145
  getFamily(key: string): Result<readonly PolicyCatalogEntry[], string>;
146
+ /**
147
+ * Resolves the one entry matching an exact variant — kind plus engine and
148
+ * payload-schema versions. Falls back to the sole family member when a key
149
+ * has exactly one entry and that entry declares no explicit version
150
+ * selector, so unversioned single-variant policies "just work" without the
151
+ * caller spelling out versions.
152
+ *
153
+ * @param params - The key and the variant coordinates to match on.
154
+ * @returns `ok` with the matching entry, or `err` when no variant matches.
155
+ */
122
156
  getVersioned(params: {
123
157
  readonly key: string;
124
158
  readonly kind: "GATE" | "COMPUTE";
@@ -126,7 +160,9 @@ declare class PolicyCatalog {
126
160
  readonly computeEngineVersion?: number;
127
161
  readonly payloadSchemaVersion?: number;
128
162
  }): Result<PolicyCatalogEntry, string>;
163
+ /** Lists every registered variant across all keys — useful for introspection and diagnostics. */
129
164
  list(): readonly PolicyCatalogEntry[];
165
+ /** Returns whether any variant is registered under the given key. */
130
166
  has(key: string): boolean;
131
167
  }
132
168
  //#endregion
@@ -422,6 +458,16 @@ declare class PolicyAsOfResolver {
422
458
  * 5. policyVersion descending (semver — final deterministic tiebreaker)
423
459
  */
424
460
  declare class PolicyResolver {
461
+ /**
462
+ * Picks the single winning definition from an already-filtered candidate
463
+ * list by applying the class's ordering criteria in priority order. The sort
464
+ * runs over a copy, so the caller's array is left untouched, and the final
465
+ * semver tiebreaker guarantees the winner is fully deterministic — it never
466
+ * depends on the order the repository returned the candidates in.
467
+ *
468
+ * @param candidates - Definitions already filtered to match key, scope, and as-of.
469
+ * @returns `ok` with the highest-ranked definition, or `err` when the list is empty.
470
+ */
425
471
  resolveBest(candidates: readonly PolicyDefinition[]): Result<PolicyDefinition, string>;
426
472
  }
427
473
  //#endregion
@@ -485,6 +531,13 @@ declare class PolicyEvaluationErrors {
485
531
  }
486
532
  //#endregion
487
533
  //#region src/core/policies/service/policy-service.d.ts
534
+ /**
535
+ * Everything a single policy evaluation needs. `policyKey` names the policy,
536
+ * `scopeChain` narrows the search from most-specific to least-specific scope,
537
+ * `contextVersion` pins which context schema applies, and `seed` carries the
538
+ * raw facts the context builder expands. `decisionId` is the caller's
539
+ * idempotency/audit handle, echoed back on the result.
540
+ */
488
541
  interface EvaluateInput {
489
542
  readonly decisionId: PolicyDecisionId;
490
543
  readonly policyKey: string;
@@ -492,10 +545,22 @@ interface EvaluateInput {
492
545
  readonly contextVersion: number;
493
546
  readonly seed: ContextSeed;
494
547
  }
548
+ /**
549
+ * Cross-cutting knobs for a {@link PolicyService}: how the as-of instant is
550
+ * derived ({@link asOf}) and where evaluation telemetry is sent
551
+ * ({@link reporter}). Both are optional; the service defaults to a silent
552
+ * reporter so telemetry is opt-in.
553
+ */
495
554
  interface PolicyServiceOptions {
496
555
  readonly asOf?: DeriveAsOfOptions;
497
556
  readonly reporter?: PolicyReporter;
498
557
  }
558
+ /**
559
+ * The collaborators a {@link PolicyService} is wired with. Each is an injected
560
+ * port so the service stays storage- and engine-agnostic: the catalog defines
561
+ * the universe of policies, `defRepo` supplies their versioned definitions, the
562
+ * `resolver` picks the winning definition, and the engine registries execute it.
563
+ */
499
564
  interface PolicyServiceParams {
500
565
  readonly catalog: PolicyCatalog;
501
566
  readonly contextBuilder: PolicyContextBuilder;
@@ -507,6 +572,13 @@ interface PolicyServiceParams {
507
572
  }
508
573
  /** Union of all possible policy decision Outcomes. */
509
574
  type PolicyDecision = GateOutcome | ComputeOutcome;
575
+ /**
576
+ * The full record of one successful evaluation. Beyond the business
577
+ * {@link decision}, it pins the exact definition that produced it — id, key,
578
+ * version, payload hash, and engine version — together with the `asOf` instant
579
+ * the policy was selected for and the wall-clock `evaluatedAt`. That provenance
580
+ * is what makes a decision reproducible and auditable after the fact.
581
+ */
510
582
  interface PolicyEvaluationResult {
511
583
  readonly decisionId: PolicyDecisionId;
512
584
  readonly ref: {
@@ -524,6 +596,18 @@ interface PolicyEvaluationResult {
524
596
  /** Business decision expressed as an Outcome — not a technical Result. */
525
597
  readonly decision: PolicyDecision;
526
598
  }
599
+ /**
600
+ * Orchestrates the end-to-end evaluation of a policy: it parses and validates
601
+ * the context seed, derives the as-of instant, resolves the best matching
602
+ * definition for the requested key/scope/version, builds the context the policy
603
+ * needs, and runs it through the right engine (gate or compute).
604
+ *
605
+ * The service never throws for an expected failure: every step returns a
606
+ * {@link Result}, and the failures are folded into a typed
607
+ * {@link PolicyEvaluationError} so callers branch on `isErr()` rather than
608
+ * catching. Telemetry is best-effort — a throwing reporter can never abort an
609
+ * evaluation — which keeps observability strictly side-band.
610
+ */
527
611
  declare class PolicyService {
528
612
  #private;
529
613
  private readonly catalog;
@@ -535,6 +619,21 @@ declare class PolicyService {
535
619
  private readonly options;
536
620
  constructor(params: PolicyServiceParams);
537
621
  private resolveEvaluationNow;
622
+ /**
623
+ * Evaluates a policy and returns its decision.
624
+ *
625
+ * This is the single public entry point. It delegates the actual work to the
626
+ * private pipeline and wraps it with telemetry: a completed or failed event
627
+ * is reported either way, but reporting is guarded so it can never change the
628
+ * outcome. The returned {@link Result} is `ok` with a
629
+ * {@link PolicyEvaluationResult} on success, or `err` with a typed
630
+ * {@link PolicyEvaluationError} describing which stage rejected the input —
631
+ * the method itself does not throw for expected failures.
632
+ *
633
+ * @param input - The policy key, scope chain, context version, and seed to
634
+ * evaluate, plus the caller's `decisionId`.
635
+ * @returns A `Result` carrying the decision or the evaluation error.
636
+ */
538
637
  evaluate(input: EvaluateInput): Promise<Result<PolicyEvaluationResult, PolicyEvaluationError>>;
539
638
  }
540
639
  //#endregion