@ddd-ts-kit/kernel 0.114.1 → 0.116.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 (341) hide show
  1. package/README.fr.md +74 -60
  2. package/README.md +68 -55
  3. package/dist/application/audit/restamped.d.ts +9 -0
  4. package/dist/application/audit/restamped.d.ts.map +1 -0
  5. package/dist/application/audit/restamped.js +9 -0
  6. package/dist/application/audit/restamped.js.map +1 -0
  7. package/dist/application/audit/stamp-update.d.ts +1 -6
  8. package/dist/application/audit/stamp-update.d.ts.map +1 -1
  9. package/dist/application/audit/stamp-update.js +2 -8
  10. package/dist/application/audit/stamp-update.js.map +1 -1
  11. package/dist/application/background/enqueued-job.d.ts +1 -1
  12. package/dist/application/background/enqueued-job.d.ts.map +1 -1
  13. package/dist/application/error-reporting/report-once.d.ts.map +1 -1
  14. package/dist/application/error-reporting/report-once.js +2 -6
  15. package/dist/application/error-reporting/report-once.js.map +1 -1
  16. package/dist/application/event-sourcing/event-envelope.d.ts +2 -1
  17. package/dist/application/event-sourcing/event-envelope.d.ts.map +1 -1
  18. package/dist/application/event-sourcing/event-to-append.d.ts +1 -1
  19. package/dist/application/event-sourcing/event-to-append.d.ts.map +1 -1
  20. package/dist/application/execution/with-actor.d.ts +2 -2
  21. package/dist/application/execution/with-actor.js +3 -3
  22. package/dist/application/execution/with-actor.js.map +1 -1
  23. package/dist/application/files/stored-file.d.ts +3 -3
  24. package/dist/application/files/stored-file.d.ts.map +1 -1
  25. package/dist/application/hydration/hydration.d.ts.map +1 -1
  26. package/dist/application/hydration/hydration.js +3 -2
  27. package/dist/application/hydration/hydration.js.map +1 -1
  28. package/dist/application/logging/hidden-keys.d.ts +8 -0
  29. package/dist/application/logging/hidden-keys.d.ts.map +1 -0
  30. package/dist/application/logging/hidden-keys.js +10 -0
  31. package/dist/application/logging/hidden-keys.js.map +1 -0
  32. package/dist/application/logging/index.d.ts +1 -0
  33. package/dist/application/logging/index.d.ts.map +1 -1
  34. package/dist/application/logging/index.js +1 -0
  35. package/dist/application/logging/index.js.map +1 -1
  36. package/dist/application/observation/safely.d.ts +6 -0
  37. package/dist/application/observation/safely.d.ts.map +1 -0
  38. package/dist/application/observation/safely.js +13 -0
  39. package/dist/application/observation/safely.js.map +1 -0
  40. package/dist/application/persistence/append-changes.d.ts +1 -0
  41. package/dist/application/persistence/append-changes.d.ts.map +1 -1
  42. package/dist/application/persistence/append-changes.js +7 -6
  43. package/dist/application/persistence/append-changes.js.map +1 -1
  44. package/dist/application/persistence/optimistic-update.d.ts +6 -2
  45. package/dist/application/persistence/optimistic-update.d.ts.map +1 -1
  46. package/dist/application/persistence/optimistic-update.js +11 -3
  47. package/dist/application/persistence/optimistic-update.js.map +1 -1
  48. package/dist/application/ports/domain-event-dispatcher.d.ts +1 -1
  49. package/dist/application/ports/domain-event-dispatcher.js +1 -1
  50. package/dist/application/ports/logger.d.ts +3 -3
  51. package/dist/application/ports/unit-of-work.d.ts +1 -1
  52. package/dist/application/ports/unit-of-work.js +1 -1
  53. package/dist/application/read-model/stamp-of.d.ts +11 -4
  54. package/dist/application/read-model/stamp-of.d.ts.map +1 -1
  55. package/dist/application/read-model/stamp-of.js +10 -8
  56. package/dist/application/read-model/stamp-of.js.map +1 -1
  57. package/dist/application/session/anonymous-session.d.ts.map +1 -1
  58. package/dist/application/session/anonymous-session.js +4 -2
  59. package/dist/application/session/anonymous-session.js.map +1 -1
  60. package/dist/application/session/never-issued.d.ts +2 -1
  61. package/dist/application/session/never-issued.d.ts.map +1 -1
  62. package/dist/application/session/never-issued.js +4 -1
  63. package/dist/application/session/never-issued.js.map +1 -1
  64. package/dist/application/session/system-session.d.ts.map +1 -1
  65. package/dist/application/session/system-session.js +2 -2
  66. package/dist/application/session/system-session.js.map +1 -1
  67. package/dist/application/undecided/index.d.ts +3 -0
  68. package/dist/application/undecided/index.d.ts.map +1 -0
  69. package/dist/application/undecided/index.js +3 -0
  70. package/dist/application/undecided/index.js.map +1 -0
  71. package/dist/application/undecided/undecided-error.d.ts +12 -0
  72. package/dist/application/undecided/undecided-error.d.ts.map +1 -0
  73. package/dist/application/undecided/undecided-error.js +15 -0
  74. package/dist/application/undecided/undecided-error.js.map +1 -0
  75. package/dist/application/undecided/undecided.d.ts +7 -0
  76. package/dist/application/undecided/undecided.d.ts.map +1 -0
  77. package/dist/application/undecided/undecided.js +9 -0
  78. package/dist/application/undecided/undecided.js.map +1 -0
  79. package/dist/domain/aggregate-root.d.ts +6 -13
  80. package/dist/domain/aggregate-root.d.ts.map +1 -1
  81. package/dist/domain/aggregate-root.js +10 -16
  82. package/dist/domain/aggregate-root.js.map +1 -1
  83. package/dist/domain/aggregate-tracking.d.ts +30 -0
  84. package/dist/domain/aggregate-tracking.d.ts.map +1 -0
  85. package/dist/domain/aggregate-tracking.js +48 -0
  86. package/dist/domain/aggregate-tracking.js.map +1 -0
  87. package/dist/domain/domain-event.d.ts +4 -0
  88. package/dist/domain/domain-event.d.ts.map +1 -1
  89. package/dist/domain/domain-event.js.map +1 -1
  90. package/dist/domain/errors/domain-error.d.ts.map +1 -1
  91. package/dist/domain/errors/domain-error.js +2 -1
  92. package/dist/domain/errors/domain-error.js.map +1 -1
  93. package/dist/domain/errors/factual-refusal.d.ts.map +1 -1
  94. package/dist/domain/errors/factual-refusal.js +3 -0
  95. package/dist/domain/errors/factual-refusal.js.map +1 -1
  96. package/dist/domain/errors/kit-codes.d.ts +2 -0
  97. package/dist/domain/errors/kit-codes.d.ts.map +1 -1
  98. package/dist/domain/errors/kit-codes.js +2 -0
  99. package/dist/domain/errors/kit-codes.js.map +1 -1
  100. package/dist/domain/event-id-of.d.ts +8 -0
  101. package/dist/domain/event-id-of.d.ts.map +1 -0
  102. package/dist/domain/event-id-of.js +10 -0
  103. package/dist/domain/event-id-of.js.map +1 -0
  104. package/dist/domain/event-rank.d.ts +8 -0
  105. package/dist/domain/event-rank.d.ts.map +1 -0
  106. package/dist/domain/event-rank.js +8 -0
  107. package/dist/domain/event-rank.js.map +1 -0
  108. package/dist/domain/event-sourcing/event-sourced-aggregate.d.ts +0 -1
  109. package/dist/domain/event-sourcing/event-sourced-aggregate.d.ts.map +1 -1
  110. package/dist/domain/event-sourcing/event-sourced-aggregate.js +4 -8
  111. package/dist/domain/event-sourcing/event-sourced-aggregate.js.map +1 -1
  112. package/dist/domain/named-domain-event.d.ts +11 -4
  113. package/dist/domain/named-domain-event.d.ts.map +1 -1
  114. package/dist/domain/named-domain-event.js +14 -3
  115. package/dist/domain/named-domain-event.js.map +1 -1
  116. package/dist/domain/rank-of.d.ts +8 -0
  117. package/dist/domain/rank-of.d.ts.map +1 -0
  118. package/dist/domain/rank-of.js +14 -0
  119. package/dist/domain/rank-of.js.map +1 -0
  120. package/dist/domain/ranked.d.ts +10 -0
  121. package/dist/domain/ranked.d.ts.map +1 -0
  122. package/dist/domain/ranked.js +19 -0
  123. package/dist/domain/ranked.js.map +1 -0
  124. package/dist/domain/result/unwrap.d.ts +1 -0
  125. package/dist/domain/result/unwrap.d.ts.map +1 -1
  126. package/dist/domain/result/unwrap.js +4 -1
  127. package/dist/domain/result/unwrap.js.map +1 -1
  128. package/dist/domain/state-machine/state-machine.d.ts +4 -0
  129. package/dist/domain/state-machine/state-machine.d.ts.map +1 -1
  130. package/dist/domain/state-machine/state-machine.js +14 -4
  131. package/dist/domain/state-machine/state-machine.js.map +1 -1
  132. package/dist/domain/value-object/frozen-copy.d.ts +8 -0
  133. package/dist/domain/value-object/frozen-copy.d.ts.map +1 -0
  134. package/dist/domain/value-object/frozen-copy.js +34 -0
  135. package/dist/domain/value-object/frozen-copy.js.map +1 -0
  136. package/dist/domain/value-object/index.d.ts +2 -0
  137. package/dist/domain/value-object/index.d.ts.map +1 -0
  138. package/dist/domain/value-object/index.js +2 -0
  139. package/dist/domain/value-object/index.js.map +1 -0
  140. package/dist/domain/value-object/is-plain-record.d.ts +3 -0
  141. package/dist/domain/value-object/is-plain-record.d.ts.map +1 -0
  142. package/dist/domain/value-object/is-plain-record.js +9 -0
  143. package/dist/domain/value-object/is-plain-record.js.map +1 -0
  144. package/dist/domain/value-object/same-value.d.ts +8 -0
  145. package/dist/domain/value-object/same-value.d.ts.map +1 -0
  146. package/dist/domain/value-object/same-value.js +43 -0
  147. package/dist/domain/value-object/same-value.js.map +1 -0
  148. package/dist/domain/value-object/value-object.d.ts +28 -0
  149. package/dist/domain/value-object/value-object.d.ts.map +1 -0
  150. package/dist/domain/value-object/value-object.js +24 -0
  151. package/dist/domain/value-object/value-object.js.map +1 -0
  152. package/dist/index.d.ts +10 -12
  153. package/dist/index.d.ts.map +1 -1
  154. package/dist/index.js +10 -12
  155. package/dist/index.js.map +1 -1
  156. package/dist/infrastructure/aggregates/aggregate-mapper.d.ts +21 -0
  157. package/dist/infrastructure/aggregates/aggregate-mapper.d.ts.map +1 -0
  158. package/dist/infrastructure/aggregates/aggregate-mapper.js +18 -0
  159. package/dist/infrastructure/aggregates/aggregate-mapper.js.map +1 -0
  160. package/dist/infrastructure/aggregates/aggregate-save.d.ts +22 -0
  161. package/dist/infrastructure/aggregates/aggregate-save.d.ts.map +1 -0
  162. package/dist/infrastructure/aggregates/aggregate-save.js +2 -0
  163. package/dist/infrastructure/aggregates/aggregate-save.js.map +1 -0
  164. package/dist/infrastructure/aggregates/as-found.d.ts +8 -0
  165. package/dist/infrastructure/aggregates/as-found.d.ts.map +1 -0
  166. package/dist/infrastructure/aggregates/as-found.js +2 -0
  167. package/dist/infrastructure/aggregates/as-found.js.map +1 -0
  168. package/dist/infrastructure/aggregates/give-back.d.ts +9 -0
  169. package/dist/infrastructure/aggregates/give-back.d.ts.map +1 -0
  170. package/dist/infrastructure/aggregates/give-back.js +13 -0
  171. package/dist/infrastructure/aggregates/give-back.js.map +1 -0
  172. package/dist/infrastructure/aggregates/index.d.ts +7 -0
  173. package/dist/infrastructure/aggregates/index.d.ts.map +1 -0
  174. package/dist/infrastructure/aggregates/index.js +7 -0
  175. package/dist/infrastructure/aggregates/index.js.map +1 -0
  176. package/dist/infrastructure/aggregates/loaded-at.d.ts +8 -0
  177. package/dist/infrastructure/aggregates/loaded-at.d.ts.map +1 -0
  178. package/dist/infrastructure/aggregates/loaded-at.js +12 -0
  179. package/dist/infrastructure/aggregates/loaded-at.js.map +1 -0
  180. package/dist/infrastructure/aggregates/noted-as-found.d.ts +8 -0
  181. package/dist/infrastructure/aggregates/noted-as-found.d.ts.map +1 -0
  182. package/dist/infrastructure/aggregates/noted-as-found.js +15 -0
  183. package/dist/infrastructure/aggregates/noted-as-found.js.map +1 -0
  184. package/dist/infrastructure/aggregates/recorded-events-of.d.ts +4 -0
  185. package/dist/infrastructure/aggregates/recorded-events-of.d.ts.map +1 -0
  186. package/dist/infrastructure/aggregates/recorded-events-of.js +6 -0
  187. package/dist/infrastructure/aggregates/recorded-events-of.js.map +1 -0
  188. package/dist/infrastructure/aggregates/save-aggregate-row.d.ts +23 -0
  189. package/dist/infrastructure/aggregates/save-aggregate-row.d.ts.map +1 -0
  190. package/dist/infrastructure/aggregates/save-aggregate-row.js +17 -0
  191. package/dist/infrastructure/aggregates/save-aggregate-row.js.map +1 -0
  192. package/dist/infrastructure/aggregates/stored-at.d.ts +7 -0
  193. package/dist/infrastructure/aggregates/stored-at.d.ts.map +1 -0
  194. package/dist/infrastructure/aggregates/stored-at.js +14 -0
  195. package/dist/infrastructure/aggregates/stored-at.js.map +1 -0
  196. package/dist/infrastructure/aggregates/take-recorded-events.d.ts +9 -0
  197. package/dist/infrastructure/aggregates/take-recorded-events.d.ts.map +1 -0
  198. package/dist/infrastructure/aggregates/take-recorded-events.js +17 -0
  199. package/dist/infrastructure/aggregates/take-recorded-events.js.map +1 -0
  200. package/dist/infrastructure/aggregates/unstored-events-of.d.ts +4 -0
  201. package/dist/infrastructure/aggregates/unstored-events-of.d.ts.map +1 -0
  202. package/dist/infrastructure/aggregates/unstored-events-of.js +7 -0
  203. package/dist/infrastructure/aggregates/unstored-events-of.js.map +1 -0
  204. package/dist/infrastructure/clock/fixed-clock.d.ts +2 -1
  205. package/dist/infrastructure/clock/fixed-clock.d.ts.map +1 -1
  206. package/dist/infrastructure/clock/fixed-clock.js +5 -4
  207. package/dist/infrastructure/clock/fixed-clock.js.map +1 -1
  208. package/dist/infrastructure/context/scoped-actor-context.d.ts.map +1 -1
  209. package/dist/infrastructure/context/scoped-actor-context.js +2 -6
  210. package/dist/infrastructure/context/scoped-actor-context.js.map +1 -1
  211. package/dist/infrastructure/domain-events/announce-domain-events.d.ts +1 -1
  212. package/dist/infrastructure/domain-events/announce-domain-events.js +1 -1
  213. package/dist/infrastructure/domain-events/dispatching-on-save.d.ts +1 -1
  214. package/dist/infrastructure/domain-events/dispatching-on-save.d.ts.map +1 -1
  215. package/dist/infrastructure/domain-events/dispatching-on-save.js +3 -2
  216. package/dist/infrastructure/domain-events/dispatching-on-save.js.map +1 -1
  217. package/dist/infrastructure/domain-events/index.d.ts +14 -0
  218. package/dist/infrastructure/domain-events/index.d.ts.map +1 -0
  219. package/dist/infrastructure/domain-events/index.js +14 -0
  220. package/dist/infrastructure/domain-events/index.js.map +1 -0
  221. package/dist/infrastructure/domain-events/on-rollback.d.ts +10 -0
  222. package/dist/infrastructure/domain-events/on-rollback.d.ts.map +1 -0
  223. package/dist/infrastructure/domain-events/on-rollback.js +17 -0
  224. package/dist/infrastructure/domain-events/on-rollback.js.map +1 -0
  225. package/dist/infrastructure/domain-events/recorded-aggregates.d.ts +2 -5
  226. package/dist/infrastructure/domain-events/recorded-aggregates.d.ts.map +1 -1
  227. package/dist/infrastructure/domain-events/recorded-aggregates.js +3 -5
  228. package/dist/infrastructure/domain-events/recorded-aggregates.js.map +1 -1
  229. package/dist/infrastructure/domain-events/unit-of-work-aborted-error.d.ts +10 -0
  230. package/dist/infrastructure/domain-events/unit-of-work-aborted-error.d.ts.map +1 -0
  231. package/dist/infrastructure/domain-events/unit-of-work-aborted-error.js +13 -0
  232. package/dist/infrastructure/domain-events/unit-of-work-aborted-error.js.map +1 -0
  233. package/dist/infrastructure/domain-events/unit-of-work-over.d.ts +37 -0
  234. package/dist/infrastructure/domain-events/unit-of-work-over.d.ts.map +1 -0
  235. package/dist/infrastructure/domain-events/unit-of-work-over.js +146 -0
  236. package/dist/infrastructure/domain-events/unit-of-work-over.js.map +1 -0
  237. package/dist/infrastructure/domain-events/unit-of-work-scope.d.ts +11 -1
  238. package/dist/infrastructure/domain-events/unit-of-work-scope.d.ts.map +1 -1
  239. package/dist/infrastructure/domain-events/unit-of-work-scope.js.map +1 -1
  240. package/dist/infrastructure/domain-events/unscoped-unit-of-work-error.d.ts +8 -0
  241. package/dist/infrastructure/domain-events/unscoped-unit-of-work-error.d.ts.map +1 -0
  242. package/dist/infrastructure/domain-events/unscoped-unit-of-work-error.js +11 -0
  243. package/dist/infrastructure/domain-events/unscoped-unit-of-work-error.js.map +1 -0
  244. package/dist/infrastructure/domain-events/when-committed.d.ts.map +1 -1
  245. package/dist/infrastructure/domain-events/when-committed.js +2 -9
  246. package/dist/infrastructure/domain-events/when-committed.js.map +1 -1
  247. package/dist/infrastructure/event-sourcing/aggregate-id-of.d.ts +4 -0
  248. package/dist/infrastructure/event-sourcing/aggregate-id-of.d.ts.map +1 -0
  249. package/dist/infrastructure/event-sourcing/aggregate-id-of.js +6 -0
  250. package/dist/infrastructure/event-sourcing/aggregate-id-of.js.map +1 -0
  251. package/dist/infrastructure/event-sourcing/event-serializer.d.ts +3 -4
  252. package/dist/infrastructure/event-sourcing/event-serializer.d.ts.map +1 -1
  253. package/dist/infrastructure/event-sourcing/event-serializer.js +10 -12
  254. package/dist/infrastructure/event-sourcing/event-serializer.js.map +1 -1
  255. package/dist/infrastructure/event-sourcing/event-store-personal-data-export.d.ts.map +1 -1
  256. package/dist/infrastructure/event-sourcing/event-store-personal-data-export.js +1 -5
  257. package/dist/infrastructure/event-sourcing/event-store-personal-data-export.js.map +1 -1
  258. package/dist/infrastructure/events/idempotent.d.ts.map +1 -1
  259. package/dist/infrastructure/events/idempotent.js +9 -3
  260. package/dist/infrastructure/events/idempotent.js.map +1 -1
  261. package/dist/infrastructure/in-memory/as-json-carries.d.ts +9 -0
  262. package/dist/infrastructure/in-memory/as-json-carries.d.ts.map +1 -0
  263. package/dist/infrastructure/in-memory/as-json-carries.js +12 -0
  264. package/dist/infrastructure/in-memory/as-json-carries.js.map +1 -0
  265. package/dist/infrastructure/in-memory/composite-key.d.ts +6 -0
  266. package/dist/infrastructure/in-memory/composite-key.d.ts.map +1 -0
  267. package/dist/infrastructure/in-memory/composite-key.js +8 -0
  268. package/dist/infrastructure/in-memory/composite-key.js.map +1 -0
  269. package/dist/infrastructure/in-memory/in-memory-cache.d.ts +3 -1
  270. package/dist/infrastructure/in-memory/in-memory-cache.d.ts.map +1 -1
  271. package/dist/infrastructure/in-memory/in-memory-cache.js +7 -3
  272. package/dist/infrastructure/in-memory/in-memory-cache.js.map +1 -1
  273. package/dist/infrastructure/in-memory/in-memory-checkpoint-store.d.ts +1 -1
  274. package/dist/infrastructure/in-memory/in-memory-checkpoint-store.d.ts.map +1 -1
  275. package/dist/infrastructure/in-memory/in-memory-checkpoint-store.js +3 -2
  276. package/dist/infrastructure/in-memory/in-memory-checkpoint-store.js.map +1 -1
  277. package/dist/infrastructure/in-memory/in-memory-domain-event-dispatcher.d.ts +0 -1
  278. package/dist/infrastructure/in-memory/in-memory-domain-event-dispatcher.d.ts.map +1 -1
  279. package/dist/infrastructure/in-memory/in-memory-domain-event-dispatcher.js +2 -9
  280. package/dist/infrastructure/in-memory/in-memory-domain-event-dispatcher.js.map +1 -1
  281. package/dist/infrastructure/in-memory/in-memory-event-bus.d.ts +7 -14
  282. package/dist/infrastructure/in-memory/in-memory-event-bus.d.ts.map +1 -1
  283. package/dist/infrastructure/in-memory/in-memory-event-bus.js +17 -9
  284. package/dist/infrastructure/in-memory/in-memory-event-bus.js.map +1 -1
  285. package/dist/infrastructure/in-memory/in-memory-event-store.d.ts +8 -2
  286. package/dist/infrastructure/in-memory/in-memory-event-store.d.ts.map +1 -1
  287. package/dist/infrastructure/in-memory/in-memory-event-store.js +29 -14
  288. package/dist/infrastructure/in-memory/in-memory-event-store.js.map +1 -1
  289. package/dist/infrastructure/in-memory/in-memory-process-store.d.ts +1 -1
  290. package/dist/infrastructure/in-memory/in-memory-process-store.d.ts.map +1 -1
  291. package/dist/infrastructure/in-memory/in-memory-process-store.js +7 -8
  292. package/dist/infrastructure/in-memory/in-memory-process-store.js.map +1 -1
  293. package/dist/infrastructure/in-memory/in-memory-processed-event-store.d.ts +1 -0
  294. package/dist/infrastructure/in-memory/in-memory-processed-event-store.d.ts.map +1 -1
  295. package/dist/infrastructure/in-memory/in-memory-processed-event-store.js +6 -6
  296. package/dist/infrastructure/in-memory/in-memory-processed-event-store.js.map +1 -1
  297. package/dist/infrastructure/in-memory/in-memory-read-model-table.d.ts +2 -1
  298. package/dist/infrastructure/in-memory/in-memory-read-model-table.d.ts.map +1 -1
  299. package/dist/infrastructure/in-memory/in-memory-read-model-table.js +5 -3
  300. package/dist/infrastructure/in-memory/in-memory-read-model-table.js.map +1 -1
  301. package/dist/infrastructure/in-memory/in-memory-snapshot-store.d.ts +1 -1
  302. package/dist/infrastructure/in-memory/in-memory-snapshot-store.d.ts.map +1 -1
  303. package/dist/infrastructure/in-memory/in-memory-snapshot-store.js +3 -2
  304. package/dist/infrastructure/in-memory/in-memory-snapshot-store.js.map +1 -1
  305. package/dist/infrastructure/in-memory/in-memory-unit-of-work.d.ts +5 -2
  306. package/dist/infrastructure/in-memory/in-memory-unit-of-work.d.ts.map +1 -1
  307. package/dist/infrastructure/in-memory/in-memory-unit-of-work.js +7 -4
  308. package/dist/infrastructure/in-memory/in-memory-unit-of-work.js.map +1 -1
  309. package/dist/infrastructure/in-memory/in-process-bus.d.ts +1 -0
  310. package/dist/infrastructure/in-memory/in-process-bus.d.ts.map +1 -1
  311. package/dist/infrastructure/in-memory/in-process-bus.js +4 -3
  312. package/dist/infrastructure/in-memory/in-process-bus.js.map +1 -1
  313. package/dist/infrastructure/in-memory/rollback-map.d.ts +15 -0
  314. package/dist/infrastructure/in-memory/rollback-map.d.ts.map +1 -0
  315. package/dist/infrastructure/in-memory/rollback-map.js +52 -0
  316. package/dist/infrastructure/in-memory/rollback-map.js.map +1 -0
  317. package/dist/infrastructure/in-memory/unit-of-work-middleware.d.ts +5 -5
  318. package/dist/infrastructure/in-memory/unit-of-work-middleware.d.ts.map +1 -1
  319. package/dist/infrastructure/in-memory/unit-of-work-middleware.js +13 -4
  320. package/dist/infrastructure/in-memory/unit-of-work-middleware.js.map +1 -1
  321. package/package.json +1 -1
  322. package/dist/domain/event-sourcing/unstored-events.d.ts +0 -8
  323. package/dist/domain/event-sourcing/unstored-events.d.ts.map +0 -1
  324. package/dist/domain/event-sourcing/unstored-events.js +0 -7
  325. package/dist/domain/event-sourcing/unstored-events.js.map +0 -1
  326. package/dist/domain/value-object.d.ts +0 -12
  327. package/dist/domain/value-object.d.ts.map +0 -1
  328. package/dist/domain/value-object.js +0 -40
  329. package/dist/domain/value-object.js.map +0 -1
  330. package/dist/infrastructure/domain-events/within-unit-of-work.d.ts +0 -25
  331. package/dist/infrastructure/domain-events/within-unit-of-work.d.ts.map +0 -1
  332. package/dist/infrastructure/domain-events/within-unit-of-work.js +0 -85
  333. package/dist/infrastructure/domain-events/within-unit-of-work.js.map +0 -1
  334. package/dist/infrastructure/event-sourcing/stored-origins.d.ts +0 -5
  335. package/dist/infrastructure/event-sourcing/stored-origins.d.ts.map +0 -1
  336. package/dist/infrastructure/event-sourcing/stored-origins.js +0 -3
  337. package/dist/infrastructure/event-sourcing/stored-origins.js.map +0 -1
  338. package/dist/infrastructure/event-sourcing/stored-stamp-of.d.ts +0 -11
  339. package/dist/infrastructure/event-sourcing/stored-stamp-of.d.ts.map +0 -1
  340. package/dist/infrastructure/event-sourcing/stored-stamp-of.js +0 -15
  341. package/dist/infrastructure/event-sourcing/stored-stamp-of.js.map +0 -1
package/README.fr.md CHANGED
@@ -1,5 +1,5 @@
1
1
  [English](README.md) · **Français**
2
- <!-- translation-of: README.md sha256:32d9cb44336efff6 -->
2
+ <!-- translation-of: README.md sha256:0cd38c85fd4eb805 -->
3
3
 
4
4
  # @ddd-ts-kit/kernel
5
5
 
@@ -35,11 +35,11 @@ avec une bibliothèque.
35
35
  | Domaine | `Entity`, `AggregateRoot` (version, événements enregistrés), `ValueObject`, `DomainEvent`, `DomainError` avec un `code` stable, `ConceptError` (les erreurs d'un concept, chacune construite par une fabrique statique : voir « Erreurs du domaine »), `DomainRefusal` (une classe par refus, construite par des fabriques statiques), `FactualRefusal`, `isRefusal`, `CodeOf`, `RefusalOf`, `Refusal`, `RefusalFacts`, le générique `InvariantViolation`, `NotFoundError`, `ConflictError` (et `UniqueViolationError`, une valeur qu'une contrainte d'unicité garde déjà détenue), `ConcurrencyError`, `PreconditionFailedError`, `Result` avec `ok`, `err`, `unwrap` |
36
36
  | Ports | `Clock`, `IdGenerator`, `UnitOfWork`, `Repository` (classes abstraites : chacune est son propre jeton d'injection), `UseCase`, `DependencyKind` (les rôles que déclare une liaison, lus par di, le traçage et les aspects : `repository`, `gateway`, `external`, `use-case`, `publisher`, `consumer`, `domain-event-handler`, `job`) |
37
37
  | Bus | `Command`, `Query`, `CommandBus`, `QueryBus`, `BusMiddleware`, les `InMemoryCommandBus` et `InMemoryQueryBus` en processus (`register(type, handler, { context })` nomme le contexte délimité dans `MessageInfo`), `unitOfWorkMiddleware` |
38
- | Événements | `IntegrationEvent`, `IntegrationEventPublisher`, `IntegrationEventSubscriber`, `EventBus` (les deux à la fois), `EventSubscribers` (l'abonné de chaque contexte délimité), `ProcessedEventStore`, `idempotent`, `InMemoryEventBus` (exécute chaque gestionnaire d'un événement, puis rejette avec une `AggregateError` des échecs ; avec `{ failures: 'as-thrown' }`, la valeur par défaut d'une prochaine version mineure, l'échec d'un seul gestionnaire est relancé tel quel, avec son `code`), `EventBusFailures`, `DomainEventDispatcher`, `IntegrationEventCallback` et `DomainEventCallback` (les fonctions que reçoivent un abonné et un distributeur), `executionContextOfEvent`, `inEventScope`, `scopedPublisher`, `EventDelivery` (ce qu'un fournisseur dit d'une livraison : tentative, dernière tentative, transport, source, consommateur), `messagingSystemOf` |
39
- | Événements du domaine et unité de travail | `dispatchingOnSave` (l'enveloppe qui fait remettre par un *repository* ce qu'ont enregistré les agrégats qu'on lui confie), `announceDomainEvents`, `withinUnitOfWork` (ce sur quoi repose chaque `UnitOfWork.run` : file, distribution avant la validation, phase `after-commit`), `unitOfWorkStage` et `UnitOfWorkStage`, `DomainEventPhase`, `DomainEventSubscription`, `SaveAfterCommitError`, `AfterCommitFailure`, `reportAfterCommitFailures`, `InMemoryDomainEventDispatcher` |
38
+ | Événements | `IntegrationEvent`, `IntegrationEventPublisher`, `IntegrationEventSubscriber`, `EventBus` (les deux à la fois), `EventSubscribers` (l'abonné de chaque contexte délimité), `ProcessedEventStore`, `idempotent`, `InMemoryEventBus` (exécute chaque gestionnaire d'un événement, puis rejette avec l'échec d'un seul gestionnaire tel quel, avec son `code`, et avec une `AggregateError` de plusieurs ; un événement est livré et consigné dans `published` tel qu'un *broker* le porte, en JSON : une copie, une `Date` sous forme de texte, un événement que JSON ne peut pas porter refusé), `DomainEventDispatcher`, `IntegrationEventCallback` et `DomainEventCallback` (les fonctions que reçoivent un abonné et un distributeur), `executionContextOfEvent`, `inEventScope`, `scopedPublisher`, `EventDelivery` (ce qu'un fournisseur dit d'une livraison : tentative, dernière tentative, transport, source, consommateur), `messagingSystemOf` |
39
+ | Événements du domaine et unité de travail | `dispatchingOnSave` (l'enveloppe qui fait remettre par un *repository* ce qu'ont enregistré les agrégats qu'on lui confie), `announceDomainEvents`, `unitOfWorkOver` (ce sur quoi repose chaque `UnitOfWork` : file, distribution avant la validation, phase `after-commit`), `UnscopedUnitOfWorkError`, `UnitOfWorkAbortedError`, `unitOfWorkStage` et `UnitOfWorkStage`, `DomainEventPhase`, `DomainEventSubscription`, `SaveAfterCommitError`, `AfterCommitFailure`, `reportAfterCommitFailures`, `InMemoryDomainEventDispatcher` |
40
40
  | Machines à états | `defineStateMachine`, `StateMachine`, `TransitionError`, `InvalidStateMachineError`, `mermaidOfStateMachine` (voir « Machines à états ») |
41
41
  | Acteur | `Actor`, `AuthorizedCommand`, `AuthorizedQuery`, `ActorContext`, `systemActor` |
42
- | Interfaces standard | `Session`, `ExecutionContext` et `ExecutionScope`, `Logger`, `Metrics`, `ErrorReporter`, `Cache`, `CacheInvalidation` et `CachePurger` (avec `cacheTag`, `tenantCacheTags`, `CachePurgeRequest`, `PublishedCacheInvalidation`, `PurgingPublisher`, `RepeatedCachePurger` : voir « Purger les caches HTTP »), `Lock`, `RateLimiter`, `Page` et `PageRequest`, `AuditStamp`, `TenantScoped`, `AuditTrail`, `AuditReader` et `AuditEntry` |
42
+ | Interfaces standard | `Session`, `ExecutionContext` et `ExecutionScope`, `Logger`, `Metrics`, `ErrorReporter`, `Cache`, `CacheInvalidation` et `CachePurger` (avec `cacheTag`, `tenantCacheTags`, `CachePurgeRequest`, `PublishedCacheInvalidation`, `PurgingPublisher`, `RepeatedCachePurger` : voir « Purger les caches HTTP »), `Lock`, `RateLimiter`, `Page` et `PageRequest`, `AuditStamp`, `TenantScoped`, `AuditTrail`, `AuditReader` et `AuditEntry`, `safely` (exécute un hook, un logger ou une mesure et abandonne ce qu'il lève : observer ne casse jamais ce qui est observé) |
43
43
  | *Jobs* planifiés | `JobScheduler`, `ScheduledJob`, `JobExecution`, `JobSchedule`, `JobOptions`, `JobDefinition`, `JobRun`, `JobDescription`, `parseJobSchedule`, `describeJobSchedule`, `jobPolicy`, `executionContextOfJob` |
44
44
  | *Jobs* en arrière-plan | `JobQueue`, `BackgroundJob`, `BackgroundJobExecution`, `BackgroundJobPayloadSchema`, `processTimeoutDuePayload`, `EnqueueOptions`, `QueuedJob`, `QueuedJobStatus`, `backgroundJobPolicy`, `retryDelayMs`, `executionContextOfBackgroundJob`, `whenCommitted` (voir « JobQueue ») |
45
45
  | Gestionnaires de processus | `ProcessManager`, `ProcessDecision`, `ProcessRunner`, `ProcessStore`, `InMemoryProcessStore`, `UnreadableProcessStateError` (voir « ProcessRunner et ProcessStore ») |
@@ -48,9 +48,9 @@ avec une bibliothèque.
48
48
  | *Event sourcing* | `EventSourcedAggregate`, `EventStore`, `defineStoredEvent`, `EventSerializer`, `EventSourcedRepository`, `SnapshotPolicy`, `personalData`, `PersonalDataCipher`, `CatchUpSubscription`, `EventStoreProjectionRebuild`, `InMemoryEventStore`, `PostgresEventStore` (voir « Event sourcing ») |
49
49
  | Données personnelles | `personalFields`, `PersonalDataErasure`, `PersonalDataExport`, `eraseDataSubject`, `exportDataSubject`, `PersonalDataExportDocument`, `inEachTenant`, `recordsInEachTenant`, `isDataSubjectId`, `PersonalDataRecord`, `InMemoryPersonalData` (voir « Données personnelles ») |
50
50
  | Côté lecture | `Criteria`, `defineCriteria`, `validateCriteria`, `scoped`, `planCriteria`, `evaluateCriteria`, `pageOfPlan`, `hydrate`, `ReadModelStore`, `stampOf`, `TableReadModelStore`, `ProjectionRebuild`, `InMemoryReadModelStore` (voir « Critères », « Hydratation » et « Projections ») |
51
- | Aides à la persistance | `optimisticUpdate`, `expectVersion` (la version qu'un appelant a lue, `If-Match` en HTTP, est toujours la version courante, sinon `PreconditionFailedError` : 412), `schemaNameOf`, `stampCreation`, `stampUpdate`, `tenantScopeOf`, `encodeCursor`, `decodeCursor` |
51
+ | Aides à la persistance | `aggregateMapper` (un *mapper* qui déclare l'état et jamais la version), `loadedAt`, `optimisticUpdate`, `expectVersion` (la version qu'un appelant a lue, `If-Match` en HTTP, est toujours la version courante, sinon `PreconditionFailedError` : 412), `schemaNameOf`, `stampCreation`, `stampUpdate`, `restamped`, `tenantScopeOf`, `encodeCursor`, `decodeCursor` |
52
52
  | Remontée des erreurs | `ErrorReporter`, `ErrorReport`, `errorReportOf`, `reportOnce`, `isUnexpectedError`, `errorReportingMiddleware`, `DeadLetterReports`, `reportProcessFailures`, `NoopErrorReporter` |
53
- | Doubles | `FixedClock`, `SequentialIdGenerator`, `InMemoryUnitOfWork`, `FixedActorContext`, `FixedExecutionScope`, `InMemoryLogger`, `InMemoryMetrics`, `InMemoryErrorReporter`, `InMemoryCache`, `InMemoryCacheInvalidation`, `InMemoryCachePurger`, `InMemoryLock`, `InMemoryRateLimiter` |
53
+ | Doubles | `FixedClock`, `SequentialIdGenerator`, `InMemoryUnitOfWork`, `RollbackMap`, `onRollback`, `FixedActorContext`, `FixedExecutionScope`, `InMemoryLogger`, `InMemoryMetrics`, `InMemoryErrorReporter`, `InMemoryCache`, `InMemoryCacheInvalidation`, `InMemoryCachePurger`, `InMemoryLock`, `InMemoryRateLimiter` |
54
54
  | Tests (`@ddd-ts-kit/kernel/testing`) | `RecordingCommandBus`, `RecordingQueryBus` : des bus qui gardent chaque message qu'on leur confie, dans l'ordre (`executed`), et répondent ce que la *spec* leur a dit (`answering(type, answer)`), rien sinon (voir « La *spec* d'une réaction ») |
55
55
  | Déclarations (`@ddd-ts-kit/kernel/declarations`) | `Requires`, `Public`, `CommandHandler`, `QueryHandler`, `IntegrationEventHandler`, `DomainEventHandler`, `Scheduled`, `Background`, `Projection`, `On`, `applyingProjection`, `Repository`, `Gateway`, `Adapter`, `Policy`, `Edge` (pour les décorateurs d'un *package* de transport, comme `@Controller`), `injected`, `injectedDependencies`, `declarationOf`, `listDeclarations`, `DeclarationError`, `Token`, `describeToken`, `tokenIdentity`, `portDefect` |
56
56
 
@@ -63,7 +63,7 @@ chacun son propre fichier, et `ddd-ts-kit generate` les écrit) :
63
63
 
64
64
  <!-- checked sample -->
65
65
  ```ts
66
- import { AggregateRoot, DomainRefusal, Entity, ValueObject, NamedDomainEvent } from '@ddd-ts-kit/kernel';
66
+ import { AggregateRoot, DomainRefusal, Entity, ValueObject, NamedDomainEvent, recordedEventsOf } from '@ddd-ts-kit/kernel';
67
67
 
68
68
  // Les codes du contexte, dans <context>.codes.ts, et ses refus, une classe chacun (voir « Erreurs du domaine »).
69
69
  export const OrderingCodes = {
@@ -128,11 +128,11 @@ export class OrderLine extends Entity {
128
128
  // Un événement du domaine : un fait passé, nommé <contexte>.<agrégat>.<fait>.
129
129
  export class OrderPlaced extends NamedDomainEvent('ordering.order.placed') {
130
130
  constructor(
131
- readonly aggregateId: string,
132
- readonly occurredAt: Date,
131
+ aggregateId: string,
132
+ occurredAt: Date,
133
133
  readonly lineCount: number,
134
134
  ) {
135
- super();
135
+ super(aggregateId, occurredAt);
136
136
  }
137
137
  }
138
138
 
@@ -176,7 +176,7 @@ const order = Order.open('o-1');
176
176
  order.add('p-7', Quantity.create(2));
177
177
  order.place(new Date('2026-01-05T09:00:00Z'));
178
178
 
179
- order.pullEvents(); // [OrderPlaced { aggregateId: 'o-1', lineCount: 1, ... }]
179
+ recordedEventsOf(order); // [OrderPlaced { aggregateId: 'o-1', lineCount: 1, ... }]
180
180
  Quantity.create(2).equals(Quantity.create(2)); // true : même valeur
181
181
  new OrderLine('p-7', Quantity.create(1)).equals(new OrderLine('p-7', Quantity.create(5))); // true : même identité
182
182
  ```
@@ -184,9 +184,9 @@ new OrderLine('p-7', Quantity.create(1)).equals(new OrderLine('p-7', Quantity.cr
184
184
  | Bloc | Ce que le noyau lui donne |
185
185
  |---|---|
186
186
  | `Entity<Id>` | `id` et `equals` : deux entités sont égales quand leur classe et leur id le sont |
187
- | `ValueObject<Props>` | des `props` gelées, `equals` par valeur (les dates par leur instant, les listes et les enregistrements en profondeur), `toJSON` |
188
- | `AggregateRoot<Id>` | une entité avec `version`, le jeton de concurrence optimiste que gère l'adaptateur de son *repository*, `record(event)` pour ses méthodes et `pullEvents()`. Les événements enregistrés ne sont pas énumérables : décomposer, comparer ou sérialiser un agrégat ne les voit jamais |
189
- | `DomainEvent` | une interface : `name`, `occurredAt`, `aggregateId` |
187
+ | `ValueObject<Props>` | une copie de ses `props` gelée en profondeur (`ValueObjectProps` : primitives, dates, objets-valeurs, listes et enregistrements simples de ceux-ci), `equals` par valeur (les dates par leur instant, les listes et les enregistrements en profondeur, un objet-valeur qu'il tient par son propre `equals`), `toJSON` |
188
+ | `AggregateRoot<Id>` | une entité avec une `version` en lecture seule, le jeton de concurrence optimiste que déplace l'adaptateur de son *repository* (`loadedAt`, `optimisticUpdate`), et `record(event)` pour ses méthodes. Une sauvegarde porte la version au rang du dernier événement que l'agrégat a enregistré, et l'avance de un quand il n'en a enregistré aucun. La version et les événements enregistrés ne sont pas énumérables : décomposer, comparer ou sérialiser un agrégat ne les voit jamais |
189
+ | `DomainEvent` | une interface : `name`, `occurredAt`, `aggregateId`. `NamedDomainEvent('<name>')` est sa classe de base : elle écrit le nom une seule fois et porte les deux autres, l'id de l'agrégat en texte quel que soit son type, si bien qu'un événement sans fait propre s'écrit `class OrderPlaced extends NamedDomainEvent('ordering.order.placed') {}`. L'agrégat qui enregistre un événement lui donne son rang dans son histoire, à partir de 1 (`rankOf(event)`), et son identité découle des deux : `eventIdOf(event)` vaut `<name>:<aggregateId>:<rang>`, la même pour l'événement qu'une sauvegarde distribue et pour celui relu depuis un flux. Un test qui construit un événement à la main dit où il se place : `ranked(event, rang)` |
190
190
 
191
191
  Plutôt que de changer l'état depuis l'extérieur, où chaque appelant doit se souvenir de la
192
192
  règle :
@@ -288,7 +288,7 @@ Les codes que lèvent les paquets du kit forment eux aussi une liste, `KitCodes`
288
288
  `NotFound`, `Conflict`, `InvariantViolation`, `Unauthorized`, `NotAcceptable`, `ConcurrencyConflict`,
289
289
  `InvalidCriteria`, `InvalidPageRequest`, `Timeout`, `CircuitOpen`, `BulkheadFull`, `AttemptsExhausted`,
290
290
  `ServiceUnavailable`, `PreconditionFailed`, `PreconditionRequired`, `FileTooLarge`, `UnsupportedMediaType`,
291
- `FileNotFound`, `FileRejected` et `InvalidFileKey`. Une route les nomme dans `errors` et un test les attend
291
+ `FileNotFound`, `FileRejected`, `InvalidFileKey`, `InvalidFileUrlExpiry` et `ForbiddenTransition`. Une route les nomme dans `errors` et un test les attend
292
292
  (`rejects.toMatchObject({ code: KitCodes.Forbidden })`) sans écrire la chaîne : l'éditeur complète la clé,
293
293
  et une clé mal orthographiée ne compile pas.
294
294
 
@@ -500,8 +500,9 @@ réentrance, échecs, ordre des enveloppes) est dans le README de ce *package*.
500
500
  récursion. Puis la transaction est validée.
501
501
  - Les événements ne sont tirés que si l'appel a réussi. Le premier gestionnaire `before-commit`
502
502
  qui échoue rejette l'unité de travail ; le travail, un save ultérieur ou la validation aussi.
503
- Les événements en file sont alors abandonnés et jamais remis sur les agrégats : une nouvelle
504
- tentative les recharge.
503
+ Les événements en file n'atteignent alors aucun gestionnaire, et les agrégats que le travail a
504
+ sauvegardés sont remis comme il les a trouvés, à la version où ils ont été chargés et avec leurs
505
+ événements : les mêmes instances peuvent être sauvegardées à nouveau.
505
506
  - Hors de toute unité de travail, le save distribue avant de se résoudre, les gestionnaires
506
507
  `before-commit` puis les `after-commit`.
507
508
 
@@ -518,14 +519,7 @@ import { NamedDomainEvent,
518
519
  type DomainEvent,
519
520
  } from '@ddd-ts-kit/kernel';
520
521
 
521
- class CartOpened extends NamedDomainEvent('shop.cart.opened') {
522
- constructor(
523
- readonly aggregateId: string,
524
- readonly occurredAt: Date,
525
- ) {
526
- super();
527
- }
528
- }
522
+ class CartOpened extends NamedDomainEvent('shop.cart.opened') {}
529
523
 
530
524
  class Cart extends AggregateRoot {
531
525
  static open(id: string, now: Date): Cart {
@@ -571,10 +565,12 @@ await unitOfWork.run(async () => {
571
565
  // after-commit c1, after-commit c2
572
566
  ```
573
567
 
574
- `pullEvents()` reste public pour cette enveloppe et pour les specs d'un agrégat ; un cas d'usage
575
- et un adaptateur de *repository* ne l'appellent jamais. Un agrégat se reconnaît à ce qu'il fait
576
- (il a `pullEvents`), si bien qu'un contexte compilé contre une autre copie du noyau est suivi lui
577
- aussi.
568
+ Un agrégat n'a aucune méthode qui remet ses événements. L'enveloppe les prend avec
569
+ `takeRecordedEvents(aggregate)`, une fonction de l'infrastructure qu'un cas d'usage et un adaptateur
570
+ de *repository* n'appellent jamais ; une spec les lit avec `recordedBy(aggregate)` de
571
+ `@ddd-ts-kit/testing`. Ce que l'infrastructure garde d'un agrégat (sa version, ses événements
572
+ enregistrés) est indexé pour tout le processus, si bien qu'un contexte compilé contre une autre copie
573
+ du noyau est suivi lui aussi.
578
574
 
579
575
  ### Deux phases
580
576
 
@@ -650,27 +646,42 @@ export const sent = commands.executed; // [new ScheduleReminderCommand('invoice-
650
646
 
651
647
  ### Une unité de travail à vous
652
648
 
653
- La file vit dans une portée `AsyncLocalStorage` ouverte par `withinUnitOfWork(work, transaction)`.
654
- `InMemoryUnitOfWork` et les unités de travail des *packages* ORM reposent dessus, si bien qu'un
655
- `run` appelé directement (un consommateur, un script) a le déroulement d'une commande.
656
- `unitOfWorkMiddleware` l'appelle aussi : une commande est couverte même avec un `UnitOfWork` qui
657
- ne le fait pas. Un `run` imbriqué, ou une commande envoyée depuis une unité de travail, rejoint
658
- la portée en cours : une seule distribution, à la fin de la plus externe, et la phase
659
- `after-commit` après la validation la plus externe. Deux commandes concurrentes ne partagent
660
- jamais une portée.
661
-
662
- Un `UnitOfWork` écrit dans un projet construit `run` dessus. `transaction` commence, appelle ce
663
- qu'on lui donne, valide quand cela s'est résolu et annule quand cela a été rejeté :
649
+ La file vit dans une portée `AsyncLocalStorage` ouverte par l'unité de travail que rend
650
+ `unitOfWorkOver(transaction)`. `InMemoryUnitOfWork` et les unités de travail des *packages* ORM
651
+ reposent dessus, si bien qu'un `run` appelé directement (un consommateur, un script) a le
652
+ déroulement d'une commande. `unitOfWorkMiddleware` ne fait qu'appeler `run` : un `UnitOfWork`
653
+ qui n'ouvre aucune portée est refusé avant le gestionnaire (`UnscopedUnitOfWorkError`). Un `run`
654
+ imbriqué, ou une commande envoyée depuis une unité de travail, rejoint la portée en cours : une
655
+ seule distribution, à la fin de la plus externe, et la phase `after-commit` après la validation
656
+ la plus externe. Deux commandes concurrentes ne partagent jamais une portée, et deux bases de
657
+ données non plus : une unité de travail exécutée dans celle d'une autre base de données ouvre sa
658
+ propre transaction et distribue ses événements avant sa propre validation.
659
+
660
+ Une unité de travail est validée ou annulée en entier. Un `run` imbriqué qui échoue l'interrompt :
661
+ quand l'échec remonte, le `run` le plus externe est rejeté avec lui ; quand le travail l'a
662
+ intercepté et a continué (`await unitOfWork.run(step).catch(fallback)`, une nouvelle tentative
663
+ autour d'une commande envoyée depuis un gestionnaire), le `run` le plus externe est rejeté avec
664
+ une `UnitOfWorkAbortedError` dont la `cause` est cet échec, avant toute distribution
665
+ d'événement. Ce que l'étape en échec a écrit n'est jamais validé à part du reste : décidez avant
666
+ l'écriture, ou laissez passer l'échec.
667
+
668
+ `InMemoryUnitOfWork` n'a pas de transaction, et s'annule quand même : un magasin en mémoire confie
669
+ à `onRollback` l'annulation de chaque écriture, et le `run` le plus externe rejeté les exécute, de la
670
+ plus récente à la plus ancienne. Une `RollbackMap` est une Map qui le fait pour chaque clé, et laisse
671
+ une clé qu'une commande exécutée à côté a écrite depuis ; les *fakes* du kit reposent dessus, et un
672
+ *fake* à vous peut aussi.
673
+
674
+ Un `UnitOfWork` écrit dans un projet repose dessus. `transaction` commence, appelle ce qu'on lui
675
+ donne, valide quand cela s'est résolu et annule quand cela a été rejeté ; elle est appelée pour
676
+ ouvrir une transaction, jamais par un `run` qui en rejoint une :
664
677
 
665
678
  ```ts
666
- run<T>(work: () => Promise<T>): Promise<T> {
667
- return withinUnitOfWork(work, (scoped) => {
668
- if (this.current.getStore() !== undefined) { // imbriqué : rejoindre la transaction
669
- return scoped();
670
- }
679
+ private readonly unitOfWork = unitOfWorkOver((work) =>
680
+ this.database.transaction((transaction) => this.current.run(transaction, work)),
681
+ );
671
682
 
672
- return this.database.transaction((transaction) => this.current.run(transaction, scoped));
673
- });
683
+ run<T>(work: () => Promise<T>): Promise<T> {
684
+ return this.unitOfWork.run(work);
674
685
  }
675
686
  ```
676
687
 
@@ -1178,7 +1189,8 @@ lit par-dessus les *tenants*, voir « Multitenance »), `locale?`, `deadline?`,
1178
1189
  (pour un *job* planifié, l'instant où il était dû), `origin` (`http`, `event`, `schedule`,
1179
1190
  `queue` pour un *job* en arrière-plan, `cli`, ou une chaîne du projet) et `extensions`.
1180
1191
  `executionContext(init)` en construit un et prend le *tenant* de l'acteur ;
1181
- `withActor(context, actor)` est le même travail vu par un autre acteur.
1192
+ `withActor(context, actor)` est le même travail vu par un autre acteur, sans la session ni
1193
+ l'élévation du précédent.
1182
1194
 
1183
1195
  `ExecutionScope` (`current()`, `require()`, `run(context, work)`) donne le contexte du travail en
1184
1196
  cours au code à qui on ne le passe pas. La frontière le pose une fois :
@@ -1308,19 +1320,19 @@ enfants. Interrogez-le avant de construire des champs coûteux ; le kit le fait,
1308
1320
  `loggingMiddleware` et le planificateur. `NoopLogger` répond `false`.
1309
1321
 
1310
1322
  **`flush()`** se résout une fois que chaque entrée journalisée jusque-là, par le *logger* ou un
1311
- enfant, a été remise à sa destination, et ne rejette jamais. On l'appelle une fois, à l'arrêt du
1312
- processus, après la dernière entrée : l'application de `@ddd-ts-kit/di` l'appelle à la fin de
1313
- `stop()`. Ce qui est journalisé après un *flush* n'est pas spécifié, et ne lève jamais : pino et
1314
- `StdoutLogger` l'écrivent encore, winston, dont le *flush* termine le *logger*, l'abandonne. Un
1315
- second appel se résout aussi.
1323
+ enfant, a été remise à sa destination, et ne rejette jamais. Il ne clôt rien : une entrée
1324
+ journalisée ensuite est écrite comme les autres, par chaque *logger* du kit, et un appel
1325
+ ultérieur la vide à son tour. L'application de `@ddd-ts-kit/di` l'appelle à la fin de `stop()`,
1326
+ après la dernière entrée de ses modules.
1316
1327
 
1317
1328
  `InMemoryLogger` prend `{ level?, fields?, base?, scrubMessages? }` comme un vrai adaptateur : un
1318
1329
  seuil (par défaut `debug`, chaque entrée), des champs lus à chaque entrée, des champs ajoutés à
1319
1330
  chaque entrée. Ses `entries` contiennent ce qu'écrit un *logger* : une erreur passée en champ est
1320
1331
  enregistrée sous forme de sa description. `CREDENTIAL_KEYS` et `REDACTED` sont les noms de champs
1321
1332
  et le marqueur avec lesquels `StdoutLogger` et les adaptateurs pino et winston masquent, et
1322
- `isCredentialKey(name)` la comparaison qu'ils partagent, sans tenir compte de la casse ;
1323
- `InMemoryLogger` ne masque rien.
1333
+ `hiddenKeys(added)` la seule question qu'ils posent à un nom de champ : est-il l'une des
1334
+ `CREDENTIAL_KEYS` (`isCredentialKey(name)`) ou l'un des noms qu'un projet ajoute par `redact`,
1335
+ sans tenir compte de la casse. `InMemoryLogger` ne masque rien.
1324
1336
 
1325
1337
  ### Metrics
1326
1338
 
@@ -1384,7 +1396,9 @@ await cache.get(quoteKey('EUR-USD')); // undefined : expirée, selon l'horloge
1384
1396
  ```
1385
1397
 
1386
1398
  La clé porte le type de sa valeur. `InMemoryCache(clock, { maxEntries? })` expire selon le
1387
- `Clock` et est borné. `tenantCacheKey<Quote>(scope, 'quote', pair)` est la même clé confinée au
1399
+ `Clock` et est borné ; il garde et rend une valeur comme le fait un cache partagé, telle que JSON la
1400
+ porte : une copie à chaque écriture et à chaque lecture, une `Date` sous forme de texte, une valeur que
1401
+ JSON ne peut pas porter (un bigint, un cycle) refusée à l'écriture. `tenantCacheKey<Quote>(scope, 'quote', pair)` est la même clé confinée au
1388
1402
  *tenant* du travail en cours : ce qu'un *tenant* a mis en cache n'est jamais servi à un autre.
1389
1403
 
1390
1404
  ### Purger les caches HTTP
@@ -1737,7 +1751,7 @@ const row = { ...toRow(order), ...tenantScopeOf(scope), ...stampCreation(scope,
1737
1751
  await update({ ...toRow(order), ...stampUpdate(scope, clock) }, { id: order.id, ...tenantScopeOf(scope) });
1738
1752
  ```
1739
1753
 
1740
- `stampUpdate(stamp, scope, clock)` est la forme pour un adaptateur qui détient le tampon stocké
1754
+ `restamped(stamp, scope, clock)` sert à un adaptateur qui détient le tampon stocké
1741
1755
  (un store de documents qui réécrit l'enregistrement entier) : il le renvoie entier, création
1742
1756
  intacte. `tenantScopeOf` lève `NoCurrentTenantError` pour un travail qui ne nomme aucun *tenant*,
1743
1757
  si bien qu'une instruction ne peut jamais s'exécuter sans restriction par oubli. Chaque *package*
@@ -2076,7 +2090,7 @@ et une écriture n'a lieu que si son événement est plus récent :
2076
2090
 
2077
2091
  | Règle | |
2078
2092
  |---|---|
2079
- | Tampon | `stampOf(event)` : l'id et l'instant d'un événement d'intégration ; le nom, l'agrégat et l'instant d'un événement du domaine ; plus `stampOf(event, version)` quand l'événement porte une version par clé |
2093
+ | Tampon | `stampOf(event)` : l'id et l'instant d'un événement d'intégration, plus `stampOf(event, version)` quand sa charge utile porte une version par clé ; l'identité et l'instant d'un événement du domaine, avec son rang dans son agrégat pour version, si bien que les événements qu'une commande enregistre sont appliqués dans l'ordre de l'agrégat, même au même instant. Une clé qu'écrivent les événements de plusieurs agrégats n'a pas d'histoire unique : tamponnez-la `{ eventId: eventIdOf(event), occurredAt: event.occurredAt }` |
2080
2094
  | Plus récent | une `version` plus grande quand les deux tampons en portent une ; sinon un instant plus tardif ; au même instant, le plus grand id d'événement. Un même événement n'est jamais plus récent que lui-même. L'ordre est total parmi des tampons qui portent tous une version, et parmi des tampons qui n'en portent aucune ; entre un de chaque les instants décident, ce qui n'est pas un ordre, si bien qu'une clé devrait n'en voir qu'une sorte ([une seule sorte de tampon par clé](../../docs/concepts/cqrs.fr.md#quelle-écriture-pour-quel-événement)) |
2081
2095
  | `upsertIfNewer(key, stamp, next)` | pour un événement qui dit toute la ligne, ou peut la créer : écrit `next(current)`, `current` valant `undefined` quand la clé ne tient aucune ligne ; `stale` quand la ligne contient cet événement ou un plus tardif ; `ignored` quand `next` renvoie `undefined`, ce qui est un filtre (l'événement ne concerne pas ce modèle de lecture) et jamais la façon d'attendre une ligne |
2082
2096
  | `updateIfNewer(key, stamp, change)` | pour un événement qui change une partie d'une ligne qu'un autre événement a créée : écrit `change(current)` ; `stale` quand la ligne, ou la trace de sa suppression, contient cet événement ou un plus tardif ; `missing` quand la clé ne tient aucune ligne, la trace d'une suppression plus ancienne que l'événement, ou une ligne d'un autre locataire : rien n'est écrit, le store ne lève jamais pour cela, et la projection décide. Juste seulement quand les événements de la clé sont appliqués dans l'ordre ([quelle écriture pour quel événement](../../docs/concepts/cqrs.fr.md#quelle-écriture-pour-quel-événement)) |
@@ -2205,7 +2219,7 @@ await new EventStoreProjectionRebuild({
2205
2219
  |---|---|
2206
2220
  | `CatchUpSubscription` | Lit le store après le point de reprise de son abonné (`CheckpointStore`), applique un lot et déplace le point de reprise en une unité de travail. Un échec n'applique rien du lot ; deux exécutions d'un même abonné ne le déplacent jamais toutes les deux (`ConcurrencyError`). Une nouvelle projection commence à zéro, si bien qu'elle rattrape tout l'historique |
2207
2221
  | `applyingProjection(projection, serializer)` | (`@ddd-ts-kit/kernel/declarations`) remet à la méthode `@On` qui l'applique chaque événement stocké, relu par le sérialiseur de son agrégat ; passe sur le reste du store |
2208
- | `storedStampOf(event)` | Le tampon d'un événement lu depuis le store : son id, son instant et sa version dans son flux, si bien que les lignes d'un même flux sont ordonnées par le flux, pas par les horloges. `undefined` pour un événement qui ne vient pas d'un store |
2222
+ | `stampOf(event)` | Le tampon d'un événement relu depuis le store est celui du même événement distribué par sa sauvegarde : son identité, son instant et, pour version, son rang dans son flux, si bien que les lignes d'un même flux sont ordonnées par le flux, pas par les horloges, et qu'un événement appliqué deux fois ne change rien |
2209
2223
  | `EventStoreProjectionRebuild` | Remplit une copie vide de la table en rejouant le store depuis la position zéro à travers la projection construite sur la copie (`ShadowReadModelStore`) ; puis, en une transaction, retient les écrivains, rejoue ce qui a été ajouté entre-temps et met la copie à la place de la table. L'abonnement continue depuis son point de reprise ; ce qu'il applique à nouveau est périmé face à la copie. Une reconstruction échouée laisse la table telle qu'elle était |
2210
2224
 
2211
2225
  Une projection alimentée par le store n'applique que les événements du domaine de son contexte :
@@ -2285,7 +2299,7 @@ export class AttendanceRecord extends EventSourcedAggregate<AttendanceEvent, Att
2285
2299
  | `appendChanges(aggregate, append)` | Ce qu'appelle un adaptateur de *repository* : les événements enregistrés depuis le chargement et la version que le flux doit encore avoir ; en cas de succès l'agrégat est à la nouvelle version |
2286
2300
  | `EventStore` | Le port : `append(stream, expectedVersion, events)` (une `ConcurrencyError` quand quelqu'un a ajouté d'abord, rien n'en est gardé), `readStream(stream, after?)`, `readAll(after, limit)` dans l'ordre où les ajouts ont été validés, `head()`. `InMemoryEventStore` ici ; PostgreSQL par chaque adaptateur ORM. Tenu à `eventStoreContract` |
2287
2301
  | `defineStoredEvent(Event, spec)` | Comment un événement est stocké : `version` de sa forme, `encode(event): NamedData` (données simples, dates gardées en texte ISO), `decode(data, envelope)` qui lit chaque champ par type (`data.text('x')`, `data.instant('at')`, `data.record('amount')`), et des `upcasters` depuis chaque version antérieure |
2288
- | `EventSerializer<E>` | Chaque événement stocké d'un agrégat (`StoredEventTypes<E>` : une entrée par événement, sinon cela ne compile pas). Un événement stocké n'est jamais réécrit : il passe par un *upcaster* à la lecture. Un événement d'une forme plus récente que ce que connaît la version publiée, ou une version sans *upcaster*, est une `UnreadableEventError` |
2302
+ | `EventSerializer<E>` | Chaque événement stocké d'un agrégat (`StoredEventTypes<E>` : une entrée par événement, sinon cela ne compile pas). Un événement stocké n'est jamais réécrit : il passe par un *upcaster* à la lecture. Un événement est stocké sous sa propre identité (`eventIdOf`), qu'aucun générateur ne tire. Un événement d'une forme plus récente que ce que connaît la version publiée, ou une version sans *upcaster*, est une `UnreadableEventError` |
2289
2303
  | `EventSourcedRepository` | Ce à quoi délègue l'adaptateur de *repository* : `findById` rejoue le flux `<category>-<id>` (depuis le dernier *snapshot*), `save` ajoute dans la transaction de l'unité de travail ; les événements partent ensuite avec l'enregistrement comme n'importe quels autres |
2290
2304
  | `SnapshotPolicy` | Par agrégat : `every` tant d'événements, une `version` de la forme (une autre est ignorée, le flux rejoué), `encode`, qui scelle une valeur personnelle avec `personalData` comme dans un événement, et `decode`. `expectSnapshotEquivalence` de `@ddd-ts-kit/testing` prouve qu'un *snapshot* reconstruit l'état que donne un rejeu complet |
2291
2305
  | `personalData(subject, value)` | Marque une valeur personnelle dans `encode`. `PersonalDataCipher` sur un `SubjectKeyStore` la scelle avec la clé de sa personne concernée (AES-256-GCM) ; `SubjectKeyStore.erase(subject)` détruit la clé, et un rejeu lit alors `ERASED_PERSONAL_DATA`. `decode` lit une valeur personnelle avec `data.personalText('x')`, `data.personalInstant('at')` ou `data.personal('email', Email.of)`, qui répondent `undefined` une fois la personne effacée : une valeur qui n'est pas un texte libre ne rend jamais l'agrégat illisible ; `data.isErased('x')` dit si elle l'a été. Le chiffreur ouvre une valeur effacée en `ErasedValue`, `{ $erased: { key } }`, jamais en texte : `data.text` la lit `ERASED_PERSONAL_DATA`, un texte qui se lit `[erased]` n'est pas pris pour elle, et un upcaster voit cette forme |
package/README.md CHANGED
@@ -32,11 +32,11 @@ starts, so a business rule never changes with a library.
32
32
  | Domain | `Entity`, `AggregateRoot` (version, recorded events), `ValueObject`, `DomainEvent`, `DomainError` with a stable `code`, `ConceptError` (the errors of one concept, each built by a static factory: see "Domain errors"), `DomainRefusal` (one class per refusal, built by static factories), `FactualRefusal`, `isRefusal`, `CodeOf`, `RefusalOf`, `Refusal`, `RefusalFacts`, the generic `InvariantViolation`, `NotFoundError`, `ConflictError` (and `UniqueViolationError`, a value a unique constraint keeps already held), `ConcurrencyError`, `PreconditionFailedError`, `Result` with `ok`, `err`, `unwrap` |
33
33
  | Ports | `Clock`, `IdGenerator`, `UnitOfWork`, `Repository` (abstract classes: each one is its own injection token), `UseCase`, `DependencyKind` (the roles a binding declares, read by di, tracing and aspects: `repository`, `gateway`, `external`, `use-case`, `publisher`, `consumer`, `domain-event-handler`, `job`) |
34
34
  | Buses | `Command`, `Query`, `CommandBus`, `QueryBus`, `BusMiddleware`, the in-process `InMemoryCommandBus` and `InMemoryQueryBus` (`register(type, handler, { context })` names the bounded context in `MessageInfo`), `unitOfWorkMiddleware` |
35
- | Events | `IntegrationEvent`, `IntegrationEventPublisher`, `IntegrationEventSubscriber`, `EventBus` (both at once), `EventSubscribers` (the subscriber of each bounded context), `ProcessedEventStore`, `idempotent`, `InMemoryEventBus` (runs every handler of an event, then rejects with an `AggregateError` of the failures; with `{ failures: 'as-thrown' }`, the default in a later minor version, the failure of a single handler is rethrown as it is, with its `code`), `EventBusFailures`, `DomainEventDispatcher`, `IntegrationEventCallback` and `DomainEventCallback` (the functions a subscriber and a dispatcher are given), `executionContextOfEvent`, `inEventScope`, `scopedPublisher`, `EventDelivery` (what a provider says of one delivery: attempt, last attempt, transport, source, consumer), `messagingSystemOf` |
36
- | Domain events and the unit of work | `dispatchingOnSave` (the wrapper that makes a repository hand over what the aggregates it is given recorded), `announceDomainEvents`, `withinUnitOfWork` (what every `UnitOfWork.run` is built on: queue, dispatch before the commit, `after-commit` phase), `unitOfWorkStage` and `UnitOfWorkStage`, `DomainEventPhase`, `DomainEventSubscription`, `SaveAfterCommitError`, `AfterCommitFailure`, `reportAfterCommitFailures`, `InMemoryDomainEventDispatcher` |
35
+ | Events | `IntegrationEvent`, `IntegrationEventPublisher`, `IntegrationEventSubscriber`, `EventBus` (both at once), `EventSubscribers` (the subscriber of each bounded context), `ProcessedEventStore`, `idempotent`, `InMemoryEventBus` (runs every handler of an event, then rejects with the failure of a single handler as it is, with its `code`, and with an `AggregateError` of several; an event is delivered and logged in `published` as a broker carries it, as JSON: a copy, a `Date` as its text, an event JSON cannot carry refused), `DomainEventDispatcher`, `IntegrationEventCallback` and `DomainEventCallback` (the functions a subscriber and a dispatcher are given), `executionContextOfEvent`, `inEventScope`, `scopedPublisher`, `EventDelivery` (what a provider says of one delivery: attempt, last attempt, transport, source, consumer), `messagingSystemOf` |
36
+ | Domain events and the unit of work | `dispatchingOnSave` (the wrapper that makes a repository hand over what the aggregates it is given recorded), `announceDomainEvents`, `unitOfWorkOver` (what every `UnitOfWork` is built on: queue, dispatch before the commit, `after-commit` phase), `UnscopedUnitOfWorkError`, `UnitOfWorkAbortedError`, `unitOfWorkStage` and `UnitOfWorkStage`, `DomainEventPhase`, `DomainEventSubscription`, `SaveAfterCommitError`, `AfterCommitFailure`, `reportAfterCommitFailures`, `InMemoryDomainEventDispatcher` |
37
37
  | State machines | `defineStateMachine`, `StateMachine`, `TransitionError`, `InvalidStateMachineError`, `mermaidOfStateMachine` (see "State machines") |
38
38
  | Actor | `Actor`, `AuthorizedCommand`, `AuthorizedQuery`, `ActorContext`, `systemActor` |
39
- | Standard interfaces | `Session`, `ExecutionContext` and `ExecutionScope`, `Logger`, `Metrics`, `ErrorReporter`, `Cache`, `CacheInvalidation` and `CachePurger` (with `cacheTag`, `tenantCacheTags`, `CachePurgeRequest`, `PublishedCacheInvalidation`, `PurgingPublisher`, `RepeatedCachePurger`: see "Purging the HTTP caches"), `Lock`, `RateLimiter`, `Page` and `PageRequest`, `AuditStamp`, `TenantScoped`, `AuditTrail`, `AuditReader` and `AuditEntry` |
39
+ | Standard interfaces | `Session`, `ExecutionContext` and `ExecutionScope`, `Logger`, `Metrics`, `ErrorReporter`, `Cache`, `CacheInvalidation` and `CachePurger` (with `cacheTag`, `tenantCacheTags`, `CachePurgeRequest`, `PublishedCacheInvalidation`, `PurgingPublisher`, `RepeatedCachePurger`: see "Purging the HTTP caches"), `Lock`, `RateLimiter`, `Page` and `PageRequest`, `AuditStamp`, `TenantScoped`, `AuditTrail`, `AuditReader` and `AuditEntry`, `safely` (runs a hook, a logger or a meter and drops what it throws: observation never breaks what it observes) |
40
40
  | Scheduled jobs | `JobScheduler`, `ScheduledJob`, `JobExecution`, `JobSchedule`, `JobOptions`, `JobDefinition`, `JobRun`, `JobDescription`, `parseJobSchedule`, `describeJobSchedule`, `jobPolicy`, `executionContextOfJob` |
41
41
  | Background jobs | `JobQueue`, `BackgroundJob`, `BackgroundJobExecution`, `BackgroundJobPayloadSchema`, `processTimeoutDuePayload`, `EnqueueOptions`, `QueuedJob`, `QueuedJobStatus`, `backgroundJobPolicy`, `retryDelayMs`, `executionContextOfBackgroundJob`, `whenCommitted` (see "JobQueue") |
42
42
  | Process managers | `ProcessManager`, `ProcessDecision`, `ProcessRunner`, `ProcessStore`, `InMemoryProcessStore`, `UnreadableProcessStateError` (see "ProcessRunner and ProcessStore") |
@@ -45,9 +45,9 @@ starts, so a business rule never changes with a library.
45
45
  | Event sourcing | `EventSourcedAggregate`, `EventStore`, `defineStoredEvent`, `EventSerializer`, `EventSourcedRepository`, `SnapshotPolicy`, `personalData`, `PersonalDataCipher`, `CatchUpSubscription`, `EventStoreProjectionRebuild`, `InMemoryEventStore`, `PostgresEventStore` (see "Event sourcing") |
46
46
  | Personal data | `personalFields`, `PersonalDataErasure`, `PersonalDataExport`, `eraseDataSubject`, `exportDataSubject`, `PersonalDataExportDocument`, `inEachTenant`, `recordsInEachTenant`, `isDataSubjectId`, `PersonalDataRecord`, `InMemoryPersonalData` (see "Personal data") |
47
47
  | Read side | `Criteria`, `defineCriteria`, `validateCriteria`, `scoped`, `planCriteria`, `evaluateCriteria`, `pageOfPlan`, `hydrate`, `ReadModelStore`, `stampOf`, `TableReadModelStore`, `ProjectionRebuild`, `InMemoryReadModelStore` (see "Criteria", "Hydration" and "Projections") |
48
- | Persistence helpers | `optimisticUpdate`, `expectVersion` (the version a caller read, `If-Match` over HTTP, still the current one, else `PreconditionFailedError`: 412), `schemaNameOf`, `stampCreation`, `stampUpdate`, `tenantScopeOf`, `encodeCursor`, `decodeCursor` |
48
+ | Persistence helpers | `aggregateMapper` (a mapper that declares the state and never the version), `loadedAt`, `optimisticUpdate`, `expectVersion` (the version a caller read, `If-Match` over HTTP, still the current one, else `PreconditionFailedError`: 412), `schemaNameOf`, `stampCreation`, `stampUpdate`, `restamped`, `tenantScopeOf`, `encodeCursor`, `decodeCursor` |
49
49
  | Error reporting | `ErrorReporter`, `ErrorReport`, `errorReportOf`, `reportOnce`, `isUnexpectedError`, `errorReportingMiddleware`, `DeadLetterReports`, `reportProcessFailures`, `NoopErrorReporter` |
50
- | Doubles | `FixedClock`, `SequentialIdGenerator`, `InMemoryUnitOfWork`, `FixedActorContext`, `FixedExecutionScope`, `InMemoryLogger`, `InMemoryMetrics`, `InMemoryErrorReporter`, `InMemoryCache`, `InMemoryCacheInvalidation`, `InMemoryCachePurger`, `InMemoryLock`, `InMemoryRateLimiter` |
50
+ | Doubles | `FixedClock`, `SequentialIdGenerator`, `InMemoryUnitOfWork`, `RollbackMap`, `onRollback`, `FixedActorContext`, `FixedExecutionScope`, `InMemoryLogger`, `InMemoryMetrics`, `InMemoryErrorReporter`, `InMemoryCache`, `InMemoryCacheInvalidation`, `InMemoryCachePurger`, `InMemoryLock`, `InMemoryRateLimiter` |
51
51
  | Testing (`@ddd-ts-kit/kernel/testing`) | `RecordingCommandBus`, `RecordingQueryBus`: buses that keep every message they are handed, in order (`executed`), and answer what the spec told them (`answering(type, answer)`), nothing otherwise (see "The spec of a reaction") |
52
52
  | Declarations (`@ddd-ts-kit/kernel/declarations`) | `Requires`, `Public`, `CommandHandler`, `QueryHandler`, `IntegrationEventHandler`, `DomainEventHandler`, `Scheduled`, `Background`, `Projection`, `On`, `applyingProjection`, `Repository`, `Gateway`, `Adapter`, `Policy`, `Edge` (for the decorators of a transport package, such as `@Controller`), `injected`, `injectedDependencies`, `declarationOf`, `listDeclarations`, `DeclarationError`, `Token`, `describeToken`, `tokenIdentity`, `portDefect` |
53
53
 
@@ -60,7 +60,7 @@ file, and `ddd-ts-kit generate` writes them):
60
60
 
61
61
  <!-- checked sample -->
62
62
  ```ts
63
- import { AggregateRoot, DomainRefusal, Entity, ValueObject, NamedDomainEvent } from '@ddd-ts-kit/kernel';
63
+ import { AggregateRoot, DomainRefusal, Entity, ValueObject, NamedDomainEvent, recordedEventsOf } from '@ddd-ts-kit/kernel';
64
64
 
65
65
  // The codes of the context, in <context>.codes.ts, and its refusals, one class each (see "Domain errors").
66
66
  export const OrderingCodes = {
@@ -125,11 +125,11 @@ export class OrderLine extends Entity {
125
125
  // A domain event: a fact of the past, named <context>.<aggregate>.<fact>.
126
126
  export class OrderPlaced extends NamedDomainEvent('ordering.order.placed') {
127
127
  constructor(
128
- readonly aggregateId: string,
129
- readonly occurredAt: Date,
128
+ aggregateId: string,
129
+ occurredAt: Date,
130
130
  readonly lineCount: number,
131
131
  ) {
132
- super();
132
+ super(aggregateId, occurredAt);
133
133
  }
134
134
  }
135
135
 
@@ -173,7 +173,7 @@ const order = Order.open('o-1');
173
173
  order.add('p-7', Quantity.create(2));
174
174
  order.place(new Date('2026-01-05T09:00:00Z'));
175
175
 
176
- order.pullEvents(); // [OrderPlaced { aggregateId: 'o-1', lineCount: 1, ... }]
176
+ recordedEventsOf(order); // [OrderPlaced { aggregateId: 'o-1', lineCount: 1, ... }]
177
177
  Quantity.create(2).equals(Quantity.create(2)); // true: same value
178
178
  new OrderLine('p-7', Quantity.create(1)).equals(new OrderLine('p-7', Quantity.create(5))); // true: same identity
179
179
  ```
@@ -181,9 +181,9 @@ new OrderLine('p-7', Quantity.create(1)).equals(new OrderLine('p-7', Quantity.cr
181
181
  | Block | What the kernel gives it |
182
182
  |---|---|
183
183
  | `Entity<Id>` | `id` and `equals`: two entities are equal when their class and their id are |
184
- | `ValueObject<Props>` | frozen `props`, `equals` by value (dates by their time, lists and records deeply), `toJSON` |
185
- | `AggregateRoot<Id>` | an entity with `version`, the optimistic concurrency token its repository adapter manages, `record(event)` for its methods and `pullEvents()`. The recorded events are not enumerable: spreading, comparing or serialising an aggregate never sees them |
186
- | `DomainEvent` | an interface: `name`, `occurredAt`, `aggregateId` |
184
+ | `ValueObject<Props>` | a copy of its `props` frozen in depth (`ValueObjectProps`: primitives, dates, value objects, lists and plain records of those), `equals` by value (dates by their time, lists and records deeply, a value object it holds by its own `equals`), `toJSON` |
185
+ | `AggregateRoot<Id>` | an entity with a read-only `version`, the optimistic concurrency token its repository adapter moves (`loadedAt`, `optimisticUpdate`), and `record(event)` for its methods. A save moves the version to the rank of the last event the aggregate recorded, and by one when it recorded none. The version and the recorded events are not enumerable: spreading, comparing or serialising an aggregate never sees them |
186
+ | `DomainEvent` | an interface: `name`, `occurredAt`, `aggregateId`. `NamedDomainEvent('<name>')` is its base class: it writes the name once and carries the other two, the id of the aggregate as text whatever its type, so an event with no fact of its own is `class OrderPlaced extends NamedDomainEvent('ordering.order.placed') {}`. The aggregate that records an event gives it its rank in its history, from 1 (`rankOf(event)`), and its identity follows from both: `eventIdOf(event)` is `<name>:<aggregateId>:<rank>`, the same for the event a save dispatches and for the one read back from a stream. A test that builds an event by hand says where it stands: `ranked(event, rank)` |
187
187
 
188
188
  Instead of changing the state from outside, where every caller has to remember the rule:
189
189
 
@@ -283,7 +283,7 @@ The codes the packages of the kit raise are a list too, `KitCodes`, with its typ
283
283
  `NotFound`, `Conflict`, `InvariantViolation`, `Unauthorized`, `NotAcceptable`, `ConcurrencyConflict`,
284
284
  `InvalidCriteria`, `InvalidPageRequest`, `Timeout`, `CircuitOpen`, `BulkheadFull`, `AttemptsExhausted`,
285
285
  `ServiceUnavailable`, `PreconditionFailed`, `PreconditionRequired`, `FileTooLarge`, `UnsupportedMediaType`,
286
- `FileNotFound`, `FileRejected` and `InvalidFileKey`. A route names them in `errors` and a test expects them
286
+ `FileNotFound`, `FileRejected`, `InvalidFileKey`, `InvalidFileUrlExpiry` and `ForbiddenTransition`. A route names them in `errors` and a test expects them
287
287
  (`rejects.toMatchObject({ code: KitCodes.Forbidden })`) without writing the string: the editor completes
288
288
  the key, and a misspelled one does not compile.
289
289
 
@@ -491,7 +491,8 @@ failures, wrapper order) is in the README of that package. In short:
491
491
  without recursion. Then the transaction commits.
492
492
  - The events are pulled only when the call succeeded. The first `before-commit` handler that
493
493
  fails rejects the unit of work; so does the work, a later save or the commit. The queued
494
- events are then dropped and never put back on the aggregates: a retry reloads them.
494
+ events then reach no handler, and the aggregates the work saved are put back as it found them,
495
+ at the version they were loaded at and with their events: the same instances can be saved again.
495
496
  - Outside any unit of work the save dispatches before it resolves, `before-commit` handlers
496
497
  then `after-commit` ones.
497
498
 
@@ -507,14 +508,7 @@ import { NamedDomainEvent,
507
508
  type DomainEvent,
508
509
  } from '@ddd-ts-kit/kernel';
509
510
 
510
- class CartOpened extends NamedDomainEvent('shop.cart.opened') {
511
- constructor(
512
- readonly aggregateId: string,
513
- readonly occurredAt: Date,
514
- ) {
515
- super();
516
- }
517
- }
511
+ class CartOpened extends NamedDomainEvent('shop.cart.opened') {}
518
512
 
519
513
  class Cart extends AggregateRoot {
520
514
  static open(id: string, now: Date): Cart {
@@ -560,9 +554,11 @@ await unitOfWork.run(async () => {
560
554
  // after-commit c1, after-commit c2
561
555
  ```
562
556
 
563
- `pullEvents()` stays public for this wrapper and for the specs of an aggregate; a use case and
564
- a repository adapter never call it. An aggregate is recognised by what it does (it has
565
- `pullEvents`), so a context compiled against another copy of the kernel is followed too.
557
+ An aggregate has no method that hands its events over. The wrapper takes them with
558
+ `takeRecordedEvents(aggregate)`, a function of the infrastructure that a use case and a repository
559
+ adapter never call; a spec reads them with `recordedBy(aggregate)` of `@ddd-ts-kit/testing`. What
560
+ the infrastructure keeps of an aggregate (its version, its recorded events) is keyed process-wide,
561
+ so a context compiled against another copy of the kernel is followed too.
566
562
 
567
563
  ### Two phases
568
564
 
@@ -635,26 +631,39 @@ export const sent = commands.executed; // [new ScheduleReminderCommand('invoice-
635
631
 
636
632
  ### A unit of work of your own
637
633
 
638
- The queue lives in an `AsyncLocalStorage` scope opened by `withinUnitOfWork(work, transaction)`.
639
- `InMemoryUnitOfWork` and the units of work of the ORM packages are built on it, so a `run`
640
- called directly (a consumer, a script) has the timing of a command. `unitOfWorkMiddleware`
641
- calls it too: a command is covered even with a `UnitOfWork` that does not. A nested `run`, or a
642
- command sent from inside a unit of work, joins the scope in progress: one dispatch, at the end
643
- of the outermost, and the `after-commit` phase after the outermost commit. Two concurrent
644
- commands never share a scope.
645
-
646
- A `UnitOfWork` written in a project builds `run` on it. `transaction` begins, calls what it is
647
- given, commits when it resolved and rolls back when it rejected:
634
+ The queue lives in an `AsyncLocalStorage` scope opened by the unit of work that
635
+ `unitOfWorkOver(transaction)` answers. `InMemoryUnitOfWork` and the units of work of the ORM
636
+ packages are built on it, so a `run` called directly (a consumer, a script) has the timing of a
637
+ command. `unitOfWorkMiddleware` only calls `run`: a `UnitOfWork` that opens no scope is refused
638
+ before the handler (`UnscopedUnitOfWorkError`). A nested `run`, or a command sent from inside a
639
+ unit of work, joins the scope in progress: one dispatch, at the end of the outermost, and the
640
+ `after-commit` phase after the outermost commit. Two concurrent commands never share a scope,
641
+ and neither do two databases: a unit of work run inside the one of another database opens its
642
+ own transaction and dispatches its events before its own commit.
643
+
644
+ A unit of work commits or rolls back as a whole. A nested `run` that fails aborts it: when the
645
+ failure travels up, the outermost `run` rejects with it; when the work caught it and went on
646
+ (`await unitOfWork.run(step).catch(fallback)`, a retry around a command sent from a handler),
647
+ the outermost `run` rejects with a `UnitOfWorkAbortedError` whose `cause` is that failure,
648
+ before any event is dispatched. What the failed step wrote is never committed apart from the
649
+ rest: decide before the write, or let the failure through.
650
+
651
+ `InMemoryUnitOfWork` has no transaction, and rolls back all the same: a store in memory hands
652
+ `onRollback` the undo of each write, and the outermost `run` that rejects runs them, newest first.
653
+ A `RollbackMap` is a Map that does so for each key, and leaves a key a command running alongside
654
+ wrote since; the fakes of the kit are built on it, and a fake of your own can be too.
655
+
656
+ A `UnitOfWork` written in a project is built on it. `transaction` begins, calls what it is
657
+ given, commits when it resolved and rolls back when it rejected; it is called to open a
658
+ transaction, never by a `run` that joins one:
648
659
 
649
660
  ```ts
650
- run<T>(work: () => Promise<T>): Promise<T> {
651
- return withinUnitOfWork(work, (scoped) => {
652
- if (this.current.getStore() !== undefined) { // nested: join the transaction
653
- return scoped();
654
- }
661
+ private readonly unitOfWork = unitOfWorkOver((work) =>
662
+ this.database.transaction((transaction) => this.current.run(transaction, work)),
663
+ );
655
664
 
656
- return this.database.transaction((transaction) => this.current.run(transaction, scoped));
657
- });
665
+ run<T>(work: () => Promise<T>): Promise<T> {
666
+ return this.unitOfWork.run(work);
658
667
  }
659
668
  ```
660
669
 
@@ -1138,7 +1147,8 @@ What every unit of work carries, whatever started it: `correlationId`, `causatio
1138
1147
  `locale?`, `deadline?`, `scheduledAt?` (for a scheduled job, the instant it was due), `origin`
1139
1148
  (`http`, `event`, `schedule`, `queue` for a background job, `cli`, or a string of the project)
1140
1149
  and `extensions`. `executionContext(init)` builds one and takes the tenant of the actor;
1141
- `withActor(context, actor)` is the same work seen as another actor.
1150
+ `withActor(context, actor)` is the same work seen as another actor, without the session and
1151
+ the elevation of the previous one.
1142
1152
 
1143
1153
  `ExecutionScope` (`current()`, `require()`, `run(context, work)`) gives the context of the work
1144
1154
  in progress to code that is not handed it. The boundary sets it once:
@@ -1263,17 +1273,18 @@ logger and its children. Ask it before building fields that cost; the kit does,
1263
1273
  `loggingMiddleware` and the scheduler. `NoopLogger` answers `false`.
1264
1274
 
1265
1275
  **`flush()`** resolves once every entry logged so far, through the logger or a child, was
1266
- handed to its destination, and never rejects. It is called once, when the process stops, after
1267
- the last entry: the application of `@ddd-ts-kit/di` calls it at the end of `stop()`. What is
1268
- logged after a flush is unspecified, and never throws: pino and `StdoutLogger` still write it,
1269
- winston, whose flush ends the logger, drops it. A second call resolves too.
1276
+ handed to its destination, and never rejects. It ends nothing: an entry logged afterwards is
1277
+ written like the others, by every logger of the kit, and a later call flushes it in turn. The
1278
+ application of `@ddd-ts-kit/di` calls it at the end of `stop()`, after the last entry of its
1279
+ modules.
1270
1280
 
1271
1281
  `InMemoryLogger` takes `{ level?, fields?, base?, scrubMessages? }` like a real adapter: a
1272
1282
  threshold (default `debug`, every entry), fields read at each entry, fields added to every
1273
1283
  entry. Its `entries` hold what a logger writes: an error passed as a field is recorded as its
1274
1284
  description. `CREDENTIAL_KEYS` and `REDACTED` are the field names and the marker `StdoutLogger`
1275
- and the pino and winston adapters redact with, and `isCredentialKey(name)` the comparison they
1276
- share, without case; `InMemoryLogger` redacts nothing.
1285
+ and the pino and winston adapters redact with. `hiddenKeys(added)` is the one question they
1286
+ ask of a field name: whether it is one of `CREDENTIAL_KEYS` (`isCredentialKey(name)`) or of the
1287
+ names a project adds through `redact`, without case. `InMemoryLogger` redacts nothing.
1277
1288
 
1278
1289
  ### Metrics
1279
1290
 
@@ -1335,7 +1346,9 @@ await cache.get(quoteKey('EUR-USD')); // undefined: expired, by the clock
1335
1346
  ```
1336
1347
 
1337
1348
  The key carries the type of its value. `InMemoryCache(clock, { maxEntries? })` expires by the
1338
- `Clock` and is bounded. `tenantCacheKey<Quote>(scope, 'quote', pair)` is the same key confined to
1349
+ `Clock` and is bounded; it keeps and hands a value as a shared cache does, as JSON carries it: a
1350
+ copy at each write and each read, a `Date` as its text, a value JSON cannot carry (a bigint, a
1351
+ cycle) refused at the write. `tenantCacheKey<Quote>(scope, 'quote', pair)` is the same key confined to
1339
1352
  the tenant of the work in progress: what one tenant cached is never served to another.
1340
1353
 
1341
1354
  ### Purging the HTTP caches
@@ -1664,7 +1677,7 @@ const row = { ...toRow(order), ...tenantScopeOf(scope), ...stampCreation(scope,
1664
1677
  await update({ ...toRow(order), ...stampUpdate(scope, clock) }, { id: order.id, ...tenantScopeOf(scope) });
1665
1678
  ```
1666
1679
 
1667
- `stampUpdate(stamp, scope, clock)` is the form for an adapter that holds the stored stamp (a
1680
+ `restamped(stamp, scope, clock)` is for an adapter that holds the stored stamp (a
1668
1681
  document store rewriting the whole record): it answers it whole, creation untouched.
1669
1682
  `tenantScopeOf` raises `NoCurrentTenantError` for work that names no tenant, so a statement can
1670
1683
  never run unscoped by omission. Every adapter package names the columns the same way:
@@ -1992,7 +2005,7 @@ write happens only if its event is newer:
1992
2005
 
1993
2006
  | Rule | |
1994
2007
  |---|---|
1995
- | Stamp | `stampOf(event)`: the id and the instant of an integration event; the name, the aggregate and the instant of a domain event; plus `stampOf(event, version)` when the event carries a per-key version |
2008
+ | Stamp | `stampOf(event)`: the id and the instant of an integration event, plus `stampOf(event, version)` when its payload carries a per-key version; the identity and the instant of a domain event, with its rank in its aggregate as the version, so the events one command records are applied in the order of the aggregate even at the same instant. A key the events of several aggregates write has no single history: stamp it `{ eventId: eventIdOf(event), occurredAt: event.occurredAt }` |
1996
2009
  | Newer | a greater `version` when both stamps carry one; else a later instant; at the same instant, the greater event id. The same event is never newer than itself. The order is total among stamps that all carry a version, and among stamps that carry none; between one of each the instants decide, which is not an order, so a key should see one kind ([one kind of stamp per key](../../docs/concepts/cqrs.md#which-write-for-which-event)) |
1997
2010
  | `upsertIfNewer(key, stamp, next)` | for an event that says the whole row, or may create it: writes `next(current)`, `current` being `undefined` when the key holds no row; `stale` when the row holds this event or a later one; `ignored` when `next` answers `undefined`, which is a filter (the event does not concern this read model) and never the way to wait for a row |
1998
2011
  | `updateIfNewer(key, stamp, change)` | for an event that changes part of a row another event created: writes `change(current)`; `stale` when the row, or the trace of its deletion, holds this event or a later one; `missing` when the key holds no row, the trace of a deletion older than the event, or a row of another tenant: nothing is written, the store never throws for it, and the projection decides. Right only when the events of the key are applied in order ([which write for which event](../../docs/concepts/cqrs.md#which-write-for-which-event)) |
@@ -2115,7 +2128,7 @@ await new EventStoreProjectionRebuild({
2115
2128
  |---|---|
2116
2129
  | `CatchUpSubscription` | Reads the store after the checkpoint of its subscriber (`CheckpointStore`), applies a batch and moves the checkpoint in one unit of work. A failure applies none of the batch; two runs of one subscriber never both move it (`ConcurrencyError`). A new projection starts at zero, so it catches up on the whole history |
2117
2130
  | `applyingProjection(projection, serializer)` | (`@ddd-ts-kit/kernel/declarations`) hands each stored event an `@On` method applies, read back by the serializer of its aggregate, to that method; passes over the rest of the store |
2118
- | `storedStampOf(event)` | The stamp of an event read from the store: its id, instant and version in its stream, so the rows of one stream are ordered by the stream, not by clocks. `undefined` for an event that did not come from a store |
2131
+ | `stampOf(event)` | The stamp of an event read back from the store is the one of the same event dispatched by its save: its identity, its instant and, as the version, its rank in its stream, so the rows of one stream are ordered by the stream, not by clocks, and an event applied twice changes nothing |
2119
2132
  | `EventStoreProjectionRebuild` | Fills an empty copy of the table by replaying the store from position zero through the projection built over the copy (`ShadowReadModelStore`); then, in one transaction, holds the writers, replays what was appended meanwhile and puts the copy in place of the table. The subscription goes on from its checkpoint; what it applies again is stale against the copy. A failed rebuild leaves the table as it was |
2120
2133
 
2121
2134
  A projection fed by the store applies the domain events of its context only: an integration
@@ -2195,7 +2208,7 @@ export class AttendanceRecord extends EventSourcedAggregate<AttendanceEvent, Att
2195
2208
  | `appendChanges(aggregate, append)` | What a repository adapter calls: the events recorded since the load and the version the stream must still have; on success the aggregate is at the new version |
2196
2209
  | `EventStore` | The port: `append(stream, expectedVersion, events)` (a `ConcurrencyError` when somebody appended first, nothing kept of it), `readStream(stream, after?)`, `readAll(after, limit)` in the order the appends committed, `head()`. `InMemoryEventStore` here; PostgreSQL through every ORM adapter. Held to `eventStoreContract` |
2197
2210
  | `defineStoredEvent(Event, spec)` | How one event is stored: `version` of its shape, `encode(event): NamedData` (plain data, dates kept as ISO text), `decode(data, envelope)` reading each field by type (`data.text('x')`, `data.instant('at')`, `data.record('amount')`), and `upcasters` from each older version |
2198
- | `EventSerializer<E>` | Every stored event of one aggregate (`StoredEventTypes<E>`: one entry per event, or it does not compile). A stored event is never rewritten: it is upcast when read. An event of a later shape than the release knows, or a version without upcaster, is an `UnreadableEventError` |
2211
+ | `EventSerializer<E>` | Every stored event of one aggregate (`StoredEventTypes<E>`: one entry per event, or it does not compile). A stored event is never rewritten: it is upcast when read. An event is stored under its own identity (`eventIdOf`), which no generator draws. An event of a later shape than the release knows, or a version without upcaster, is an `UnreadableEventError` |
2199
2212
  | `EventSourcedRepository` | What the repository adapter delegates to: `findById` replays the stream `<category>-<id>` (from the last snapshot), `save` appends in the transaction of the unit of work; the events then leave with the save like any other |
2200
2213
  | `SnapshotPolicy` | Per aggregate: `every` so many events, a `version` of the shape (another one is ignored, the stream replayed), `encode`, which seals a personal value with `personalData` as in an event, and `decode`. `expectSnapshotEquivalence` of `@ddd-ts-kit/testing` proves a snapshot rebuilds the state a full replay does |
2201
2214
  | `personalData(subject, value)` | Marks a personal value in `encode`. `PersonalDataCipher` over a `SubjectKeyStore` seals it with the key of its data subject (AES-256-GCM); `SubjectKeyStore.erase(subject)` destroys the key, and a replay then reads `ERASED_PERSONAL_DATA`. `decode` reads a personal value with `data.personalText('x')`, `data.personalInstant('at')` or `data.personal('email', Email.of)`, which answer `undefined` once the subject is erased, so a value that is not free text never makes the aggregate unreadable; `data.isErased('x')` says whether it was. The cipher opens an erased value as an `ErasedValue`, `{ $erased: { key } }`, never as a text: `data.text` reads it `ERASED_PERSONAL_DATA`, a text that reads `[erased]` is not taken for one, and an upcaster sees that shape |
@@ -0,0 +1,9 @@
1
+ import type { Clock } from '../ports/clock.js';
2
+ import type { ExecutionScope } from '../ports/execution-scope.js';
3
+ import type { AuditStamp } from './audit-stamp.js';
4
+ /**
5
+ * For an adapter that holds the stored stamp, a document store rewriting the whole record: the
6
+ * stamp whole, updated by the current actor at the current instant, its creation kept as it is.
7
+ */
8
+ export declare function restamped(stamp: AuditStamp, scope: ExecutionScope, clock: Clock): AuditStamp;
9
+ //# sourceMappingURL=restamped.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restamped.d.ts","sourceRoot":"","sources":["../../../src/application/audit/restamped.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD;;;GAGG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE,KAAK,GAAG,UAAU,CAE5F"}