@cullet/erp-core 1.4.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 +7 -1
  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 +21 -6
  9. package/dist/app-error.cjs.map +1 -1
  10. package/dist/app-error.js +21 -6
  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 +117 -172
  27. package/dist/condition-evaluator.cjs.map +1 -1
  28. package/dist/condition-evaluator.js +118 -167
  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 +3 -2
  51. package/dist/errors/index.d.cts +1 -1
  52. package/dist/errors/index.d.ts +1 -1
  53. package/dist/errors/index.js +3 -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 +2 -44
  67. package/dist/hashing.cjs.map +1 -1
  68. package/dist/hashing.js +3 -39
  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 +15 -11
  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 +8 -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 -13
  109. package/dist/policies/engines/v1/gate/index.d.ts +3 -13
  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 +41 -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 +43 -48
  123. package/dist/policy-service.js.map +1 -1
  124. package/dist/requested-by.cjs +4 -4
  125. package/dist/requested-by.cjs.map +1 -1
  126. package/dist/requested-by.js +2 -2
  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 +87 -0
  143. package/dist/stable-stringify.cjs.map +1 -0
  144. package/dist/stable-stringify.js +76 -0
  145. package/dist/stable-stringify.js.map +1 -0
  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 +174 -16
  149. package/dist/temporal-use-case.cjs.map +1 -1
  150. package/dist/temporal-use-case.d.cts +82 -44
  151. package/dist/temporal-use-case.d.ts +82 -44
  152. package/dist/temporal-use-case.js +167 -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 +141 -8
  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 -8
  163. package/dist/uuid-identifier.js.map +1 -1
  164. package/dist/uuid.cjs +23 -0
  165. package/dist/uuid.cjs.map +1 -0
  166. package/dist/uuid.js +18 -0
  167. package/dist/uuid.js.map +1 -0
  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 +29 -8
  177. package/dist/validation-error.d.ts +29 -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 +23 -4
  195. package/dist/value-object.cjs.map +1 -1
  196. package/dist/value-object.d.cts +25 -1
  197. package/dist/value-object.d.ts +25 -1
  198. package/dist/value-object.js +23 -4
  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 +5 -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 +13 -5
  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 +25 -3
  218. package/src/core/application/temporal/temporal-use-case.ts +31 -4
  219. package/src/core/application/use-case.ts +45 -8
  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 +51 -8
  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 +6 -11
  232. package/src/core/domain/value-object.ts +29 -3
  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 +35 -12
  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 +120 -291
  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 -57
  281. package/src/core/shared/immutable.ts +22 -4
  282. package/src/core/shared/stable-stringify.ts +144 -0
  283. package/src/core/shared/uuid.ts +16 -0
  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 -126
  300. package/dist/entity.cjs.map +0 -1
  301. package/dist/entity.js +0 -115
  302. package/dist/entity.js.map +0 -1
  303. package/dist/use-case.cjs +0 -96
  304. package/dist/use-case.cjs.map +0 -1
  305. package/dist/use-case.js +0 -91
  306. package/dist/use-case.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"temporal-use-case.cjs","names":["UseCase","version","BusinessRuleViolationError","NotFoundError","UnexpectedError","UseCase","version","makeImmutable","UseCase"],"sources":["../src/core/application/commands/command.ts","../src/core/application/policy-error-mapper.ts","../src/core/application/queries/query.ts","../src/core/application/temporal/temporal-context.ts","../src/core/application/temporal/temporal-use-case.ts"],"sourcesContent":["import { UseCase } from \"../use-case.js\";\nimport { version } from \"../../versioning/version.js\";\nimport type { Result } from \"../../result/result.js\";\n\nimport { RequestedBy } from \"./requested-by.js\";\n\ninterface CommandInput {\n readonly requestedBy: RequestedBy;\n}\n\n/**\n * Base for use cases that **mutate state** (writes), following CQS.\n *\n * - `Input extends CommandInput` ensures every mutation records who triggered it.\n * - `Output extends Result<unknown, unknown>` ensures business errors are\n * explicit values, never thrown exceptions.\n *\n * The Command/Query distinction is semantic: the type declares the intent\n * before any implementation exists, guiding code review and API contracts.\n */\n@version(\"1.0\")\nabstract class Command<\n Input extends CommandInput,\n Output extends Result<unknown, unknown> = Result<void, never>,\n> extends UseCase<Input, Output> {}\n\nexport type { CommandInput };\nexport { Command };\n","import {\n type AppError,\n BusinessRuleViolationError,\n NotFoundError,\n UnexpectedError,\n} from \"../errors/index.js\";\nimport type { PolicyEvaluationError } from \"../policies/index.js\";\n\nexport function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError {\n switch (err.kind) {\n case \"INVALID_CONTEXT\":\n return new BusinessRuleViolationError(\n `policy.${err.stage.toLowerCase()}`,\n err.message,\n { policyKey: err.policyKey, stage: err.stage },\n { cause: err.cause },\n );\n case \"INVALID_POLICY_KEY\":\n return new BusinessRuleViolationError(\n \"policy.invalid_key\",\n err.message,\n { rawPolicyKey: err.rawPolicyKey },\n { cause: err.cause },\n );\n case \"POLICY_NOT_FOUND\":\n return new NotFoundError(\n \"Policy\",\n { policyKey: err.policyKey },\n { cause: err.cause },\n );\n case \"POLICY_DEFINITION_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyDefinition\",\n {\n policyKey: err.policyKey,\n contextVersion: err.contextVersion,\n asOf: err.asOf.toISOString(),\n },\n { cause: err.cause },\n );\n case \"POLICY_VARIANT_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyVariant\",\n {\n policyKey: err.policyKey,\n policyKind: err.policyKind,\n payloadSchemaVersion: err.payloadSchemaVersion,\n },\n { cause: err.cause },\n );\n case \"ENGINE_FAILURE\":\n return new UnexpectedError(err.message, err.cause, {\n metadata: {\n policyKey: err.policyKey,\n engine: err.engine,\n engineVersion: err.engineVersion,\n },\n });\n }\n}\n","import { UseCase } from \"../use-case.js\";\nimport { version } from \"../../versioning/version.js\";\nimport type { AppError } from \"../../errors/index.js\";\nimport type { Result } from \"../../result/result.js\";\n\n/**\n * Paginated result of a list query.\n * Use as `Output` when the query returns a collection with pagination metadata.\n */\ninterface Page<T> {\n readonly items: readonly T[];\n readonly total: number;\n readonly page: number;\n readonly pageSize: number;\n}\n\n/**\n * Cache strategy declared by the query type.\n * Infrastructure reads this value to decide whether and how to cache the result.\n */\ntype CacheStrategy =\n | { readonly kind: \"NO_CACHE\" }\n | { readonly kind: \"TIME_TO_LIVE\"; readonly ttlMs: number }\n | { readonly kind: \"STALE_WHILE_REVALIDATE\"; readonly ttlMs: number };\n\ntype QueryOutput = object | string | number | boolean | bigint | symbol | null;\n\n/**\n * Base for use cases that **only read state**, with no side effects, following CQS.\n *\n * - `Data extends QueryOutput` prevents a query from declaring a `void` or\n * `undefined` success payload, while still allowing primitive projections\n * and `null` when that makes sense for the read. Failures stay explicit in\n * `Result<T, E>`.\n * - Override `cacheStrategy()` to declare how infrastructure should cache the\n * result. By default, no cache is applied.\n *\n * A Query must never mutate persisted data — its execution must be idempotent\n * and safe to call multiple times with the same input.\n */\n@version(\"1.0\")\nabstract class Query<\n Input = void,\n Data extends QueryOutput = never,\n Failure = AppError,\n> extends UseCase<Input, Result<Data, Failure>> {\n protected cacheStrategy(): CacheStrategy {\n return { kind: \"NO_CACHE\" };\n }\n}\n\nexport type { CacheStrategy, Page, QueryOutput };\nexport { Query };\n","import { makeImmutable } from \"../../shared/immutable.js\";\nimport { assertValidDate } from \"../../shared/temporal-guards.js\";\n\ninterface TemporalContext {\n readonly asOf: Date;\n readonly requestedAt: Date;\n}\n\ninterface CreateTemporalContextInput {\n readonly asOf?: Date;\n readonly requestedAt?: Date;\n}\n\nfunction assertTemporalContext(\n temporalContext: TemporalContext,\n fieldName: string = \"temporalContext\",\n): void {\n assertValidDate(`${fieldName}.asOf`, temporalContext.asOf);\n assertValidDate(`${fieldName}.requestedAt`, temporalContext.requestedAt);\n}\n\nfunction createTemporalContext(\n input: CreateTemporalContextInput = {},\n): TemporalContext {\n const requestedAt = input.requestedAt ?? new Date();\n const asOf = input.asOf ?? requestedAt;\n\n assertTemporalContext({ asOf, requestedAt });\n\n return makeImmutable({\n asOf,\n requestedAt,\n });\n}\n\nexport {\n assertTemporalContext,\n createTemporalContext,\n type CreateTemporalContextInput,\n type TemporalContext,\n};\n","import { UseCase } from \"../use-case.js\";\nimport type { ContextSeed } from \"../../policies/index.js\";\nimport type { Result } from \"../../result/result.js\";\n\nimport {\n createTemporalContext,\n type TemporalContext,\n} from \"./temporal-context.js\";\n\ninterface TemporalUseCaseInput {\n readonly temporalContext?: TemporalContext;\n}\n\n/**\n * A {@link ContextSeed} after temporal enrichment by\n * {@link TemporalUseCase.buildPolicySeed}: structurally identical to `TSeed`,\n * except `fields.now` is now guaranteed present as a `Date` (injected from the\n * resolved {@link TemporalContext}). Downstream policies can therefore read\n * `seed.fields.now` without a presence/type guard.\n */\ntype TemporalizedContextSeed<TSeed extends ContextSeed> = Omit<\n TSeed,\n \"fields\"\n> & {\n readonly fields: TSeed[\"fields\"] & { readonly now: Date };\n};\n\nabstract class TemporalUseCase<\n Input extends object,\n Output extends Result<unknown, unknown>,\n> extends UseCase<Input & TemporalUseCaseInput, Output> {\n protected resolveTemporalContext(\n input: Input & TemporalUseCaseInput,\n ): TemporalContext {\n return createTemporalContext(input.temporalContext);\n }\n\n protected buildPolicySeed<TSeed extends ContextSeed>(\n seed: TSeed,\n temporalContext: TemporalContext,\n ): TemporalizedContextSeed<TSeed> {\n return Object.freeze({\n ...seed,\n fields: {\n ...seed.fields,\n now: new Date(temporalContext.requestedAt.getTime()),\n },\n }) as TemporalizedContextSeed<TSeed>;\n }\n}\n\nexport type { TemporalizedContextSeed, TemporalUseCaseInput };\nexport { TemporalUseCase };\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,IAAA,UAAA,MACe,gBAGLA,iBAAAA,QAAuB,CAAC;wCAJjCC,kBAAAA,QAAQ,KAAK,CAAA,GAAA,OAAA;;;ACZd,SAAgB,yBAAyB,KAAsC;CAC3E,QAAQ,IAAI,MAAZ;EACI,KAAK,mBACD,OAAO,IAAIC,wBAAAA,2BACP,UAAU,IAAI,MAAM,YAAY,KAChC,IAAI,SACJ;GAAE,WAAW,IAAI;GAAW,OAAO,IAAI;EAAM,GAC7C,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,sBACD,OAAO,IAAIA,wBAAAA,2BACP,sBACA,IAAI,SACJ,EAAE,cAAc,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f,OAAO,sBAAsB,MAAM,eAAe;CACtD;CAEA,gBACI,MACA,iBAC8B;EAC9B,OAAO,OAAO,OAAO;GACjB,GAAG;GACH,QAAQ;IACJ,GAAG,KAAK;IACR,KAAK,IAAI,KAAK,gBAAgB,YAAY,QAAQ,CAAC;GACvD;EACJ,CAAC;CACL;AACJ"}
1
+ {"version":3,"file":"temporal-use-case.cjs","names":["version","AppError","version","BusinessRuleViolationError","NotFoundError","UnexpectedError","version","makeImmutable","version"],"sources":["../src/core/application/use-case.ts","../src/core/application/commands/command.ts","../src/core/application/policy-error-mapper.ts","../src/core/application/queries/query.ts","../src/core/application/temporal/temporal-context.ts","../src/core/application/temporal/temporal-use-case.ts"],"sourcesContent":["import { type ContractVersion, version } from \"../versioning/version.js\";\nimport { AppError } from \"../errors/index.js\";\nimport type { Result } from \"../result/result.js\";\n\nimport type { LoggerPort } from \"./ports/logger.port.js\";\nimport type { MetricsPort } from \"./ports/metrics.port.js\";\nimport type { TraceAttributeValue, TracerPort } from \"./ports/tracer.port.js\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/**\n * Observability adapters a use case may opt into.\n *\n * All fields are optional: a use case that provides none keeps the plain\n * `input → Result` behavior with zero overhead. When provided, {@link UseCase.run}\n * instruments every execution around `execute()` — opening a span, recording\n * duration, counting outcomes, and logging business/unexpected failures.\n */\ninterface UseCaseObservability {\n readonly logger?: LoggerPort;\n readonly metrics?: MetricsPort;\n readonly tracer?: TracerPort;\n}\n\nconst EXECUTION_COUNTER = \"use_case.executions\";\nconst DURATION_HISTOGRAM = \"use_case.duration_ms\";\n\ntype ExecutionOutcome = \"ok\" | \"error\" | \"exception\";\n\n@version(\"1.0\")\nabstract class UseCase<\n Input = void,\n Output extends Result<unknown, unknown> = Result<void, never>,\n> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n public get contractVersion(): ContractVersion {\n return (this.constructor as typeof UseCase).CONTRACT_VERSION;\n }\n\n /**\n * Runs the use case.\n *\n * `run()` is the single seam every use case crosses, so it is where\n * cross-cutting instrumentation lives. When {@link observability} exposes\n * any adapter, the call to `execute()` is wrapped with tracing, metrics and\n * failure logging; otherwise it delegates directly with no overhead.\n *\n * Observability is strictly side-effecting: a misbehaving adapter never\n * changes the business result nor masks a thrown error — its own failures\n * are swallowed.\n */\n public async run(input: Input): Promise<Output> {\n const observability = this.observability();\n if (\n !observability.logger &&\n !observability.metrics &&\n !observability.tracer\n ) {\n return await this.execute(input);\n }\n\n return await this.runInstrumented(input, observability);\n }\n\n /**\n * Adapters used to instrument {@link run}. Override to opt a use case into\n * tracing/metrics/logging. Returns an empty object by default, which keeps\n * the plain delegating behavior.\n */\n protected observability(): UseCaseObservability {\n return {};\n }\n\n /**\n * Stable identity used for span names and metric labels. Defaults to the\n * runtime class name; override when bundling/minification would otherwise\n * erase a meaningful name.\n */\n protected get useCaseName(): string {\n return this.constructor.name;\n }\n\n protected abstract execute(input: Input): MaybePromise<Output>;\n\n /**\n * Extra attributes stamped onto the span and every metric emitted for this\n * execution. Override to attach stable, **low-cardinality** dimensions\n * (e.g. `Command` adds `requested_by.kind`). Keep values bounded — they\n * become metric label values, so a user id or free-form string here would\n * explode the metric's cardinality. Defaults to none.\n */\n protected spanAttributes(\n _input: Input,\n ): Readonly<Record<string, TraceAttributeValue>> {\n return {};\n }\n\n private async runInstrumented(\n input: Input,\n observability: UseCaseObservability,\n ): Promise<Output> {\n const { logger, metrics, tracer } = observability;\n const name = this.useCaseName;\n const attributes = safely(() => this.spanAttributes(input)) ?? {};\n const span = safely(() =>\n tracer?.startSpan(name, { \"use_case.name\": name, ...attributes }),\n );\n const startedAt = performance.now();\n // Declared here (not inside `try`) so the `finally` histogram can label\n // duration by outcome; defaults to \"exception\" and is overwritten once\n // execute() returns without throwing.\n let outcome: ExecutionOutcome = \"exception\";\n\n try {\n const output = await this.execute(input);\n outcome = output.isOk() ? \"ok\" : \"error\";\n\n if (outcome === \"error\") {\n const code = businessErrorCode(output);\n safely(() =>\n logger?.warn(`${name} returned a business error`, {\n useCase: name,\n ...(code ? { code } : {}),\n }),\n );\n }\n safely(() => span?.setAttribute(\"use_case.outcome\", outcome));\n safely(() =>\n metrics?.counter(EXECUTION_COUNTER, 1, {\n useCase: name,\n outcome,\n ...attributes,\n }),\n );\n\n return output;\n } catch (error) {\n safely(() =>\n logger?.error(`${name} threw an unexpected error`, {\n useCase: name,\n }),\n );\n safely(() => span?.setAttribute(\"use_case.outcome\", \"exception\"));\n safely(() => span?.recordException(error));\n safely(() =>\n metrics?.counter(EXECUTION_COUNTER, 1, {\n useCase: name,\n outcome: \"exception\",\n ...attributes,\n }),\n );\n\n throw error;\n } finally {\n safely(() =>\n metrics?.histogram(\n DURATION_HISTOGRAM,\n performance.now() - startedAt,\n { useCase: name, outcome, ...attributes },\n ),\n );\n safely(() => span?.end());\n }\n }\n}\n\n/**\n * Pulls the stable `code` off a business-error `Result` for logging. Returns\n * `undefined` when the error is not an {@link AppError} — the code is safe to\n * log (it's the public contract), unlike the message which may carry PII.\n */\nfunction businessErrorCode(\n output: Result<unknown, unknown>,\n): string | undefined {\n const error = output.errorOrNull();\n return error instanceof AppError ? error.code : undefined;\n}\n\n/**\n * Invokes an observability side effect, isolating any adapter failure so it\n * cannot alter the use case outcome.\n */\nfunction safely<R>(effect: () => R): R | undefined {\n try {\n return effect();\n } catch {\n return undefined;\n }\n}\n\nexport { type MaybePromise, UseCase, type UseCaseObservability };\n","import { UseCase } from \"../use-case.js\";\nimport { version } from \"../../versioning/version.js\";\nimport type { TraceAttributeValue } from \"../ports/tracer.port.js\";\nimport type { Result } from \"../../result/result.js\";\n\nimport { RequestedBy } from \"./requested-by.js\";\n\ninterface CommandInput {\n readonly requestedBy: RequestedBy;\n}\n\n/**\n * Base for use cases that **mutate state** (writes), following CQS.\n *\n * - `Input extends CommandInput` ensures every mutation records who triggered it.\n * - `Output extends Result<unknown, unknown>` ensures business errors are\n * explicit values, never thrown exceptions.\n *\n * The Command/Query distinction is semantic: the type declares the intent\n * before any implementation exists, guiding code review and API contracts.\n */\n@version(\"1.0\")\nabstract class Command<\n Input extends CommandInput,\n Output extends Result<unknown, unknown> = Result<void, never>,\n> extends UseCase<Input, Output> {\n /**\n * Surfaces the actor's *kind* (`\"user\"` / `\"system\"`) on the span and\n * metrics so a write can be sliced by origin. Only the low-cardinality\n * `kind` is emitted — never the raw id, which would blow up label\n * cardinality and could leak a user identifier into metrics.\n */\n protected override spanAttributes(\n input: Input,\n ): Readonly<Record<string, TraceAttributeValue>> {\n return { \"requested_by.kind\": input.requestedBy.kind };\n }\n}\n\nexport type { CommandInput };\nexport { Command };\n","import {\n type AppError,\n BusinessRuleViolationError,\n NotFoundError,\n UnexpectedError,\n} from \"../errors/index.js\";\nimport type { PolicyEvaluationError } from \"../policies/index.js\";\n\nexport function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError {\n switch (err.kind) {\n case \"INVALID_CONTEXT\":\n return new BusinessRuleViolationError(\n `policy.${err.stage.toLowerCase()}`,\n err.message,\n { policyKey: err.policyKey, stage: err.stage },\n { cause: err.cause },\n );\n case \"INVALID_POLICY_KEY\":\n return new BusinessRuleViolationError(\n \"policy.invalid_key\",\n err.message,\n { rawPolicyKey: err.rawPolicyKey },\n { cause: err.cause },\n );\n case \"POLICY_NOT_FOUND\":\n return new NotFoundError(\n \"Policy\",\n { policyKey: err.policyKey },\n { cause: err.cause },\n );\n case \"POLICY_DEFINITION_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyDefinition\",\n {\n policyKey: err.policyKey,\n contextVersion: err.contextVersion,\n asOf: err.asOf.toISOString(),\n },\n { cause: err.cause },\n );\n case \"POLICY_VARIANT_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyVariant\",\n {\n policyKey: err.policyKey,\n policyKind: err.policyKind,\n payloadSchemaVersion: err.payloadSchemaVersion,\n },\n { cause: err.cause },\n );\n case \"ENGINE_FAILURE\":\n // `engine`/`engineVersion` are internal detail kept in `metadata`\n // for logs. `publicMessage` gives the HTTP boundary a safe string\n // to expose so it never has to serialize this metadata to a client\n // on a 500. (Whether the boundary leaks `metadata` is still its\n // call — this only hands it the non-leaking alternative.)\n return new UnexpectedError(err.message, err.cause, {\n publicMessage: \"Policy evaluation failed unexpectedly.\",\n metadata: {\n policyKey: err.policyKey,\n engine: err.engine,\n engineVersion: err.engineVersion,\n },\n });\n }\n}\n","import { UseCase } from \"../use-case.js\";\nimport { version } from \"../../versioning/version.js\";\nimport type { AppError } from \"../../errors/index.js\";\nimport type { Result } from \"../../result/result.js\";\n\n/**\n * Paginated result of a list query (offset-based).\n * Use as `Output` when the query returns a collection with pagination metadata.\n * For cursor/keyset pagination, model your own `Output` type instead.\n */\ninterface Page<T> {\n readonly items: readonly T[];\n /** Total rows across all pages, ignoring `page`/`pageSize`. */\n readonly total: number;\n /** 1-based page number (the first page is `1`, not `0`). */\n readonly page: number;\n readonly pageSize: number;\n}\n\n/**\n * Cache strategy declared by the query type.\n * Infrastructure reads this value to decide whether and how to cache the result.\n *\n * These are pure descriptors: the type cannot enforce that a duration is finite\n * and positive, so the caching adapter must validate `ttlMs` /\n * `staleWhileRevalidateMs` (`> 0`, finite) before honoring the strategy.\n */\ntype CacheStrategy =\n | { readonly kind: \"NO_CACHE\" }\n | { readonly kind: \"TIME_TO_LIVE\"; readonly ttlMs: number }\n | {\n readonly kind: \"STALE_WHILE_REVALIDATE\";\n /** How long the entry is served fresh. */\n readonly ttlMs: number;\n /**\n * How long *after* `ttlMs` a stale entry may still be served while a\n * background refresh runs. SWR needs both windows; a single TTL is\n * ambiguous and each adapter would guess the second one.\n */\n readonly staleWhileRevalidateMs: number;\n };\n\ntype QueryOutput = object | string | number | boolean | bigint | symbol | null;\n\n/**\n * Base for use cases that **only read state**, with no side effects, following CQS.\n *\n * - `Data extends QueryOutput` prevents a query from declaring a `void` or\n * `undefined` success payload, while still allowing primitive projections\n * and `null` when that makes sense for the read. Failures stay explicit in\n * `Result<T, E>`.\n * - Override `cacheStrategy()` to declare how infrastructure should cache the\n * result. By default, no cache is applied.\n *\n * A Query must never mutate persisted data — its execution must be idempotent\n * and safe to call multiple times with the same input.\n */\n@version(\"1.0\")\nabstract class Query<\n Input = void,\n Data extends QueryOutput = never,\n Failure = AppError,\n> extends UseCase<Input, Result<Data, Failure>> {\n /**\n * Declares how infrastructure should cache this query's result. Public so\n * a caching adapter can actually read it off the instance; overrides must\n * stay public.\n */\n public cacheStrategy(): CacheStrategy {\n return { kind: \"NO_CACHE\" };\n }\n}\n\nexport type { CacheStrategy, Page, QueryOutput };\nexport { Query };\n","import { makeImmutable } from \"../../shared/immutable.js\";\nimport { assertValidDate } from \"../../shared/temporal-guards.js\";\n\ninterface TemporalContext {\n readonly asOf: Date;\n readonly requestedAt: Date;\n}\n\ninterface CreateTemporalContextInput {\n readonly asOf?: Date;\n readonly requestedAt?: Date;\n}\n\nfunction assertTemporalContext(\n temporalContext: TemporalContext,\n fieldName: string = \"temporalContext\",\n): void {\n assertValidDate(`${fieldName}.asOf`, temporalContext.asOf);\n assertValidDate(`${fieldName}.requestedAt`, temporalContext.requestedAt);\n}\n\nfunction createTemporalContext(\n input: CreateTemporalContextInput = {},\n): TemporalContext {\n const requestedAt = input.requestedAt ?? new Date();\n const asOf = input.asOf ?? requestedAt;\n\n assertTemporalContext({ asOf, requestedAt });\n\n return makeImmutable({\n asOf,\n requestedAt,\n });\n}\n\nexport {\n assertTemporalContext,\n createTemporalContext,\n type CreateTemporalContextInput,\n type TemporalContext,\n};\n","import { UseCase } from \"../use-case.js\";\nimport { version } from \"../../versioning/version.js\";\nimport type { ContextSeed } from \"../../policies/index.js\";\nimport type { Result } from \"../../result/result.js\";\n\nimport {\n createTemporalContext,\n type TemporalContext,\n} from \"./temporal-context.js\";\n\n/**\n * Marker mixed into a temporal use case's `Input`.\n *\n * The consumer's `Input` must not re-declare `temporalContext` with an\n * incompatible type: `TemporalUseCase` intersects the two, and a clashing\n * declaration collapses the field to `never` (surfacing only as a confusing\n * error at the call site, not here).\n */\ninterface TemporalUseCaseInput {\n readonly temporalContext?: TemporalContext;\n}\n\n/**\n * A {@link ContextSeed} after temporal enrichment by\n * {@link TemporalUseCase.buildPolicySeed}: structurally identical to `TSeed`,\n * except `fields.now` is now guaranteed present as a `Date` (injected from the\n * resolved {@link TemporalContext}). Downstream policies can therefore read\n * `seed.fields.now` without a presence/type guard.\n */\ntype TemporalizedContextSeed<TSeed extends ContextSeed> = Omit<\n TSeed,\n \"fields\"\n> & {\n readonly fields: TSeed[\"fields\"] & { readonly now: Date };\n};\n\n@version(\"1.0\")\nabstract class TemporalUseCase<\n Input extends object,\n Output extends Result<unknown, unknown>,\n> extends UseCase<Input & TemporalUseCaseInput, Output> {\n protected resolveTemporalContext(\n input: Input & TemporalUseCaseInput,\n ): TemporalContext {\n return createTemporalContext(input.temporalContext);\n }\n\n /**\n * Enriches a policy `ContextSeed` with `fields.now`, taken from the\n * context's `requestedAt` (wall-clock time of the request).\n *\n * NOTE: this injects **only** `now` (from `requestedAt`) — it does *not*\n * propagate `temporalContext.asOf`. Policy evaluation derives its own\n * `asOf` from whichever seed field the policy's `asOfSource` points at\n * (via `fields.now` by default). So a retroactive use case (an `asOf` in\n * the past) will still evaluate policies at the *current* time unless the\n * author maps `temporalContext.asOf` onto that seed field explicitly. Do\n * that mapping in the use case when back-dated evaluation is intended.\n */\n protected buildPolicySeed<TSeed extends ContextSeed>(\n seed: TSeed,\n temporalContext: TemporalContext,\n ): TemporalizedContextSeed<TSeed> {\n // ponytail: shallow-freeze the two objects we create (outer + fields);\n // nested `fields` values belong to the caller's seed — not ours to\n // deep-freeze (would freeze shared refs) or structuredClone (would\n // flatten any class instances the seed carries).\n const fields = Object.freeze({\n ...seed.fields,\n now: new Date(temporalContext.requestedAt.getTime()),\n });\n return Object.freeze({\n ...seed,\n fields,\n }) as TemporalizedContextSeed<TSeed>;\n }\n}\n\nexport type { TemporalizedContextSeed, TemporalUseCaseInput };\nexport { TemporalUseCase };\n"],"mappings":";;;;;;;AAwBA,MAAM,oBAAoB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AO;GACzB,GAAG,KAAK;GACR,KAAK,IAAI,KAAK,gBAAgB,YAAY,QAAQ,CAAC;EACvD,CAAC;EACD,OAAO,OAAO,OAAO;GACjB,GAAG;GACH;EACJ,CAAC;CACL;AACJ;+CAxCCC,kBAAAA,QAAQ,KAAK,CAAA,GAAA,eAAA"}
@@ -1,9 +1,9 @@
1
1
  import { t as RequestedBy } from "./requested-by.cjs";
2
2
  import { t as AppError } from "./app-error.cjs";
3
3
  import { r as Result } from "./result.cjs";
4
- import { t as DeepReadonly } from "./immutable.cjs";
5
4
  import { n as ContractVersion } from "./version.cjs";
6
5
  import { b as ContextSeed, r as PolicyEvaluationResult, s as PolicyEvaluationError, t as EvaluateInput } from "./policy-service.cjs";
6
+ import { n as TemporalSnapshot } from "./temporal-snapshot.cjs";
7
7
 
8
8
  //#region src/core/application/ports/logger.port.d.ts
9
9
  type LogPayload = Record<string, unknown>;
@@ -77,6 +77,14 @@ declare abstract class UseCase<Input = void, Output extends Result<unknown, unkn
77
77
  */
78
78
  protected get useCaseName(): string;
79
79
  protected abstract execute(input: Input): MaybePromise<Output>;
80
+ /**
81
+ * Extra attributes stamped onto the span and every metric emitted for this
82
+ * execution. Override to attach stable, **low-cardinality** dimensions
83
+ * (e.g. `Command` adds `requested_by.kind`). Keep values bounded — they
84
+ * become metric label values, so a user id or free-form string here would
85
+ * explode the metric's cardinality. Defaults to none.
86
+ */
87
+ protected spanAttributes(_input: Input): Readonly<Record<string, TraceAttributeValue>>;
80
88
  private runInstrumented;
81
89
  }
82
90
  //#endregion
@@ -94,7 +102,15 @@ interface CommandInput {
94
102
  * The Command/Query distinction is semantic: the type declares the intent
95
103
  * before any implementation exists, guiding code review and API contracts.
96
104
  */
97
- declare abstract class Command<Input extends CommandInput, Output extends Result<unknown, unknown> = Result<void, never>> extends UseCase<Input, Output> {}
105
+ declare abstract class Command<Input extends CommandInput, Output extends Result<unknown, unknown> = Result<void, never>> extends UseCase<Input, Output> {
106
+ /**
107
+ * Surfaces the actor's *kind* (`"user"` / `"system"`) on the span and
108
+ * metrics so a write can be sliced by origin. Only the low-cardinality
109
+ * `kind` is emitted — never the raw id, which would blow up label
110
+ * cardinality and could leak a user identifier into metrics.
111
+ */
112
+ protected spanAttributes(input: Input): Readonly<Record<string, TraceAttributeValue>>;
113
+ }
98
114
  //#endregion
99
115
  //#region src/core/application/ports/policy-port.d.ts
100
116
  type PolicyEvaluationInput = EvaluateInput;
@@ -152,71 +168,61 @@ interface ResultRepository<TEntity, TId, TError = AppError> {
152
168
  delete(id: TId): Promise<Result<void, TError>>;
153
169
  }
154
170
  //#endregion
155
- //#region src/core/domain/temporal/transaction-time.d.ts
156
- /**
157
- * Represents transaction time (Transaction Time).
158
- * Defines when the system learned about or recorded a piece of information.
159
- * Useful for auditing and reconstructing system state at a specific past moment.
160
- */
161
- interface TransactionTime {
162
- /** When the information was first recorded in the system. */
163
- readonly recordedAt: Date;
164
- /** When this information was superseded or invalidated by a newer version. */
165
- readonly supersededAt?: Date;
166
- }
167
- //#endregion
168
- //#region src/core/domain/temporal/valid-time.d.ts
169
- /**
170
- * Represents business time (Valid Time).
171
- * Defines when a piece of information is considered true or in effect in the real world.
172
- */
173
- interface ValidTime {
174
- /** Start of the validity window (inclusive). */
175
- readonly from: Date;
176
- /** End of the validity window (exclusive). When absent, the information is still in effect. */
177
- readonly to?: Date;
178
- }
179
- //#endregion
180
- //#region src/core/domain/temporal/temporal-snapshot.d.ts
181
- /**
182
- * Pairs a domain datum with its time dimensions (Business and Transaction).
183
- * It is the representation of an entry in the append-only (historical) table.
184
- */
185
- interface TemporalSnapshot<T> {
186
- /** The data or state captured by the snapshot. */
187
- readonly data: DeepReadonly<T>;
188
- /** Period during which this datum was valid in the real world. */
189
- readonly validTime: ValidTime;
190
- /** Period during which this record was the state known to the system. */
191
- readonly txTime: TransactionTime;
192
- }
193
- //#endregion
194
171
  //#region src/core/application/ports/temporal-repository.port.d.ts
195
172
  type TemporalHistory<TEntity> = readonly TemporalSnapshot<TEntity>[];
173
+ /**
174
+ * Bitemporal persistence port in the imperative (exception-raising) style.
175
+ *
176
+ * `delete(id)` is inherited from {@link Repository} and its bitemporal meaning
177
+ * is intentionally left to the implementation: it may close the current
178
+ * valid-time interval (a logical end-of-validity that preserves history) or
179
+ * physically purge the row's whole history. Pick one per adapter and document
180
+ * it — callers cannot tell which from this type. Prefer closing validity so
181
+ * `findAsOf`/`findHistory` stay meaningful for past instants.
182
+ */
196
183
  interface TemporalRepository<TEntity, TId> extends Repository<TEntity, TId> {
197
184
  findAsOf(id: TId, asOf: Date): Promise<TEntity | null>;
198
185
  findAtTransaction(id: TId, txTime: Date): Promise<TEntity | null>;
199
186
  findHistory(id: TId): Promise<TemporalHistory<TEntity>>;
200
187
  save(entity: TEntity, validFrom?: Date): Promise<void>;
201
188
  }
189
+ /**
190
+ * `Result`-returning counterpart of {@link TemporalRepository}, aligned with the
191
+ * "errors as values" philosophy (mirrors the {@link Repository} /
192
+ * {@link ResultRepository} pair). The `delete` semantics note above applies
193
+ * unchanged.
194
+ */
195
+ interface ResultTemporalRepository<TEntity, TId, TError = AppError> extends ResultRepository<TEntity, TId, TError> {
196
+ findAsOf(id: TId, asOf: Date): Promise<Result<TEntity | null, TError>>;
197
+ findAtTransaction(id: TId, txTime: Date): Promise<Result<TEntity | null, TError>>;
198
+ findHistory(id: TId): Promise<Result<TemporalHistory<TEntity>, TError>>;
199
+ save(entity: TEntity, validFrom?: Date): Promise<Result<void, TError>>;
200
+ }
202
201
  //#endregion
203
202
  //#region src/core/application/policy-error-mapper.d.ts
204
203
  declare function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError;
205
204
  //#endregion
206
205
  //#region src/core/application/queries/query.d.ts
207
206
  /**
208
- * Paginated result of a list query.
207
+ * Paginated result of a list query (offset-based).
209
208
  * Use as `Output` when the query returns a collection with pagination metadata.
209
+ * For cursor/keyset pagination, model your own `Output` type instead.
210
210
  */
211
211
  interface Page<T> {
212
212
  readonly items: readonly T[];
213
+ /** Total rows across all pages, ignoring `page`/`pageSize`. */
213
214
  readonly total: number;
215
+ /** 1-based page number (the first page is `1`, not `0`). */
214
216
  readonly page: number;
215
217
  readonly pageSize: number;
216
218
  }
217
219
  /**
218
220
  * Cache strategy declared by the query type.
219
221
  * Infrastructure reads this value to decide whether and how to cache the result.
222
+ *
223
+ * These are pure descriptors: the type cannot enforce that a duration is finite
224
+ * and positive, so the caching adapter must validate `ttlMs` /
225
+ * `staleWhileRevalidateMs` (`> 0`, finite) before honoring the strategy.
220
226
  */
221
227
  type CacheStrategy = {
222
228
  readonly kind: "NO_CACHE";
@@ -225,7 +231,14 @@ type CacheStrategy = {
225
231
  readonly ttlMs: number;
226
232
  } | {
227
233
  readonly kind: "STALE_WHILE_REVALIDATE";
234
+ /** How long the entry is served fresh. */
228
235
  readonly ttlMs: number;
236
+ /**
237
+ * How long *after* `ttlMs` a stale entry may still be served while a
238
+ * background refresh runs. SWR needs both windows; a single TTL is
239
+ * ambiguous and each adapter would guess the second one.
240
+ */
241
+ readonly staleWhileRevalidateMs: number;
229
242
  };
230
243
  type QueryOutput = object | string | number | boolean | bigint | symbol | null;
231
244
  /**
@@ -242,7 +255,12 @@ type QueryOutput = object | string | number | boolean | bigint | symbol | null;
242
255
  * and safe to call multiple times with the same input.
243
256
  */
244
257
  declare abstract class Query<Input = void, Data extends QueryOutput = never, Failure = AppError> extends UseCase<Input, Result<Data, Failure>> {
245
- protected cacheStrategy(): CacheStrategy;
258
+ /**
259
+ * Declares how infrastructure should cache this query's result. Public so
260
+ * a caching adapter can actually read it off the instance; overrides must
261
+ * stay public.
262
+ */
263
+ cacheStrategy(): CacheStrategy;
246
264
  }
247
265
  //#endregion
248
266
  //#region src/core/application/temporal/temporal-context.d.ts
@@ -258,6 +276,14 @@ declare function assertTemporalContext(temporalContext: TemporalContext, fieldNa
258
276
  declare function createTemporalContext(input?: CreateTemporalContextInput): TemporalContext;
259
277
  //#endregion
260
278
  //#region src/core/application/temporal/temporal-use-case.d.ts
279
+ /**
280
+ * Marker mixed into a temporal use case's `Input`.
281
+ *
282
+ * The consumer's `Input` must not re-declare `temporalContext` with an
283
+ * incompatible type: `TemporalUseCase` intersects the two, and a clashing
284
+ * declaration collapses the field to `never` (surfacing only as a confusing
285
+ * error at the call site, not here).
286
+ */
261
287
  interface TemporalUseCaseInput {
262
288
  readonly temporalContext?: TemporalContext;
263
289
  }
@@ -275,8 +301,20 @@ type TemporalizedContextSeed<TSeed extends ContextSeed> = Omit<TSeed, "fields">
275
301
  };
276
302
  declare abstract class TemporalUseCase<Input extends object, Output extends Result<unknown, unknown>> extends UseCase<Input & TemporalUseCaseInput, Output> {
277
303
  protected resolveTemporalContext(input: Input & TemporalUseCaseInput): TemporalContext;
304
+ /**
305
+ * Enriches a policy `ContextSeed` with `fields.now`, taken from the
306
+ * context's `requestedAt` (wall-clock time of the request).
307
+ *
308
+ * NOTE: this injects **only** `now` (from `requestedAt`) — it does *not*
309
+ * propagate `temporalContext.asOf`. Policy evaluation derives its own
310
+ * `asOf` from whichever seed field the policy's `asOfSource` points at
311
+ * (via `fields.now` by default). So a retroactive use case (an `asOf` in
312
+ * the past) will still evaluate policies at the *current* time unless the
313
+ * author maps `temporalContext.asOf` onto that seed field explicitly. Do
314
+ * that mapping in the use case when back-dated evaluation is intended.
315
+ */
278
316
  protected buildPolicySeed<TSeed extends ContextSeed>(seed: TSeed, temporalContext: TemporalContext): TemporalizedContextSeed<TSeed>;
279
317
  }
280
318
  //#endregion
281
- export { LogPayload as A, UseCase as C, TracerPort as D, TraceSpan as E, MetricLabels as O, MaybePromise as S, TraceAttributeValue as T, PolicyEvaluationOutput as _, TemporalContext as a, Command as b, CacheStrategy as c, mapPolicyEvaluationError as d, TemporalHistory as f, PolicyEvaluationInput as g, ResultRepository as h, CreateTemporalContextInput as i, LoggerPort as j, MetricsPort as k, Page as l, Repository as m, TemporalUseCaseInput as n, assertTemporalContext as o, TemporalRepository as p, TemporalizedContextSeed as r, createTemporalContext as s, TemporalUseCase as t, Query as u, PolicyPort as v, UseCaseObservability as w, CommandInput as x, PolicyPortError as y };
319
+ export { MetricLabels as A, CommandInput as C, TraceAttributeValue as D, UseCaseObservability as E, LogPayload as M, LoggerPort as N, TraceSpan as O, Command as S, UseCase as T, ResultRepository as _, TemporalContext as a, PolicyPort as b, CacheStrategy as c, QueryOutput as d, mapPolicyEvaluationError as f, Repository as g, TemporalRepository as h, CreateTemporalContextInput as i, MetricsPort as j, TracerPort as k, Page as l, TemporalHistory as m, TemporalUseCaseInput as n, assertTemporalContext as o, ResultTemporalRepository as p, TemporalizedContextSeed as r, createTemporalContext as s, TemporalUseCase as t, Query as u, PolicyEvaluationInput as v, MaybePromise as w, PolicyPortError as x, PolicyEvaluationOutput as y };
282
320
  //# sourceMappingURL=temporal-use-case.d.cts.map
@@ -1,9 +1,9 @@
1
1
  import { t as RequestedBy } from "./requested-by.js";
2
2
  import { t as AppError } from "./app-error.js";
3
3
  import { r as Result } from "./result.js";
4
- import { t as DeepReadonly } from "./immutable.js";
5
4
  import { n as ContractVersion } from "./version.js";
6
5
  import { b as ContextSeed, r as PolicyEvaluationResult, s as PolicyEvaluationError, t as EvaluateInput } from "./policy-service.js";
6
+ import { n as TemporalSnapshot } from "./temporal-snapshot.js";
7
7
 
8
8
  //#region src/core/application/ports/logger.port.d.ts
9
9
  type LogPayload = Record<string, unknown>;
@@ -77,6 +77,14 @@ declare abstract class UseCase<Input = void, Output extends Result<unknown, unkn
77
77
  */
78
78
  protected get useCaseName(): string;
79
79
  protected abstract execute(input: Input): MaybePromise<Output>;
80
+ /**
81
+ * Extra attributes stamped onto the span and every metric emitted for this
82
+ * execution. Override to attach stable, **low-cardinality** dimensions
83
+ * (e.g. `Command` adds `requested_by.kind`). Keep values bounded — they
84
+ * become metric label values, so a user id or free-form string here would
85
+ * explode the metric's cardinality. Defaults to none.
86
+ */
87
+ protected spanAttributes(_input: Input): Readonly<Record<string, TraceAttributeValue>>;
80
88
  private runInstrumented;
81
89
  }
82
90
  //#endregion
@@ -94,7 +102,15 @@ interface CommandInput {
94
102
  * The Command/Query distinction is semantic: the type declares the intent
95
103
  * before any implementation exists, guiding code review and API contracts.
96
104
  */
97
- declare abstract class Command<Input extends CommandInput, Output extends Result<unknown, unknown> = Result<void, never>> extends UseCase<Input, Output> {}
105
+ declare abstract class Command<Input extends CommandInput, Output extends Result<unknown, unknown> = Result<void, never>> extends UseCase<Input, Output> {
106
+ /**
107
+ * Surfaces the actor's *kind* (`"user"` / `"system"`) on the span and
108
+ * metrics so a write can be sliced by origin. Only the low-cardinality
109
+ * `kind` is emitted — never the raw id, which would blow up label
110
+ * cardinality and could leak a user identifier into metrics.
111
+ */
112
+ protected spanAttributes(input: Input): Readonly<Record<string, TraceAttributeValue>>;
113
+ }
98
114
  //#endregion
99
115
  //#region src/core/application/ports/policy-port.d.ts
100
116
  type PolicyEvaluationInput = EvaluateInput;
@@ -152,71 +168,61 @@ interface ResultRepository<TEntity, TId, TError = AppError> {
152
168
  delete(id: TId): Promise<Result<void, TError>>;
153
169
  }
154
170
  //#endregion
155
- //#region src/core/domain/temporal/transaction-time.d.ts
156
- /**
157
- * Represents transaction time (Transaction Time).
158
- * Defines when the system learned about or recorded a piece of information.
159
- * Useful for auditing and reconstructing system state at a specific past moment.
160
- */
161
- interface TransactionTime {
162
- /** When the information was first recorded in the system. */
163
- readonly recordedAt: Date;
164
- /** When this information was superseded or invalidated by a newer version. */
165
- readonly supersededAt?: Date;
166
- }
167
- //#endregion
168
- //#region src/core/domain/temporal/valid-time.d.ts
169
- /**
170
- * Represents business time (Valid Time).
171
- * Defines when a piece of information is considered true or in effect in the real world.
172
- */
173
- interface ValidTime {
174
- /** Start of the validity window (inclusive). */
175
- readonly from: Date;
176
- /** End of the validity window (exclusive). When absent, the information is still in effect. */
177
- readonly to?: Date;
178
- }
179
- //#endregion
180
- //#region src/core/domain/temporal/temporal-snapshot.d.ts
181
- /**
182
- * Pairs a domain datum with its time dimensions (Business and Transaction).
183
- * It is the representation of an entry in the append-only (historical) table.
184
- */
185
- interface TemporalSnapshot<T> {
186
- /** The data or state captured by the snapshot. */
187
- readonly data: DeepReadonly<T>;
188
- /** Period during which this datum was valid in the real world. */
189
- readonly validTime: ValidTime;
190
- /** Period during which this record was the state known to the system. */
191
- readonly txTime: TransactionTime;
192
- }
193
- //#endregion
194
171
  //#region src/core/application/ports/temporal-repository.port.d.ts
195
172
  type TemporalHistory<TEntity> = readonly TemporalSnapshot<TEntity>[];
173
+ /**
174
+ * Bitemporal persistence port in the imperative (exception-raising) style.
175
+ *
176
+ * `delete(id)` is inherited from {@link Repository} and its bitemporal meaning
177
+ * is intentionally left to the implementation: it may close the current
178
+ * valid-time interval (a logical end-of-validity that preserves history) or
179
+ * physically purge the row's whole history. Pick one per adapter and document
180
+ * it — callers cannot tell which from this type. Prefer closing validity so
181
+ * `findAsOf`/`findHistory` stay meaningful for past instants.
182
+ */
196
183
  interface TemporalRepository<TEntity, TId> extends Repository<TEntity, TId> {
197
184
  findAsOf(id: TId, asOf: Date): Promise<TEntity | null>;
198
185
  findAtTransaction(id: TId, txTime: Date): Promise<TEntity | null>;
199
186
  findHistory(id: TId): Promise<TemporalHistory<TEntity>>;
200
187
  save(entity: TEntity, validFrom?: Date): Promise<void>;
201
188
  }
189
+ /**
190
+ * `Result`-returning counterpart of {@link TemporalRepository}, aligned with the
191
+ * "errors as values" philosophy (mirrors the {@link Repository} /
192
+ * {@link ResultRepository} pair). The `delete` semantics note above applies
193
+ * unchanged.
194
+ */
195
+ interface ResultTemporalRepository<TEntity, TId, TError = AppError> extends ResultRepository<TEntity, TId, TError> {
196
+ findAsOf(id: TId, asOf: Date): Promise<Result<TEntity | null, TError>>;
197
+ findAtTransaction(id: TId, txTime: Date): Promise<Result<TEntity | null, TError>>;
198
+ findHistory(id: TId): Promise<Result<TemporalHistory<TEntity>, TError>>;
199
+ save(entity: TEntity, validFrom?: Date): Promise<Result<void, TError>>;
200
+ }
202
201
  //#endregion
203
202
  //#region src/core/application/policy-error-mapper.d.ts
204
203
  declare function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError;
205
204
  //#endregion
206
205
  //#region src/core/application/queries/query.d.ts
207
206
  /**
208
- * Paginated result of a list query.
207
+ * Paginated result of a list query (offset-based).
209
208
  * Use as `Output` when the query returns a collection with pagination metadata.
209
+ * For cursor/keyset pagination, model your own `Output` type instead.
210
210
  */
211
211
  interface Page<T> {
212
212
  readonly items: readonly T[];
213
+ /** Total rows across all pages, ignoring `page`/`pageSize`. */
213
214
  readonly total: number;
215
+ /** 1-based page number (the first page is `1`, not `0`). */
214
216
  readonly page: number;
215
217
  readonly pageSize: number;
216
218
  }
217
219
  /**
218
220
  * Cache strategy declared by the query type.
219
221
  * Infrastructure reads this value to decide whether and how to cache the result.
222
+ *
223
+ * These are pure descriptors: the type cannot enforce that a duration is finite
224
+ * and positive, so the caching adapter must validate `ttlMs` /
225
+ * `staleWhileRevalidateMs` (`> 0`, finite) before honoring the strategy.
220
226
  */
221
227
  type CacheStrategy = {
222
228
  readonly kind: "NO_CACHE";
@@ -225,7 +231,14 @@ type CacheStrategy = {
225
231
  readonly ttlMs: number;
226
232
  } | {
227
233
  readonly kind: "STALE_WHILE_REVALIDATE";
234
+ /** How long the entry is served fresh. */
228
235
  readonly ttlMs: number;
236
+ /**
237
+ * How long *after* `ttlMs` a stale entry may still be served while a
238
+ * background refresh runs. SWR needs both windows; a single TTL is
239
+ * ambiguous and each adapter would guess the second one.
240
+ */
241
+ readonly staleWhileRevalidateMs: number;
229
242
  };
230
243
  type QueryOutput = object | string | number | boolean | bigint | symbol | null;
231
244
  /**
@@ -242,7 +255,12 @@ type QueryOutput = object | string | number | boolean | bigint | symbol | null;
242
255
  * and safe to call multiple times with the same input.
243
256
  */
244
257
  declare abstract class Query<Input = void, Data extends QueryOutput = never, Failure = AppError> extends UseCase<Input, Result<Data, Failure>> {
245
- protected cacheStrategy(): CacheStrategy;
258
+ /**
259
+ * Declares how infrastructure should cache this query's result. Public so
260
+ * a caching adapter can actually read it off the instance; overrides must
261
+ * stay public.
262
+ */
263
+ cacheStrategy(): CacheStrategy;
246
264
  }
247
265
  //#endregion
248
266
  //#region src/core/application/temporal/temporal-context.d.ts
@@ -258,6 +276,14 @@ declare function assertTemporalContext(temporalContext: TemporalContext, fieldNa
258
276
  declare function createTemporalContext(input?: CreateTemporalContextInput): TemporalContext;
259
277
  //#endregion
260
278
  //#region src/core/application/temporal/temporal-use-case.d.ts
279
+ /**
280
+ * Marker mixed into a temporal use case's `Input`.
281
+ *
282
+ * The consumer's `Input` must not re-declare `temporalContext` with an
283
+ * incompatible type: `TemporalUseCase` intersects the two, and a clashing
284
+ * declaration collapses the field to `never` (surfacing only as a confusing
285
+ * error at the call site, not here).
286
+ */
261
287
  interface TemporalUseCaseInput {
262
288
  readonly temporalContext?: TemporalContext;
263
289
  }
@@ -275,8 +301,20 @@ type TemporalizedContextSeed<TSeed extends ContextSeed> = Omit<TSeed, "fields">
275
301
  };
276
302
  declare abstract class TemporalUseCase<Input extends object, Output extends Result<unknown, unknown>> extends UseCase<Input & TemporalUseCaseInput, Output> {
277
303
  protected resolveTemporalContext(input: Input & TemporalUseCaseInput): TemporalContext;
304
+ /**
305
+ * Enriches a policy `ContextSeed` with `fields.now`, taken from the
306
+ * context's `requestedAt` (wall-clock time of the request).
307
+ *
308
+ * NOTE: this injects **only** `now` (from `requestedAt`) — it does *not*
309
+ * propagate `temporalContext.asOf`. Policy evaluation derives its own
310
+ * `asOf` from whichever seed field the policy's `asOfSource` points at
311
+ * (via `fields.now` by default). So a retroactive use case (an `asOf` in
312
+ * the past) will still evaluate policies at the *current* time unless the
313
+ * author maps `temporalContext.asOf` onto that seed field explicitly. Do
314
+ * that mapping in the use case when back-dated evaluation is intended.
315
+ */
278
316
  protected buildPolicySeed<TSeed extends ContextSeed>(seed: TSeed, temporalContext: TemporalContext): TemporalizedContextSeed<TSeed>;
279
317
  }
280
318
  //#endregion
281
- export { LogPayload as A, UseCase as C, TracerPort as D, TraceSpan as E, MetricLabels as O, MaybePromise as S, TraceAttributeValue as T, PolicyEvaluationOutput as _, TemporalContext as a, Command as b, CacheStrategy as c, mapPolicyEvaluationError as d, TemporalHistory as f, PolicyEvaluationInput as g, ResultRepository as h, CreateTemporalContextInput as i, LoggerPort as j, MetricsPort as k, Page as l, Repository as m, TemporalUseCaseInput as n, assertTemporalContext as o, TemporalRepository as p, TemporalizedContextSeed as r, createTemporalContext as s, TemporalUseCase as t, Query as u, PolicyPort as v, UseCaseObservability as w, CommandInput as x, PolicyPortError as y };
319
+ export { MetricLabels as A, CommandInput as C, TraceAttributeValue as D, UseCaseObservability as E, LogPayload as M, LoggerPort as N, TraceSpan as O, Command as S, UseCase as T, ResultRepository as _, TemporalContext as a, PolicyPort as b, CacheStrategy as c, QueryOutput as d, mapPolicyEvaluationError as f, Repository as g, TemporalRepository as h, CreateTemporalContextInput as i, MetricsPort as j, TracerPort as k, Page as l, TemporalHistory as m, TemporalUseCaseInput as n, assertTemporalContext as o, ResultTemporalRepository as p, TemporalizedContextSeed as r, createTemporalContext as s, TemporalUseCase as t, Query as u, PolicyEvaluationInput as v, MaybePromise as w, PolicyPortError as x, PolicyEvaluationOutput as y };
282
320
  //# sourceMappingURL=temporal-use-case.d.ts.map