@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,54 @@
1
+ import { t as InvariantViolationException } from "./invariant-violation-exception.js";
2
+ //#region src/core/versioning/version.ts
3
+ const CONTRACT_VERSION_PROPERTY = "CONTRACT_VERSION";
4
+ const CONTRACT_VERSION_PATTERN = /^\d+\.\d+$/;
5
+ function version(contractVersion) {
6
+ if (!CONTRACT_VERSION_PATTERN.test(contractVersion)) throw new TypeError(`Invalid contract version "${contractVersion}". Expected MAJOR.MINOR.`);
7
+ return (target) => {
8
+ Object.defineProperty(target, CONTRACT_VERSION_PROPERTY, {
9
+ value: contractVersion,
10
+ writable: false,
11
+ configurable: false,
12
+ enumerable: false
13
+ });
14
+ };
15
+ }
16
+ //#endregion
17
+ //#region \0@oxc-project+runtime@0.132.0/helpers/decorate.js
18
+ function __decorate(decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ }
24
+ //#endregion
25
+ //#region src/core/shared/immutable.ts
26
+ function deepFreeze(value) {
27
+ return deepFreezeInternal(value, /* @__PURE__ */ new WeakSet());
28
+ }
29
+ function deepFreezeInternal(value, seen) {
30
+ if (typeof value !== "object" || value === null || value instanceof Date) return value;
31
+ if (seen.has(value)) return value;
32
+ seen.add(value);
33
+ if (Array.isArray(value)) {
34
+ for (const item of value) deepFreezeInternal(item, seen);
35
+ return Object.freeze(value);
36
+ }
37
+ const objectValue = value;
38
+ for (const propertyKey of Reflect.ownKeys(objectValue)) deepFreezeInternal(objectValue[propertyKey], seen);
39
+ return Object.freeze(value);
40
+ }
41
+ function makeImmutable(value) {
42
+ if (typeof value !== "object" || value === null) return value;
43
+ let snapshot;
44
+ try {
45
+ snapshot = structuredClone(value);
46
+ } catch (error) {
47
+ throw new InvariantViolationException(`makeImmutable requires a structured-cloneable value: ${error instanceof Error ? error.message : String(error)}`);
48
+ }
49
+ return deepFreeze(snapshot);
50
+ }
51
+ //#endregion
52
+ export { version as i, __decorate as n, CONTRACT_VERSION_PROPERTY as r, makeImmutable as t };
53
+
54
+ //# sourceMappingURL=immutable.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"immutable.js","names":[],"sources":["../src/core/versioning/version.ts","../src/core/shared/immutable.ts"],"sourcesContent":["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\";\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"],"mappings":";;AAMA,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AAEjC,SAAS,QACL,iBACF;CACE,IAAI,CAAC,yBAAyB,KAAK,eAAe,GAC9C,MAAM,IAAI,UACN,6BAA6B,gBAAgB,yBACjD;CAGJ,QAAQ,WAAkC;EACtC,OAAO,eAAe,QAAQ,2BAA2B;GACrD,OAAO;GACP,UAAU;GACV,cAAc;GACd,YAAY;EAChB,CAAC;CACL;AACJ;;;;;;;;;;;ACTA,SAAS,WAAc,OAAa;CAChC,OAAO,mBAAmB,uBAAO,IAAI,QAAgB,CAAC;AAC1D;AAEA,SAAS,mBAAsB,OAAU,MAA0B;CAO/D,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,iBAAiB,MAChE,OAAO;CAKX,IAAI,KAAK,IAAI,KAAK,GACd,OAAO;CAEX,KAAK,IAAI,KAAK;CAEd,IAAI,MAAM,QAAQ,KAAK,GAAG;EACtB,KAAK,MAAM,QAAQ,OACf,mBAAmB,MAAM,IAAI;EAGjC,OAAO,OAAO,OAAO,KAAK;CAC9B;CAEA,MAAM,cAAc;CAEpB,KAAK,MAAM,eAAe,QAAQ,QAAQ,WAAW,GACjD,mBAAmB,YAAY,cAAc,IAAI;CAGrD,OAAO,OAAO,OAAO,KAAK;AAC9B;AAEA,SAAS,cAAiB,OAA2B;CACjD,IAAI,OAAO,UAAU,YAAY,UAAU,MACvC,OAAO;CAGX,IAAI;CACJ,IAAI;EACA,WAAW,gBAAgB,KAAK;CACpC,SAAS,OAAO;EAIZ,MAAM,IAAI,4BACN,wDACI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAE7D;CACJ;CAEA,OAAO,WAAW,QAAQ;AAC9B"}
package/dist/index.d.ts CHANGED
@@ -1,209 +1,30 @@
1
- import { $ as ErrorCodes, A as IdempotencyPayloadMismatchError, B as UniqueConstraintViolation, C as IntegrationErrorMetadata, D as IdempotencyFailureKind, E as IdempotencyErrorMetadata, F as AlreadyExistsError, G as AuthorizationErrorMetadata, H as translateUniqueViolationToDuplicate, I as ConflictError, J as AuthenticationError, K as AuthorizationErrorReason, L as ConflictErrorMetadata, M as payloadHash, N as sha256Hex, O as IdempotencyInProgressError, P as stableStringify, Q as assertJsonSafeMetadata, R as ConflictKind, S as IntegrationError, T as IdempotencyError, U as BusinessRuleViolationError, V as UniqueConstraintViolationError, W as AuthorizationError, X as AuthenticationErrorReason, Y as AuthenticationErrorMetadata, Z as AppError, _ as SerializationMessages, a as TemporalError, at as JsonSafeValue, b as NotFoundError, c as TemporalPrecision, d as SerializationCodes, et as serializationErrorCode, f as SerializationDirection, g as SerializationInError, h as SerializationFailureCategory, i as NotYetValidError, it as JsonSafeRecord, j as IdempotencyReplayNotSupportedError, k as IdempotencyKeyMissingError, l as evaluateTemporalWindow, m as SerializationErrorMetadata, n as UnexpectedError, nt as ErrorSeverity, o as TemporalErrorMetadata, p as SerializationError, q as AuthorizationRequirement, r as ExpiredError, rt as JsonSafePrimitive, s as TemporalKind, t as ValidationError, tt as AppErrorOptions, u as SerializationBoundary, v as SerializationOutError, w as IntegrationErrorReason, x as LegacyIncompatibleError, y as safePreview, z as DuplicateError } from "./validation-error.js";
1
+ import { i as version, n as ContractVersion, r as VersionedTarget, t as CONTRACT_VERSION_PROPERTY } from "./version.js";
2
+ import { a as Result, i as Ok, n as Outcome, r as Err, t as CommonOutcomeStatus } from "./outcome.js";
3
+ import { A as MetricLabels, C as RequestedByKind, D as TraceAttributeValue, E as UseCaseObservability, M as LogPayload, N as LoggerPort, O as TraceSpan, S as RequestedBy, T as UseCase, _ as PolicyEvaluationOutput, a as TemporalContext, b as Command, c as CacheStrategy, d as mapPolicyEvaluationError, f as TemporalHistory, g as PolicyEvaluationInput, h as ResultRepository, i as CreateTemporalContextInput, j as MetricsPort, k as TracerPort, l as Page, m as Repository, n as TemporalUseCaseInput, o as assertTemporalContext, p as TemporalRepository, r as TemporalizedContextSeed, s as createTemporalContext, t as TemporalUseCase, u as Query, v as PolicyPort, w as MaybePromise, x as CommandInput, y as PolicyPortError } from "./temporal-use-case.js";
4
+ import { a as JsonSafeRecord, i as JsonSafePrimitive, n as AppErrorOptions, o as JsonSafeValue, r as ErrorSeverity, t as AppError } from "./app-error.js";
5
+ import { $ as serializationErrorCode, A as IdempotencyPayloadMismatchError, B as UniqueConstraintViolation, C as IntegrationErrorMetadata, D as IdempotencyFailureKind, E as IdempotencyErrorMetadata, F as AlreadyExistsError, G as AuthorizationErrorMetadata, H as translateUniqueViolationToDuplicate, I as ConflictError, J as AuthenticationError, K as AuthorizationErrorReason, L as ConflictErrorMetadata, M as payloadHash, N as sha256Hex, O as IdempotencyInProgressError, P as stableStringify, Q as ErrorCodes, R as ConflictKind, S as IntegrationError, T as IdempotencyError, U as BusinessRuleViolationError, V as UniqueConstraintViolationError, W as AuthorizationError, X as AuthenticationErrorReason, Y as AuthenticationErrorMetadata, Z as assertJsonSafeMetadata, _ as SerializationMessages, a as TemporalError, b as NotFoundError, c as TemporalPrecision, d as SerializationCodes, f as SerializationDirection, g as SerializationInError, h as SerializationFailureCategory, i as NotYetValidError, j as IdempotencyReplayNotSupportedError, k as IdempotencyKeyMissingError, l as evaluateTemporalWindow, m as SerializationErrorMetadata, n as UnexpectedError, o as TemporalErrorMetadata, p as SerializationError, q as AuthorizationRequirement, r as ExpiredError, s as TemporalKind, t as ValidationError, u as SerializationBoundary, v as SerializationOutError, w as IntegrationErrorReason, x as LegacyIncompatibleError, y as safePreview, z as DuplicateError } from "./validation-error.js";
6
+ import { t as ValidationCode } from "./validation-code.js";
2
7
  import { t as ValidationField } from "./validation-field.js";
3
- import { A as ConditionEvaluationReport, C as TenantId, D as asTenantId, E as asSchoolId, F as Ok, I as Result, M as ConditionEvaluationReportTag, N as ConditionEvaluatorReporter, O as ConditionEvaluationCause, P as Err, S as SchoolId, T as asPolicyDefinitionId, _ as CoreConfigOptions, a as GateTraceNodeSnapshot, b as PolicyDecisionId, c as PolicyViolation, g as CoreConfig, h as Outcome, i as GateTraceLeafSnapshot, j as ConditionEvaluationReportLevel, k as ConditionEvaluationOptions, l as VersionedGateEngine, m as CommonOutcomeStatus, n as GateOutcomeData, o as GateViolationTrace, r as GateStatus, s as PolicyContext, t as GateOutcome, u as GatePayload, v as CoreObservabilityConfig, w as asPolicyDecisionId, x as PolicyDefinitionId } from "./gate-types.js";
4
- import { A as FindCandidatesParams, B as PolicyKey, C as ContextSeed, D as InMemoryPolicyDefinitionRepository, E as PolicyPackage, F as PolicyScope, G as PolicyHashing, H as PolicyKind, I as PolicyScopeMatcher, K as coreConfig, L as ScopeChain, M as PolicyDefinition, N as PolicyDefinitionProps, O as BasePolicyDefinitionProps, P as PolicyDefinitionStatus, R as PolicyCatalog, S as ContextValueResolver, T as PolicyCatalogFactory, U as PolicyOwner, V as AsOfSource, W as PolicyScopeLevel, _ as ContextResolverRegistry, a as PolicyServiceOptions, b as ContextResolverResilienceOptions, c as PolicyEvaluationErrors, d as PolicyAsOfResolver, f as PolicyContextPath, g as PolicyContextBuilderOptions, h as PolicyContextBuilder, i as PolicyService, j as GatePolicyDefinitionProps, k as ComputePolicyDefinitionProps, l as PolicyResolver, m as registerNamespacedContextResolvers, n as PolicyDecision, o as PolicyServiceParams, p as contextResolverRegistry, r as PolicyEvaluationResult, s as PolicyEvaluationError, t as EvaluateInput, u as DeriveAsOfOptions, v as registerNamespacedContextResolversIn, w as ContextSeedValidator, x as ContextResolverRetryOptions, y as ContextResolverCircuitBreakerOptions, z as PolicyCatalogEntryProps } from "./policy-service.js";
5
- import { a as ComputePayloadParserRegistry, c as ComputeRegistry, d as ComputeEvaluator, f as ComputeEvaluatorRegistration, g as VersionedComputeEngine, h as ComputeStatus, l as ComputeEngineRegistry, m as ComputeOutcomeData, o as ComputePayloadParsers, p as ComputeOutcome, r as GatePayloadParsers, s as GateEngineRegistry, u as ComputeEvaluatorRegistry } from "./parse-gate-payload.js";
8
+ import { A as ConditionEvaluationReportTag, C as asPolicyDefinitionId, D as ConditionEvaluationOptions, E as ConditionEvaluationCause, O as ConditionEvaluationReport, S as asPolicyDecisionId, T as asTenantId, a as GateTraceNodeSnapshot, b as SchoolId, c as PolicyViolation, g as CoreObservabilityConfig, h as CoreConfigOptions, i as GateTraceLeafSnapshot, j as ConditionEvaluatorReporter, k as ConditionEvaluationReportLevel, l as VersionedGateEngine, m as CoreConfig, n as GateOutcomeData, o as GateViolationTrace, r as GateStatus, s as PolicyContext, t as GateOutcome, u as GatePayload, v as PolicyDecisionId, w as asSchoolId, x as TenantId, y as PolicyDefinitionId } from "./gate-types.js";
9
+ import { a as PolicyPackage, c as coreConfig, i as PolicyCatalogFactory, n as contextResolverRegistry, o as InMemoryPolicyDefinitionRepository, r as registerNamespacedContextResolvers, s as PolicyHashing, t as PolicyContextPath } from "./path.js";
10
+ import { A as PolicyScope, C as BasePolicyDefinitionProps, D as PolicyDefinition, E as GatePolicyDefinitionProps, F as PolicyKey, I as AsOfSource, L as PolicyKind, M as ScopeChain, N as PolicyCatalog, O as PolicyDefinitionProps, P as PolicyCatalogEntryProps, R as PolicyOwner, T as FindCandidatesParams, _ as ContextResolverResilienceOptions, a as PolicyServiceOptions, b as ContextSeed, c as PolicyEvaluationErrors, d as PolicyAsOfResolver, f as PolicyContextBuilder, g as ContextResolverCircuitBreakerOptions, h as registerNamespacedContextResolversIn, i as PolicyService, j as PolicyScopeMatcher, k as PolicyDefinitionStatus, l as PolicyResolver, m as ContextResolverRegistry, n as PolicyDecision, o as PolicyServiceParams, p as PolicyContextBuilderOptions, r as PolicyEvaluationResult, s as PolicyEvaluationError, t as EvaluateInput, u as DeriveAsOfOptions, v as ContextResolverRetryOptions, w as ComputePolicyDefinitionProps, x as ContextSeedValidator, y as ContextValueResolver, z as PolicyScopeLevel } from "./policy-service.js";
11
+ import { a as ComputeOutcome, c as VersionedComputeEngine, i as ComputeEvaluatorRegistration, n as ComputeRegistry, o as ComputeOutcomeData, r as ComputeEvaluator, s as ComputeStatus, t as GateEngineRegistry } from "./gate-engine-registry.js";
12
+ import { a as ComputePayloadParserRegistry, c as ComputeEvaluatorRegistry, o as ComputePayloadParsers, r as GatePayloadParsers, s as ComputeEngineRegistry } from "./parse-gate-payload.js";
13
+ import { t as DeepReadonly } from "./immutable.js";
14
+ import { a as EntityState, i as Entity, n as ValueObject, r as ValueObjectPluginContract, t as UuidIdentifier } from "./uuid-identifier.js";
15
+ import { a as PluginContract, i as PipelineReducer, n as BasePlugin, r as InvokeOptions, t as PluginManager } from "./plugin.js";
16
+ import { t as DomainException } from "./domain-exception.js";
17
+ import { a as InvariantViolationException, c as BusinessRuleViolationException, i as ValidationViolation, n as MultipleValidationException, o as InvalidStateTransitionException, r as ValidationException, s as EntityNotFoundException, t as InvalidValueException } from "./validation-exception.js";
18
+ import { a as Ruleset, i as InvariantRuleset, n as RulesetRegistry, o as RulesetId, r as CreationRuleset, t as ValueObjectRuleset } from "./value-object-ruleset.contracts.js";
19
+ import { a as buildDomainEventContractVersions, i as DomainEventEnvelope, n as DomainEventContractSelection, o as createDomainEventEnvelope, r as DomainEventContractVersions, t as CreateDomainEventEnvelopeInput } from "./domain-event-contracts.js";
6
20
 
7
- //#region src/core/versioning/version.d.ts
8
- type ContractVersion = `${number}.${number}`;
9
- //#endregion
10
- //#region src/core/application/ports/logger.port.d.ts
11
- type LogPayload = Record<string, unknown>;
12
- interface LoggerPort {
13
- debug(message: string, payload?: LogPayload): void;
14
- info(message: string, payload?: LogPayload): void;
15
- warn(message: string, payload?: LogPayload): void;
16
- error(message: string, payload?: LogPayload): void;
17
- }
18
- //#endregion
19
- //#region src/core/application/ports/metrics.port.d.ts
20
- type MetricLabels = Readonly<Record<string, string | number | boolean>>;
21
- interface MetricsPort {
22
- counter(name: string, value: number, labels?: MetricLabels): void;
23
- gauge(name: string, value: number, labels?: MetricLabels): void;
24
- histogram(name: string, value: number, labels?: MetricLabels): void;
25
- }
26
- //#endregion
27
- //#region src/core/shared/immutable.d.ts
28
- type PrimitiveValue = bigint | boolean | null | number | string | symbol | undefined;
29
- type DeepReadonly<T> = T extends PrimitiveValue | Date ? T : T extends readonly (infer TItem)[] ? readonly DeepReadonly<TItem>[] : { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> };
30
- //#endregion
31
- //#region src/core/application/ports/tracer.port.d.ts
32
- type TraceAttributeValue = string | number | boolean;
33
- interface TraceSpan {
34
- setAttribute(key: string, value: TraceAttributeValue): void;
35
- recordException(error: unknown): void;
36
- end(): void;
37
- }
38
- interface TracerPort {
39
- startSpan(name: string, attributes?: Record<string, TraceAttributeValue>): TraceSpan;
40
- }
41
- //#endregion
42
- //#region src/core/application/policy-error-mapper.d.ts
43
- declare function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError;
44
- //#endregion
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
- */
54
- interface EntityState<TIdentifier> {
55
- readonly id: TIdentifier;
56
- readonly createdAt: Date;
57
- readonly updatedAt: Date;
58
- readonly aggregateVersion: number;
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
- */
74
- declare abstract class Entity<TIdentifier> {
75
- static readonly CONTRACT_VERSION: ContractVersion;
76
- private readonly _id;
77
- private readonly _createdAt;
78
- private _updatedAt;
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
- */
94
- protected constructor(state: EntityState<TIdentifier>);
95
- /** The entity's stable identity — the basis for equality between entities. */
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
- */
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
- */
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
- */
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
- */
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
- */
135
- protected markAsModified(updatedAt?: Date): number;
136
- }
137
- //#endregion
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
- */
154
- declare abstract class ValueObject<T, P> {
155
- static readonly CONTRACT_VERSION: ContractVersion;
156
- /** The wrapped data, deep-frozen so it can never be mutated after construction. */
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
- */
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
- */
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
- */
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
- */
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
- */
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
- */
197
- abstract toPrimitive(): P;
198
- }
199
- //#endregion
200
21
  //#region src/index.d.ts
201
22
  declare const ERP_CORE_NAME = "erp-core";
202
- declare const ERP_CORE_VERSION = "1.0.11";
23
+ declare const ERP_CORE_VERSION = "1.2.0";
203
24
  declare const erpCoreRelease: {
204
25
  readonly name: "erp-core";
205
- readonly version: "1.0.11";
26
+ readonly version: "1.2.0";
206
27
  };
207
28
  //#endregion
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 };
29
+ export { AlreadyExistsError, AppError, AppErrorOptions, AsOfSource, AuthenticationError, AuthenticationErrorMetadata, AuthenticationErrorReason, AuthorizationError, AuthorizationErrorMetadata, AuthorizationErrorReason, AuthorizationRequirement, BasePlugin, BasePolicyDefinitionProps, BusinessRuleViolationError, BusinessRuleViolationException, CONTRACT_VERSION_PROPERTY, CacheStrategy, Command, CommandInput, 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, ContractVersion, CoreConfig, CoreConfigOptions, CoreObservabilityConfig, CreateDomainEventEnvelopeInput, CreateTemporalContextInput, CreationRuleset, DeepReadonly, DeriveAsOfOptions, SerializationInError as DeserializationError, SerializationInError, DomainEventContractSelection, DomainEventContractVersions, DomainEventEnvelope, DomainException, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, EntityNotFoundException, 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, InvalidStateTransitionException, InvalidValueException, InvariantRuleset, InvariantViolationException, InvokeOptions, JsonSafePrimitive, JsonSafeRecord, JsonSafeValue, LegacyIncompatibleError, LogPayload, LoggerPort, MaybePromise, MetricLabels, MetricsPort, MultipleValidationException, NotFoundError, NotYetValidError, Ok, Outcome, Page, PipelineReducer, PluginContract, PluginManager, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogEntryProps, PolicyCatalogFactory, PolicyContext, PolicyContextBuilder, PolicyContextBuilderOptions, PolicyContextPath, PolicyDecision, PolicyDecisionId, PolicyDefinition, PolicyDefinitionId, PolicyDefinitionProps, PolicyDefinitionStatus, PolicyEvaluationError, PolicyEvaluationErrors, PolicyEvaluationInput, PolicyEvaluationOutput, PolicyEvaluationResult, PolicyHashing, PolicyKey, PolicyKind, PolicyOwner, PolicyPackage, PolicyPort, PolicyPortError, PolicyResolver, PolicyScope, PolicyScopeLevel, PolicyScopeMatcher, PolicyService, PolicyServiceOptions, PolicyServiceParams, PolicyViolation, Query, Repository, RequestedBy, RequestedByKind, Result, ResultRepository, Ruleset, RulesetId, RulesetRegistry, SchoolId, ScopeChain, SerializationBoundary, SerializationCodes, SerializationDirection, SerializationError, SerializationErrorMetadata, SerializationFailureCategory, SerializationMessages, SerializationOutError, TemporalContext, TemporalError, TemporalHistory, TemporalKind, TemporalRepository, TemporalUseCase, TemporalUseCaseInput, TemporalizedContextSeed, TenantId, TraceAttributeValue, TraceSpan, TracerPort, UnexpectedError, UniqueConstraintViolation, UniqueConstraintViolationError, UseCase, UseCaseObservability, UuidIdentifier, ValidationCode, ValidationError, ValidationException, ValidationField, ValidationViolation, ValueObject, ValueObjectPluginContract, ValueObjectRuleset, VersionedComputeEngine, VersionedGateEngine, VersionedTarget, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, assertTemporalContext, buildDomainEventContractVersions, contextResolverRegistry, coreConfig, createDomainEventEnvelope, createTemporalContext, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate, version };
209
30
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,258 +1,28 @@
1
- import { a as stableStringify, c as ErrorCodes, i as sha256Hex, l as serializationErrorCode, n as UnexpectedError, o as AppError, r as payloadHash, s as assertJsonSafeMetadata } from "./validation-code.js";
2
- import { C as UniqueConstraintViolationError, D as AuthenticationError, E as AuthorizationError, S as DuplicateError, T as BusinessRuleViolationError, _ as IdempotencyKeyMissingError, a as evaluateTemporalWindow, b as AlreadyExistsError, c as SerializationInError, d as safePreview, f as NotFoundError, g as IdempotencyInProgressError, h as IdempotencyError, i as TemporalError, l as SerializationMessages, m as IntegrationError, n as ExpiredError, o as SerializationCodes, p as LegacyIncompatibleError, r as NotYetValidError, s as SerializationError, t as ValidationError, u as SerializationOutError, v as IdempotencyPayloadMismatchError, w as translateUniqueViolationToDuplicate, x as ConflictError, y as IdempotencyReplayNotSupportedError } from "./validation-error.js";
1
+ import { a as serializationErrorCode, i as ErrorCodes, n as AppError, r as assertJsonSafeMetadata, t as UnexpectedError } from "./unexpected-error.js";
2
+ import { C as translateUniqueViolationToDuplicate, S as UniqueConstraintViolationError, T as AuthenticationError, _ as IdempotencyPayloadMismatchError, a as evaluateTemporalWindow, b as ConflictError, c as SerializationInError, d as safePreview, f as LegacyIncompatibleError, g as IdempotencyKeyMissingError, h as IdempotencyInProgressError, i as TemporalError, l as SerializationMessages, m as IdempotencyError, n as ExpiredError, o as SerializationCodes, p as IntegrationError, r as NotYetValidError, s as SerializationError, t as ValidationError, u as SerializationOutError, v as IdempotencyReplayNotSupportedError, w as AuthorizationError, x as DuplicateError, y as AlreadyExistsError } from "./validation-error.js";
3
+ import { n as BusinessRuleViolationError, t as NotFoundError } from "./not-found-error.js";
4
+ import { n as sha256Hex, r as stableStringify, t as payloadHash } from "./hashing.js";
5
+ import { t as ValidationCode } from "./validation-code.js";
3
6
  import { t as ValidationField } from "./validation-field.js";
4
- import { c as Ok, d as CoreConfig, g as InvariantViolationException, l as Result, m as cloneDate, o as PolicyContextPath, p as assertValidDate, s as Err, u as coreConfig } from "./gate-v1-payload.schema.js";
7
+ import { t as DomainException } from "./domain-exception.js";
8
+ import { n as EntityNotFoundException, r as BusinessRuleViolationException, t as InvalidStateTransitionException } from "./invalid-state-transition-exception.js";
9
+ import { t as InvariantViolationException } from "./invariant-violation-exception.js";
10
+ import { n as MultipleValidationException, r as ValidationException, t as InvalidValueException } from "./validation-exception.js";
11
+ import { i as version, r as CONTRACT_VERSION_PROPERTY } from "./immutable.js";
12
+ import { t as UseCase } from "./use-case.js";
13
+ import { a as mapPolicyEvaluationError, i as Query, n as assertTemporalContext, o as Command, r as createTemporalContext, s as RequestedBy, t as TemporalUseCase } from "./temporal-use-case.js";
14
+ import { n as Entity, t as ValueObject } from "./value-object.js";
15
+ import { t as PluginManager } from "./plugin.js";
16
+ import { t as UuidIdentifier } from "./uuid-identifier.js";
17
+ import { t as RulesetRegistry } from "./ruleset-registry.js";
18
+ import { n as createDomainEventEnvelope, t as buildDomainEventContractVersions } from "./domain-event-contracts.js";
19
+ import { c as CoreConfig, o as PolicyContextPath, s as coreConfig } from "./gate-v1-payload.schema.js";
20
+ import { n as Ok, r as Result, t as Err } from "./result.js";
5
21
  import { t as Outcome } from "./outcome.js";
6
22
  import { _ as asPolicyDecisionId, a as ContextSeedValidator, b as asTenantId, c as ContextResolverRegistry, d as PolicyDefinition, f as InMemoryPolicyDefinitionRepository, g as PolicyCatalog, h as PolicyCatalogFactory, i as PolicyAsOfResolver, l as registerNamespacedContextResolversIn, m as PolicyKey, n as PolicyEvaluationErrors, o as contextResolverRegistry, p as PolicyScopeMatcher, r as PolicyResolver, s as registerNamespacedContextResolvers, t as PolicyService, u as PolicyContextBuilder, v as asPolicyDefinitionId, x as PolicyHashing, y as asSchoolId } from "./policy-service.js";
7
23
  import { a as ComputeEvaluatorRegistry, c as ComputePayloadParsers, i as ComputeRegistry, o as ComputeEngineRegistry, r as GatePayloadParsers, s as ComputePayloadParserRegistry, t as GateEngineRegistry } from "./gate-engine-registry.js";
8
24
  //#region src/version.ts
9
- const version$1 = "1.0.11";
10
- //#endregion
11
- //#region src/core/application/policy-error-mapper.ts
12
- function mapPolicyEvaluationError(err) {
13
- switch (err.kind) {
14
- case "INVALID_CONTEXT": return new BusinessRuleViolationError(`policy.${err.stage.toLowerCase()}`, err.message, {
15
- policyKey: err.policyKey,
16
- stage: err.stage
17
- }, { cause: err.cause });
18
- case "INVALID_POLICY_KEY": return new BusinessRuleViolationError("policy.invalid_key", err.message, { rawPolicyKey: err.rawPolicyKey }, { cause: err.cause });
19
- case "POLICY_NOT_FOUND": return new NotFoundError("Policy", { policyKey: err.policyKey }, { cause: err.cause });
20
- case "POLICY_DEFINITION_NOT_FOUND": return new NotFoundError("PolicyDefinition", {
21
- policyKey: err.policyKey,
22
- contextVersion: err.contextVersion,
23
- asOf: err.asOf.toISOString()
24
- }, { cause: err.cause });
25
- case "POLICY_VARIANT_NOT_FOUND": return new NotFoundError("PolicyVariant", {
26
- policyKey: err.policyKey,
27
- policyKind: err.policyKind,
28
- payloadSchemaVersion: err.payloadSchemaVersion
29
- }, { cause: err.cause });
30
- case "ENGINE_FAILURE": return new UnexpectedError(err.message, err.cause, { metadata: {
31
- policyKey: err.policyKey,
32
- engine: err.engine,
33
- engineVersion: err.engineVersion
34
- } });
35
- }
36
- }
37
- //#endregion
38
- //#region src/core/shared/aggregate-version.ts
39
- function assertValidAggregateVersion(aggregateVersion) {
40
- if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) throw new InvariantViolationException(`aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`);
41
- }
42
- //#endregion
43
- //#region src/core/versioning/version.ts
44
- const CONTRACT_VERSION_PROPERTY = "CONTRACT_VERSION";
45
- const CONTRACT_VERSION_PATTERN = /^\d+\.\d+$/;
46
- function version(contractVersion) {
47
- if (!CONTRACT_VERSION_PATTERN.test(contractVersion)) throw new TypeError(`Invalid contract version "${contractVersion}". Expected MAJOR.MINOR.`);
48
- return (target) => {
49
- Object.defineProperty(target, CONTRACT_VERSION_PROPERTY, {
50
- value: contractVersion,
51
- writable: false,
52
- configurable: false,
53
- enumerable: false
54
- });
55
- };
56
- }
57
- //#endregion
58
- //#region \0@oxc-project+runtime@0.132.0/helpers/decorate.js
59
- function __decorate(decorators, target, key, desc) {
60
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
61
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
62
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
63
- return c > 3 && r && Object.defineProperty(target, key, r), r;
64
- }
65
- //#endregion
66
- //#region src/core/domain/entity.ts
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
- */
82
- let Entity = class Entity {
83
- static {
84
- _Entity = this;
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
- */
100
- constructor(state) {
101
- assertValidDate("createdAt", state.createdAt);
102
- assertValidDate("updatedAt", state.updatedAt);
103
- assertValidAggregateVersion(state.aggregateVersion);
104
- if (state.updatedAt.getTime() < state.createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
105
- this._id = state.id;
106
- this._createdAt = cloneDate(state.createdAt);
107
- this._updatedAt = cloneDate(state.updatedAt);
108
- this._aggregateVersion = state.aggregateVersion;
109
- }
110
- /** The entity's stable identity — the basis for equality between entities. */
111
- get id() {
112
- return this._id;
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
- */
120
- get createdAt() {
121
- return cloneDate(this._createdAt);
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
- */
129
- get updatedAt() {
130
- return cloneDate(this._updatedAt);
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
- */
137
- get aggregateVersion() {
138
- return this._aggregateVersion;
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
- */
145
- get contractVersion() {
146
- return _Entity.CONTRACT_VERSION;
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
- */
160
- markAsModified(updatedAt = /* @__PURE__ */ new Date()) {
161
- assertValidDate("updatedAt", updatedAt);
162
- if (updatedAt.getTime() < this._createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
163
- this._updatedAt = cloneDate(updatedAt);
164
- this._aggregateVersion += 1;
165
- return this._aggregateVersion;
166
- }
167
- };
168
- Entity = _Entity = __decorate([version("1.0")], Entity);
169
- //#endregion
170
- //#region src/core/shared/immutable.ts
171
- function deepFreeze(value) {
172
- return deepFreezeInternal(value, /* @__PURE__ */ new WeakSet());
173
- }
174
- function deepFreezeInternal(value, seen) {
175
- if (typeof value !== "object" || value === null || value instanceof Date) return value;
176
- if (seen.has(value)) return value;
177
- seen.add(value);
178
- if (Array.isArray(value)) {
179
- for (const item of value) deepFreezeInternal(item, seen);
180
- return Object.freeze(value);
181
- }
182
- const objectValue = value;
183
- for (const propertyKey of Reflect.ownKeys(objectValue)) deepFreezeInternal(objectValue[propertyKey], seen);
184
- return Object.freeze(value);
185
- }
186
- function makeImmutable(value) {
187
- if (typeof value !== "object" || value === null) return value;
188
- let snapshot;
189
- try {
190
- snapshot = structuredClone(value);
191
- } catch (error) {
192
- throw new InvariantViolationException(`makeImmutable requires a structured-cloneable value: ${error instanceof Error ? error.message : String(error)}`);
193
- }
194
- return deepFreeze(snapshot);
195
- }
196
- //#endregion
197
- //#region src/core/domain/value-object.ts
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
- */
214
- let ValueObject = class ValueObject {
215
- static {
216
- _ValueObject = this;
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
- */
223
- constructor(value) {
224
- this.value = makeImmutable(value);
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
- */
230
- get contractVersion() {
231
- return _ValueObject.CONTRACT_VERSION;
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
- */
243
- finalize() {
244
- Object.freeze(this);
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
- */
251
- toJSON() {
252
- return this.toPrimitive();
253
- }
254
- };
255
- ValueObject = _ValueObject = __decorate([version("1.0")], ValueObject);
25
+ const version$1 = "1.2.0";
256
26
  //#endregion
257
27
  //#region src/index.ts
258
28
  const ERP_CORE_NAME = "erp-core";
@@ -262,6 +32,6 @@ const erpCoreRelease = {
262
32
  version: ERP_CORE_VERSION
263
33
  };
264
34
  //#endregion
265
- export { AlreadyExistsError, AppError, AuthenticationError, AuthorizationError, BusinessRuleViolationError, ComputeEngineRegistry, ComputeEvaluatorRegistry, ComputePayloadParserRegistry, ComputePayloadParsers, ComputeRegistry, ConflictError, ContextResolverRegistry, ContextSeedValidator, CoreConfig, SerializationInError as DeserializationError, SerializationInError, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, Err, ErrorCodes, ExpiredError, GateEngineRegistry, GatePayloadParsers, IdempotencyError, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, InMemoryPolicyDefinitionRepository, IntegrationError, LegacyIncompatibleError, NotFoundError, NotYetValidError, Ok, Outcome, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogFactory, PolicyContextBuilder, PolicyContextPath, PolicyDefinition, PolicyEvaluationErrors, PolicyHashing, PolicyKey, PolicyResolver, PolicyScopeMatcher, PolicyService, Result, SerializationCodes, SerializationError, SerializationMessages, SerializationOutError, TemporalError, UnexpectedError, UniqueConstraintViolationError, ValidationError, ValidationField, ValueObject, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, contextResolverRegistry, coreConfig, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate };
35
+ export { AlreadyExistsError, AppError, AuthenticationError, AuthorizationError, BusinessRuleViolationError, BusinessRuleViolationException, CONTRACT_VERSION_PROPERTY, Command, ComputeEngineRegistry, ComputeEvaluatorRegistry, ComputePayloadParserRegistry, ComputePayloadParsers, ComputeRegistry, ConflictError, ContextResolverRegistry, ContextSeedValidator, CoreConfig, SerializationInError as DeserializationError, SerializationInError, DomainException, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, EntityNotFoundException, Err, ErrorCodes, ExpiredError, GateEngineRegistry, GatePayloadParsers, IdempotencyError, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, InMemoryPolicyDefinitionRepository, IntegrationError, InvalidStateTransitionException, InvalidValueException, InvariantViolationException, LegacyIncompatibleError, MultipleValidationException, NotFoundError, NotYetValidError, Ok, Outcome, PluginManager, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogFactory, PolicyContextBuilder, PolicyContextPath, PolicyDefinition, PolicyEvaluationErrors, PolicyHashing, PolicyKey, PolicyResolver, PolicyScopeMatcher, PolicyService, Query, RequestedBy, Result, RulesetRegistry, SerializationCodes, SerializationError, SerializationMessages, SerializationOutError, TemporalError, TemporalUseCase, UnexpectedError, UniqueConstraintViolationError, UseCase, UuidIdentifier, ValidationCode, ValidationError, ValidationException, ValidationField, ValueObject, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, assertTemporalContext, buildDomainEventContractVersions, contextResolverRegistry, coreConfig, createDomainEventEnvelope, createTemporalContext, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate, version };
266
36
 
267
37
  //# sourceMappingURL=index.js.map