@cullet/erp-core 1.5.0 → 2.0.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 (306) hide show
  1. package/KIT_CONTEXT.md +2 -2
  2. package/dist/abac/index.d.cts +2 -2
  3. package/dist/abac/index.d.ts +2 -2
  4. package/dist/aggregate-version.cjs +14 -0
  5. package/dist/aggregate-version.cjs.map +1 -0
  6. package/dist/aggregate-version.js +9 -0
  7. package/dist/aggregate-version.js.map +1 -0
  8. package/dist/app-error.cjs +8 -1
  9. package/dist/app-error.cjs.map +1 -1
  10. package/dist/app-error.js +8 -1
  11. package/dist/app-error.js.map +1 -1
  12. package/dist/application/index.cjs +8 -4
  13. package/dist/application/index.d.cts +2 -2
  14. package/dist/application/index.d.ts +2 -2
  15. package/dist/application/index.js +1 -2
  16. package/dist/authorization-error.cjs +67 -17
  17. package/dist/authorization-error.cjs.map +1 -1
  18. package/dist/authorization-error.d.cts +6 -2
  19. package/dist/authorization-error.d.ts +6 -2
  20. package/dist/authorization-error.js +50 -18
  21. package/dist/authorization-error.js.map +1 -1
  22. package/dist/authorizer.port.d.cts +18 -3
  23. package/dist/authorizer.port.d.ts +18 -3
  24. package/dist/composite-authorizer.d.cts +63 -10
  25. package/dist/composite-authorizer.d.ts +63 -10
  26. package/dist/condition-evaluator.cjs +115 -184
  27. package/dist/condition-evaluator.cjs.map +1 -1
  28. package/dist/condition-evaluator.js +116 -179
  29. package/dist/condition-evaluator.js.map +1 -1
  30. package/dist/core-config.d.cts +53 -6
  31. package/dist/core-config.d.ts +53 -6
  32. package/dist/decorate.cjs +14 -0
  33. package/dist/decorate.js +9 -0
  34. package/dist/domain/index.cjs +107 -2
  35. package/dist/domain/index.cjs.map +1 -0
  36. package/dist/domain/index.d.cts +25 -1
  37. package/dist/domain/index.d.ts +25 -1
  38. package/dist/domain/index.js +99 -3
  39. package/dist/domain/index.js.map +1 -0
  40. package/dist/domain-event-contracts.cjs +12 -8
  41. package/dist/domain-event-contracts.cjs.map +1 -1
  42. package/dist/domain-event-contracts.d.cts +29 -4
  43. package/dist/domain-event-contracts.d.ts +29 -4
  44. package/dist/domain-event-contracts.js +11 -7
  45. package/dist/domain-event-contracts.js.map +1 -1
  46. package/dist/domain-exception.cjs +2 -1
  47. package/dist/domain-exception.cjs.map +1 -1
  48. package/dist/domain-exception.js +2 -1
  49. package/dist/domain-exception.js.map +1 -1
  50. package/dist/errors/index.cjs +1 -1
  51. package/dist/errors/index.d.cts +1 -1
  52. package/dist/errors/index.d.ts +1 -1
  53. package/dist/errors/index.js +2 -2
  54. package/dist/exceptions/index.cjs +2 -2
  55. package/dist/exceptions/index.d.cts +1 -2
  56. package/dist/exceptions/index.d.ts +1 -2
  57. package/dist/exceptions/index.js +2 -2
  58. package/dist/gate-engine-registry.cjs.map +1 -1
  59. package/dist/gate-engine-registry.d.cts +1 -1
  60. package/dist/gate-engine-registry.d.ts +1 -1
  61. package/dist/gate-engine-registry.js.map +1 -1
  62. package/dist/gate-v1-payload.schema.cjs +11 -6
  63. package/dist/gate-v1-payload.schema.cjs.map +1 -1
  64. package/dist/gate-v1-payload.schema.js +11 -6
  65. package/dist/gate-v1-payload.schema.js.map +1 -1
  66. package/dist/hashing.cjs +1 -1
  67. package/dist/hashing.cjs.map +1 -1
  68. package/dist/hashing.js +2 -2
  69. package/dist/hashing.js.map +1 -1
  70. package/dist/immutable.cjs +25 -12
  71. package/dist/immutable.cjs.map +1 -1
  72. package/dist/immutable.js +24 -11
  73. package/dist/immutable.js.map +1 -1
  74. package/dist/index.cjs +13 -10
  75. package/dist/index.cjs.map +1 -1
  76. package/dist/index.d.cts +9 -10
  77. package/dist/index.d.ts +9 -10
  78. package/dist/index.js +7 -9
  79. package/dist/index.js.map +1 -1
  80. package/dist/invalid-state-transition-exception.cjs +6 -6
  81. package/dist/invalid-state-transition-exception.cjs.map +1 -1
  82. package/dist/invalid-state-transition-exception.js +6 -6
  83. package/dist/invalid-state-transition-exception.js.map +1 -1
  84. package/dist/invariant-violation-exception.cjs +2 -2
  85. package/dist/invariant-violation-exception.cjs.map +1 -1
  86. package/dist/invariant-violation-exception.js +2 -2
  87. package/dist/invariant-violation-exception.js.map +1 -1
  88. package/dist/not-found-error.cjs +6 -4
  89. package/dist/not-found-error.cjs.map +1 -1
  90. package/dist/not-found-error.js +6 -4
  91. package/dist/not-found-error.js.map +1 -1
  92. package/dist/outcome.cjs +5 -5
  93. package/dist/outcome.cjs.map +1 -1
  94. package/dist/outcome.js +5 -5
  95. package/dist/outcome.js.map +1 -1
  96. package/dist/parse-gate-payload.d.cts +1 -1
  97. package/dist/parse-gate-payload.d.ts +1 -1
  98. package/dist/path.d.cts +2 -2
  99. package/dist/path.d.ts +2 -2
  100. package/dist/plugin.cjs +23 -13
  101. package/dist/plugin.cjs.map +1 -1
  102. package/dist/plugin.d.cts +22 -8
  103. package/dist/plugin.d.ts +22 -8
  104. package/dist/plugin.js +23 -13
  105. package/dist/plugin.js.map +1 -1
  106. package/dist/policies/engines/index.d.cts +1 -1
  107. package/dist/policies/engines/index.d.ts +1 -1
  108. package/dist/policies/engines/v1/gate/index.d.cts +3 -15
  109. package/dist/policies/engines/v1/gate/index.d.ts +3 -15
  110. package/dist/policies/index.d.cts +1 -1
  111. package/dist/policies/index.d.ts +1 -1
  112. package/dist/policy-bridge.cjs +30 -2
  113. package/dist/policy-bridge.cjs.map +1 -1
  114. package/dist/policy-bridge.d.cts +18 -0
  115. package/dist/policy-bridge.d.ts +18 -0
  116. package/dist/policy-bridge.js +30 -2
  117. package/dist/policy-bridge.js.map +1 -1
  118. package/dist/policy-service.cjs +40 -46
  119. package/dist/policy-service.cjs.map +1 -1
  120. package/dist/policy-service.d.cts +72 -9
  121. package/dist/policy-service.d.ts +72 -9
  122. package/dist/policy-service.js +42 -48
  123. package/dist/policy-service.js.map +1 -1
  124. package/dist/requested-by.cjs +1 -1
  125. package/dist/requested-by.cjs.map +1 -1
  126. package/dist/requested-by.js +1 -1
  127. package/dist/requested-by.js.map +1 -1
  128. package/dist/result.cjs +29 -1
  129. package/dist/result.cjs.map +1 -1
  130. package/dist/result.d.cts +12 -0
  131. package/dist/result.d.ts +12 -0
  132. package/dist/result.js +29 -1
  133. package/dist/result.js.map +1 -1
  134. package/dist/rule.cjs +94 -24
  135. package/dist/rule.cjs.map +1 -1
  136. package/dist/rule.js +94 -24
  137. package/dist/rule.js.map +1 -1
  138. package/dist/ruleset-registry.cjs +19 -0
  139. package/dist/ruleset-registry.cjs.map +1 -1
  140. package/dist/ruleset-registry.js +19 -0
  141. package/dist/ruleset-registry.js.map +1 -1
  142. package/dist/stable-stringify.cjs +43 -3
  143. package/dist/stable-stringify.cjs.map +1 -1
  144. package/dist/stable-stringify.js +38 -4
  145. package/dist/stable-stringify.js.map +1 -1
  146. package/dist/temporal-snapshot.d.cts +87 -0
  147. package/dist/temporal-snapshot.d.ts +87 -0
  148. package/dist/temporal-use-case.cjs +169 -16
  149. package/dist/temporal-use-case.cjs.map +1 -1
  150. package/dist/temporal-use-case.d.cts +76 -43
  151. package/dist/temporal-use-case.d.ts +76 -43
  152. package/dist/temporal-use-case.js +162 -15
  153. package/dist/temporal-use-case.js.map +1 -1
  154. package/dist/unexpected-error.cjs +4 -2
  155. package/dist/unexpected-error.cjs.map +1 -1
  156. package/dist/unexpected-error.js +4 -2
  157. package/dist/unexpected-error.js.map +1 -1
  158. package/dist/uuid-identifier.cjs +140 -2
  159. package/dist/uuid-identifier.cjs.map +1 -1
  160. package/dist/uuid-identifier.d.cts +26 -7
  161. package/dist/uuid-identifier.d.ts +26 -7
  162. package/dist/uuid-identifier.js +135 -3
  163. package/dist/uuid-identifier.js.map +1 -1
  164. package/dist/uuid.cjs +11 -6
  165. package/dist/uuid.cjs.map +1 -1
  166. package/dist/uuid.js +11 -6
  167. package/dist/uuid.js.map +1 -1
  168. package/dist/validation-code.cjs +9 -0
  169. package/dist/validation-code.cjs.map +1 -1
  170. package/dist/validation-code.d.cts +3 -0
  171. package/dist/validation-code.d.ts +3 -0
  172. package/dist/validation-code.js +9 -0
  173. package/dist/validation-code.js.map +1 -1
  174. package/dist/validation-error.cjs +42 -67
  175. package/dist/validation-error.cjs.map +1 -1
  176. package/dist/validation-error.d.cts +24 -8
  177. package/dist/validation-error.d.ts +24 -8
  178. package/dist/validation-error.js +41 -66
  179. package/dist/validation-error.js.map +1 -1
  180. package/dist/validation-exception.cjs +17 -6
  181. package/dist/validation-exception.cjs.map +1 -1
  182. package/dist/validation-exception.d.cts +33 -9
  183. package/dist/validation-exception.d.ts +33 -9
  184. package/dist/validation-exception.js +17 -6
  185. package/dist/validation-exception.js.map +1 -1
  186. package/dist/validation-field.cjs +3 -0
  187. package/dist/validation-field.cjs.map +1 -1
  188. package/dist/validation-field.d.cts +1 -0
  189. package/dist/validation-field.d.ts +1 -0
  190. package/dist/validation-field.js +3 -0
  191. package/dist/validation-field.js.map +1 -1
  192. package/dist/value-object-ruleset.contracts.d.cts +10 -0
  193. package/dist/value-object-ruleset.contracts.d.ts +10 -0
  194. package/dist/value-object.cjs +12 -2
  195. package/dist/value-object.cjs.map +1 -1
  196. package/dist/value-object.d.cts +16 -0
  197. package/dist/value-object.d.ts +16 -0
  198. package/dist/value-object.js +13 -3
  199. package/dist/value-object.js.map +1 -1
  200. package/dist/version.d.cts +27 -0
  201. package/dist/version.d.ts +27 -0
  202. package/dist/versioning/index.d.cts +2 -2
  203. package/dist/versioning/index.d.ts +2 -2
  204. package/meta.json +3 -2
  205. package/package.json +1 -1
  206. package/src/core/abac/authorizer.ts +60 -10
  207. package/src/core/abac/domain/policy-set.ts +52 -5
  208. package/src/core/abac/domain/rule.ts +28 -16
  209. package/src/core/abac/index.ts +7 -1
  210. package/src/core/application/commands/command.ts +14 -1
  211. package/src/core/application/commands/requested-by.ts +12 -3
  212. package/src/core/application/index.ts +2 -1
  213. package/src/core/application/policy-error-mapper.ts +6 -0
  214. package/src/core/application/ports/index.ts +7 -0
  215. package/src/core/application/ports/temporal-repository.port.ts +35 -2
  216. package/src/core/application/queries/index.ts +1 -1
  217. package/src/core/application/queries/query.ts +19 -2
  218. package/src/core/application/temporal/temporal-use-case.ts +31 -4
  219. package/src/core/application/use-case.ts +44 -7
  220. package/src/core/config/core-config.ts +46 -25
  221. package/src/core/config/index.ts +1 -0
  222. package/src/core/config/policy-reporter.ts +32 -1
  223. package/src/core/domain/entity.ts +50 -7
  224. package/src/core/domain/rulesets/entity-ruleset.contracts.ts +0 -2
  225. package/src/core/domain/rulesets/ruleset-registry.ts +24 -0
  226. package/src/core/domain/rulesets/value-object-ruleset.contracts.ts +1 -7
  227. package/src/core/domain/temporal/half-open-interval.ts +34 -0
  228. package/src/core/domain/temporal/temporal-snapshot.ts +13 -2
  229. package/src/core/domain/temporal/transaction-time.ts +19 -15
  230. package/src/core/domain/temporal/valid-time.ts +20 -15
  231. package/src/core/domain/uuid-identifier.ts +5 -3
  232. package/src/core/domain/value-object.ts +17 -0
  233. package/src/core/errors/authentication-error.ts +5 -31
  234. package/src/core/errors/authorization-error.ts +12 -20
  235. package/src/core/errors/business-rule-violation-error.ts +4 -1
  236. package/src/core/errors/idempotency-error.ts +5 -2
  237. package/src/core/errors/index.ts +4 -0
  238. package/src/core/errors/integration-error.ts +4 -24
  239. package/src/core/errors/legacy-incompatible-error.ts +1 -0
  240. package/src/core/errors/not-found-error.ts +4 -1
  241. package/src/core/errors/temporal-error.ts +22 -20
  242. package/src/core/errors/unexpected-error.ts +5 -1
  243. package/src/core/errors/utils/factory-helpers.ts +70 -0
  244. package/src/core/errors/utils/index.ts +5 -0
  245. package/src/core/errors/utils/json-safe.ts +15 -1
  246. package/src/core/errors/validation-error.ts +4 -1
  247. package/src/core/exceptions/business-rule-violation-exception.ts +2 -1
  248. package/src/core/exceptions/domain-exception.ts +9 -1
  249. package/src/core/exceptions/entity-not-found-exception.ts +5 -1
  250. package/src/core/exceptions/invalid-state-transition-exception.ts +5 -2
  251. package/src/core/exceptions/invariant-violation-exception.ts +2 -2
  252. package/src/core/exceptions/validation-code.ts +14 -0
  253. package/src/core/exceptions/validation-exception.ts +44 -5
  254. package/src/core/exceptions/validation-field.ts +11 -1
  255. package/src/core/plugins/plugin.ts +25 -15
  256. package/src/core/plugins/types.ts +4 -2
  257. package/src/core/policies/asof/asof.ts +12 -0
  258. package/src/core/policies/catalog/policy-catalog-entry.ts +3 -1
  259. package/src/core/policies/catalog/policy-catalog.ts +5 -1
  260. package/src/core/policies/context/context-builder.ts +20 -0
  261. package/src/core/policies/context/context-resolver.ts +5 -0
  262. package/src/core/policies/context/context-seed.ts +11 -0
  263. package/src/core/policies/defs/in-memory-policy-definition-repo.ts +0 -2
  264. package/src/core/policies/engines/parse-gate-payload.ts +9 -0
  265. package/src/core/policies/engines/v1/condition-date-operands.ts +112 -0
  266. package/src/core/policies/engines/v1/condition-evaluator.ts +99 -325
  267. package/src/core/policies/engines/v1/condition-schema.ts +23 -19
  268. package/src/core/policies/engines/v1/condition-types.ts +18 -11
  269. package/src/core/policies/index.ts +4 -6
  270. package/src/core/policies/service/policy-service.ts +46 -35
  271. package/src/core/policies/utils/hash.ts +5 -69
  272. package/src/core/policies/utils/result.ts +1 -1
  273. package/src/core/rbac/access-request.ts +12 -2
  274. package/src/core/rbac/authorizer.ts +8 -1
  275. package/src/core/rbac/domain/role.ts +20 -0
  276. package/src/core/rbac/domain/scope.ts +6 -1
  277. package/src/core/result/index.ts +5 -0
  278. package/src/core/result/outcome.ts +5 -7
  279. package/src/core/result/result.ts +34 -1
  280. package/src/core/shared/hashing.ts +6 -3
  281. package/src/core/shared/immutable.ts +22 -4
  282. package/src/core/shared/stable-stringify.ts +91 -4
  283. package/src/core/shared/uuid.ts +11 -6
  284. package/src/core/versioning/domain-event-contracts.ts +43 -15
  285. package/src/core/versioning/index.ts +1 -0
  286. package/src/core/versioning/version.ts +30 -1
  287. package/src/domain/index.ts +5 -0
  288. package/src/examples/rulesets/entity/order-creation-rules-v1.ts +1 -1
  289. package/src/examples/rulesets/entity/order-invariants-v1.ts +2 -4
  290. package/src/examples/rulesets/entity/order-invariants-v2.ts +2 -4
  291. package/src/examples/rulesets/value-object/cpf-rules-v1.ts +2 -4
  292. package/src/examples/rulesets/value-object/cpf-rules-v2.ts +2 -4
  293. package/src/examples/rulesets/value-object/person-name-rules-v1.ts +2 -4
  294. package/src/examples/rulesets/value-object/person-name-rules-v2.ts +2 -4
  295. package/src/result/index.ts +7 -2
  296. package/src/version.ts +1 -1
  297. package/dist/domain-exception.d.cts +0 -7
  298. package/dist/domain-exception.d.ts +0 -7
  299. package/dist/entity.cjs +0 -122
  300. package/dist/entity.cjs.map +0 -1
  301. package/dist/entity.js +0 -111
  302. package/dist/entity.js.map +0 -1
  303. package/dist/use-case.cjs +0 -92
  304. package/dist/use-case.cjs.map +0 -1
  305. package/dist/use-case.js +0 -87
  306. package/dist/use-case.js.map +0 -1
package/KIT_CONTEXT.md CHANGED
@@ -20,7 +20,7 @@ Núcleo arquitetural para sistemas ERP (e domínios transacionais com temporalid
20
20
 
21
21
  - **Domínio lança, aplicação retorna `Result`, infra traduz.** Não há `Result` no domínio.
22
22
  - **Sem lib de log/observabilidade no runtime.** Portas vivem em `application/ports/`; adapters são opt-in.
23
- - **Temporalidade interna ao kit** — suporte temporal no código-base, mas a API pública não publica `Timeline<T>` nem helpers temporais no barrel raiz.
23
+ - **Temporalidade fora do barrel raiz** — o barrel raiz não publica `Timeline<T>` nem helpers temporais; as primitivas bitemporais (`createValidTime`, `createTemporalSnapshot`, ranges) são publicadas apenas no subpath `./domain`, porque a porta pública `TemporalRepository` expõe `TemporalSnapshot` e quem a implementa precisa das factories validantes.
24
24
  - **Policies como dados**, não como if-statements: avaliáveis, compostas, serializáveis.
25
25
  - **Policies permitem disable sem remover código**: `PolicyDefinition` aceita `enabled: false` e o repositório ignora definições desabilitadas.
26
26
  - **Composição isolada é de primeira classe**: use `new CoreConfig()`, `new ContextResolverRegistry()` e `registerNamespacedContextResolversIn(...)` quando precisar evitar singletons compartilhados.
@@ -37,7 +37,7 @@ Implemente as portas em `application/ports/` para conectar a stack real:
37
37
  ## [known-limits] Limitações conhecidas
38
38
 
39
39
  - **Dois registries são estado global de processo** (a promessa "composição sem singletons" não os cobre): `GatePayloadParsers` (parsers de payload gate) e `ValueObject.plugins` (plugin de igualdade) valem para o processo inteiro — hosts multi-tenant no mesmo processo compartilham esses registros mesmo usando `CoreConfig`/registries isolados.
40
- - **ABAC é fail-closed por regra não-avaliável**: toda condição do set é avaliada, independente do algoritmo de combinação adicionar uma regra que referencia um atributo que um call site não fornece passa a negar (403 `forbidden`) nesses call sites até o atributo ser suprido.
40
+ - **ABAC é fail-closed por regra não-avaliável** (atributo ausente = erro que nega o set inteiro com `forbidden`, atribuído à regra culpada). Válvula de escape: `AbacPolicySet.of(rules, { onEvaluationError: "skip-rule" })` descarta a regra não-avaliável. `isNull`/`isNotNull` testam `null` explícito, não chave ausente. Decisões (PERMIT/DENY) saem como evento `abac-decision` no reporter (silencioso por padrão). Detalhe completo no JSDoc de `AbacRule`.
41
41
  - **`Date` aninhado em `ValueObject` não é congelável** (`Object.freeze` não bloqueia `setTime`): o clone protege do caller, mas quem lê `value` consegue mutar o `Date` interno. Prefira ISO string/timestamp no estado do VO.
42
42
 
43
43
  ## [non-goals] Não-objetivos
@@ -1,2 +1,2 @@
1
- import { a as AbacPolicySet, c as AbacRuleProps, d as AbacAuthorizerPort, f as AbacAttributes, i as AbacDecision, l as RuleEffect, n as CompositeAuthorizer, o as CombiningAlgorithm, p as AbacRequest, r as AbacAuthorizer, s as AbacRule, t as CompositeAccessRequest, u as abacContext } from "../composite-authorizer.cjs";
2
- export { AbacAttributes, AbacAuthorizer, AbacAuthorizerPort, AbacDecision, AbacPolicySet, AbacRequest, AbacRule, AbacRuleProps, CombiningAlgorithm, CompositeAccessRequest, CompositeAuthorizer, RuleEffect, abacContext };
1
+ import { a as AbacPolicySet, c as AbacRule, d as abacContext, f as AbacAuthorizerPort, i as AbacDecision, l as AbacRuleProps, m as AbacRequest, n as CompositeAuthorizer, o as OnEvaluationError, p as AbacAttributes, r as AbacAuthorizer, s as CombiningAlgorithm, t as CompositeAccessRequest, u as RuleEffect } from "../composite-authorizer.cjs";
2
+ export { AbacAttributes, AbacAuthorizer, AbacAuthorizerPort, AbacDecision, AbacPolicySet, AbacRequest, AbacRule, AbacRuleProps, CombiningAlgorithm, CompositeAccessRequest, CompositeAuthorizer, OnEvaluationError, RuleEffect, abacContext };
@@ -1,2 +1,2 @@
1
- import { a as AbacPolicySet, c as AbacRuleProps, d as AbacAuthorizerPort, f as AbacAttributes, i as AbacDecision, l as RuleEffect, n as CompositeAuthorizer, o as CombiningAlgorithm, p as AbacRequest, r as AbacAuthorizer, s as AbacRule, t as CompositeAccessRequest, u as abacContext } from "../composite-authorizer.js";
2
- export { AbacAttributes, AbacAuthorizer, AbacAuthorizerPort, AbacDecision, AbacPolicySet, AbacRequest, AbacRule, AbacRuleProps, CombiningAlgorithm, CompositeAccessRequest, CompositeAuthorizer, RuleEffect, abacContext };
1
+ import { a as AbacPolicySet, c as AbacRule, d as abacContext, f as AbacAuthorizerPort, i as AbacDecision, l as AbacRuleProps, m as AbacRequest, n as CompositeAuthorizer, o as OnEvaluationError, p as AbacAttributes, r as AbacAuthorizer, s as CombiningAlgorithm, t as CompositeAccessRequest, u as RuleEffect } from "../composite-authorizer.js";
2
+ export { AbacAttributes, AbacAuthorizer, AbacAuthorizerPort, AbacDecision, AbacPolicySet, AbacRequest, AbacRule, AbacRuleProps, CombiningAlgorithm, CompositeAccessRequest, CompositeAuthorizer, OnEvaluationError, RuleEffect, abacContext };
@@ -0,0 +1,14 @@
1
+ const require_invariant_violation_exception = require("./invariant-violation-exception.cjs");
2
+ //#region src/core/shared/aggregate-version.ts
3
+ function assertValidAggregateVersion(aggregateVersion) {
4
+ if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) throw new require_invariant_violation_exception.InvariantViolationException(`aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`);
5
+ }
6
+ //#endregion
7
+ Object.defineProperty(exports, "assertValidAggregateVersion", {
8
+ enumerable: true,
9
+ get: function() {
10
+ return assertValidAggregateVersion;
11
+ }
12
+ });
13
+
14
+ //# sourceMappingURL=aggregate-version.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregate-version.cjs","names":["InvariantViolationException"],"sources":["../src/core/shared/aggregate-version.ts"],"sourcesContent":["import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\nfunction assertValidAggregateVersion(aggregateVersion: number): void {\n if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) {\n throw new InvariantViolationException(\n `aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`,\n );\n }\n}\n\nexport { assertValidAggregateVersion };\n"],"mappings":";;AAEA,SAAS,4BAA4B,kBAAgC;CACjE,IAAI,CAAC,OAAO,UAAU,gBAAgB,KAAK,mBAAmB,GAC1D,MAAM,IAAIA,sCAAAA,4BACN,8DAA8D,kBAClE;AAER"}
@@ -0,0 +1,9 @@
1
+ import { t as InvariantViolationException } from "./invariant-violation-exception.js";
2
+ //#region src/core/shared/aggregate-version.ts
3
+ function assertValidAggregateVersion(aggregateVersion) {
4
+ if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) throw new InvariantViolationException(`aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`);
5
+ }
6
+ //#endregion
7
+ export { assertValidAggregateVersion as t };
8
+
9
+ //# sourceMappingURL=aggregate-version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregate-version.js","names":[],"sources":["../src/core/shared/aggregate-version.ts"],"sourcesContent":["import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\nfunction assertValidAggregateVersion(aggregateVersion: number): void {\n if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) {\n throw new InvariantViolationException(\n `aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`,\n );\n }\n}\n\nexport { assertValidAggregateVersion };\n"],"mappings":";;AAEA,SAAS,4BAA4B,kBAAgC;CACjE,IAAI,CAAC,OAAO,UAAU,gBAAgB,KAAK,mBAAmB,GAC1D,MAAM,IAAI,4BACN,8DAA8D,kBAClE;AAER"}
@@ -76,7 +76,14 @@ function sanitizeValue(value, seen) {
76
76
  const result = {};
77
77
  for (const [key, val] of Object.entries(value)) {
78
78
  if (val === void 0) continue;
79
- result[key] = sanitizeValue(val, seen);
79
+ const sanitized = sanitizeValue(val, seen);
80
+ if (key === "__proto__") Object.defineProperty(result, key, {
81
+ value: sanitized,
82
+ enumerable: true,
83
+ writable: true,
84
+ configurable: true
85
+ });
86
+ else result[key] = sanitized;
80
87
  }
81
88
  seen.delete(value);
82
89
  return result;
@@ -1 +1 @@
1
- {"version":3,"file":"app-error.cjs","names":[],"sources":["../src/core/errors/error-codes.ts","../src/core/errors/utils/json-safe.ts","../src/core/errors/app-error.ts"],"sourcesContent":["const ErrorCodes = {\n authentication: {\n missingToken: \"sec.authn.missing_token\",\n invalidToken: \"sec.authn.invalid_token\",\n expiredToken: \"sec.authn.expired_token\",\n invalidCredentials: \"sec.authn.invalid_credentials\",\n },\n authorization: {\n forbidden: \"sec.authz.forbidden\",\n policyDenied: \"sec.authz.policy_denied\",\n missingRole: \"sec.authz.missing_role\",\n missingCapability: \"sec.authz.missing_capability\",\n outOfScope: \"sec.authz.out_of_scope\",\n },\n businessRuleViolation: \"business_rule_violation\",\n conflict: {\n alreadyExists: \"conf.already_exists\",\n duplicate: \"conf.duplicate\",\n uniqueViolation: \"conf.unique_violation\",\n },\n idempotency: {\n keyMissing: \"idemp.key_missing\",\n inProgress: \"idemp.in_progress\",\n payloadMismatch: \"idemp.payload_mismatch\",\n replayNotSupported: \"idemp.replay_not_supported\",\n },\n integration: {\n timeout: \"int.timeout\",\n unreachable: \"int.unreachable\",\n badResponse: \"int.bad_response\",\n },\n legacyIncompatible: \"legacy_incompatible\",\n notFound: \"not_found\",\n serialization: {\n deserializePrefix: \"ser.des\",\n serializePrefix: \"ser.ser\",\n },\n temporal: {\n expired: \"tmp.expired\",\n notYetValid: \"tmp.not_yet_valid\",\n },\n unexpected: \"unexpected\",\n validation: \"validation_error\",\n} as const;\n\ntype SerializationCodeDirection = \"deserialize\" | \"serialize\";\n\nfunction serializationErrorCode(\n direction: SerializationCodeDirection,\n category: string,\n): string {\n const prefix =\n direction === \"deserialize\"\n ? ErrorCodes.serialization.deserializePrefix\n : ErrorCodes.serialization.serializePrefix;\n\n return `${prefix}.${category}`;\n}\n\nexport { ErrorCodes, serializationErrorCode };\nexport type { SerializationCodeDirection };\n","// Utilities for ensuring metadata is JSON-serializable.\n\nimport type { JsonSafeRecord, JsonSafeValue } from \"../types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Constants\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst NON_SERIALIZABLE_PLACEHOLDER = \"[NonSerializable]\";\nconst CIRCULAR_REFERENCE_PLACEHOLDER = \"[Circular]\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// `seen` tracks the ancestors on the current traversal branch (a DFS path), not\n// every object visited. This collapses true circular references to a placeholder\n// while still serializing the same object referenced more than once across\n// sibling branches (a DAG) — matching `JSON.stringify`, which only rejects\n// cycles, not shared references.\nfunction sanitizeValue(value: unknown, seen: WeakSet<object>): JsonSafeValue {\n // Null passthrough\n if (value === null) return null;\n\n const type = typeof value;\n\n // Primitives (non-finite numbers are not JSON-representable — placeholder)\n if (type === \"number\") {\n return Number.isFinite(value)\n ? (value as number)\n : NON_SERIALIZABLE_PLACEHOLDER;\n }\n if (type === \"string\" || type === \"boolean\") {\n return value as JsonSafeValue;\n }\n\n // `undefined` only reaches here as an array item: object properties with\n // undefined values are omitted by the plain-object branch below. Both\n // mirror `JSON.stringify` semantics.\n if (value === undefined) return null;\n\n // Non-serializable primitives\n if (type === \"bigint\" || type === \"function\" || type === \"symbol\") {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Arrays (recursive)\n if (Array.isArray(value)) {\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const sanitized = value.map((item) => sanitizeValue(item, seen));\n seen.delete(value);\n return sanitized;\n }\n\n // Date → placeholder (could also use .toISOString() if preferred)\n if (value instanceof Date) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Class instances and non-plain objects → placeholder\n if (!isPlainObject(value)) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Plain object (recursive)\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const result: Record<string, JsonSafeValue> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === undefined) continue;\n result[key] = sanitizeValue(val, seen);\n }\n seen.delete(value);\n return result;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public API\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Ensures metadata is JSON-serializable.\n *\n * **Allowed:** finite number, string, boolean, null, arrays, and plain objects.\n *\n * **Dropped (mirroring `JSON.stringify`):** object properties whose value is\n * `undefined` (the key is omitted); an `undefined` array item becomes `null`.\n *\n * **Converted to placeholder:** Date, BigInt, class instances, functions,\n * symbols, non-finite numbers (`NaN`/`Infinity`), and circular references\n * (which would otherwise make `JSON.stringify` throw).\n *\n * @throws {TypeError} If `input` is not a plain object at the root level.\n */\nfunction assertJsonSafeMetadata(input: unknown): JsonSafeRecord {\n if (input === undefined) {\n return {};\n }\n\n if (!isPlainObject(input)) {\n throw new TypeError(\n \"metadata must be a plain object (Record<string, unknown>).\",\n );\n }\n\n return sanitizeValue(input, new WeakSet<object>()) as JsonSafeRecord;\n}\n\nexport {\n assertJsonSafeMetadata,\n CIRCULAR_REFERENCE_PLACEHOLDER,\n NON_SERIALIZABLE_PLACEHOLDER,\n};\n","// Base application error for the domain/application layer.\n// Encapsulates a code, optional cause, and JSON-safe metadata.\n\nimport type {\n AppErrorOptions,\n ErrorSeverity,\n JsonSafeRecord,\n} from \"./types.js\";\nimport { assertJsonSafeMetadata } from \"./utils/index.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AppError (abstract base class)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Root of the application/domain error hierarchy. Every error the system raises\n * on purpose extends `AppError`, which gives callers a single `instanceof` to\n * catch and a uniform, serializable shape to log and transport.\n *\n * Beyond the native `Error` message it carries a stable `code` (the contract the\n * outside world matches on), an optional non-leaking `publicMessage`, a\n * severity, JSON-safe `metadata`, and the correlation/request/command ids that\n * stitch an error back to the request that produced it. The metadata is\n * validated as JSON-safe on construction, so a logger can serialize any\n * `AppError` without hitting a circular reference or a non-serializable value.\n *\n * Abstract on purpose: callers should throw a specific subclass (e.g.\n * {@link ValidationError}, {@link NotFoundError}) so the `code` and shape are\n * meaningful, never a bare `AppError`.\n */\nabstract class AppError extends Error {\n public readonly code: string;\n public readonly cause?: unknown;\n public readonly metadata?: JsonSafeRecord;\n public readonly type?: string;\n public readonly severity?: ErrorSeverity;\n public readonly createdAtIso: string;\n public readonly publicMessage?: string;\n /**\n * Identifies a single execution \"story\" in the system. All operations\n * related to the same logical flow must share the same correlationId.\n */\n public readonly correlationId?: string;\n /**\n * Identifies a specific technical request attempt (each retry may produce\n * a new requestId), even when the correlationId stays the same.\n */\n public readonly requestId?: string;\n /**\n * Marks the business intent / idempotency key; stays the same across\n * technical retries and multiple requests that represent the same intent.\n */\n public readonly commandId?: string;\n\n /**\n * Builds the common error envelope shared by every subclass.\n *\n * `name` is taken from `new.target` so the thrown instance reports its\n * concrete subclass name (not `\"AppError\"`), and the prototype is re-pinned\n * via `setPrototypeOf` so `instanceof` keeps working after transpilation to\n * older targets where extending built-ins breaks the chain. `createdAtIso`\n * defaults to now, and `metadata` is validated as JSON-safe so the error is\n * always serializable.\n *\n * Declared `protected`: instantiate a concrete subclass, never `AppError`.\n *\n * @param message - The internal, developer-facing message.\n * @param code - The stable machine-readable code callers match on.\n * @param options - Optional cause, metadata, severity, and correlation ids.\n * @throws When `options.metadata` contains a value that is not JSON-safe.\n */\n protected constructor(\n message: string,\n code: string,\n options?: AppErrorOptions,\n ) {\n super(message);\n\n this.name = new.target.name;\n this.code = code;\n this.cause = options?.cause;\n this.type = options?.type;\n this.severity = options?.severity;\n this.correlationId = options?.correlationId;\n this.requestId = options?.requestId;\n this.commandId = options?.commandId;\n this.createdAtIso = options?.createdAtIso ?? new Date().toISOString();\n this.publicMessage = options?.publicMessage;\n\n this.metadata = options?.metadata\n ? assertJsonSafeMetadata(options.metadata)\n : undefined;\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Returns a JSON-safe representation of the error.\n * Does NOT include `cause` by default (to avoid leaking internal details).\n */\n public toJSON(): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n name: this.name,\n code: this.code,\n message: this.message,\n createdAtIso: this.createdAtIso,\n };\n\n // Optional fields are emitted only when defined, so the serialized\n // shape never carries `undefined`-valued keys (consistent with how the\n // correlation/request/command ids are handled).\n if (this.type !== undefined) payload.type = this.type;\n if (this.severity !== undefined) payload.severity = this.severity;\n if (this.publicMessage !== undefined)\n payload.publicMessage = this.publicMessage;\n if (this.metadata !== undefined) payload.metadata = this.metadata;\n if (this.correlationId !== undefined)\n payload.correlationId = this.correlationId;\n if (this.requestId !== undefined) payload.requestId = this.requestId;\n if (this.commandId !== undefined) payload.commandId = this.commandId;\n\n return payload;\n }\n}\n\nexport { AppError };\n"],"mappings":";AAAA,MAAM,aAAa;CACf,gBAAgB;EACZ,cAAc;EACd,cAAc;EACd,cAAc;EACd,oBAAoB;CACxB;CACA,eAAe;EACX,WAAW;EACX,cAAc;EACd,aAAa;EACb,mBAAmB;EACnB,YAAY;CAChB;CACA,uBAAuB;CACvB,UAAU;EACN,eAAe;EACf,WAAW;EACX,iBAAiB;C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I,KAAK,kBAAkB,KAAA,GACvB,QAAQ,gBAAgB,KAAK;EACjC,IAAI,KAAK,cAAc,KAAA,GAAW,QAAQ,YAAY,KAAK;EAC3D,IAAI,KAAK,cAAc,KAAA,GAAW,QAAQ,YAAY,KAAK;EAE3D,OAAO;CACX;AACJ"}
1
+ {"version":3,"file":"app-error.cjs","names":[],"sources":["../src/core/errors/error-codes.ts","../src/core/errors/utils/json-safe.ts","../src/core/errors/app-error.ts"],"sourcesContent":["const ErrorCodes = {\n authentication: {\n missingToken: \"sec.authn.missing_token\",\n invalidToken: \"sec.authn.invalid_token\",\n expiredToken: \"sec.authn.expired_token\",\n invalidCredentials: \"sec.authn.invalid_credentials\",\n },\n authorization: {\n forbidden: \"sec.authz.forbidden\",\n policyDenied: \"sec.authz.policy_denied\",\n missingRole: \"sec.authz.missing_role\",\n missingCapability: \"sec.authz.missing_capability\",\n outOfScope: \"sec.authz.out_of_scope\",\n },\n businessRuleViolation: \"business_rule_violation\",\n conflict: {\n alreadyExists: \"conf.already_exists\",\n duplicate: \"conf.duplicate\",\n uniqueViolation: \"conf.unique_violation\",\n },\n idempotency: {\n keyMissing: \"idemp.key_missing\",\n inProgress: \"idemp.in_progress\",\n payloadMismatch: \"idemp.payload_mismatch\",\n replayNotSupported: \"idemp.replay_not_supported\",\n },\n integration: {\n timeout: \"int.timeout\",\n unreachable: \"int.unreachable\",\n badResponse: \"int.bad_response\",\n },\n legacyIncompatible: \"legacy_incompatible\",\n notFound: \"not_found\",\n serialization: {\n deserializePrefix: \"ser.des\",\n serializePrefix: \"ser.ser\",\n },\n temporal: {\n expired: \"tmp.expired\",\n notYetValid: \"tmp.not_yet_valid\",\n },\n unexpected: \"unexpected\",\n validation: \"validation_error\",\n} as const;\n\ntype SerializationCodeDirection = \"deserialize\" | \"serialize\";\n\nfunction serializationErrorCode(\n direction: SerializationCodeDirection,\n category: string,\n): string {\n const prefix =\n direction === \"deserialize\"\n ? ErrorCodes.serialization.deserializePrefix\n : ErrorCodes.serialization.serializePrefix;\n\n return `${prefix}.${category}`;\n}\n\nexport { ErrorCodes, serializationErrorCode };\nexport type { SerializationCodeDirection };\n","// Utilities for ensuring metadata is JSON-serializable.\n\nimport type { JsonSafeRecord, JsonSafeValue } from \"../types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Constants\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst NON_SERIALIZABLE_PLACEHOLDER = \"[NonSerializable]\";\nconst CIRCULAR_REFERENCE_PLACEHOLDER = \"[Circular]\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// `seen` tracks the ancestors on the current traversal branch (a DFS path), not\n// every object visited. This collapses true circular references to a placeholder\n// while still serializing the same object referenced more than once across\n// sibling branches (a DAG) — matching `JSON.stringify`, which only rejects\n// cycles, not shared references.\nfunction sanitizeValue(value: unknown, seen: WeakSet<object>): JsonSafeValue {\n // Null passthrough\n if (value === null) return null;\n\n const type = typeof value;\n\n // Primitives (non-finite numbers are not JSON-representable — placeholder)\n if (type === \"number\") {\n return Number.isFinite(value)\n ? (value as number)\n : NON_SERIALIZABLE_PLACEHOLDER;\n }\n if (type === \"string\" || type === \"boolean\") {\n return value as JsonSafeValue;\n }\n\n // `undefined` only reaches here as an array item: object properties with\n // undefined values are omitted by the plain-object branch below. Both\n // mirror `JSON.stringify` semantics.\n if (value === undefined) return null;\n\n // Non-serializable primitives\n if (type === \"bigint\" || type === \"function\" || type === \"symbol\") {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Arrays (recursive)\n if (Array.isArray(value)) {\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const sanitized = value.map((item) => sanitizeValue(item, seen));\n seen.delete(value);\n return sanitized;\n }\n\n // Date → placeholder (could also use .toISOString() if preferred)\n if (value instanceof Date) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Class instances and non-plain objects → placeholder\n if (!isPlainObject(value)) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Plain object (recursive)\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const result: Record<string, JsonSafeValue> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === undefined) continue;\n const sanitized = sanitizeValue(val, seen);\n if (key === \"__proto__\") {\n // Plain `result.__proto__ = x` would reparent `result` instead of\n // creating an own data property, silently dropping the key. Define\n // it explicitly so `__proto__` survives as data — matching how\n // JSON.stringify/JSON.parse round-trip it.\n Object.defineProperty(result, key, {\n value: sanitized,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n } else {\n result[key] = sanitized;\n }\n }\n seen.delete(value);\n return result;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public API\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Ensures metadata is JSON-serializable.\n *\n * **Allowed:** finite number, string, boolean, null, arrays, and plain objects.\n *\n * **Dropped (mirroring `JSON.stringify`):** object properties whose value is\n * `undefined` (the key is omitted); an `undefined` array item becomes `null`.\n *\n * **Converted to placeholder:** Date, BigInt, class instances, functions,\n * symbols, non-finite numbers (`NaN`/`Infinity`), and circular references\n * (which would otherwise make `JSON.stringify` throw).\n *\n * @throws {TypeError} If `input` is not a plain object at the root level.\n */\nfunction assertJsonSafeMetadata(input: unknown): JsonSafeRecord {\n if (input === undefined) {\n return {};\n }\n\n if (!isPlainObject(input)) {\n throw new TypeError(\n \"metadata must be a plain object (Record<string, unknown>).\",\n );\n }\n\n return sanitizeValue(input, new WeakSet<object>()) as JsonSafeRecord;\n}\n\nexport {\n assertJsonSafeMetadata,\n CIRCULAR_REFERENCE_PLACEHOLDER,\n NON_SERIALIZABLE_PLACEHOLDER,\n};\n","// Base application error for the domain/application layer.\n// Encapsulates a code, optional cause, and JSON-safe metadata.\n\nimport type {\n AppErrorOptions,\n ErrorSeverity,\n JsonSafeRecord,\n} from \"./types.js\";\nimport { assertJsonSafeMetadata } from \"./utils/index.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AppError (abstract base class)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Root of the application/domain error hierarchy. Every error the system raises\n * on purpose extends `AppError`, which gives callers a single `instanceof` to\n * catch and a uniform, serializable shape to log and transport.\n *\n * Beyond the native `Error` message it carries a stable `code` (the contract the\n * outside world matches on), an optional non-leaking `publicMessage`, a\n * severity, JSON-safe `metadata`, and the correlation/request/command ids that\n * stitch an error back to the request that produced it. The metadata is\n * validated as JSON-safe on construction, so a logger can serialize any\n * `AppError` without hitting a circular reference or a non-serializable value.\n *\n * Abstract on purpose: callers should throw a specific subclass (e.g.\n * {@link ValidationError}, {@link NotFoundError}) so the `code` and shape are\n * meaningful, never a bare `AppError`.\n */\nabstract class AppError extends Error {\n public readonly code: string;\n public readonly cause?: unknown;\n public readonly metadata?: JsonSafeRecord;\n public readonly type?: string;\n public readonly severity?: ErrorSeverity;\n public readonly createdAtIso: string;\n public readonly publicMessage?: string;\n /**\n * Identifies a single execution \"story\" in the system. All operations\n * related to the same logical flow must share the same correlationId.\n */\n public readonly correlationId?: string;\n /**\n * Identifies a specific technical request attempt (each retry may produce\n * a new requestId), even when the correlationId stays the same.\n */\n public readonly requestId?: string;\n /**\n * Marks the business intent / idempotency key; stays the same across\n * technical retries and multiple requests that represent the same intent.\n */\n public readonly commandId?: string;\n\n /**\n * Builds the common error envelope shared by every subclass.\n *\n * `name` is taken from `new.target` so the thrown instance reports its\n * concrete subclass name (not `\"AppError\"`), and the prototype is re-pinned\n * via `setPrototypeOf` so `instanceof` keeps working after transpilation to\n * older targets where extending built-ins breaks the chain. `createdAtIso`\n * defaults to now, and `metadata` is validated as JSON-safe so the error is\n * always serializable.\n *\n * Declared `protected`: instantiate a concrete subclass, never `AppError`.\n *\n * @param message - The internal, developer-facing message.\n * @param code - The stable machine-readable code callers match on.\n * @param options - Optional cause, metadata, severity, and correlation ids.\n * @throws When `options.metadata` contains a value that is not JSON-safe.\n */\n protected constructor(\n message: string,\n code: string,\n options?: AppErrorOptions,\n ) {\n super(message);\n\n this.name = new.target.name;\n this.code = code;\n this.cause = options?.cause;\n this.type = options?.type;\n this.severity = options?.severity;\n this.correlationId = options?.correlationId;\n this.requestId = options?.requestId;\n this.commandId = options?.commandId;\n this.createdAtIso = options?.createdAtIso ?? new Date().toISOString();\n this.publicMessage = options?.publicMessage;\n\n this.metadata = options?.metadata\n ? assertJsonSafeMetadata(options.metadata)\n : undefined;\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Returns a JSON-safe representation of the error.\n * Does NOT include `cause` by default (to avoid leaking internal details).\n */\n public toJSON(): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n name: this.name,\n code: this.code,\n message: this.message,\n createdAtIso: this.createdAtIso,\n };\n\n // Optional fields are emitted only when defined, so the serialized\n // shape never carries `undefined`-valued keys (consistent with how the\n // correlation/request/command ids are handled).\n if (this.type !== undefined) payload.type = this.type;\n if (this.severity !== undefined) payload.severity = this.severity;\n if (this.publicMessage !== undefined)\n payload.publicMessage = this.publicMessage;\n if (this.metadata !== undefined) payload.metadata = this.metadata;\n if (this.correlationId !== undefined)\n payload.correlationId = this.correlationId;\n if (this.requestId !== undefined) payload.requestId = this.requestId;\n if (this.commandId !== undefined) payload.commandId = this.commandId;\n\n return payload;\n }\n}\n\nexport { AppError };\n"],"mappings":";AAAA,MAAM,aAAa;CACf,gBAAgB;EACZ,cAAc;EACd,cAAc;EACd,cAAc;EACd,oBAAoB;CACxB;CACA,eAAe;EACX,WAAW;EACX,cAAc;EACd,aAAa;EACb,mBAAmB;EACnB,YAAY;CAChB;CACA,uBAAuB;CACvB,UAAU;EACN,eAAe;EACf,WAAW;EACX,iBAAiB;CACrB;CACA,aAAa;EACT,YAAY;E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,KAAA,GACvB,QAAQ,gBAAgB,KAAK;EACjC,IAAI,KAAK,aAAa,KAAA,GAAW,QAAQ,WAAW,KAAK;EACzD,IAAI,KAAK,kBAAkB,KAAA,GACvB,QAAQ,gBAAgB,KAAK;EACjC,IAAI,KAAK,cAAc,KAAA,GAAW,QAAQ,YAAY,KAAK;EAC3D,IAAI,KAAK,cAAc,KAAA,GAAW,QAAQ,YAAY,KAAK;EAE3D,OAAO;CACX;AACJ"}
package/dist/app-error.js CHANGED
@@ -76,7 +76,14 @@ function sanitizeValue(value, seen) {
76
76
  const result = {};
77
77
  for (const [key, val] of Object.entries(value)) {
78
78
  if (val === void 0) continue;
79
- result[key] = sanitizeValue(val, seen);
79
+ const sanitized = sanitizeValue(val, seen);
80
+ if (key === "__proto__") Object.defineProperty(result, key, {
81
+ value: sanitized,
82
+ enumerable: true,
83
+ writable: true,
84
+ configurable: true
85
+ });
86
+ else result[key] = sanitized;
80
87
  }
81
88
  seen.delete(value);
82
89
  return result;
@@ -1 +1 @@
1
- {"version":3,"file":"app-error.js","names":[],"sources":["../src/core/errors/error-codes.ts","../src/core/errors/utils/json-safe.ts","../src/core/errors/app-error.ts"],"sourcesContent":["const ErrorCodes = {\n authentication: {\n missingToken: \"sec.authn.missing_token\",\n invalidToken: \"sec.authn.invalid_token\",\n expiredToken: \"sec.authn.expired_token\",\n invalidCredentials: \"sec.authn.invalid_credentials\",\n },\n authorization: {\n forbidden: \"sec.authz.forbidden\",\n policyDenied: \"sec.authz.policy_denied\",\n missingRole: \"sec.authz.missing_role\",\n missingCapability: \"sec.authz.missing_capability\",\n outOfScope: \"sec.authz.out_of_scope\",\n },\n businessRuleViolation: \"business_rule_violation\",\n conflict: {\n alreadyExists: \"conf.already_exists\",\n duplicate: \"conf.duplicate\",\n uniqueViolation: \"conf.unique_violation\",\n },\n idempotency: {\n keyMissing: \"idemp.key_missing\",\n inProgress: \"idemp.in_progress\",\n payloadMismatch: \"idemp.payload_mismatch\",\n replayNotSupported: \"idemp.replay_not_supported\",\n },\n integration: {\n timeout: \"int.timeout\",\n unreachable: \"int.unreachable\",\n badResponse: \"int.bad_response\",\n },\n legacyIncompatible: \"legacy_incompatible\",\n notFound: \"not_found\",\n serialization: {\n deserializePrefix: \"ser.des\",\n serializePrefix: \"ser.ser\",\n },\n temporal: {\n expired: \"tmp.expired\",\n notYetValid: \"tmp.not_yet_valid\",\n },\n unexpected: \"unexpected\",\n validation: \"validation_error\",\n} as const;\n\ntype SerializationCodeDirection = \"deserialize\" | \"serialize\";\n\nfunction serializationErrorCode(\n direction: SerializationCodeDirection,\n category: string,\n): string {\n const prefix =\n direction === \"deserialize\"\n ? ErrorCodes.serialization.deserializePrefix\n : ErrorCodes.serialization.serializePrefix;\n\n return `${prefix}.${category}`;\n}\n\nexport { ErrorCodes, serializationErrorCode };\nexport type { SerializationCodeDirection };\n","// Utilities for ensuring metadata is JSON-serializable.\n\nimport type { JsonSafeRecord, JsonSafeValue } from \"../types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Constants\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst NON_SERIALIZABLE_PLACEHOLDER = \"[NonSerializable]\";\nconst CIRCULAR_REFERENCE_PLACEHOLDER = \"[Circular]\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// `seen` tracks the ancestors on the current traversal branch (a DFS path), not\n// every object visited. This collapses true circular references to a placeholder\n// while still serializing the same object referenced more than once across\n// sibling branches (a DAG) — matching `JSON.stringify`, which only rejects\n// cycles, not shared references.\nfunction sanitizeValue(value: unknown, seen: WeakSet<object>): JsonSafeValue {\n // Null passthrough\n if (value === null) return null;\n\n const type = typeof value;\n\n // Primitives (non-finite numbers are not JSON-representable — placeholder)\n if (type === \"number\") {\n return Number.isFinite(value)\n ? (value as number)\n : NON_SERIALIZABLE_PLACEHOLDER;\n }\n if (type === \"string\" || type === \"boolean\") {\n return value as JsonSafeValue;\n }\n\n // `undefined` only reaches here as an array item: object properties with\n // undefined values are omitted by the plain-object branch below. Both\n // mirror `JSON.stringify` semantics.\n if (value === undefined) return null;\n\n // Non-serializable primitives\n if (type === \"bigint\" || type === \"function\" || type === \"symbol\") {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Arrays (recursive)\n if (Array.isArray(value)) {\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const sanitized = value.map((item) => sanitizeValue(item, seen));\n seen.delete(value);\n return sanitized;\n }\n\n // Date → placeholder (could also use .toISOString() if preferred)\n if (value instanceof Date) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Class instances and non-plain objects → placeholder\n if (!isPlainObject(value)) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Plain object (recursive)\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const result: Record<string, JsonSafeValue> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === undefined) continue;\n result[key] = sanitizeValue(val, seen);\n }\n seen.delete(value);\n return result;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public API\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Ensures metadata is JSON-serializable.\n *\n * **Allowed:** finite number, string, boolean, null, arrays, and plain objects.\n *\n * **Dropped (mirroring `JSON.stringify`):** object properties whose value is\n * `undefined` (the key is omitted); an `undefined` array item becomes `null`.\n *\n * **Converted to placeholder:** Date, BigInt, class instances, functions,\n * symbols, non-finite numbers (`NaN`/`Infinity`), and circular references\n * (which would otherwise make `JSON.stringify` throw).\n *\n * @throws {TypeError} If `input` is not a plain object at the root level.\n */\nfunction assertJsonSafeMetadata(input: unknown): JsonSafeRecord {\n if (input === undefined) {\n return {};\n }\n\n if (!isPlainObject(input)) {\n throw new TypeError(\n \"metadata must be a plain object (Record<string, unknown>).\",\n );\n }\n\n return sanitizeValue(input, new WeakSet<object>()) as JsonSafeRecord;\n}\n\nexport {\n assertJsonSafeMetadata,\n CIRCULAR_REFERENCE_PLACEHOLDER,\n NON_SERIALIZABLE_PLACEHOLDER,\n};\n","// Base application error for the domain/application layer.\n// Encapsulates a code, optional cause, and JSON-safe metadata.\n\nimport type {\n AppErrorOptions,\n ErrorSeverity,\n JsonSafeRecord,\n} from \"./types.js\";\nimport { assertJsonSafeMetadata } from \"./utils/index.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AppError (abstract base class)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Root of the application/domain error hierarchy. Every error the system raises\n * on purpose extends `AppError`, which gives callers a single `instanceof` to\n * catch and a uniform, serializable shape to log and transport.\n *\n * Beyond the native `Error` message it carries a stable `code` (the contract the\n * outside world matches on), an optional non-leaking `publicMessage`, a\n * severity, JSON-safe `metadata`, and the correlation/request/command ids that\n * stitch an error back to the request that produced it. The metadata is\n * validated as JSON-safe on construction, so a logger can serialize any\n * `AppError` without hitting a circular reference or a non-serializable value.\n *\n * Abstract on purpose: callers should throw a specific subclass (e.g.\n * {@link ValidationError}, {@link NotFoundError}) so the `code` and shape are\n * meaningful, never a bare `AppError`.\n */\nabstract class AppError extends Error {\n public readonly code: string;\n public readonly cause?: unknown;\n public readonly metadata?: JsonSafeRecord;\n public readonly type?: string;\n public readonly severity?: ErrorSeverity;\n public readonly createdAtIso: string;\n public readonly publicMessage?: string;\n /**\n * Identifies a single execution \"story\" in the system. All operations\n * related to the same logical flow must share the same correlationId.\n */\n public readonly correlationId?: string;\n /**\n * Identifies a specific technical request attempt (each retry may produce\n * a new requestId), even when the correlationId stays the same.\n */\n public readonly requestId?: string;\n /**\n * Marks the business intent / idempotency key; stays the same across\n * technical retries and multiple requests that represent the same intent.\n */\n public readonly commandId?: string;\n\n /**\n * Builds the common error envelope shared by every subclass.\n *\n * `name` is taken from `new.target` so the thrown instance reports its\n * concrete subclass name (not `\"AppError\"`), and the prototype is re-pinned\n * via `setPrototypeOf` so `instanceof` keeps working after transpilation to\n * older targets where extending built-ins breaks the chain. `createdAtIso`\n * defaults to now, and `metadata` is validated as JSON-safe so the error is\n * always serializable.\n *\n * Declared `protected`: instantiate a concrete subclass, never `AppError`.\n *\n * @param message - The internal, developer-facing message.\n * @param code - The stable machine-readable code callers match on.\n * @param options - Optional cause, metadata, severity, and correlation ids.\n * @throws When `options.metadata` contains a value that is not JSON-safe.\n */\n protected constructor(\n message: string,\n code: string,\n options?: AppErrorOptions,\n ) {\n super(message);\n\n this.name = new.target.name;\n this.code = code;\n this.cause = options?.cause;\n this.type = options?.type;\n this.severity = options?.severity;\n this.correlationId = options?.correlationId;\n this.requestId = options?.requestId;\n this.commandId = options?.commandId;\n this.createdAtIso = options?.createdAtIso ?? new Date().toISOString();\n this.publicMessage = options?.publicMessage;\n\n this.metadata = options?.metadata\n ? assertJsonSafeMetadata(options.metadata)\n : undefined;\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Returns a JSON-safe representation of the error.\n * Does NOT include `cause` by default (to avoid leaking internal details).\n */\n public toJSON(): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n name: this.name,\n code: this.code,\n message: this.message,\n createdAtIso: this.createdAtIso,\n };\n\n // Optional fields are emitted only when defined, so the serialized\n // shape never carries `undefined`-valued keys (consistent with how the\n // correlation/request/command ids are handled).\n if (this.type !== undefined) payload.type = this.type;\n if (this.severity !== undefined) payload.severity = this.severity;\n if (this.publicMessage !== undefined)\n payload.publicMessage = this.publicMessage;\n if (this.metadata !== undefined) payload.metadata = this.metadata;\n if (this.correlationId !== undefined)\n payload.correlationId = this.correlationId;\n if (this.requestId !== undefined) payload.requestId = this.requestId;\n if (this.commandId !== undefined) payload.commandId = this.commandId;\n\n return payload;\n }\n}\n\nexport { AppError };\n"],"mappings":";AAAA,MAAM,aAAa;CACf,gBAA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OAAO,KAAK;EACjD,IAAI,KAAK,aAAa,KAAA,GAAW,QAAQ,WAAW,KAAK;EACzD,IAAI,KAAK,kBAAkB,KAAA,GACvB,QAAQ,gBAAgB,KAAK;EACjC,IAAI,KAAK,aAAa,KAAA,GAAW,QAAQ,WAAW,KAAK;EACzD,IAAI,KAAK,kBAAkB,KAAA,GACvB,QAAQ,gBAAgB,KAAK;EACjC,IAAI,KAAK,cAAc,KAAA,GAAW,QAAQ,YAAY,KAAK;EAC3D,IAAI,KAAK,cAAc,KAAA,GAAW,QAAQ,YAAY,KAAK;EAE3D,OAAO;CACX;AACJ"}
1
+ {"version":3,"file":"app-error.js","names":[],"sources":["../src/core/errors/error-codes.ts","../src/core/errors/utils/json-safe.ts","../src/core/errors/app-error.ts"],"sourcesContent":["const ErrorCodes = {\n authentication: {\n missingToken: \"sec.authn.missing_token\",\n invalidToken: \"sec.authn.invalid_token\",\n expiredToken: \"sec.authn.expired_token\",\n invalidCredentials: \"sec.authn.invalid_credentials\",\n },\n authorization: {\n forbidden: \"sec.authz.forbidden\",\n policyDenied: \"sec.authz.policy_denied\",\n missingRole: \"sec.authz.missing_role\",\n missingCapability: \"sec.authz.missing_capability\",\n outOfScope: \"sec.authz.out_of_scope\",\n },\n businessRuleViolation: \"business_rule_violation\",\n conflict: {\n alreadyExists: \"conf.already_exists\",\n duplicate: \"conf.duplicate\",\n uniqueViolation: \"conf.unique_violation\",\n },\n idempotency: {\n keyMissing: \"idemp.key_missing\",\n inProgress: \"idemp.in_progress\",\n payloadMismatch: \"idemp.payload_mismatch\",\n replayNotSupported: \"idemp.replay_not_supported\",\n },\n integration: {\n timeout: \"int.timeout\",\n unreachable: \"int.unreachable\",\n badResponse: \"int.bad_response\",\n },\n legacyIncompatible: \"legacy_incompatible\",\n notFound: \"not_found\",\n serialization: {\n deserializePrefix: \"ser.des\",\n serializePrefix: \"ser.ser\",\n },\n temporal: {\n expired: \"tmp.expired\",\n notYetValid: \"tmp.not_yet_valid\",\n },\n unexpected: \"unexpected\",\n validation: \"validation_error\",\n} as const;\n\ntype SerializationCodeDirection = \"deserialize\" | \"serialize\";\n\nfunction serializationErrorCode(\n direction: SerializationCodeDirection,\n category: string,\n): string {\n const prefix =\n direction === \"deserialize\"\n ? ErrorCodes.serialization.deserializePrefix\n : ErrorCodes.serialization.serializePrefix;\n\n return `${prefix}.${category}`;\n}\n\nexport { ErrorCodes, serializationErrorCode };\nexport type { SerializationCodeDirection };\n","// Utilities for ensuring metadata is JSON-serializable.\n\nimport type { JsonSafeRecord, JsonSafeValue } from \"../types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Constants\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst NON_SERIALIZABLE_PLACEHOLDER = \"[NonSerializable]\";\nconst CIRCULAR_REFERENCE_PLACEHOLDER = \"[Circular]\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// `seen` tracks the ancestors on the current traversal branch (a DFS path), not\n// every object visited. This collapses true circular references to a placeholder\n// while still serializing the same object referenced more than once across\n// sibling branches (a DAG) — matching `JSON.stringify`, which only rejects\n// cycles, not shared references.\nfunction sanitizeValue(value: unknown, seen: WeakSet<object>): JsonSafeValue {\n // Null passthrough\n if (value === null) return null;\n\n const type = typeof value;\n\n // Primitives (non-finite numbers are not JSON-representable — placeholder)\n if (type === \"number\") {\n return Number.isFinite(value)\n ? (value as number)\n : NON_SERIALIZABLE_PLACEHOLDER;\n }\n if (type === \"string\" || type === \"boolean\") {\n return value as JsonSafeValue;\n }\n\n // `undefined` only reaches here as an array item: object properties with\n // undefined values are omitted by the plain-object branch below. Both\n // mirror `JSON.stringify` semantics.\n if (value === undefined) return null;\n\n // Non-serializable primitives\n if (type === \"bigint\" || type === \"function\" || type === \"symbol\") {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Arrays (recursive)\n if (Array.isArray(value)) {\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const sanitized = value.map((item) => sanitizeValue(item, seen));\n seen.delete(value);\n return sanitized;\n }\n\n // Date → placeholder (could also use .toISOString() if preferred)\n if (value instanceof Date) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Class instances and non-plain objects → placeholder\n if (!isPlainObject(value)) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Plain object (recursive)\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const result: Record<string, JsonSafeValue> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === undefined) continue;\n const sanitized = sanitizeValue(val, seen);\n if (key === \"__proto__\") {\n // Plain `result.__proto__ = x` would reparent `result` instead of\n // creating an own data property, silently dropping the key. Define\n // it explicitly so `__proto__` survives as data — matching how\n // JSON.stringify/JSON.parse round-trip it.\n Object.defineProperty(result, key, {\n value: sanitized,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n } else {\n result[key] = sanitized;\n }\n }\n seen.delete(value);\n return result;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public API\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Ensures metadata is JSON-serializable.\n *\n * **Allowed:** finite number, string, boolean, null, arrays, and plain objects.\n *\n * **Dropped (mirroring `JSON.stringify`):** object properties whose value is\n * `undefined` (the key is omitted); an `undefined` array item becomes `null`.\n *\n * **Converted to placeholder:** Date, BigInt, class instances, functions,\n * symbols, non-finite numbers (`NaN`/`Infinity`), and circular references\n * (which would otherwise make `JSON.stringify` throw).\n *\n * @throws {TypeError} If `input` is not a plain object at the root level.\n */\nfunction assertJsonSafeMetadata(input: unknown): JsonSafeRecord {\n if (input === undefined) {\n return {};\n }\n\n if (!isPlainObject(input)) {\n throw new TypeError(\n \"metadata must be a plain object (Record<string, unknown>).\",\n );\n }\n\n return sanitizeValue(input, new WeakSet<object>()) as JsonSafeRecord;\n}\n\nexport {\n assertJsonSafeMetadata,\n CIRCULAR_REFERENCE_PLACEHOLDER,\n NON_SERIALIZABLE_PLACEHOLDER,\n};\n","// Base application error for the domain/application layer.\n// Encapsulates a code, optional cause, and JSON-safe metadata.\n\nimport type {\n AppErrorOptions,\n ErrorSeverity,\n JsonSafeRecord,\n} from \"./types.js\";\nimport { assertJsonSafeMetadata } from \"./utils/index.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AppError (abstract base class)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Root of the application/domain error hierarchy. Every error the system raises\n * on purpose extends `AppError`, which gives callers a single `instanceof` to\n * catch and a uniform, serializable shape to log and transport.\n *\n * Beyond the native `Error` message it carries a stable `code` (the contract the\n * outside world matches on), an optional non-leaking `publicMessage`, a\n * severity, JSON-safe `metadata`, and the correlation/request/command ids that\n * stitch an error back to the request that produced it. The metadata is\n * validated as JSON-safe on construction, so a logger can serialize any\n * `AppError` without hitting a circular reference or a non-serializable value.\n *\n * Abstract on purpose: callers should throw a specific subclass (e.g.\n * {@link ValidationError}, {@link NotFoundError}) so the `code` and shape are\n * meaningful, never a bare `AppError`.\n */\nabstract class AppError extends Error {\n public readonly code: string;\n public readonly cause?: unknown;\n public readonly metadata?: JsonSafeRecord;\n public readonly type?: string;\n public readonly severity?: ErrorSeverity;\n public readonly createdAtIso: string;\n public readonly publicMessage?: string;\n /**\n * Identifies a single execution \"story\" in the system. All operations\n * related to the same logical flow must share the same correlationId.\n */\n public readonly correlationId?: string;\n /**\n * Identifies a specific technical request attempt (each retry may produce\n * a new requestId), even when the correlationId stays the same.\n */\n public readonly requestId?: string;\n /**\n * Marks the business intent / idempotency key; stays the same across\n * technical retries and multiple requests that represent the same intent.\n */\n public readonly commandId?: string;\n\n /**\n * Builds the common error envelope shared by every subclass.\n *\n * `name` is taken from `new.target` so the thrown instance reports its\n * concrete subclass name (not `\"AppError\"`), and the prototype is re-pinned\n * via `setPrototypeOf` so `instanceof` keeps working after transpilation to\n * older targets where extending built-ins breaks the chain. `createdAtIso`\n * defaults to now, and `metadata` is validated as JSON-safe so the error is\n * always serializable.\n *\n * Declared `protected`: instantiate a concrete subclass, never `AppError`.\n *\n * @param message - The internal, developer-facing message.\n * @param code - The stable machine-readable code callers match on.\n * @param options - Optional cause, metadata, severity, and correlation ids.\n * @throws When `options.metadata` contains a value that is not JSON-safe.\n */\n protected constructor(\n message: string,\n code: string,\n options?: AppErrorOptions,\n ) {\n super(message);\n\n this.name = new.target.name;\n this.code = code;\n this.cause = options?.cause;\n this.type = options?.type;\n this.severity = options?.severity;\n this.correlationId = options?.correlationId;\n this.requestId = options?.requestId;\n this.commandId = options?.commandId;\n this.createdAtIso = options?.createdAtIso ?? new Date().toISOString();\n this.publicMessage = options?.publicMessage;\n\n this.metadata = options?.metadata\n ? assertJsonSafeMetadata(options.metadata)\n : undefined;\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Returns a JSON-safe representation of the error.\n * Does NOT include `cause` by default (to avoid leaking internal details).\n */\n public toJSON(): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n name: this.name,\n code: this.code,\n message: this.message,\n createdAtIso: this.createdAtIso,\n };\n\n // Optional fields are emitted only when defined, so the serialized\n // shape never carries `undefined`-valued keys (consistent with how the\n // correlation/request/command ids are handled).\n if (this.type !== undefined) payload.type = this.type;\n if (this.severity !== undefined) payload.severity = this.severity;\n if (this.publicMessage !== undefined)\n payload.publicMessage = this.publicMessage;\n if (this.metadata !== undefined) payload.metadata = this.metadata;\n if (this.correlationId !== undefined)\n payload.correlationId = this.correlationId;\n if (this.requestId !== undefined) payload.requestId = this.requestId;\n if (this.commandId !== undefined) payload.commandId = this.commandId;\n\n return payload;\n }\n}\n\nexport { AppError };\n"],"mappings":";AAAA,MAAM,aAAa;CACf,gBAAgB;EACZ,cAAc;EACd,cAAc;EACd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X,MAAM,KAAK;GACX,SAAS,KAAK;GACd,cAAc,KAAK;EACvB;EAKA,IAAI,KAAK,SAAS,KAAA,GAAW,QAAQ,OAAO,KAAK;EACjD,IAAI,KAAK,aAAa,KAAA,GAAW,QAAQ,WAAW,KAAK;EACzD,IAAI,KAAK,kBAAkB,KAAA,GACvB,QAAQ,gBAAgB,KAAK;EACjC,IAAI,KAAK,aAAa,KAAA,GAAW,QAAQ,WAAW,KAAK;EACzD,IAAI,KAAK,kBAAkB,KAAA,GACvB,QAAQ,gBAAgB,KAAK;EACjC,IAAI,KAAK,cAAc,KAAA,GAAW,QAAQ,YAAY,KAAK;EAC3D,IAAI,KAAK,cAAc,KAAA,GAAW,QAAQ,YAAY,KAAK;EAE3D,OAAO;CACX;AACJ"}
@@ -1,7 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_use_case = require("../use-case.cjs");
3
- const require_requested_by = require("../requested-by.cjs");
4
2
  const require_temporal_use_case = require("../temporal-use-case.cjs");
3
+ const require_requested_by = require("../requested-by.cjs");
5
4
  Object.defineProperty(exports, "Command", {
6
5
  enumerable: true,
7
6
  get: function() {
@@ -15,11 +14,16 @@ Object.defineProperty(exports, "Query", {
15
14
  }
16
15
  });
17
16
  exports.RequestedBy = require_requested_by.RequestedBy;
18
- exports.TemporalUseCase = require_temporal_use_case.TemporalUseCase;
17
+ Object.defineProperty(exports, "TemporalUseCase", {
18
+ enumerable: true,
19
+ get: function() {
20
+ return require_temporal_use_case.TemporalUseCase;
21
+ }
22
+ });
19
23
  Object.defineProperty(exports, "UseCase", {
20
24
  enumerable: true,
21
25
  get: function() {
22
- return require_use_case.UseCase;
26
+ return require_temporal_use_case.UseCase;
23
27
  }
24
28
  });
25
29
  exports.assertTemporalContext = require_temporal_use_case.assertTemporalContext;
@@ -1,3 +1,3 @@
1
1
  import { n as RequestedByKind, t as RequestedBy } from "../requested-by.cjs";
2
- import { A as LogPayload, C as UseCase, D as TracerPort, E as TraceSpan, O as MetricLabels, S as MaybePromise, T as TraceAttributeValue, _ 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 LoggerPort, k as MetricsPort, 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 UseCaseObservability, x as CommandInput, y as PolicyPortError } from "../temporal-use-case.cjs";
3
- export { CacheStrategy, Command, CommandInput, CreateTemporalContextInput, LogPayload, LoggerPort, MaybePromise, MetricLabels, MetricsPort, Page, PolicyEvaluationInput, PolicyEvaluationOutput, PolicyPort, PolicyPortError, Query, Repository, RequestedBy, RequestedByKind, ResultRepository, TemporalContext, TemporalHistory, TemporalRepository, TemporalUseCase, TemporalUseCaseInput, TemporalizedContextSeed, TraceAttributeValue, TraceSpan, TracerPort, UseCase, UseCaseObservability, assertTemporalContext, createTemporalContext, mapPolicyEvaluationError };
2
+ import { A as MetricLabels, C as CommandInput, D as TraceAttributeValue, E as UseCaseObservability, M as LogPayload, N as LoggerPort, O as TraceSpan, S as Command, T as UseCase, _ as ResultRepository, a as TemporalContext, b as PolicyPort, c as CacheStrategy, d as QueryOutput, f as mapPolicyEvaluationError, g as Repository, h as TemporalRepository, i as CreateTemporalContextInput, j as MetricsPort, k as TracerPort, l as Page, m as TemporalHistory, n as TemporalUseCaseInput, o as assertTemporalContext, p as ResultTemporalRepository, r as TemporalizedContextSeed, s as createTemporalContext, t as TemporalUseCase, u as Query, v as PolicyEvaluationInput, w as MaybePromise, x as PolicyPortError, y as PolicyEvaluationOutput } from "../temporal-use-case.cjs";
3
+ export { CacheStrategy, Command, CommandInput, CreateTemporalContextInput, LogPayload, LoggerPort, MaybePromise, MetricLabels, MetricsPort, Page, PolicyEvaluationInput, PolicyEvaluationOutput, PolicyPort, PolicyPortError, Query, QueryOutput, Repository, RequestedBy, RequestedByKind, ResultRepository, ResultTemporalRepository, TemporalContext, TemporalHistory, TemporalRepository, TemporalUseCase, TemporalUseCaseInput, TemporalizedContextSeed, TraceAttributeValue, TraceSpan, TracerPort, UseCase, UseCaseObservability, assertTemporalContext, createTemporalContext, mapPolicyEvaluationError };
@@ -1,3 +1,3 @@
1
1
  import { n as RequestedByKind, t as RequestedBy } from "../requested-by.js";
2
- import { A as LogPayload, C as UseCase, D as TracerPort, E as TraceSpan, O as MetricLabels, S as MaybePromise, T as TraceAttributeValue, _ 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 LoggerPort, k as MetricsPort, 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 UseCaseObservability, x as CommandInput, y as PolicyPortError } from "../temporal-use-case.js";
3
- export { CacheStrategy, Command, CommandInput, CreateTemporalContextInput, LogPayload, LoggerPort, MaybePromise, MetricLabels, MetricsPort, Page, PolicyEvaluationInput, PolicyEvaluationOutput, PolicyPort, PolicyPortError, Query, Repository, RequestedBy, RequestedByKind, ResultRepository, TemporalContext, TemporalHistory, TemporalRepository, TemporalUseCase, TemporalUseCaseInput, TemporalizedContextSeed, TraceAttributeValue, TraceSpan, TracerPort, UseCase, UseCaseObservability, assertTemporalContext, createTemporalContext, mapPolicyEvaluationError };
2
+ import { A as MetricLabels, C as CommandInput, D as TraceAttributeValue, E as UseCaseObservability, M as LogPayload, N as LoggerPort, O as TraceSpan, S as Command, T as UseCase, _ as ResultRepository, a as TemporalContext, b as PolicyPort, c as CacheStrategy, d as QueryOutput, f as mapPolicyEvaluationError, g as Repository, h as TemporalRepository, i as CreateTemporalContextInput, j as MetricsPort, k as TracerPort, l as Page, m as TemporalHistory, n as TemporalUseCaseInput, o as assertTemporalContext, p as ResultTemporalRepository, r as TemporalizedContextSeed, s as createTemporalContext, t as TemporalUseCase, u as Query, v as PolicyEvaluationInput, w as MaybePromise, x as PolicyPortError, y as PolicyEvaluationOutput } from "../temporal-use-case.js";
3
+ export { CacheStrategy, Command, CommandInput, CreateTemporalContextInput, LogPayload, LoggerPort, MaybePromise, MetricLabels, MetricsPort, Page, PolicyEvaluationInput, PolicyEvaluationOutput, PolicyPort, PolicyPortError, Query, QueryOutput, Repository, RequestedBy, RequestedByKind, ResultRepository, ResultTemporalRepository, TemporalContext, TemporalHistory, TemporalRepository, TemporalUseCase, TemporalUseCaseInput, TemporalizedContextSeed, TraceAttributeValue, TraceSpan, TracerPort, UseCase, UseCaseObservability, assertTemporalContext, createTemporalContext, mapPolicyEvaluationError };
@@ -1,4 +1,3 @@
1
- import { t as UseCase } from "../use-case.js";
1
+ import { a as mapPolicyEvaluationError, i as Query, n as assertTemporalContext, o as Command, r as createTemporalContext, s as UseCase, t as TemporalUseCase } from "../temporal-use-case.js";
2
2
  import { t as RequestedBy } from "../requested-by.js";
3
- import { a as mapPolicyEvaluationError, i as Query, n as assertTemporalContext, o as Command, r as createTemporalContext, t as TemporalUseCase } from "../temporal-use-case.js";
4
3
  export { Command, Query, RequestedBy, TemporalUseCase, UseCase, assertTemporalContext, createTemporalContext, mapPolicyEvaluationError };
@@ -1,4 +1,48 @@
1
1
  const require_app_error = require("./app-error.cjs");
2
+ //#region src/core/errors/utils/factory-helpers.ts
3
+ /** The envelope fields AppError understands; everything else is metadata. */
4
+ const APP_ERROR_OPTION_KEYS = [
5
+ "cause",
6
+ "type",
7
+ "severity",
8
+ "correlationId",
9
+ "requestId",
10
+ "commandId",
11
+ "createdAtIso",
12
+ "publicMessage"
13
+ ];
14
+ /**
15
+ * Picks the AppError envelope fields out of a flat factory input, so they can
16
+ * be forwarded to the constructor as options instead of leaking into metadata.
17
+ */
18
+ function pickAppErrorOptions(input) {
19
+ return {
20
+ cause: input?.cause,
21
+ type: input?.type,
22
+ severity: input?.severity,
23
+ correlationId: input?.correlationId,
24
+ requestId: input?.requestId,
25
+ commandId: input?.commandId,
26
+ createdAtIso: input?.createdAtIso,
27
+ publicMessage: input?.publicMessage
28
+ };
29
+ }
30
+ /**
31
+ * The complement of {@link pickAppErrorOptions}: everything that is *not* an
32
+ * AppError envelope field, i.e. the caller-supplied metadata. Keeps the cause
33
+ * and the public message out of the internal data block.
34
+ */
35
+ function stripAppErrorOptions(input) {
36
+ const result = { ...input };
37
+ for (const key of APP_ERROR_OPTION_KEYS) delete result[key];
38
+ return result;
39
+ }
40
+ /** Drops keys whose value is `undefined` (mirrors how JSON.stringify treats them). */
41
+ function compactMetadata(input) {
42
+ if (!input) return void 0;
43
+ return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0));
44
+ }
45
+ //#endregion
2
46
  //#region src/core/errors/authorization-error.ts
3
47
  /**
4
48
  * Raised when an authenticated actor is not allowed to perform a business
@@ -44,7 +88,7 @@ var AuthorizationError = class AuthorizationError extends require_app_error.AppE
44
88
  reason: "forbidden",
45
89
  ...extractMetadataOnly(input)
46
90
  },
47
- ...extractAppErrorOptions(input)
91
+ ...pickAppErrorOptions(input)
48
92
  });
49
93
  }
50
94
  /**
@@ -66,7 +110,7 @@ var AuthorizationError = class AuthorizationError extends require_app_error.AppE
66
110
  ...extractMetadataOnly(input),
67
111
  decision: "deny"
68
112
  },
69
- ...extractAppErrorOptions(input)
113
+ ...pickAppErrorOptions(input)
70
114
  });
71
115
  }
72
116
  /**
@@ -87,7 +131,7 @@ var AuthorizationError = class AuthorizationError extends require_app_error.AppE
87
131
  reason: "missing_role",
88
132
  ...extractMetadataOnly(input)
89
133
  },
90
- ...extractAppErrorOptions(input)
134
+ ...pickAppErrorOptions(input)
91
135
  });
92
136
  }
93
137
  /**
@@ -106,7 +150,7 @@ var AuthorizationError = class AuthorizationError extends require_app_error.AppE
106
150
  reason: "missing_capability",
107
151
  ...extractMetadataOnly(input)
108
152
  },
109
- ...extractAppErrorOptions(input)
153
+ ...pickAppErrorOptions(input)
110
154
  });
111
155
  }
112
156
  /**
@@ -126,22 +170,10 @@ var AuthorizationError = class AuthorizationError extends require_app_error.AppE
126
170
  reason: "out_of_scope",
127
171
  ...extractMetadataOnly(input)
128
172
  },
129
- ...extractAppErrorOptions(input)
173
+ ...pickAppErrorOptions(input)
130
174
  });
131
175
  }
132
176
  };
133
- function extractAppErrorOptions(options) {
134
- return {
135
- cause: options?.cause,
136
- type: options?.type,
137
- severity: options?.severity,
138
- correlationId: options?.correlationId,
139
- requestId: options?.requestId,
140
- commandId: options?.commandId,
141
- createdAtIso: options?.createdAtIso,
142
- publicMessage: options?.publicMessage
143
- };
144
- }
145
177
  function extractMetadataOnly(input) {
146
178
  const { cause, type, severity, correlationId, requestId, commandId, createdAtIso, publicMessage, ...metadata } = input;
147
179
  return metadata;
@@ -153,5 +185,23 @@ Object.defineProperty(exports, "AuthorizationError", {
153
185
  return AuthorizationError;
154
186
  }
155
187
  });
188
+ Object.defineProperty(exports, "compactMetadata", {
189
+ enumerable: true,
190
+ get: function() {
191
+ return compactMetadata;
192
+ }
193
+ });
194
+ Object.defineProperty(exports, "pickAppErrorOptions", {
195
+ enumerable: true,
196
+ get: function() {
197
+ return pickAppErrorOptions;
198
+ }
199
+ });
200
+ Object.defineProperty(exports, "stripAppErrorOptions", {
201
+ enumerable: true,
202
+ get: function() {
203
+ return stripAppErrorOptions;
204
+ }
205
+ });
156
206
 
157
207
  //# sourceMappingURL=authorization-error.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"authorization-error.cjs","names":["AppError","ErrorCodes"],"sources":["../src/core/errors/authorization-error.ts"],"sourcesContent":["import { AppError } from \"./app-error.js\";\nimport { ErrorCodes } from \"./error-codes.js\";\nimport type { AppErrorOptions, ErrorSeverity } from \"./types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\ntype AuthorizationErrorReason =\n | \"forbidden\"\n | \"missing_role\"\n | \"missing_capability\"\n | \"out_of_scope\"\n | \"outside_time_window\"\n | \"policy_denied\"\n | \"unknown\";\n\ntype AuthorizationRequirement = {\n role?: string;\n capability?: string;\n scope?: string; // e.g.: \"school:{id}\" or \"class:{id}\"\n};\n\ntype AuthorizationErrorMetadata = {\n reason: AuthorizationErrorReason;\n\n /** Stable action you evaluated (not an HTTP route — a \"business action\") */\n action: string;\n\n /** Resource identification (without leaking the full payload) */\n resource?: { type: string; id?: string };\n\n /** Optional: actor (do not include sensitive data) */\n actor?: { userId: string; role?: string };\n\n /** Optional: expected requirement */\n required?: AuthorizationRequirement;\n\n /** Optional: policy (when you already have PolicyEvaluation or similar) */\n policyId?: string;\n policyVersion?: number;\n evaluatedAtIso?: string;\n decision?: \"allow\" | \"deny\";\n reasonCode?: string;\n\n /** Optional: additional non-sensitive info */\n details?: string;\n};\n\n/**\n * Options for AuthorizationError factory methods.\n * Combines metadata fields (except 'reason') with common AppError options.\n */\ntype AuthorizationErrorFactoryOptions = Omit<\n AuthorizationErrorMetadata,\n \"reason\"\n> &\n Omit<AppErrorOptions, \"metadata\">;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AuthorizationError\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Raised when an authenticated actor is not allowed to perform a business\n * action — the \"you may not\" error, distinct from authentication (\"who are\n * you\"). Maps to an HTTP 403 at the edge.\n *\n * The discriminating {@link reason} records *why* access was denied (a flat\n * forbid, a missing role/capability, an out-of-scope target, or a policy\n * decision) so the boundary can shape the response without re-deriving it. The\n * metadata is deliberately built around a stable business `action` and a\n * type/id resource reference rather than an HTTP route or full payload, keeping\n * sensitive data out of logs. Instances are frozen. Construct through the\n * static factories, never directly.\n */\nclass AuthorizationError extends AppError {\n public readonly reason: AuthorizationErrorReason;\n\n private constructor(params: {\n message: string;\n code: string;\n reason: AuthorizationErrorReason;\n metadata: AuthorizationErrorMetadata;\n cause?: unknown;\n type?: string;\n severity?: ErrorSeverity;\n correlationId?: string;\n requestId?: string;\n commandId?: string;\n createdAtIso?: string;\n publicMessage?: string;\n }) {\n super(params.message, params.code, {\n cause: params.cause,\n metadata: params.metadata,\n type: params.type,\n severity: params.severity,\n correlationId: params.correlationId,\n requestId: params.requestId,\n commandId: params.commandId,\n createdAtIso: params.createdAtIso,\n publicMessage: params.publicMessage,\n });\n\n this.reason = params.reason;\n Object.freeze(this);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Factories\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * A flat denial with no more specific reason — the actor simply may not\n * perform this action. Reach for a more precise factory\n * ({@link AuthorizationError.missingCapability}, {@link AuthorizationError.outOfScope},\n * {@link AuthorizationError.policyDenied}) when the cause is known.\n */\n static forbidden(\n input: AuthorizationErrorFactoryOptions,\n ): AuthorizationError {\n return new AuthorizationError({\n message: \"Action not allowed\",\n code: ErrorCodes.authorization.forbidden,\n reason: \"forbidden\",\n metadata: { reason: \"forbidden\", ...extractMetadataOnly(input) },\n ...extractAppErrorOptions(input),\n });\n }\n\n /**\n * The action was denied by an evaluated policy. Captures the deciding\n * policy's id, version, and evaluation instant into the metadata (with\n * `decision: \"deny\"`) so the denial is auditable back to the exact policy\n * that produced it.\n *\n * @param input - Factory options plus the required `policyId`,\n * `policyVersion`, and `evaluatedAtIso` of the deciding policy.\n */\n static policyDenied(\n input: AuthorizationErrorFactoryOptions & {\n policyId: string;\n policyVersion: number;\n evaluatedAtIso: string;\n },\n ): AuthorizationError {\n return new AuthorizationError({\n message: \"Action denied by policy\",\n code: ErrorCodes.authorization.policyDenied,\n reason: \"policy_denied\",\n metadata: {\n reason: \"policy_denied\",\n ...extractMetadataOnly(input),\n decision: \"deny\",\n },\n ...extractAppErrorOptions(input),\n });\n }\n\n /**\n * The actor holds no role at all that bears on the action — the most basic\n * denial, distinct from {@link AuthorizationError.missingCapability} (which\n * means the actor *has* roles, just none granting the required capability).\n * The expected {@link AuthorizationRequirement} is recorded so the boundary\n * can tell the caller what grant is missing.\n *\n * @param input - Factory options plus the `required` role/capability/scope.\n */\n static missingRole(\n input: AuthorizationErrorFactoryOptions & {\n required: AuthorizationRequirement;\n },\n ): AuthorizationError {\n return new AuthorizationError({\n message: \"Missing required role to perform the action\",\n code: ErrorCodes.authorization.missingRole,\n reason: \"missing_role\",\n metadata: {\n reason: \"missing_role\",\n ...extractMetadataOnly(input),\n },\n ...extractAppErrorOptions(input),\n });\n }\n\n /**\n * The actor lacks a required role or capability. The expected\n * {@link AuthorizationRequirement} is recorded so the boundary can tell the\n * caller precisely what grant is missing.\n *\n * @param input - Factory options plus the `required` role/capability/scope.\n */\n static missingCapability(\n input: AuthorizationErrorFactoryOptions & {\n required: AuthorizationRequirement;\n },\n ): AuthorizationError {\n return new AuthorizationError({\n message: \"Insufficient capability to perform the action\",\n code: ErrorCodes.authorization.missingCapability,\n reason: \"missing_capability\",\n metadata: {\n reason: \"missing_capability\",\n ...extractMetadataOnly(input),\n },\n ...extractAppErrorOptions(input),\n });\n }\n\n /**\n * The actor may perform the action in general, but not on *this* target —\n * the resource falls outside the actor's permitted scope (e.g. a different\n * school or tenant than the one they are bound to).\n *\n * @param input - Factory options plus the optional `required` scope that the\n * target failed to satisfy.\n */\n static outOfScope(\n input: AuthorizationErrorFactoryOptions & {\n required?: AuthorizationRequirement;\n },\n ): AuthorizationError {\n return new AuthorizationError({\n message: \"Action outside the allowed scope\",\n code: ErrorCodes.authorization.outOfScope,\n reason: \"out_of_scope\",\n metadata: { reason: \"out_of_scope\", ...extractMetadataOnly(input) },\n ...extractAppErrorOptions(input),\n });\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction extractAppErrorOptions(options?: Partial<AppErrorOptions>) {\n return {\n cause: options?.cause,\n type: options?.type,\n severity: options?.severity,\n correlationId: options?.correlationId,\n requestId: options?.requestId,\n commandId: options?.commandId,\n createdAtIso: options?.createdAtIso,\n publicMessage: options?.publicMessage,\n };\n}\n\nfunction extractMetadataOnly(\n input: AuthorizationErrorFactoryOptions,\n): Omit<AuthorizationErrorMetadata, \"reason\"> {\n const {\n cause,\n type,\n severity,\n correlationId,\n requestId,\n commandId,\n createdAtIso,\n publicMessage,\n ...metadata\n } = input;\n return metadata;\n}\n\nexport { AuthorizationError };\nexport type {\n AuthorizationErrorMetadata,\n AuthorizationErrorReason,\n AuthorizationRequirement,\n};\n"],"mappings":";;;;;;;;;;;;;;;AA4EA,IAAM,qBAAN,MAAM,2BAA2BA,kBAAAA,SAAS;CAGtC,YAAoB,QAajB;EACC,MAAM,OAAO,SAAS,OAAO,MAAM;GAC/B,OAAO,OAAO;GACd,UAAU,OAAO;GACjB,MAAM,OAAO;GACb,UAAU,OAAO;GACjB,eAAe,OAAO;GACtB,WAAW,OAAO;GAClB,WAAW,OAAO;GAClB,cAAc,OAAO;GACrB,eAAe,OAAO;EAC1B,CAAC;EAED,KAAK,SAAS,OAAO;EACrB,OAAO,OAAO,IAAI;CACtB;;;;;;;CAYA,OAAO,UACH,OACkB;EAClB,OAAO,IAAI,mBAAmB;GAC1B,SAAS;GACT,MAAMC,kBAAAA,WAAW,cAAc;GAC/B,QAAQ;GACR,UAAU;IAAE,QAAQ;IAAa,GAAG,oBAAoB,KAAK;GAAE;GAC/D,GAAG,uBAAuB,KAAK;EACnC,CAAC;CACL;;;;;;;;;;CAWA,OAAO,aACH,OAKkB;EAClB,OAAO,IAAI,mBAAmB;GAC1B,SAAS;GACT,MAAMA,kBAAAA,WAAW,cAAc;GAC/B,QAAQ;GACR,UAAU;IACN,QAAQ;IACR,GAAG,oBAAoB,KAAK;IAC5B,UAAU;GACd;GACA,GAAG,uBAAuB,KAAK;EACnC,CAAC;CACL;;;;;;;;;;CAWA,OAAO,YACH,OAGkB;EAClB,OAAO,IAAI,mBAAmB;GAC1B,SAAS;GACT,MAAMA,kBAAAA,WAAW,cAAc;GAC/B,QAAQ;GACR,UAAU;IACN,QAAQ;IACR,GAAG,oBAAoB,KAAK;GAChC;GACA,GAAG,uBAAuB,KAAK;EACnC,CAAC;CACL;;;;;;;;CASA,OAAO,kBACH,OAGkB;EAClB,OAAO,IAAI,mBAAmB;GAC1B,SAAS;GACT,MAAMA,kBAAAA,WAAW,cAAc;GAC/B,QAAQ;GACR,UAAU;IACN,QAAQ;IACR,GAAG,oBAAoB,KAAK;GAChC;GACA,GAAG,uBAAuB,KAAK;EACnC,CAAC;CACL;;;;;;;;;CAUA,OAAO,WACH,OAGkB;EAClB,OAAO,IAAI,mBAAmB;GAC1B,SAAS;GACT,MAAMA,kBAAAA,WAAW,cAAc;GAC/B,QAAQ;GACR,UAAU;IAAE,QAAQ;IAAgB,GAAG,oBAAoB,KAAK;GAAE;GAClE,GAAG,uBAAuB,KAAK;EACnC,CAAC;CACL;AACJ;AAMA,SAAS,uBAAuB,SAAoC;CAChE,OAAO;EACH,OAAO,SAAS;EAChB,MAAM,SAAS;EACf,UAAU,SAAS;EACnB,eAAe,SAAS;EACxB,WAAW,SAAS;EACpB,WAAW,SAAS;EACpB,cAAc,SAAS;EACvB,eAAe,SAAS;CAC5B;AACJ;AAEA,SAAS,oBACL,OAC0C;CAC1C,MAAM,EACF,OACA,MACA,UACA,eACA,WACA,WACA,cACA,eACA,GAAG,aACH;CACJ,OAAO;AACX"}
1
+ {"version":3,"file":"authorization-error.cjs","names":["AppError","ErrorCodes"],"sources":["../src/core/errors/utils/factory-helpers.ts","../src/core/errors/authorization-error.ts"],"sourcesContent":["// Shared helpers for the error factories: separating the AppError envelope\n// options from the free-form metadata, and dropping undefined-valued keys.\n// Previously each of authentication/authorization/integration carried its own\n// near-identical copy of these.\n\nimport type { AppErrorOptions } from \"../types.js\";\n\n/** The envelope fields AppError understands; everything else is metadata. */\nconst APP_ERROR_OPTION_KEYS = [\n \"cause\",\n \"type\",\n \"severity\",\n \"correlationId\",\n \"requestId\",\n \"commandId\",\n \"createdAtIso\",\n \"publicMessage\",\n] as const;\n\ntype AppErrorEnvelope = Pick<\n AppErrorOptions,\n (typeof APP_ERROR_OPTION_KEYS)[number]\n>;\n\n/**\n * Picks the AppError envelope fields out of a flat factory input, so they can\n * be forwarded to the constructor as options instead of leaking into metadata.\n */\nfunction pickAppErrorOptions(\n input?: Partial<AppErrorOptions>,\n): AppErrorEnvelope {\n return {\n cause: input?.cause,\n type: input?.type,\n severity: input?.severity,\n correlationId: input?.correlationId,\n requestId: input?.requestId,\n commandId: input?.commandId,\n createdAtIso: input?.createdAtIso,\n publicMessage: input?.publicMessage,\n };\n}\n\n/**\n * The complement of {@link pickAppErrorOptions}: everything that is *not* an\n * AppError envelope field, i.e. the caller-supplied metadata. Keeps the cause\n * and the public message out of the internal data block.\n */\nfunction stripAppErrorOptions<T extends Record<string, unknown>>(\n input: T,\n): Omit<T, (typeof APP_ERROR_OPTION_KEYS)[number]> {\n const result = { ...input };\n for (const key of APP_ERROR_OPTION_KEYS) {\n delete result[key];\n }\n return result;\n}\n\n/** Drops keys whose value is `undefined` (mirrors how JSON.stringify treats them). */\nfunction compactMetadata<T extends Record<string, unknown>>(\n input?: T,\n): T | undefined {\n if (!input) return undefined;\n\n return Object.fromEntries(\n Object.entries(input).filter(([, value]) => value !== undefined),\n ) as T;\n}\n\nexport { compactMetadata, pickAppErrorOptions, stripAppErrorOptions };\n","import { AppError } from \"./app-error.js\";\nimport { ErrorCodes } from \"./error-codes.js\";\nimport type { AppErrorOptions, ErrorSeverity } from \"./types.js\";\nimport { pickAppErrorOptions } from \"./utils/index.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\ntype AuthorizationErrorReason =\n | \"forbidden\"\n | \"missing_role\"\n | \"missing_capability\"\n | \"out_of_scope\"\n | \"outside_time_window\"\n | \"policy_denied\"\n | \"unknown\";\n\ntype AuthorizationRequirement = {\n role?: string;\n capability?: string;\n scope?: string; // e.g.: \"school:{id}\" or \"class:{id}\"\n};\n\ntype AuthorizationErrorMetadata = {\n reason: AuthorizationErrorReason;\n\n /** Stable action you evaluated (not an HTTP route — a \"business action\") */\n action: string;\n\n /** Resource identification (without leaking the full payload) */\n resource?: { type: string; id?: string };\n\n /**\n * Optional: the acting principal (do not include sensitive data). `actorId`\n * is the raw `RequestedBy` value — a user UUID *or* a `\"system:<job>\"`\n * identity — so it must not be assumed to be a human user.\n */\n actor?: { actorId: string; role?: string };\n\n /** Optional: expected requirement */\n required?: AuthorizationRequirement;\n\n /** Optional: policy (when you already have PolicyEvaluation or similar) */\n policyId?: string;\n policyVersion?: number;\n evaluatedAtIso?: string;\n decision?: \"allow\" | \"deny\";\n reasonCode?: string;\n\n /** Optional: additional non-sensitive info */\n details?: string;\n};\n\n/**\n * Options for AuthorizationError factory methods.\n * Combines metadata fields (except 'reason') with common AppError options.\n */\ntype AuthorizationErrorFactoryOptions = Omit<\n AuthorizationErrorMetadata,\n \"reason\"\n> &\n Omit<AppErrorOptions, \"metadata\">;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AuthorizationError\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Raised when an authenticated actor is not allowed to perform a business\n * action — the \"you may not\" error, distinct from authentication (\"who are\n * you\"). Maps to an HTTP 403 at the edge.\n *\n * The discriminating {@link reason} records *why* access was denied (a flat\n * forbid, a missing role/capability, an out-of-scope target, or a policy\n * decision) so the boundary can shape the response without re-deriving it. The\n * metadata is deliberately built around a stable business `action` and a\n * type/id resource reference rather than an HTTP route or full payload, keeping\n * sensitive data out of logs. Instances are frozen. Construct through the\n * static factories, never directly.\n */\nclass AuthorizationError extends AppError {\n public readonly reason: AuthorizationErrorReason;\n\n private constructor(params: {\n message: string;\n code: string;\n reason: AuthorizationErrorReason;\n metadata: AuthorizationErrorMetadata;\n cause?: unknown;\n type?: string;\n severity?: ErrorSeverity;\n correlationId?: string;\n requestId?: string;\n commandId?: string;\n createdAtIso?: string;\n publicMessage?: string;\n }) {\n super(params.message, params.code, {\n cause: params.cause,\n metadata: params.metadata,\n type: params.type,\n severity: params.severity,\n correlationId: params.correlationId,\n requestId: params.requestId,\n commandId: params.commandId,\n createdAtIso: params.createdAtIso,\n publicMessage: params.publicMessage,\n });\n\n this.reason = params.reason;\n Object.freeze(this);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Factories\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * A flat denial with no more specific reason — the actor simply may not\n * perform this action. Reach for a more precise factory\n * ({@link AuthorizationError.missingCapability}, {@link AuthorizationError.outOfScope},\n * {@link AuthorizationError.policyDenied}) when the cause is known.\n */\n static forbidden(\n input: AuthorizationErrorFactoryOptions,\n ): AuthorizationError {\n return new AuthorizationError({\n message: \"Action not allowed\",\n code: ErrorCodes.authorization.forbidden,\n reason: \"forbidden\",\n metadata: { reason: \"forbidden\", ...extractMetadataOnly(input) },\n ...pickAppErrorOptions(input),\n });\n }\n\n /**\n * The action was denied by an evaluated policy. Captures the deciding\n * policy's id, version, and evaluation instant into the metadata (with\n * `decision: \"deny\"`) so the denial is auditable back to the exact policy\n * that produced it.\n *\n * @param input - Factory options plus the required `policyId`,\n * `policyVersion`, and `evaluatedAtIso` of the deciding policy.\n */\n static policyDenied(\n input: AuthorizationErrorFactoryOptions & {\n policyId: string;\n policyVersion: number;\n evaluatedAtIso: string;\n },\n ): AuthorizationError {\n return new AuthorizationError({\n message: \"Action denied by policy\",\n code: ErrorCodes.authorization.policyDenied,\n reason: \"policy_denied\",\n metadata: {\n reason: \"policy_denied\",\n ...extractMetadataOnly(input),\n decision: \"deny\",\n },\n ...pickAppErrorOptions(input),\n });\n }\n\n /**\n * The actor holds no role at all that bears on the action — the most basic\n * denial, distinct from {@link AuthorizationError.missingCapability} (which\n * means the actor *has* roles, just none granting the required capability).\n * The expected {@link AuthorizationRequirement} is recorded so the boundary\n * can tell the caller what grant is missing.\n *\n * @param input - Factory options plus the `required` role/capability/scope.\n */\n static missingRole(\n input: AuthorizationErrorFactoryOptions & {\n required: AuthorizationRequirement;\n },\n ): AuthorizationError {\n return new AuthorizationError({\n message: \"Missing required role to perform the action\",\n code: ErrorCodes.authorization.missingRole,\n reason: \"missing_role\",\n metadata: {\n reason: \"missing_role\",\n ...extractMetadataOnly(input),\n },\n ...pickAppErrorOptions(input),\n });\n }\n\n /**\n * The actor lacks a required role or capability. The expected\n * {@link AuthorizationRequirement} is recorded so the boundary can tell the\n * caller precisely what grant is missing.\n *\n * @param input - Factory options plus the `required` role/capability/scope.\n */\n static missingCapability(\n input: AuthorizationErrorFactoryOptions & {\n required: AuthorizationRequirement;\n },\n ): AuthorizationError {\n return new AuthorizationError({\n message: \"Insufficient capability to perform the action\",\n code: ErrorCodes.authorization.missingCapability,\n reason: \"missing_capability\",\n metadata: {\n reason: \"missing_capability\",\n ...extractMetadataOnly(input),\n },\n ...pickAppErrorOptions(input),\n });\n }\n\n /**\n * The actor may perform the action in general, but not on *this* target —\n * the resource falls outside the actor's permitted scope (e.g. a different\n * school or tenant than the one they are bound to).\n *\n * @param input - Factory options plus the optional `required` scope that the\n * target failed to satisfy.\n */\n static outOfScope(\n input: AuthorizationErrorFactoryOptions & {\n required?: AuthorizationRequirement;\n },\n ): AuthorizationError {\n return new AuthorizationError({\n message: \"Action outside the allowed scope\",\n code: ErrorCodes.authorization.outOfScope,\n reason: \"out_of_scope\",\n metadata: { reason: \"out_of_scope\", ...extractMetadataOnly(input) },\n ...pickAppErrorOptions(input),\n });\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction extractMetadataOnly(\n input: AuthorizationErrorFactoryOptions,\n): Omit<AuthorizationErrorMetadata, \"reason\"> {\n const {\n cause,\n type,\n severity,\n correlationId,\n requestId,\n commandId,\n createdAtIso,\n publicMessage,\n ...metadata\n } = input;\n return metadata;\n}\n\nexport { AuthorizationError };\nexport type {\n AuthorizationErrorMetadata,\n AuthorizationErrorReason,\n AuthorizationRequirement,\n};\n"],"mappings":";;;AAQA,MAAM,wBAAwB;CA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AAQ;IACR,GAAG,oBAAoB,KAAK;IAC5B,UAAU;GACd;GACA,GAAG,oBAAoB,KAAK;EAChC,CAAC;CACL;;;;;;;;;;CAWA,OAAO,YACH,OAGkB;EAClB,OAAO,IAAI,mBAAmB;GAC1B,SAAS;GACT,MAAMA,kBAAAA,WAAW,cAAc;GAC/B,QAAQ;GACR,UAAU;IACN,QAAQ;IACR,GAAG,oBAAoB,KAAK;GAChC;GACA,GAAG,oBAAoB,KAAK;EAChC,CAAC;CACL;;;;;;;;CASA,OAAO,kBACH,OAGkB;EAClB,OAAO,IAAI,mBAAmB;GAC1B,SAAS;GACT,MAAMA,kBAAAA,WAAW,cAAc;GAC/B,QAAQ;GACR,UAAU;IACN,QAAQ;IACR,GAAG,oBAAoB,KAAK;GAChC;GACA,GAAG,oBAAoB,KAAK;EAChC,CAAC;CACL;;;;;;;;;CAUA,OAAO,WACH,OAGkB;EAClB,OAAO,IAAI,mBAAmB;GAC1B,SAAS;GACT,MAAMA,kBAAAA,WAAW,cAAc;GAC/B,QAAQ;GACR,UAAU;IAAE,QAAQ;IAAgB,GAAG,oBAAoB,KAAK;GAAE;GAClE,GAAG,oBAAoB,KAAK;EAChC,CAAC;CACL;AACJ;AAMA,SAAS,oBACL,OAC0C;CAC1C,MAAM,EACF,OACA,MACA,UACA,eACA,WACA,WACA,cACA,eACA,GAAG,aACH;CACJ,OAAO;AACX"}
@@ -16,9 +16,13 @@ type AuthorizationErrorMetadata = {
16
16
  type: string;
17
17
  id?: string;
18
18
  };
19
- /** Optional: actor (do not include sensitive data) */
19
+ /**
20
+ * Optional: the acting principal (do not include sensitive data). `actorId`
21
+ * is the raw `RequestedBy` value — a user UUID *or* a `"system:<job>"`
22
+ * identity — so it must not be assumed to be a human user.
23
+ */
20
24
  actor?: {
21
- userId: string;
25
+ actorId: string;
22
26
  role?: string;
23
27
  };
24
28
  /** Optional: expected requirement */
@@ -16,9 +16,13 @@ type AuthorizationErrorMetadata = {
16
16
  type: string;
17
17
  id?: string;
18
18
  };
19
- /** Optional: actor (do not include sensitive data) */
19
+ /**
20
+ * Optional: the acting principal (do not include sensitive data). `actorId`
21
+ * is the raw `RequestedBy` value — a user UUID *or* a `"system:<job>"`
22
+ * identity — so it must not be assumed to be a human user.
23
+ */
20
24
  actor?: {
21
- userId: string;
25
+ actorId: string;
22
26
  role?: string;
23
27
  };
24
28
  /** Optional: expected requirement */