ddd-ts-kit 0.110.0 → 0.111.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 (226) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.fr.md +7 -5
  3. package/README.md +6 -4
  4. package/dist/check/explain/tenancy-docs.d.ts.map +1 -1
  5. package/dist/check/explain/tenancy-docs.js +3 -1
  6. package/dist/check/explain/tenancy-docs.js.map +1 -1
  7. package/dist/check/fixtures/tenancy-advisory-lock-fixtures.d.ts +9 -0
  8. package/dist/check/fixtures/tenancy-advisory-lock-fixtures.d.ts.map +1 -0
  9. package/dist/check/fixtures/tenancy-advisory-lock-fixtures.js +45 -0
  10. package/dist/check/fixtures/tenancy-advisory-lock-fixtures.js.map +1 -0
  11. package/dist/check/fixtures/tenancy-fixtures.d.ts.map +1 -1
  12. package/dist/check/fixtures/tenancy-fixtures.js +2 -0
  13. package/dist/check/fixtures/tenancy-fixtures.js.map +1 -1
  14. package/dist/check/rules/privacy-declared-field.js +1 -1
  15. package/dist/check/rules/privacy-declared-field.js.map +1 -1
  16. package/dist/check/rules/tenancy-scoped-statement.d.ts.map +1 -1
  17. package/dist/check/rules/tenancy-scoped-statement.js +11 -3
  18. package/dist/check/rules/tenancy-scoped-statement.js.map +1 -1
  19. package/dist/commands/generate.js +2 -0
  20. package/dist/commands/generate.js.map +1 -1
  21. package/dist/context-layout/context-layout.d.ts.map +1 -1
  22. package/dist/context-layout/context-layout.js +6 -0
  23. package/dist/context-layout/context-layout.js.map +1 -1
  24. package/dist/context-layout/module-moves.d.ts +8 -0
  25. package/dist/context-layout/module-moves.d.ts.map +1 -1
  26. package/dist/context-layout/module-moves.js +14 -3
  27. package/dist/context-layout/module-moves.js.map +1 -1
  28. package/dist/context-layout/runner-configs-by-hand.d.ts.map +1 -1
  29. package/dist/context-layout/runner-configs-by-hand.js +12 -0
  30. package/dist/context-layout/runner-configs-by-hand.js.map +1 -1
  31. package/dist/context-layout/settle.d.ts +9 -0
  32. package/dist/context-layout/settle.d.ts.map +1 -1
  33. package/dist/context-layout/settle.js +25 -3
  34. package/dist/context-layout/settle.js.map +1 -1
  35. package/dist/describe/read-adapters.d.ts.map +1 -1
  36. package/dist/describe/read-adapters.js +5 -1
  37. package/dist/describe/read-adapters.js.map +1 -1
  38. package/dist/describe/read-ports.js +8 -1
  39. package/dist/describe/read-ports.js.map +1 -1
  40. package/dist/generate/generate-options.d.ts +7 -0
  41. package/dist/generate/generate-options.d.ts.map +1 -1
  42. package/dist/generate/generate-options.js +2 -0
  43. package/dist/generate/generate-options.js.map +1 -1
  44. package/dist/generate/kind.d.ts +4 -0
  45. package/dist/generate/kind.d.ts.map +1 -1
  46. package/dist/generate/kinds/adapter-kind.d.ts.map +1 -1
  47. package/dist/generate/kinds/adapter-kind.js +12 -0
  48. package/dist/generate/kinds/adapter-kind.js.map +1 -1
  49. package/dist/generate/kinds/declare-storage.d.ts.map +1 -1
  50. package/dist/generate/kinds/declare-storage.js +3 -57
  51. package/dist/generate/kinds/declare-storage.js.map +1 -1
  52. package/dist/generate/kinds/declare-table.d.ts +14 -0
  53. package/dist/generate/kinds/declare-table.d.ts.map +1 -0
  54. package/dist/generate/kinds/declare-table.js +72 -0
  55. package/dist/generate/kinds/declare-table.js.map +1 -0
  56. package/dist/generate/kinds/e2e/job-slug.d.ts +3 -0
  57. package/dist/generate/kinds/e2e/job-slug.d.ts.map +1 -0
  58. package/dist/generate/kinds/e2e/job-slug.js +8 -0
  59. package/dist/generate/kinds/e2e/job-slug.js.map +1 -0
  60. package/dist/generate/kinds/e2e/job-spec.d.ts +16 -0
  61. package/dist/generate/kinds/e2e/job-spec.d.ts.map +1 -0
  62. package/dist/generate/kinds/e2e/job-spec.js +54 -0
  63. package/dist/generate/kinds/e2e/job-spec.js.map +1 -0
  64. package/dist/generate/kinds/e2e/jobs-sending.d.ts +17 -5
  65. package/dist/generate/kinds/e2e/jobs-sending.d.ts.map +1 -1
  66. package/dist/generate/kinds/e2e/jobs-sending.js +15 -6
  67. package/dist/generate/kinds/e2e/jobs-sending.js.map +1 -1
  68. package/dist/generate/kinds/e2e/reaction-of.d.ts +5 -5
  69. package/dist/generate/kinds/e2e/reaction-of.d.ts.map +1 -1
  70. package/dist/generate/kinds/e2e/reaction-of.js +15 -8
  71. package/dist/generate/kinds/e2e/reaction-of.js.map +1 -1
  72. package/dist/generate/kinds/e2e/starting-jobs.d.ts +10 -0
  73. package/dist/generate/kinds/e2e/starting-jobs.d.ts.map +1 -0
  74. package/dist/generate/kinds/e2e/starting-jobs.js +33 -0
  75. package/dist/generate/kinds/e2e/starting-jobs.js.map +1 -0
  76. package/dist/generate/kinds/e2e-kind.d.ts.map +1 -1
  77. package/dist/generate/kinds/e2e-kind.js +47 -35
  78. package/dist/generate/kinds/e2e-kind.js.map +1 -1
  79. package/dist/generate/kinds/generate-repository.d.ts +8 -0
  80. package/dist/generate/kinds/generate-repository.d.ts.map +1 -1
  81. package/dist/generate/kinds/generate-repository.js +2 -13
  82. package/dist/generate/kinds/generate-repository.js.map +1 -1
  83. package/dist/generate/kinds/note-the-migration.d.ts +4 -0
  84. package/dist/generate/kinds/note-the-migration.d.ts.map +1 -0
  85. package/dist/generate/kinds/note-the-migration.js +13 -0
  86. package/dist/generate/kinds/note-the-migration.js.map +1 -0
  87. package/dist/generate/kinds/personal-data/columns-of-table.d.ts +18 -0
  88. package/dist/generate/kinds/personal-data/columns-of-table.d.ts.map +1 -0
  89. package/dist/generate/kinds/personal-data/columns-of-table.js +31 -0
  90. package/dist/generate/kinds/personal-data/columns-of-table.js.map +1 -0
  91. package/dist/generate/kinds/personal-data/declare-personal-data.d.ts.map +1 -1
  92. package/dist/generate/kinds/personal-data/declare-personal-data.js +7 -52
  93. package/dist/generate/kinds/personal-data/declare-personal-data.js.map +1 -1
  94. package/dist/generate/kinds/personal-data/declare-table-personal-fields.d.ts +11 -0
  95. package/dist/generate/kinds/personal-data/declare-table-personal-fields.d.ts.map +1 -0
  96. package/dist/generate/kinds/personal-data/declare-table-personal-fields.js +71 -0
  97. package/dist/generate/kinds/personal-data/declare-table-personal-fields.js.map +1 -0
  98. package/dist/generate/kinds/personal-data/personal-request-of-table.d.ts +11 -0
  99. package/dist/generate/kinds/personal-data/personal-request-of-table.d.ts.map +1 -0
  100. package/dist/generate/kinds/personal-data/personal-request-of-table.js +20 -0
  101. package/dist/generate/kinds/personal-data/personal-request-of-table.js.map +1 -0
  102. package/dist/generate/kinds/personal-data/personal-vars.d.ts +7 -0
  103. package/dist/generate/kinds/personal-data/personal-vars.d.ts.map +1 -1
  104. package/dist/generate/kinds/personal-data/personal-vars.js +14 -11
  105. package/dist/generate/kinds/personal-data/personal-vars.js.map +1 -1
  106. package/dist/generate/kinds/personal-data/schema-table.d.ts +13 -0
  107. package/dist/generate/kinds/personal-data/schema-table.d.ts.map +1 -0
  108. package/dist/generate/kinds/personal-data/schema-table.js +2 -0
  109. package/dist/generate/kinds/personal-data/schema-table.js.map +1 -0
  110. package/dist/generate/kinds/personal-data/schema-tables-of.d.ts +9 -0
  111. package/dist/generate/kinds/personal-data/schema-tables-of.d.ts.map +1 -0
  112. package/dist/generate/kinds/personal-data/schema-tables-of.js +78 -0
  113. package/dist/generate/kinds/personal-data/schema-tables-of.js.map +1 -0
  114. package/dist/generate/kinds/personal-data/table-of-schema.d.ts +15 -0
  115. package/dist/generate/kinds/personal-data/table-of-schema.d.ts.map +1 -0
  116. package/dist/generate/kinds/personal-data/table-of-schema.js +39 -0
  117. package/dist/generate/kinds/personal-data/table-of-schema.js.map +1 -0
  118. package/dist/generate/kinds/personal-data/write-personal-declaration.d.ts +20 -0
  119. package/dist/generate/kinds/personal-data/write-personal-declaration.d.ts.map +1 -0
  120. package/dist/generate/kinds/personal-data/write-personal-declaration.js +63 -0
  121. package/dist/generate/kinds/personal-data/write-personal-declaration.js.map +1 -0
  122. package/dist/generate/kinds/personal-fields-kind.d.ts +3 -0
  123. package/dist/generate/kinds/personal-fields-kind.d.ts.map +1 -0
  124. package/dist/generate/kinds/personal-fields-kind.js +15 -0
  125. package/dist/generate/kinds/personal-fields-kind.js.map +1 -0
  126. package/dist/generate/kinds/projection-kind.d.ts.map +1 -1
  127. package/dist/generate/kinds/projection-kind.js +2 -1
  128. package/dist/generate/kinds/projection-kind.js.map +1 -1
  129. package/dist/generate/kinds/read-model/field-lines.d.ts +11 -0
  130. package/dist/generate/kinds/read-model/field-lines.d.ts.map +1 -0
  131. package/dist/generate/kinds/read-model/field-lines.js +85 -0
  132. package/dist/generate/kinds/read-model/field-lines.js.map +1 -0
  133. package/dist/generate/kinds/read-model/live-rows-check.d.ts +22 -0
  134. package/dist/generate/kinds/read-model/live-rows-check.d.ts.map +1 -0
  135. package/dist/generate/kinds/read-model/live-rows-check.js +47 -0
  136. package/dist/generate/kinds/read-model/live-rows-check.js.map +1 -0
  137. package/dist/generate/kinds/read-model/read-model-fields.d.ts +19 -0
  138. package/dist/generate/kinds/read-model/read-model-fields.d.ts.map +1 -0
  139. package/dist/generate/kinds/read-model/read-model-fields.js +31 -0
  140. package/dist/generate/kinds/read-model/read-model-fields.js.map +1 -0
  141. package/dist/generate/kinds/read-model/read-model-store.d.ts +24 -0
  142. package/dist/generate/kinds/read-model/read-model-store.d.ts.map +1 -0
  143. package/dist/generate/kinds/read-model/read-model-store.js +39 -0
  144. package/dist/generate/kinds/read-model/read-model-store.js.map +1 -0
  145. package/dist/generate/kinds/read-model/read-model-table.d.ts +11 -0
  146. package/dist/generate/kinds/read-model/read-model-table.d.ts.map +1 -0
  147. package/dist/generate/kinds/read-model/read-model-table.js +2 -0
  148. package/dist/generate/kinds/read-model/read-model-table.js.map +1 -0
  149. package/dist/generate/kinds/read-model-kind.d.ts +3 -0
  150. package/dist/generate/kinds/read-model-kind.d.ts.map +1 -0
  151. package/dist/generate/kinds/read-model-kind.js +84 -0
  152. package/dist/generate/kinds/read-model-kind.js.map +1 -0
  153. package/dist/generate/kinds.d.ts.map +1 -1
  154. package/dist/generate/kinds.js +4 -0
  155. package/dist/generate/kinds.js.map +1 -1
  156. package/dist/generate/shared-writes.d.ts.map +1 -1
  157. package/dist/generate/shared-writes.js +8 -0
  158. package/dist/generate/shared-writes.js.map +1 -1
  159. package/dist/help/tool-notes.d.ts.map +1 -1
  160. package/dist/help/tool-notes.js +2 -1
  161. package/dist/help/tool-notes.js.map +1 -1
  162. package/dist/init/files/persistence-files.d.ts.map +1 -1
  163. package/dist/init/files/persistence-files.js +2 -0
  164. package/dist/init/files/persistence-files.js.map +1 -1
  165. package/dist/init/manifest/dependencies-for.d.ts.map +1 -1
  166. package/dist/init/manifest/dependencies-for.js +10 -7
  167. package/dist/init/manifest/dependencies-for.js.map +1 -1
  168. package/dist/init/manifest/versions.js +25 -25
  169. package/dist/layout/fit-block.js +4 -0
  170. package/dist/layout/fit-block.js.map +1 -1
  171. package/dist/presets/no-flags.d.ts.map +1 -1
  172. package/dist/presets/no-flags.js +1 -0
  173. package/dist/presets/no-flags.js.map +1 -1
  174. package/dist/stack/end-to-end-vars.d.ts +9 -0
  175. package/dist/stack/end-to-end-vars.d.ts.map +1 -0
  176. package/dist/stack/end-to-end-vars.js +32 -0
  177. package/dist/stack/end-to-end-vars.js.map +1 -0
  178. package/dist/stack/stack-vars.d.ts.map +1 -1
  179. package/dist/stack/stack-vars.js +2 -0
  180. package/dist/stack/stack-vars.js.map +1 -1
  181. package/dist/version.d.ts +1 -1
  182. package/dist/version.js +1 -1
  183. package/dist/worker/briefing-of.js +2 -2
  184. package/dist/worker/briefing-of.js.map +1 -1
  185. package/package.json +6 -6
  186. package/templates/e2e/e2e-background-job-case.ts.tpl +12 -0
  187. package/templates/e2e/e2e-job.spec.ts.tpl +3 -3
  188. package/templates/init/README.md.tpl +1 -1
  189. package/templates/init/e2e/jest.e2e.config.js.tpl +24 -5
  190. package/templates/init/e2e/start-application.database.ts.tpl +40 -2
  191. package/templates/init/e2e/start-application.memory.ts.tpl +36 -0
  192. package/templates/init/e2e/vitest.e2e.config.ts.tpl +12 -3
  193. package/templates/init/platform/database/open-test-database.drizzle.ts.tpl +22 -4
  194. package/templates/init/platform/database/open-test-database.knex.ts.tpl +21 -3
  195. package/templates/init/platform/database/open-test-database.prisma.ts.tpl +22 -3
  196. package/templates/init/platform/database/open-test-database.typeorm.ts.tpl +22 -3
  197. package/templates/init/platform/database/test-database-clone.ts.tpl +184 -0
  198. package/templates/init/platform/jobs/background-jobs.ts.tpl +4 -0
  199. package/templates/init/platform/jobs/create-background-work.ts.tpl +1 -0
  200. package/templates/init/rules/infrastructure.md.tpl +1 -1
  201. package/templates/personal-data/declaration.drizzle.ts.tpl +6 -1
  202. package/templates/personal-data/declaration.knex.ts.tpl +14 -1
  203. package/templates/personal-data/declaration.prisma.ts.tpl +6 -1
  204. package/templates/personal-data/declaration.typeorm.ts.tpl +21 -1
  205. package/templates/personal-data/spec.table.ts.tpl +39 -0
  206. package/templates/pipeline/package-scripts.json +1 -1
  207. package/templates/projection/projection.manual.ts.tpl +2 -2
  208. package/templates/projection/projection.ts.tpl +2 -2
  209. package/templates/read-model/contract.spec.ts.tpl +95 -0
  210. package/templates/read-model/drizzle/schema.ts.tpl +8 -0
  211. package/templates/read-model/drizzle/store.ts.tpl +41 -0
  212. package/templates/read-model/drizzle/table.tpl +38 -0
  213. package/templates/read-model/fake.ts.tpl +8 -0
  214. package/templates/read-model/knex/store.ts.tpl +41 -0
  215. package/templates/read-model/knex/table.tpl +26 -0
  216. package/templates/read-model/none/store.ts.tpl +17 -0
  217. package/templates/read-model/port.ts.tpl +24 -0
  218. package/templates/read-model/prisma/model.tpl +25 -0
  219. package/templates/read-model/prisma/store.ts.tpl +43 -0
  220. package/templates/read-model/typeorm/schema-export.tpl +4 -0
  221. package/templates/read-model/typeorm/schema.ts.tpl +9 -0
  222. package/templates/read-model/typeorm/store.ts.tpl +30 -0
  223. package/templates/read-model/typeorm/table.tpl +54 -0
  224. package/templates/read-model/wiring.container.tpl +21 -0
  225. package/templates/repository/drizzle/table.tpl +1 -0
  226. package/templates/repository/typeorm/table.tpl +1 -0
package/CHANGELOG.md CHANGED
@@ -4,6 +4,62 @@ What each version changes for someone who uses the kit. The packages of `package
4
4
  together, under one version; the notes of each [GitHub release](https://github.com/gbourgeat/ddd-ts-kit/releases)
5
5
  list the pull requests behind it.
6
6
 
7
+ ## 0.111.0
8
+
9
+ **The briefing of a worker says upfront that a branch keeps one working migration.** A worker whose second slice changed the schema generated a second working migration, and learned only from the refusal of `drizzle-generate --replay` at the merge that a branch keeps one and generates it again. `worker-scope` and the context builder agent now say it before the first slice.
10
+
11
+ **`ddd-ts-kit context-layout` no longer puts a file kept at the level of a context in the module it imports when the code of another module imports it.** The command told the module of such a file by its imports alone: a reader that imports one module and is used by another went into the first, and the second then depended on it, which `module/no-cycle` reported when the first already depended on the second. The file now stays where it is and the command lists it with both modules, as it does a file whose imports name two modules: `move-to-module` takes it to the one it belongs to. The specs, fakes and builders are told as before.
12
+
13
+ The command also names the rules of the tests `init` wrote for the coding agents (`.claude/rules/tests.md`, `.github/instructions/tests.instructions.md`) when they still name the test folder of each context alone, once a spec moved into a module: add `<contexts>/*/*/test/**` beside it, as it already says of a config of a test runner.
14
+
15
+ **On a PostgreSQL server (`DATABASE_URL`), each end-to-end spec file of a generated project runs on a database of its own, copied from the migrated one, so the files run at the same time and two runs at once no longer block each other.** Until now every file shared the database the URL names and emptied its tables in `reset()`: the files had to run one after the other (`fileParallelism` off under Vitest, one worker under Jest), two runs started together could end in a deadlock on `truncate` (40P01), and the audit trail, which nothing empties, carried the rows of the other files. `openTestDatabase(url)` of the four ORM now creates a database from the migrated one (`create database ... template`), connects the persistence to it and drops it at `close()` (`drop database ... with (force)`); the new `test/support/test-database-clone.ts` does it for all four. The copy gives its address (`TestDatabase.url`), which `startApplication` hands to the configuration of the application as `DATABASE_URL`: an adapter that opens a connection of its own from `config.databaseUrl` reaches the copy too. `reset()` still empties the tables of the copy between two tests, the audit trail starts empty in each file, and the migrated database is never written by a test. `vitest.e2e.config.ts` and `jest.e2e.config.js` no longer read `DATABASE_URL`: they keep the files one after the other only where a server is still one for every file, a broker (`AMQP_URL`, `KAFKA_BROKERS`, `NATS_URL`) or a Redis protocol server (`REDIS_URL`). A server that was never migrated is refused with `npm run db:migrate` in the message instead of `relation does not exist`, and so are a role that may not copy the database and a migrated database somebody else is connected to. A copy is named `<database>_test_<seconds of its date>_<random>`; the ones a killed run left are dropped by the next file that starts, an hour later, and no database with another name ever is. See [the testing strategy](docs/concepts/testing-strategy.md).
16
+
17
+ What changes on the server: the role of `DATABASE_URL` needs `CREATEDB` and owns the migrated database, or is a superuser (the role of the generated `docker-compose.yml` and of the generated pipelines is one), the server is PostgreSQL 13 or later, and nobody else may be connected to the migrated database while a file starts (an application left running on it, a console): PostgreSQL copies a database only then.
18
+
19
+ To move: these files are written once by `init`, so a project already generated takes them by hand. Generate a project with the same flags in a temporary directory (`npx ddd-ts-kit init` with the `stack` of your `ddd-ts-kit.config.json`) and copy from it: `test/support/test-database-clone.ts` (new); in `src/platform/database/open-test-database.ts`, the import of `cloneDatabase` and the function `openServer`, which connects to `clone.url`, returns `url: clone.url` and ends its `close` with `await clone.drop()`, and the `url` member of `TestDatabase`; in `test/e2e/support/start-application.ts`, `DATABASE_URL: database.url ?? 'postgres://in-process/tests'` in the call of `loadConfig`; in `vitest.e2e.config.ts`, the `fileParallelism` line, removed, or kept on the broker and Redis variables alone; in `jest.e2e.config.js`, `sharedServer` and `maxWorkers`, the same way. Then, where the role is not a superuser, let it create databases and own the migrated one (`alter role <role> createdb`, `alter database <database> owner to <role>`). A spec of your own that connects to `DATABASE_URL` itself now holds a session on the migrated database and makes the other files fail: connect it to the `postgres` database, or read through the application.
20
+
21
+ **`ddd-ts-kit generate personal-fields <context> <table> --personal <column>,... --subject <column>` declares the personal data of a table no aggregate owns.** A read model, a table of received messages or a table written by hand in the schema of a context had no generator: `generate repository --personal` asks for an aggregate, so their `*.personal-fields.ts` and their lines in the erasure and the export adapters were written by hand. The new generator takes the SQL name of a table the schema file of the context declares (Drizzle, Knex, Prisma, TypeORM), writes `infrastructure/persistence/<table>.personal-fields.ts` spelled as the erasure of the ORM reads it, and joins it to the erasure and the export of the context, or writes them when the table is the first (ports, adapters, fakes, binding, the copies and the exports of the platform, and a spec that proves the fakes and names each case to prove on the test database as `it.todo`, no repository nor builder writing the rows of such a table). `--subject` is required there: the row is rarely the person, and a default of `id` would have `privacy:erase` miss it. The table is never changed: a table the schema does not declare, a table that has a declaration, a column the table does not hold and, where the erasure is confined to a tenant, a table without `tenant_id` are refused; a column that could not be read (the definition spreads shared columns) is said in the output. `--erasure`, `--retention`, `--tenant-scoped` and `--module` as on a repository. The refusal of `generate repository <context> <Aggregate> --personal ...` on a table that exists now names this command, and so does the fix of `privacy/declared-field`. See docs/concepts/personal-data.md.
22
+
23
+ **`ddd-ts-kit describe` and the "Ports" section of `CONTEXT.md` show as bound a port whose adapter extends a parent with several type arguments.** An adapter declared `class DrizzleAppointmentList extends DrizzleReadModelStore<AppointmentRow, PgQueryResultHKT> implements AppointmentList`, as a Drizzle or a Prisma read model store is, was not read as an adapter, so its port was listed `not bound` while the application ran with it. The parent is now whatever stands before `implements`, on one line or on the lines the formatter gives a long heritage. A port file that declares an interface before its abstract class is named after the abstract class, which is the injection token.
24
+
25
+ To move: run `ddd-ts-kit docs` once, so that the reference of each `CONTEXT.md` lists the adapters it missed.
26
+
27
+ **`ddd-ts-kit generate read-model <context> <Name>` writes the read model a projection keeps.** `generate projection` wrote the projector alone, and the port of its read model, its table, its store adapter and its fake were written by hand from the declarations of the packages. The new kind writes them: the port in `application/ports/<name>.port.ts` (the type `<Name>Row`, the criteria `<name>Criteria` and the abstract class `<Name>` over `ReadModelStore<<Name>Row>`), the table in the schema of the context, the store adapter `infrastructure/persistence/<orm>-<name>.repository.ts` over the read model store of the ORM package (Drizzle, Knex, Prisma, TypeORM; `InMemoryReadModelStore` in a project without an ORM), declared with `@Repository(<Name>)` or bound in the module file in the explicit style, the fake, and `test/integration/<name>.contract.spec.ts`, which runs `readModelContract` on the fake and on the adapter. `--field <name>:<string|number|boolean|instant|decimal>[:nullable]` adds a field to the row, to the criteria, to the table and to the columns of the adapter at once; `--tenant-scoped`, or a multi-tenant project, gives the table its tenant column and the store the scope of the work. The column of a field accepts null whatever the row requires, a removed row being a trace that keeps its key and its stamp alone, and a check constraint `<table>_live_rows_whole` keeps every other row whole: `check(...)` on Drizzle, `table.check(...)` on Knex, `checks` of the entity schema on TypeORM; the schema language of Prisma has none, so its model carries a `TODO(domain)` line with the `ALTER TABLE` to add to the migration. `generate projection` names the command in its file and in a note, `generate adapter` refuses the port of a read model with it, and the `persistence`, `scaffold` and `wiring` skills of the plugin say it. A repository generated after a read model in the same context finds the imports of its own table (`integer`, `auditColumns`), and a table may bear the name of a column of another.
28
+
29
+ **`readModelContract` of `@ddd-ts-kit/testing/contracts` holds the read model port of a context, on rows of its own.** `readModelStoreContract` runs on the fixed row of the kit and holds the table of an ORM package; nothing held the port a context declares over it, so its fake and its adapter were compared by hand. `readModelContract<Row>(runner, { name, createStore, createRow, change })` runs the same cases on any `ReadModelStore<Row>`: a row read back as written, nothing for an unknown key or for a change that answers nothing, an event delivered twice or older than the row ignored, a deletion an older event does not undo, a search that lists the rows held and none removed, and with `change` the current row handed to a later event (pending without it). `ddd-ts-kit generate read-model` writes the spec that runs it on the fake and on the adapter.
30
+
31
+ **A read model on `@ddd-ts-kit/typeorm` leaves a column declared `select: false` out of the rows it answers.** The rows held every column of the entity but the stamps, so a read model of tenant data answered `tenantId` even when the row of its port did not carry it, where the stores of the three other ORM answer the mapped fields only. Declare the tenant column `tenantId: { ...tenantColumn().tenantId, select: false }` in an entity typed `Row & TenantScoped & ReadModelStamps`: the store still writes it and confines every statement to it. An entity that declares the column without `select: false` answers it as before.
32
+
33
+ **Breaking: a deletion in a read model leaves its trace under a key the table does not hold, and a deleted row keeps no data.** `ReadModelStore.delete(key, stamp)` of `@ddd-ts-kit/kernel` on a key the read model did not hold wrote nothing and answered `ignored`, so a deletion delivered before the older creation it follows let that creation make a row that should not exist, and a rebuild lost a deletion made while it exported a row it had not copied yet. It now inserts the trace (the key, the stamp, `deleted`, the tenant of a read model of tenant data) and answers `traced`, a fourth value of `ReadModelWrite`: a deletion that removed no row and recorded its trace, under a key not held or over the trace of an earlier deletion (which answered `applied`). `applied` keeps one meaning, a row written or a held row removed; the older creation delivered after the trace is `stale`, and `projection_events_total` counts the result `traced`. `ignored` is left to an `upsertIfNewer` whose `next` answers `undefined`. On `@ddd-ts-kit/knex`, `@ddd-ts-kit/drizzle`, `@ddd-ts-kit/prisma` and `@ddd-ts-kit/typeorm`, a deleted row now holds NULL in every column of the row, as it already kept nothing in memory and on `@ddd-ts-kit/opensearch`: its personal data is gone and a unique value it held is free again. So every column of the row is nullable, and a table that is not ready is refused by name, `ReadModelTableNotReadyError`, which lists the columns and gives the check constraint: when the store is built on Drizzle and TypeORM, from the definition, and on the four before the first trace is written, from one read of the columns the database holds, never by a statement that would abort the transaction of the event. On TypeORM and Prisma, an insert that takes a unique value another row holds is no longer skipped in silence: only a conflict on the key is, and the other is refused, by the database on TypeORM, with `UniqueViolationError` on Prisma. `readModelStoreContract` and `readModelRowsContract` of `@ddd-ts-kit/testing` hold it, with two capabilities to give them: `stored(key)`, which reads the table beside the store, and `uniqueTitle`. A read model of tenant data keeps its keys unique across tenants: under a key another tenant holds, a deletion stays `ignored`, and an upsert is now refused at once with `ReadModelKeyHeldElsewhereError`, a `ConcurrencyError` that says the key should carry the tenant, where it spent five attempts first. See `docs/concepts/cqrs.md`, "The table of a read model, and what a deleted row leaves".
34
+
35
+ To move: for each read model table, write a migration that drops NOT NULL on every column of the row (not on the key, the tenant column, `last_event_id`, `last_event_at`, `deleted`) and keeps the live rows whole: `alter table <table> alter column <column> drop not null` for each, then `alter table <table> add constraint <table>_live_rows_whole check (deleted or (<column> is not null and ...))` over the columns that were NOT NULL; `update <table> set <column> = null, ... where deleted` empties the rows deleted before. Declare the same in the definition the store reads: no `.notNull()` on Drizzle, `nullable: true` on TypeORM, optional fields (`String?`) on Prisma. A unique index `WHERE NOT deleted` may become a plain one. A statement of your own on the table keeps filtering `deleted = false`. A `switch` over `ReadModelWrite` gains the case `traced`; code that counts the rows a deletion removed keeps counting `applied` alone, and a dashboard that sums the results of `projection_events_total` meets the new one. A `ReadModelRows` of your own now inserts an entry without a `row` (the trace) where it answered `false`, and writes no data on a replace without one. Run `readModelStoreContract` again on your stores: the table of its dataset needs the same migration.
36
+
37
+ **`ddd-ts-kit generate e2e` writes the end-to-end spec of a use case a background job starts, and the end-to-end support runs what is due on the queues.** `generate e2e <context> <UseCase>` found a route, then an integration event handler, then a scheduled job, and refused a use case only a background job sends the command of. It now finds the background jobs of the context too (`application/background/*.background-job.ts`) and writes a spec in three steps: the request whose use case enqueues the job, to send through the API (a `TODO(domain)`), `const ran = await application.runDueJobs()`, then `application.settled()` and what a client observes. The spec asserts that the job is among `ran`, so it fails until the request that enqueues is written. A use case a scheduled job and a background job both send gets one test per job. `--job <JobName>` names one job, scheduled or background, by its class (`VoidInvoice`, `VoidInvoiceBackgroundJob`) or by the name it runs under (`billing.void-invoice`), also for a use case a route reaches: that spec is written in `test/e2e/<use-case>-<job>.e2e.spec.ts`, beside the one of the route; `--event` and `--job` together are refused.
38
+
39
+ `runDueJobs()` is new in `test/e2e/support/start-application.ts`, next to `runJob(name)`, which runs a scheduled job at once: it stops the worker of the process (a queue kept in memory starts one, and a job it claimed would end behind the spec), runs every job due until none is left on the worker of the application, answers the name of each job run, and rejects when a run did not succeed, naming the job, its outcome and the code of its error, never the message. On a container it resolves the `QueueWorker` of the kernel module; where the platform is wired by hand, or under Nest, it calls `platform.backgroundJobs`, which gains `runDue()` (`src/platform/jobs/background-jobs.ts`, `create-background-work.ts`). It is the same on the three queue stores (`memory`, `database`, `redis`). A project on a container lists `@ddd-ts-kit/scheduling` in its development dependencies when its queue does not already list it at run time: the support imports the token of the worker from it. The `testing`, `scaffold` and `integration-event` skills of the plugin say it, with the pages [testing strategy](docs/concepts/testing-strategy.md) and [background jobs](docs/concepts/background-jobs.md).
40
+
41
+ To move: nothing has to change. `init` keeps the support of an existing project as it is, and `generate e2e` notes what it lacks when a spec needs it. To add `runDueJobs` by hand: declare `runDueJobs(): Promise<string[]>;` on `RunningApplication`, and implement it on the worker, `application.container.resolve(QueueWorker)` on a container (`QueueWorker` of `@ddd-ts-kit/scheduling`, to add to the development dependencies if the project does not list it), or `application.platform.backgroundJobs` by hand once `runDue: () => worker.runDue()` is among what `backgroundJobsOn` of `src/platform/jobs/create-background-work.ts` answers and `runDue(): Promise<BackgroundJobRun[]>;` is on the `BackgroundJobs` interface: `await worker.stop()`, then `const runs = await worker.runDue()`, throw when the `outcome` of a run is not `succeeded`, and answer `runs.map((run) => run.job)`.
42
+
43
+ **`advisoryLock` and `tryAdvisoryLock` serialise the units of work that decide on the same business key, on the four ORM.** A decision taken on rows that do not exist yet (count then insert, the next number of a sequence per tenant) has no version for optimistic concurrency to compare, and took a raw `pg_advisory_xact_lock` that `tenancy/scoped-statement` refuses. `@ddd-ts-kit/knex`, `@ddd-ts-kit/drizzle`, `@ddd-ts-kit/prisma` and `@ddd-ts-kit/typeorm` now export the same two functions: `advisoryLock(context, key, { tenant: scope })` waits until no other transaction holds the lock on `key` and holds it until the unit of work commits or rolls back, and `tryAdvisoryLock` answers `false` instead of waiting. The key is a text that PostgreSQL hashes into 64 bits (`hashtextextended(text, 0)`); with `tenant` it is `tenant:<id>:<key>` (`tenantKey`), so two tenants never wait for each other and work that names no tenant is refused; two keys of the same hash wait for each other, and nothing else happens. Outside a unit of work the lock would be released at once: `AdvisoryLockOutsideUnitOfWorkError` of `@ddd-ts-kit/kernel`. `tenancy/scoped-statement` accepts the helper, which is given the context and never the executor, and a raw advisory lock is still reported, with a message that now names the helper. `advisoryLockContract` of `@ddd-ts-kit/testing` holds the four packages to the same behaviour; the wait of a second unit of work runs on a real PostgreSQL (`concurrent: true`), PGlite being one session. PostgreSQL only. The page is "A decision no version protects" in `docs/tools/persistence.md`.
44
+
45
+ To move: nothing has to. A raw `pg_advisory_xact_lock` kept under a `ddd-ts-kit-disable-next-line tenancy/scoped-statement` becomes `await advisoryLock(context, key, { tenant: scope })`, and its suppression goes: `ddd-ts-kit check --rule tenancy/scoped-statement` lists what is left. The number locked on changes with the helper (the hash of the text, with the tenant in it): deploy the change to every instance at once, or two versions of the application would not wait for each other.
46
+
47
+ **A criteria searches a text whatever its case: `containsIgnoringCase` and `startsWithIgnoringCase`, on every store.** A field of type `string` declares them beside `contains` and `startsWith` (`filter: ['containsIgnoringCase']`), and `where('name', 'containsIgnoringCase', 'dupont')` then finds `Dupont` and `DUPONT`. The text is taken as literally as `contains` takes it (`%`, `_` and `\` are characters, an empty text is refused), each letter of both sides is put in lower case and nothing else is folded: an accent is kept, so `e` does not find `é`. In memory it is `foldCase` of `@ddd-ts-kit/kernel` (`toLowerCase` of JavaScript); `@ddd-ts-kit/knex`, `@ddd-ts-kit/drizzle` and `@ddd-ts-kit/typeorm` write an `ILIKE`, `@ddd-ts-kit/prisma` the `insensitive` mode, `@ddd-ts-kit/opensearch` a `regexp` query that names both forms of each letter. `criteriaContract` of `@ddd-ts-kit/testing` holds them to the same rows for the ASCII letters and for a letter with one upper-case and one lower-case form (`É` and `é`); outside them (the two `I` of Turkish, `ß`, the final sigma) each store follows its own table, and a PostgreSQL database created with the `C` locale folds the ASCII letters alone. A route that reads its criteria with `criteriaQuerySchema` of `@ddd-ts-kit/http` takes `filter[name]=containsIgnoringCase:dupont` once the definition declares the operator. No b-tree index serves an `ILIKE`: on PostgreSQL a GIN index of `pg_trgm` on the column does, in a migration of the project. The rule and its limits are in "What a criteria means" of `packages/kernel/README.md`.
48
+
49
+ To move: nothing for a project that does not declare the operators. An adapter of a read port written by hand over `Predicate` (a `switch` on `operator`) now meets two more operators, on the fields that declare them only.
50
+
51
+ **The conditional replace of a read model row compares the whole stamp on the four ORM, and Knex and TypeORM read the instant of a stamp back to the millisecond.** A write of a read model replaces the row only if it still holds the stamp that was read. The in-memory table and `@ddd-ts-kit/opensearch` compared the event id, the instant and the version; `@ddd-ts-kit/knex`, `@ddd-ts-kit/drizzle`, `@ddd-ts-kit/prisma` and `@ddd-ts-kit/typeorm` left the version out, so a row whose version alone had moved (two domain events of one name and one aggregate in the same millisecond share the two others) was replaced by a write computed from the row before it. The four now compare the version too, NULL matching NULL, and `sameStamp(left, right)` of `@ddd-ts-kit/kernel` is exported for a `ReadModelRows` of your own. On `@ddd-ts-kit/knex` and `@ddd-ts-kit/typeorm`, the instant of a stamp was read back through the text of the `Date` the driver gave, which has no milliseconds: the stamp read never matched the row, and the second event of a key ended in `ConcurrencyError` whenever the first carried milliseconds. It is read as the date it is. The order of stamps is unchanged, and now said where it is read (`isNewer`, `docs/concepts/cqrs.md`, "Which write for which event"): total among stamps that all carry a version and among stamps that carry none, decided by the instants between one of each, which is not an order, so a key should see one kind, the one mix that is meant being a deletion made outside the history of the key, such as an erasure. `readModelStoreContract` and `readModelRowsContract` of `@ddd-ts-kit/testing` hold the replace on the whole stamp, the stamp at the millisecond, the same row whatever the order of three deliveries of one kind, and such a deletion.
52
+
53
+ To move: a `ReadModelRows` of your own compares the version in `replace`, with `sameStamp`, and gives back the instant it was given, to the millisecond; run `readModelStoreContract` again on your stores. A workaround that rounded the instant of a stamp to the second for Knex or TypeORM can go.
54
+
55
+ **Breaking: `ReadModelStore.updateIfNewer` writes the change of a row another event created, and answers `missing` when that row is not there.** A projection wrote such an event (an appointment moved, a payment captured) as an `upsertIfNewer` whose `next` answered `undefined` when the key held no row, which read as `ignored`: nothing told a change that found no row from an event the read model filters. `updateIfNewer(key, stamp, change)` of `@ddd-ts-kit/kernel`, where `change` takes the row and answers the row, is the write of a partial change: `applied` on a row the key holds, `stale` when the row, or the trace of its deletion, holds this event or a later one, and `missing`, a fifth value of `ReadModelWrite`, when the key holds no row, the trace of a deletion older than the event, or a row of another tenant. Nothing is written then and the store never throws for it: the projection decides what a missing row means. It is not a cure for disorder: the store refuses to go back in time and cannot put back a change that arrived before its creation, or the older of two changes delivered out of order, which is `stale`. A partial change is right only on a feed that keeps the order of a key; an event that carries the whole row is right in any order. `docs/concepts/cqrs.md`, "Which write for which event", says which feeds keep that order (the save, a catch-up subscription, the in-process bus, the relay per key, Kafka per partition) and what to do with `missing` on each. `projection_events_total` of `@ddd-ts-kit/di` counts the result `missing`. `TableReadModelStore`, so the stores of `@ddd-ts-kit/knex`, `@ddd-ts-kit/drizzle`, `@ddd-ts-kit/prisma`, `@ddd-ts-kit/typeorm` and `@ddd-ts-kit/opensearch` and `InMemoryReadModelStore`, and `ShadowReadModelStore` have it; `readModelStoreContract`, `readModelRowsContract` and `readModelContract` of `@ddd-ts-kit/testing` hold the cases; `generate projection` of `ddd-ts-kit` names the two writes in the method it leaves to fill. `upsertIfNewer` keeps its meaning.
56
+
57
+ To move: a class of your own that extends `ReadModelStore` without extending `TableReadModelStore` implements `updateIfNewer`. A `switch` over `ReadModelWrite` gains the case `missing`, and a dashboard that sums the results of `projection_events_total` meets it. In a projection, `upsertIfNewer(key, stamp, (row) => (row === undefined ? undefined : { ...row, ... }))` may become `updateIfNewer(key, stamp, (row) => ({ ...row, ... }))`: its answer is then `missing` where it was `ignored`. Never throw on `missing` in a projection fed by the domain events of its context or by the event store; prefer events that carry the whole row where the transport keeps no order.
58
+
59
+ ## 0.110.1
60
+
61
+ **The guard lets a worker take a lock with `flock` under `$XDG_RUNTIME_DIR`.** Since 0.110.0 the guard reads the lock file of `flock` as a file the command writes, and refused `flock "$XDG_RUNTIME_DIR/heavy.lock" npm run verify` to a context worker: a variable it did not read, in a directory outside the worktree. A worker then ran its heavy command without the lock the checkouts of the machine share. The guard now reads `$XDG_RUNTIME_DIR` by its value when the session started, and a lock of `flock` there is free, as output to the system temp directory is: `flock` creates the file when it is missing and writes nothing in it. Everything else a worker writes there is still refused (a redirection, the report of `time -o`), so is a lock that is a link into a project, and a worker that sets `XDG_RUNTIME_DIR` itself is refused as one that sets `TMPDIR`.
62
+
7
63
  ## 0.110.0
8
64
 
9
65
  **A project generated on Fastify compiles again with Fastify 5.12.8.** That version types `app.addresses()` as addresses or pipe paths, and `src/platform/http/start-http-server.ts` read `.port` of the first one, so `tsc` refused a new project (`Property 'port' does not exist on type 'string | AddressInfo'`). The file now reads the port through a function that answers 0 for a server bound to a pipe.
package/README.fr.md CHANGED
@@ -1,5 +1,5 @@
1
1
  [English](README.md) · **Français**
2
- <!-- translation-of: README.md sha256:a81e842cf19ebf21 -->
2
+ <!-- translation-of: README.md sha256:a53f244ee1ee65ef -->
3
3
 
4
4
  # ddd-ts-kit
5
5
 
@@ -646,12 +646,12 @@ choix sont enregistrés sous `stack` dans la configuration, `docsUi`, `ci` et `l
646
646
  | `--storage local\|s3` | enregistré comme `stack.storage` : où vit le contenu des fichiers, jamais dans la base de données. `src/platform/config/read-files.ts` et `src/platform/files/open-files.ts`, un par choix : `local`, un répertoire en développement (`FILES_DIRECTORY`, `.data/files`) et les liens signés servis par l'application sous `/files` (`FILES_PUBLIC_URL` et `FILES_SIGNING_SECRET` requises en production) ; `s3`, un bucket de n'importe quel fournisseur du protocole S3 au moyen de `@ddd-ts-kit/s3` (les variables `S3_*`, MinIO dans la stack compose) ; la mémoire du processus dans les tests et les outils, dans les deux cas. Avec `--di tsyringe` : `files/bind-files.ts`, `files/files.module.ts` et `files/staging-uploads.ts` ; en câblage manuel, `files/create-files.ts` ; avec une *stack* HTTP, `files/file-routes.ts`. Ils lient `FileStorage`, `FileKeys`, `FileScanner` et `FileStaging`, enregistrent la purge horaire des fichiers en attente et mettent en attente le fichier que porte une commande avant sa transaction ; `generate file-upload` en a besoin. `--storage none` n'écrit rien de tout cela ([Stockage de fichiers](../../docs/concepts/file-storage.fr.md)) |
647
647
  | `--search opensearch\|none` | enregistré comme `stack.search`, `none` par défaut : où vivent les modèles de lecture qu'un contexte tient pour la recherche. `opensearch` : `@ddd-ts-kit/opensearch`, `src/platform/search/search-indexes.ts` (`SearchIndexes`, la classe abstraite que reçoit l'adaptateur d'un port de modèle de lecture : `super(search.options('billing_invoices', criteria))`) et `search/open-search.ts` (`fetchTransport` sur `OPENSEARCH_URL`, l'utilisateur d'`OPENSEARCH_USERNAME` et `OPENSEARCH_PASSWORD` les deux ou aucune, la stratégie `attribute` sous `--tenancy shared-table`, `none` sinon), lié par `search/search.module.ts` sur un conteneur du kit, `platform.search` câblé à la main et sous Nest ; l'index de chaque store construit à partir de lui provisionné avant une requête, sous tables partagées pour le locataire du travail une fois que l'annuaire des locataires de la plateforme le liste (un locataire non listé ne crée aucun index), au mieux au démarrage, qui n'échoue jamais sur la recherche, rien d'appelé sans store ; les scripts de confidentialité reçoivent le nœud ; un service compose `opensearch` (un nœud, extension de sécurité coupée). Aucun générateur n'écrit de store, et le pipeline ne démarre aucun nœud ; un contexte construit ses stores depuis `SearchIndexes` seulement (`search/store-from-platform`). [Modèles de lecture de recherche](../../docs/tools/search-read-models.fr.md) |
648
648
  | `src/platform/events/` | `event-provider.ts` (`bus`, `forConsumer(name)`, `start()`, `close()`), `in-process-events.ts`, et pour `--broker` `create-event-provider.ts` : `RabbitMqEventBus` (`AMQP_URL`), `KafkaEventBus` (`KAFKA_BROKERS`, avec `aggregate-key-of.ts` pour l'ordre par agrégat), `NatsEventBus` (`NATS_URL`) ou `RedisStreamsEventBus` de `@ddd-ts-kit/redis/event-bus` (`REDIS_URL` : Redis, Dragonfly ou Valkey), chacun avec un abonné par contexte consommateur (`forConsumer`), `assertTopology` au démarrage, son adresse validée et un service compose avec un contrôle de santé ; ou `custom-event-bus.ts` avec sa *spec* `eventBusContract`. `start-outbox-relay.ts` avec l'outbox. `--broker redis` avec `--cache redis` fait un seul serveur et un seul service compose, `cache` ; seul, le service s'appelle `streams` |
649
- | `src/platform/database/` | `persistence.ts` (`interface Persistence` : unité de travail, magasins de l'outbox et des événements traités du *package* de l'ORM, la poignée de stockage), `open-persistence.ts`, `persistence-over.ts`, `inert-persistence.ts`, la connexion (`connect-to-database.ts`, `create-client.ts` ou `create-data-source.ts`), `schema.ts` (`MESSAGING_SCHEMA`, le schéma de ce que le kit stocke pour l'application), `open-test-database.ts` (PostgreSQL dans le processus, ou le serveur nommé par une URL ; avec Vitest chaque *spec* ouvre une copie du cluster que `test/support/test-database-template.ts`, la mise en place globale de l'exécution, initialise une fois, et y crée ses tables ; avec drizzle depuis `table-statements.ts`, le SQL des tables de `schema.ts`, puisque drizzle-kit écrit des migrations, pas des tables, ses index uniques compris), `persistence.contract.spec.ts` (les stores de l'outbox, des événements traités, des *jobs* et des processus tels que la plateforme les branche, tenus aux contrats de `@ddd-ts-kit/testing` avec ce que la pile active : le *tenant* sous `--tenancy`, l'unité de travail). La classe de stockage qu'un adaptateur de *repository* nomme dans sa liste de dépendances : `database.ts` avec drizzle et prisma (`abstract class Database extends` le type de contexte du *package* de l'ORM), `KnexContext` de `@ddd-ts-kit/knex`, `TypeOrmContext` de `@ddd-ts-kit/typeorm` |
649
+ | `src/platform/database/` | `persistence.ts` (`interface Persistence` : unité de travail, magasins de l'outbox et des événements traités du *package* de l'ORM, la poignée de stockage), `open-persistence.ts`, `persistence-over.ts`, `inert-persistence.ts`, la connexion (`connect-to-database.ts`, `create-client.ts` ou `create-data-source.ts`), `schema.ts` (`MESSAGING_SCHEMA`, le schéma de ce que le kit stocke pour l'application), `open-test-database.ts` (PostgreSQL dans le processus, ou le serveur nommé par une URL, chaque appel alors sur une copie de la base migrée, créée et supprimée par `test/support/test-database-clone.ts` ; avec Vitest chaque *spec* ouvre une copie du cluster que `test/support/test-database-template.ts`, la mise en place globale de l'exécution, initialise une fois, et y crée ses tables ; avec drizzle depuis `table-statements.ts`, le SQL des tables de `schema.ts`, puisque drizzle-kit écrit des migrations, pas des tables, ses index uniques compris), `persistence.contract.spec.ts` (les stores de l'outbox, des événements traités, des *jobs* et des processus tels que la plateforme les branche, tenus aux contrats de `@ddd-ts-kit/testing` avec ce que la pile active : le *tenant* sous `--tenancy`, l'unité de travail). La classe de stockage qu'un adaptateur de *repository* nomme dans sa liste de dépendances : `database.ts` avec drizzle et prisma (`abstract class Database extends` le type de contexte du *package* de l'ORM), `KnexContext` de `@ddd-ts-kit/knex`, `TypeOrmContext` de `@ddd-ts-kit/typeorm` |
650
650
  | outillage des migrations | `drizzle.config.ts`, `knexfile.js` et le dossier `migrations/`, `prisma/schema/schema.prisma` (le client, la datasource et les tables de la plateforme ; `generate repository` ajoute le fichier de chaque contexte, `prisma/schema/<context>.prisma`) et `prisma.config.ts`, ou `data-source.ts`. Un projet qui garde le seul `prisma/schema.prisma` des versions antérieures à 0.95 le garde avec son `prisma.config.ts` et son `db:client`, même sous `--force` : `init` n'écrit rien sous `prisma/schema/`, ses notes donnent les étapes du déplacement en nommant les contextes du projet, et `generate repository` refuse jusqu'au déplacement |
651
651
  | `scripts/openapi.ts`, `scripts/events.ts` | écrivent `openapi/openapi.yaml` (un fichier par document de `openapi.documents`), `docs/integration/asyncapi.yaml` et `docs/integration/event-catalog.md`, en JSON sous `openapi.format: json` ; `--check` échoue sur une différence |
652
652
  | `scripts/privacy-erase.ts`, `scripts/privacy-export.ts` | avec `--privacy on`, les deux demandes d'une personne concernée, traitées en ligne de commande sur les sources avec les variables de `.env` (`npm run privacy:erase -- <subject-id> [--operator <qui-demande>] [--rerun]`, `npm run privacy:export -- <subject-id> > export.json`) : l'effacement détruit d'abord la clé de la personne quand le projet a un event store (`--event-sourcing on` : ses événements stockés se lisent effacés ; audité avec `--audit on`), puis efface chaque copie listée dans `src/platform/privacy/data-subject-copies.ts`, chacune laissant son entrée avec `--audit on`, et ce que l'outbox et le stockage des *jobs* gardent de la personne ; un id qui n'a rien atteint est refusé, code de sortie 1, et annoncé à personne, sauf si `--rerun` dit que cette personne a déjà été effacée ; `privacy:purge` lance à la main ce que le *job* `privacy.purge-expired` lance chaque nuit à 03:00 UTC, la purge de ce qui a dépassé sa durée de conservation (`JOB_PRIVACY_PURGE_EXPIRED_ENABLED=false` coupe le *job*) ; l'export rassemble chaque enregistrement listé dans `data-subject-exports.ts` en un document JSON daté (`format`, `subject`, `exportedAt`, `records`), l'export de chaque contexte audité avec `--audit on`, jamais les valeurs (chaque exécution laisse son entrée, un essai compris : essayez-le sur une personne de test). Avec `--tenancy shared-table`, `TENANTS` nomme les tenants, séparés par des virgules : une écriture de données de tenant n'est jamais élargie. Ni l'un ni l'autre n'atteint les sauvegardes, les journaux, une copie qu'aucun contexte n'a déclarée, un message déjà livré ou un *job* qui ne nomme aucun `subject` |
653
653
  | `docker-compose.yml`, `.env.example`, `Dockerfile`, `.dockerignore` | la base de données avec un contrôle de santé et un volume nommé, `jaegertracing/jaeger:2.22.0` derrière le profil `observability`, chaque port publié sur 127.0.0.1 seulement (une adresse plus large s'écrit dans l'entrée à dessein, le README du projet dit comment), les ports depuis `.env` ; une image multi-étapes, sans root, avec les seules dépendances de production |
654
- | `vitest.e2e.config.ts`, `test/e2e/support/` | `start-application.ts` (l'application entière sur un port libre, sur une base de données dans le processus sauf si `DATABASE_URL` est définie, aucun *job* lancé par le temps ; `settled()` se résout quand l'outbox a relayé ce que les requêtes HTTP ont enregistré ; `publish(events)` remet des événements d'intégration de l'amont à ses gestionnaires, comme le ferait le relais de cet amont), `create-credentials.ts` (au nom de qui un test appelle, `application.as({ id, roles })` ; en RBAC et en ABAC les rôles sont ceux de `Role` dans `src/platform/auth/authorization/role.ts`, si bien que `roles: [Role.Admin]` est complété par l'éditeur et qu'un rôle mal orthographié ne compile pas), `auth-environment.ts`, `test-environment.ts`, `story-of.ts` (`storyOf(trace)` : une trace sans les appels qu'un adaptateur fait sur lui-même, la forme que vérifie `expectSpanTree`) |
654
+ | `vitest.e2e.config.ts`, `test/e2e/support/` | `start-application.ts` (l'application entière sur un port libre, sur une base de données dans le processus sauf si `DATABASE_URL` est définie, alors sur une copie de cette base migrée, une par fichier de *spec*, si bien que les fichiers s'exécutent en même temps sur un serveur aussi ; aucun *job* lancé par le temps ; `settled()` se résout quand l'outbox a relayé ce que les requêtes HTTP ont enregistré ; `publish(events)` remet des événements d'intégration de l'amont à ses gestionnaires, comme le ferait le relais de cet amont), `create-credentials.ts` (au nom de qui un test appelle, `application.as({ id, roles })` ; en RBAC et en ABAC les rôles sont ceux de `Role` dans `src/platform/auth/authorization/role.ts`, si bien que `roles: [Role.Admin]` est complété par l'éditeur et qu'un rôle mal orthographié ne compile pas), `auth-environment.ts`, `test-environment.ts`, `story-of.ts` (`storyOf(trace)` : une trace sans les appels qu'un adaptateur fait sur lui-même, la forme que vérifie `expectSpanTree`) |
655
655
  | `docs/context-map.md`, `docs/integration/README.md` | voir `docs` |
656
656
  | `test/architecture/extractable.spec.ts` | écrit avec le premier contexte : démarre chaque contexte seul sur le kernel et la plateforme, ses *jobs* compris |
657
657
  | `eslint.config.mjs` | le preset `dddTsKit` de `@ddd-ts-kit/eslint-plugin`, lint typé sur le tsconfig du projet |
@@ -849,14 +849,16 @@ Next, in this order: the language of the context first, then the business decisi
849
849
  | `schema` | `<context\|shared-kernel> <Name>` | `presentation/http/shared/<name>.schema.ts` du contexte, ou `presentation/<name>.schema.ts` du noyau partagé : une forme du contrat déclarée une fois (un schéma zod avec `.meta({ id })`, une classe class-validator, ou un schéma enveloppé par `sharedSchema`), à remplir ; les routes l'utilisent en entier, imbriquée ou en partie |
850
850
  | `integration-event` | `<context> <Aggregate> <Fact> [--version n] [--module <module>]` | la déclaration `defineIntegrationEvent` dans le langage publié (sa charge utile dans `<event>.v<n>.payload.ts` avec class-validator ou un schéma à vous), l'export de l'index, le *publisher* `application/integration/publishers/<event>.publisher.ts`, une *spec*, l'enregistrement, une ligne de `platform/audit/audited-events.ts` |
851
851
  | `integration-handler` (`consumer`) | `<context> <upstreamContext> <eventType>[@v<n>] [--version <n>] [--name <Name>] [--module <module>]` | `application/integration/handlers/<name>.integration-handler.ts`, une classe `<Name>IntegrationHandler` qui dépend de `CommandBus`, sa *spec*, son abonnement idempotent sous le nom de consommateur `<context>.<name>` ; le type est pris comme `list` l'affiche, avec ou sans `@v<n>` (la version la plus récente sans, `--version <n>` disant la même chose que le suffixe) ; refusé sauf si l'amont est déclaré et publie cette version (une version introuvable est refusée, jamais remplacée par une autre) |
852
+ | `personal-fields` | `<context> <table> --personal <colonne>,... --subject <colonne> [--erasure pseudonymise\|row] [--retention <colonne>:<n><d\|m\|y>] [--tenant-scoped] [--module <module>]` | la déclaration des colonnes personnelles d'une table qu'aucun agrégat ne possède (un modèle de lecture, une table de messages reçus, une table écrite à la main), donnée par son nom SQL : `infrastructure/persistence/<table>.personal-fields.ts`, épelée comme l'effacement de l'ORM la lit (avec Drizzle et TypeORM par les propriétés que le fichier de schéma donne aux colonnes), jointe à l'effacement et à l'export du contexte, ou écrite avec eux comme `repository --personal` les écrit pour une première table, sauf la *spec* : `test/integration/<context>-personal-data.spec.ts` prouve les *fakes* et nomme en `it.todo` chaque cas à prouver sur la base de test, aucun *repository* ni *builder* n'écrivant les lignes d'une telle table. `--subject` est obligatoire : la ligne d'une telle table est rarement la personne. La table est lue dans le fichier de schéma du contexte et jamais modifiée. Refusés : une table que ce fichier ne déclare pas, une table qui a une déclaration, une colonne que la définition de la table ne tient pas (dite dans la sortie quand la définition prend des colonnes d'une décomposition ou d'une fonction), une table sans `tenant_id` là où l'effacement est confiné à un *tenant*, et ce que `--personal` d'un *repository* refuse |
852
853
  | `erasure-handler` | `<context> [--module <module>]` | `application/integration/handlers/data-subject-erased.integration-handler.ts`, une classe `DataSubjectErasedIntegrationHandler` qui efface ce que le contexte garde d'une personne par son `<Context>PersonalDataErasure` quand la plateforme annonce `privacy.data-subject.erased` (`dataSubjectErasedV1` du kernel), sa *spec* sur le *fake*, son abonnement idempotent sous le nom de consommateur `<context>.data-subject-erased` (dans une transaction derrière un *broker*) ; pour un contexte qui tourne comme un service à part ou copie des données personnelles depuis des événements. Refusé tant que le contexte n'a pas son effacement (`generate repository --personal`), et refusé sur un contexte en *event sourcing*, dont les valeurs personnelles s'effacent en détruisant la clé du sujet (`eraseDataSubject`) |
853
854
  | `event-handler` | `<context> <Aggregate> <Fact> [--phase before-commit\|after-commit] [--name <Name>] [--module <module>]` | réaction à un événement du domaine du contexte, *spec*, abonnement ; avant la validation (commit) de l'unité de travail par défaut, après elle avec `--phase after-commit` (un effet qu'aucune transaction ne couvre, au plus une fois), et la *spec* exécute la réaction dans cette phase |
854
- | `projection` (`projector`) | `<context> <Name> <event-type>[@v<n>] [--module <module>]` | un projecteur dans `application/projections/<name>.projection.ts`, déclaré avec `@Projection('<context>.<name>')` et une méthode `@On(definition)` pour l'événement d'intégration, que publie le contexte lui-même ou un amont déclaré, et sa *spec* ; le type est pris comme `list` l'affiche, `@v<n>` fixant la version (la plus récente sans). Dans le style explicite sur tsyringe, le fichier de module du contexte l'inclut par `builder.include(<Name>Projection)` ; sur une plateforme câblée à la main, la classe est simple et le module la souscrit sous son nom de consommateur. Il tient un seul modèle de lecture : son port est reçu par le constructeur |
855
+ | `projection` (`projector`) | `<context> <Name> <event-type>[@v<n>] [--module <module>]` | un projecteur dans `application/projections/<name>.projection.ts`, déclaré avec `@Projection('<context>.<name>')` et une méthode `@On(definition)` pour l'événement d'intégration, que publie le contexte lui-même ou un amont déclaré, et sa *spec* ; le type est pris comme `list` l'affiche, `@v<n>` fixant la version (la plus récente sans). Dans le style explicite sur tsyringe, le fichier de module du contexte l'inclut par `builder.include(<Name>Projection)` ; sur une plateforme câblée à la main, la classe est simple et le module la souscrit sous son nom de consommateur. Il tient un seul modèle de lecture, qu'écrit `generate read-model` : son port est reçu par le constructeur |
856
+ | `read-model` | `<context> <Name> [--field <name>:<type>[:nullable]]... [--tenant-scoped] [--module <module>]` | le modèle de lecture que tient une projection. Le port dans `application/ports/<name>.port.ts` : le type `<Name>Row` (la clé `id`, puis un champ par `--field`, de type `string`, `number`, `boolean`, `instant` ou `decimal`, `:nullable` pour celui qui peut valoir null), les critères `<name>Criteria` que ses lecteurs peuvent demander, et la classe abstraite `<Name>` au-dessus de `ReadModelStore<<Name>Row>`. Sa table, nommée d'après lui en snake_case, dans le schéma du contexte, avec la colonne de chaque champ et les colonnes du registre (`readModelColumns()` ; le modèle Prisma les porte comme champs). La colonne d'un champ accepte null quoi qu'exige la ligne, une ligne supprimée étant une trace qui ne garde que sa clé et son tampon, et une contrainte de vérification `<table>_live_rows_whole` garde entière toute autre ligne, `deleted or (<column> is not null and ...)` sur les champs que la ligne exige : `check(...)` sur Drizzle, `table.check(...)` sur Knex, `checks` du schéma d'entité sur TypeORM, et sur Prisma, dont le langage de schéma n'en a pas, une ligne `TODO(domain)` du modèle qui porte l'`ALTER TABLE` à ajouter à la migration. La colonne du *tenant* et son index avec `--tenant-scoped` ou dans un projet multi-*tenant*. L'adaptateur `infrastructure/persistence/<orm>-<name>.repository.ts`, une classe `<Orm><Name>` au-dessus du registre de modèle de lecture du paquet de l'ORM (`DrizzleReadModelStore`, `KnexReadModelStore`, `PrismaReadModelStore`, `TypeOrmReadModelStore` ; `InMemoryReadModelStore` du noyau dans un projet sans ORM), déclarée avec `@Repository(<Name>)`, ou liée dans le fichier de module dans le style explicite (une note dit où la construire sur une plateforme câblée à la main). Le *fake* `test/fakes/<name>.fake.ts` et `test/integration/<name>.contract.spec.ts`, qui lance `readModelContract` sur le *fake* et sur l'adaptateur et, avec un *tenant*, prouve qu'un *tenant* ne lit pas les lignes d'un autre. Un port de ce nom qui n'est pas un modèle de lecture est refusé |
855
857
  | `job` | `<context> <Name> (--every <duration> \| --cron "<expression>" [--time-zone <zone>]) --command <UseCaseName> [--global] [--module <module>]` | `application/scheduling/<name>.job.ts`, une classe `<Name>Job implements ScheduledJob` qui envoie la commande, en tant que `systemActor('<context>.<name>')` quand elle est protégée, avec `execution.scheduledAt` quand la commande le prend ; `test/unit/<name>.job.spec.ts`, qui exécute le *job* (par son nom sur tsyringe, `application.jobs.runNow` ; `job.run(occurrence)` en câblage manuel) et vérifie la commande qu'il a envoyée ; son enregistrement ; son interrupteur dans `platform/jobs/job-settings.ts` ; l'autorisation de son acteur système (ci-dessous) |
856
858
  | `background-job` | `<context> <Name> --command <UseCaseName> [--module <module>]` | `application/background/<name>.background-job.ts`, une classe `<Name>BackgroundJob implements BackgroundJob<<Name>Payload>` nommée par son `jobName` statique `<context>.<name>`, qui envoie la commande en tant que `execution.actor` quand elle est protégée, suivi d'un champ de `<Name>Payload` par autre paramètre du constructeur de la commande (chaînes, nombres, booléens, littéraux et listes de ceux-ci tels qu'écrits, une `Date` sous forme de son texte ISO ; tout le reste est refusé), et son `payload` statique, le schéma de cette charge utile dans la bibliothèque de validation de la pile (un `z.object` sous zod, une classe de champs décorés sans valeur initiale sous class-validator, un `Type.Object` sous TypeBox, un refus par champ écrit à la main sous Standard Schema et, avec `--validation none`, dans le `BackgroundJobPayloadSchema` du noyau ; un type qu'il ne sait pas vérifier est typé `unknown` avec un `TODO(domain)`), avec lequel le *worker* lit la charge utile stockée avant chaque exécution ; `test/unit/<name>.background-job.spec.ts`, qui le met en file avec une charge utile de chaque champ en tant qu'utilisateur et exécute ce qui est dû, puis le met en file tel qu'une version antérieure le déclarait (`earlierVersionOf` de `@ddd-ts-kit/testing`) et montre le *job* mort avec `INVALID_JOB_PAYLOAD` (à travers l'application de test sur tsyringe, à travers une file et un *worker* en mémoire sur les bus de test sinon) ; son enregistrement (`@Background()`, `builder.backgroundJob(..)` dans le fichier de module sur tsyringe, `platform.backgroundJobs.register(..)` dans le fichier de module d'une plateforme câblée à la main) |
857
859
  | `process` (`process-manager`) | `<context> <Name> [--module <module>]` | `application/processes/<name>.process.ts` (son état, `processName`, `timeoutJob`, `isState`, une première étape qui arme une échéance, une étape qui y met fin à temps, l'étape de l'échéance), `application/background/<name>-timeout.background-job.ts`, qui livre ses expirations au moyen de `ProcessRunner`, et les *specs* des deux (`givenProcess`, la file de l'application de test sur tsyringe, une file et un *runner* en mémoire sur les bus de test sinon) |
858
860
  | `acl` | `<context> <upstreamOrSystemName> [--module <module>]` | traducteur dans `infrastructure/anti-corruption/`, *spec* |
859
- | `e2e` | `<context> <UseCaseName> [--event <eventType>]` | `test/e2e/<use-case>.e2e.spec.ts` qui pilote la route du cas d'usage : 401 sans identifiant de connexion, 403 sans la permission, le statut documenté avec elle ; pour une commande, un test de plus vérifie la trace de la requête HTTP, exacte sur les noms et la structure, avec `installTestTracing()` et `expectSpanTree(storyOf(trace), [...])` de `@ddd-ts-kit/tracing/testing` (`POST /invoices`, puis `command IssueInvoiceCommand`, puis `repository InvoiceRepository.save`, et après lui, pour une commande qui donne naissance à un agrégat né avec `--birth`, `unit-of-work before-commit` et `domain-event <name>` de son événement de naissance, une note nommant ce qui y réagit déjà). Un cas d'usage qu'aucune route n'atteint, lancé par un gestionnaire d'événement d'intégration du contexte, reçoit une spec qui publie l'événement de l'amont, construit depuis sa déclaration, avec `application.publish([event])`, attend `application.settled()` et laisse des `it.todo` pour ce qu'un client observe (les routes `GET` du contexte, ou les événements qu'il publie, avec `collectEvents`) ; le gestionnaire qui envoie `<UseCase>Command` est cherché dans `application/integration/handlers/`, et `--event billing.invoice.issued` nomme l'événement quand des gestionnaires de plusieurs l'envoient, ou quand le gestionnaire ne l'envoie pas encore. Demande la route, ou ce gestionnaire |
861
+ | `e2e` | `<context> <UseCaseName> [--event <eventType> \| --job <JobName>]` | `test/e2e/<use-case>.e2e.spec.ts` qui pilote la route du cas d'usage : 401 sans identifiant de connexion, 403 sans la permission, le statut documenté avec elle ; pour une commande, un test de plus vérifie la trace de la requête HTTP, exacte sur les noms et la structure, avec `installTestTracing()` et `expectSpanTree(storyOf(trace), [...])` de `@ddd-ts-kit/tracing/testing` (`POST /invoices`, puis `command IssueInvoiceCommand`, puis `repository InvoiceRepository.save`, et après lui, pour une commande qui donne naissance à un agrégat né avec `--birth`, `unit-of-work before-commit` et `domain-event <name>` de son événement de naissance, une note nommant ce qui y réagit déjà). Un cas d'usage qu'aucune route n'atteint, lancé par un gestionnaire d'événement d'intégration du contexte, reçoit une spec qui publie l'événement de l'amont, construit depuis sa déclaration, avec `application.publish([event])`, attend `application.settled()` et laisse des `it.todo` pour ce qu'un client observe (les routes `GET` du contexte, ou les événements qu'il publie, avec `collectEvents`) ; le gestionnaire qui envoie `<UseCase>Command` est cherché dans `application/integration/handlers/`, et `--event billing.invoice.issued` nomme l'événement quand des gestionnaires de plusieurs l'envoient, ou quand le gestionnaire ne l'envoie pas encore. Un cas d'usage dont seul un *job* envoie la commande reçoit un test par *job* : `await application.runJob('<context>.<job>')` pour un *job* planifié (`application/scheduling/`), et, pour un *job* en arrière-plan (`application/background/`), la requête qui le met en file laissée à écrire, `const ran = await application.runDueJobs()`, qui exécute ce qui est échu dans les files comme le ferait le *worker*, et la vérification que le *job* est parmi `ran` ; chacun attend ensuite `application.settled()`. `--job VoidInvoice` nomme un seul *job*, par sa classe ou par le nom sous lequel il s'exécute (`billing.void-invoice`), y compris pour un cas d'usage qu'une route atteint, et écrit `test/e2e/<use-case>-<job>.e2e.spec.ts`. Demande la route, ce gestionnaire, ou un *job* qui envoie la commande |
860
862
  | `acceptance` | `<story> ["<title>"]` | `test/acceptance/<story>.acceptance.spec.ts`, écrit avant le code : un `it.todo` par critère d'acceptation de `docs/architecture/stories/<story>.md`, ou par ligne de tranche de l'histoire dans `docs/architecture/slices.md` quand elle n'en énonce aucun |
861
863
  | `policy` | `<context> <Name> --permission <aggregate>.<action> [--module <module>]` | `application/authorization/<name>.policy.ts`, *spec* ; déclaré : la classe porte `@Policy(permission, { name })` et rien d'autre n'est écrit ; explicite : l'enregistrement dans `platform/auth/authorization/access-policies.ts` |
862
864
  | `gateway` | `<context> <upstreamContext> <Name> [--module <module>]` | le contrat de lecture dans le langage publié de l'amont (`<name>.contract.ts`, une classe abstraite et le jeton de la valeur de l'amont), le port `application/ports/<name>-gateway.port.ts`, un adaptateur dans le processus dans `infrastructure/external/` lié `.as('gateway')`, un *fake*, une suite de contrat ; refusé sauf si l'amont est déclaré |
package/README.md CHANGED
@@ -616,12 +616,12 @@ config, `docsUi`, `ci` and `logger` included.
616
616
  | `--storage local\|s3` | recorded as `stack.storage`: where the content of files lives, never in the database. `src/platform/config/read-files.ts` and `src/platform/files/open-files.ts`, one per choice: `local`, a directory in development (`FILES_DIRECTORY`, `.data/files`) and the signed links answered by the application under `/files` (`FILES_PUBLIC_URL` and `FILES_SIGNING_SECRET` required in production); `s3`, a bucket of any provider of the S3 protocol through `@ddd-ts-kit/s3` (the `S3_*` variables, MinIO in the compose stack); the memory of the process in the tests and the tools, either way. With `--di tsyringe`: `files/bind-files.ts`, `files/files.module.ts` and `files/staging-uploads.ts`; with hand wiring `files/create-files.ts`; with an HTTP stack `files/file-routes.ts`. They bind `FileStorage`, `FileKeys`, `FileScanner` and `FileStaging`, register the hourly purge of staged files and stage the file a command carries before its transaction; `generate file-upload` needs them. `--storage none` writes none of this ([File storage](../../docs/concepts/file-storage.md)) |
617
617
  | `--search opensearch\|none` | recorded as `stack.search`, `none` by default: where the read models a context keeps for search live. `opensearch`: `@ddd-ts-kit/opensearch`, `src/platform/search/search-indexes.ts` (`SearchIndexes`, the abstract class the adapter of a read model port takes: `super(search.options('billing_invoices', criteria))`) and `search/open-search.ts` (`fetchTransport` on `OPENSEARCH_URL`, the user of `OPENSEARCH_USERNAME` and `OPENSEARCH_PASSWORD` both or neither, the tenancy `attribute` under `--tenancy shared-table`, `none` otherwise), bound by `search/search.module.ts` on a container of the kit, `platform.search` wired by hand and under Nest; the index of each store built from it provisioned before a request, under shared tables for the tenant of the work once the tenant directory of the platform lists it (an unlisted tenant creates no index), best effort at the start, which never fails on search, nothing called without a store; the privacy scripts given the node; a compose service `opensearch` (one node, security plugin off). No generator writes a store, and the pipeline starts no node; a context builds its stores from `SearchIndexes` only (`search/store-from-platform`). [Search read models](../../docs/tools/search-read-models.md) |
618
618
  | `src/platform/events/` | `event-provider.ts` (`bus`, `forConsumer(name)`, `start()`, `close()`), `in-process-events.ts`, and for `--broker` `create-event-provider.ts`: `RabbitMqEventBus` (`AMQP_URL`), `KafkaEventBus` (`KAFKA_BROKERS`, with `aggregate-key-of.ts` for per-aggregate order), `NatsEventBus` (`NATS_URL`) or `RedisStreamsEventBus` of `@ddd-ts-kit/redis/event-bus` (`REDIS_URL`: Redis, Dragonfly or Valkey), each with one subscriber per consuming context (`forConsumer`), `assertTopology` at start, its address validated and a compose service with a healthcheck; or `custom-event-bus.ts` with its `eventBusContract` spec. `start-outbox-relay.ts` with the outbox. `--broker redis` with `--cache redis` is one server and one compose service, `cache`; alone, the service is `streams` |
619
- | `src/platform/database/` | `persistence.ts` (`interface Persistence`: unit of work, outbox and processed-event stores of the ORM package, the storage handle), `open-persistence.ts`, `persistence-over.ts`, `inert-persistence.ts`, the connection (`connect-to-database.ts`, `create-client.ts` or `create-data-source.ts`), `schema.ts` (`MESSAGING_SCHEMA`, the schema of what the kit stores for the application), `open-test-database.ts` (PostgreSQL in process, or the server named by a URL; with Vitest each spec opens a copy of the cluster `test/support/test-database-template.ts`, the global setup of the run, initialised once, and creates its tables there; with drizzle from `table-statements.ts`, the SQL of the tables of `schema.ts`, since drizzle-kit writes migrations, not tables, its unique indexes included), `persistence.contract.spec.ts` (the outbox, processed-event, job and process stores as the platform wires them, held to the contracts of `@ddd-ts-kit/testing` with what the stack turns on: the tenant under `--tenancy`, the unit of work). The storage class a repository adapter names in its dependency list: `database.ts` with drizzle and prisma (`abstract class Database extends` the context type of the ORM package), `KnexContext` of `@ddd-ts-kit/knex`, `TypeOrmContext` of `@ddd-ts-kit/typeorm` |
619
+ | `src/platform/database/` | `persistence.ts` (`interface Persistence`: unit of work, outbox and processed-event stores of the ORM package, the storage handle), `open-persistence.ts`, `persistence-over.ts`, `inert-persistence.ts`, the connection (`connect-to-database.ts`, `create-client.ts` or `create-data-source.ts`), `schema.ts` (`MESSAGING_SCHEMA`, the schema of what the kit stores for the application), `open-test-database.ts` (PostgreSQL in process, or the server named by a URL, each call then on a copy of the migrated database, made and dropped by `test/support/test-database-clone.ts`; with Vitest each spec opens a copy of the cluster `test/support/test-database-template.ts`, the global setup of the run, initialised once, and creates its tables there; with drizzle from `table-statements.ts`, the SQL of the tables of `schema.ts`, since drizzle-kit writes migrations, not tables, its unique indexes included), `persistence.contract.spec.ts` (the outbox, processed-event, job and process stores as the platform wires them, held to the contracts of `@ddd-ts-kit/testing` with what the stack turns on: the tenant under `--tenancy`, the unit of work). The storage class a repository adapter names in its dependency list: `database.ts` with drizzle and prisma (`abstract class Database extends` the context type of the ORM package), `KnexContext` of `@ddd-ts-kit/knex`, `TypeOrmContext` of `@ddd-ts-kit/typeorm` |
620
620
  | migration tooling | `drizzle.config.ts`, `knexfile.js` and the folder `migrations/`, `prisma/schema/schema.prisma` (the client, the datasource and the tables of the platform; `generate repository` adds the file of each context, `prisma/schema/<context>.prisma`) and `prisma.config.ts`, or `data-source.ts`. A project that keeps the one `prisma/schema.prisma` of versions before 0.95 keeps it with its `prisma.config.ts` and its `db:client`, even under `--force`: `init` writes nothing under `prisma/schema/`, its notes give the steps of the move with the contexts of the project named, and `generate repository` refuses until the move |
621
621
  | `scripts/openapi.ts`, `scripts/events.ts` | write `openapi/openapi.yaml` (one file per document of `openapi.documents`), `docs/integration/asyncapi.yaml` and `docs/integration/event-catalog.md`, in JSON under `openapi.format: json`; `--check` fails on a difference |
622
622
  | `scripts/privacy-erase.ts`, `scripts/privacy-export.ts` | with `--privacy on`, the two requests of a data subject, answered from the command line on the sources with the variables of `.env` (`npm run privacy:erase -- <subject-id> [--operator <who-asks>] [--rerun]`, `npm run privacy:export -- <subject-id> > export.json`): the erasure destroys the key of the subject first when the project has an event store (`--event-sourcing on`: its stored events read as erased; audited with `--audit on`), then erases every copy listed in `src/platform/privacy/data-subject-copies.ts`, each leaving its entry with `--audit on`, and what the outbox and the job store keep of the person; an id that reached nothing is refused, exit code 1, and announced to nobody, unless `--rerun` says this person was erased before; `privacy:purge` runs by hand what the job `privacy.purge-expired` runs every night at 03:00 UTC, the purge of what outlived its retention (`JOB_PRIVACY_PURGE_EXPIRED_ENABLED=false` switches the job off); the export gathers every record listed in `data-subject-exports.ts` into one dated JSON document (`format`, `subject`, `exportedAt`, `records`), the export of each context audited with `--audit on`, never the values (every run leaves its entry, a trial included: try it on a test subject). With `--tenancy shared-table`, `TENANTS` names the tenants, comma separated: a write of tenant data is never widened. Neither reaches backups, logs, a copy no context declared, a message already delivered or a job that names no `subject` |
623
623
  | `docker-compose.yml`, `.env.example`, `Dockerfile`, `.dockerignore` | the database with a healthcheck and a named volume, `jaegertracing/jaeger:2.22.0` behind the `observability` profile, every port published on 127.0.0.1 only (a wider address is written in the entry on purpose, the README of the project says how), ports from `.env`; a multi-stage, non-root image with production dependencies only |
624
- | `vitest.e2e.config.ts`, `test/e2e/support/` | `start-application.ts` (the whole application on a free port, on an in-process database unless `DATABASE_URL` is set, no job run by time; `settled()` resolves once the outbox has relayed what the requests stored; `publish(events)` hands integration events of an upstream to its handlers, as the relay of that upstream would), `create-credentials.ts` (who a test calls as, `application.as({ id, roles })`; under RBAC and ABAC the roles are those of `Role` in `src/platform/auth/authorization/role.ts`, so `roles: [Role.Admin]` is completed by the editor and a misspelled role does not compile), `auth-environment.ts`, `test-environment.ts`, `story-of.ts` (`storyOf(trace)`: a trace without the calls an adapter makes on itself, the form `expectSpanTree` asserts) |
624
+ | `vitest.e2e.config.ts`, `test/e2e/support/` | `start-application.ts` (the whole application on a free port, on an in-process database unless `DATABASE_URL` is set, then on a copy of that migrated database, one per spec file, so the files run at the same time on a server too; no job run by time; `settled()` resolves once the outbox has relayed what the requests stored; `publish(events)` hands integration events of an upstream to its handlers, as the relay of that upstream would), `create-credentials.ts` (who a test calls as, `application.as({ id, roles })`; under RBAC and ABAC the roles are those of `Role` in `src/platform/auth/authorization/role.ts`, so `roles: [Role.Admin]` is completed by the editor and a misspelled role does not compile), `auth-environment.ts`, `test-environment.ts`, `story-of.ts` (`storyOf(trace)`: a trace without the calls an adapter makes on itself, the form `expectSpanTree` asserts) |
625
625
  | `docs/context-map.md`, `docs/integration/README.md` | see `docs` |
626
626
  | `test/architecture/extractable.spec.ts` | written with the first context: boots each context alone on the kernel and the platform, its jobs included |
627
627
  | `eslint.config.mjs` | the `dddTsKit` preset of `@ddd-ts-kit/eslint-plugin`, typed linting on the project's tsconfig |
@@ -812,14 +812,16 @@ Next, in this order: the language of the context first, then the business decisi
812
812
  | `schema` | `<context\|shared-kernel> <Name>` | `presentation/http/shared/<name>.schema.ts` of the context, or `presentation/<name>.schema.ts` of the shared kernel: one shape of the contract declared once (a zod schema with `.meta({ id })`, a class-validator class, or a schema wrapped by `sharedSchema`), to fill; the routes use it whole, nested or in part |
813
813
  | `integration-event` | `<context> <Aggregate> <Fact> [--version n] [--module <module>]` | `defineIntegrationEvent` declaration in the published language (its payload in `<event>.v<n>.payload.ts` with class-validator or a schema of your own), index export, the publisher `application/integration/publishers/<event>.publisher.ts`, spec, registration, a line of `platform/audit/audited-events.ts` |
814
814
  | `integration-handler` (`consumer`) | `<context> <upstreamContext> <eventType>[@v<n>] [--version <n>] [--name <Name>] [--module <module>]` | `application/integration/handlers/<name>.integration-handler.ts`, a class `<Name>IntegrationHandler` depending on `CommandBus`, its spec, its idempotent subscription under the consumer name `<context>.<name>`; the type is taken as `list` prints it, with or without `@v<n>` (the newest version without, `--version <n>` saying the same as the suffix); refused unless the upstream is declared and publishes that version (a version that is not found is refused, never replaced by another) |
815
+ | `personal-fields` | `<context> <table> --personal <column>,... --subject <column> [--erasure pseudonymise\|row] [--retention <column>:<n><d\|m\|y>] [--tenant-scoped] [--module <module>]` | the declaration of the personal columns of a table no aggregate owns (a read model, a table of received messages, a table written by hand), given by its SQL name: `infrastructure/persistence/<table>.personal-fields.ts`, spelled as the erasure of the ORM reads it (on Drizzle and TypeORM with the properties the schema file gives the columns), joined to the erasure and to the export of the context, or written with them as `repository --personal` writes them for a first table, except the spec: `test/integration/<context>-personal-data.spec.ts` proves the fakes and names as `it.todo` each case to prove on the test database, no repository nor builder writing the rows of such a table. `--subject` is required: the row of such a table is rarely the person. The table is read in the schema file of the context and never changed. Refused: a table that file does not declare, a table that has a declaration, a column the definition of the table does not hold (said in the output instead when the definition takes columns from a spread or a helper), a table without `tenant_id` where the erasure is confined to a tenant, and what `--personal` of a repository refuses |
815
816
  | `erasure-handler` | `<context> [--module <module>]` | `application/integration/handlers/data-subject-erased.integration-handler.ts`, a class `DataSubjectErasedIntegrationHandler` that erases what the context keeps of a person through its `<Context>PersonalDataErasure` when the platform announces `privacy.data-subject.erased` (`dataSubjectErasedV1` of the kernel), its spec on the fake, its idempotent subscription under the consumer name `<context>.data-subject-erased` (in a transaction behind a broker); for a context that runs as a service of its own or copies personal data from events. Refused until the context has its erasure (`generate repository --personal`), and refused on an event-sourced context, whose personal values are erased by destroying the key of the subject (`eraseDataSubject`) |
816
817
  | `event-handler` | `<context> <Aggregate> <Fact> [--phase before-commit\|after-commit] [--name <Name>] [--module <module>]` | reaction to a domain event of the context, spec, subscription; before the commit of the unit of work by default, after it with `--phase after-commit` (an effect no transaction covers, at most once), and the spec runs the reaction in that phase |
817
- | `projection` (`projector`) | `<context> <Name> <event-type>[@v<n>] [--module <module>]` | a projector in `application/projections/<name>.projection.ts`, declared with `@Projection('<context>.<name>')` and one `@On(definition)` method for the integration event, which the context itself or a declared upstream publishes, and its spec; the type is taken as `list` prints it, `@v<n>` pinning the version (the newest without). In the explicit style on tsyringe the module file of the context includes it with `builder.include(<Name>Projection)`; on a hand-wired platform the class is plain and the module subscribes it under its consumer name. It keeps one read model: its port is received in the constructor |
818
+ | `projection` (`projector`) | `<context> <Name> <event-type>[@v<n>] [--module <module>]` | a projector in `application/projections/<name>.projection.ts`, declared with `@Projection('<context>.<name>')` and one `@On(definition)` method for the integration event, which the context itself or a declared upstream publishes, and its spec; the type is taken as `list` prints it, `@v<n>` pinning the version (the newest without). In the explicit style on tsyringe the module file of the context includes it with `builder.include(<Name>Projection)`; on a hand-wired platform the class is plain and the module subscribes it under its consumer name. It keeps one read model, which `generate read-model` writes: its port is received in the constructor |
819
+ | `read-model` | `<context> <Name> [--field <name>:<type>[:nullable]]... [--tenant-scoped] [--module <module>]` | the read model a projection keeps. The port in `application/ports/<name>.port.ts`: the type `<Name>Row` (the key `id`, then one field per `--field`, of type `string`, `number`, `boolean`, `instant` or `decimal`, `:nullable` for one that may hold null), the criteria `<name>Criteria` its readers may ask, and the abstract class `<Name>` over `ReadModelStore<<Name>Row>`. Its table, named after it in snake_case, in the schema of the context, with the column of each field and the columns of the store (`readModelColumns()`; the Prisma model holds them as fields). The column of a field accepts null whatever the row requires, a removed row being a trace that keeps its key and its stamp alone, and a check constraint `<table>_live_rows_whole` keeps every other row whole, `deleted or (<column> is not null and ...)` over the fields the row requires: `check(...)` on Drizzle, `table.check(...)` on Knex, `checks` of the entity schema on TypeORM, and on Prisma, whose schema language has none, a `TODO(domain)` line of the model that holds the `ALTER TABLE` to add to the migration. The tenant column and its index with `--tenant-scoped` or in a multi-tenant project. The store adapter `infrastructure/persistence/<orm>-<name>.repository.ts`, a class `<Orm><Name>` over the read model store of the ORM package (`DrizzleReadModelStore`, `KnexReadModelStore`, `PrismaReadModelStore`, `TypeOrmReadModelStore`; `InMemoryReadModelStore` of the kernel in a project without an ORM), declared with `@Repository(<Name>)`, or bound in the module file in the explicit style (a note says where to build it on a hand-wired platform). The fake `test/fakes/<name>.fake.ts` and `test/integration/<name>.contract.spec.ts`, which runs `readModelContract` on the fake and on the adapter, and with a tenant proves that one tenant does not read the rows of another. A port of that name that is no read model is refused |
818
820
  | `job` | `<context> <Name> (--every <duration> \| --cron "<expression>" [--time-zone <zone>]) --command <UseCaseName> [--global] [--module <module>]` | `application/scheduling/<name>.job.ts`, a class `<Name>Job implements ScheduledJob` that sends the command, as `systemActor('<context>.<name>')` when it is protected, with `execution.scheduledAt` when the command takes it; `test/unit/<name>.job.spec.ts`, which runs the job (by name on tsyringe, `application.jobs.runNow`; `job.run(occurrence)` with hand wiring) and asserts the command it sent; its registration; its switch in `platform/jobs/job-settings.ts`; the grant of its system actor (below) |
819
821
  | `background-job` | `<context> <Name> --command <UseCaseName> [--module <module>]` | `application/background/<name>.background-job.ts`, a class `<Name>BackgroundJob implements BackgroundJob<<Name>Payload>` named by its static `jobName` `<context>.<name>`, that sends the command as `execution.actor` when it is protected, followed by one field of `<Name>Payload` per other parameter of the constructor of the command (strings, numbers, booleans, literals and lists of them as written, a `Date` as its ISO text; anything else is refused), and its static `payload`, the schema of that payload in the validation library of the stack (a `z.object` under zod, a class of decorated fields without initial value under class-validator, a `Type.Object` under TypeBox, one refusal per field written by hand under Standard Schema and, with `--validation none`, in the `BackgroundJobPayloadSchema` of the kernel; a type it writes no check for is typed `unknown` with a `TODO(domain)`), which the worker reads the stored payload with before each run; `test/unit/<name>.background-job.spec.ts`, which enqueues it with a payload of every field as a user and runs what is due, then enqueues it as an earlier version declared it (`earlierVersionOf` of `@ddd-ts-kit/testing`) and shows the job dead with `INVALID_JOB_PAYLOAD` (through the test application on tsyringe, through a queue and a worker in memory on the test buses otherwise); its registration (`@Background()`, `builder.backgroundJob(..)` in the module file on tsyringe, `platform.backgroundJobs.register(..)` in the module file of a platform wired by hand) |
820
822
  | `process` (`process-manager`) | `<context> <Name> [--module <module>]` | `application/processes/<name>.process.ts` (its state, `processName`, `timeoutJob`, `isState`, a first step that arms a deadline, a step that ends it in time, the step of the deadline), `application/background/<name>-timeout.background-job.ts`, which delivers its timeouts through `ProcessRunner`, and the specs of both (`givenProcess`, the queue of the test application on tsyringe, a queue and a runner in memory on the test buses otherwise) |
821
823
  | `acl` | `<context> <upstreamOrSystemName> [--module <module>]` | translator in `infrastructure/anti-corruption/`, spec |
822
- | `e2e` | `<context> <UseCaseName> [--event <eventType>]` | `test/e2e/<use-case>.e2e.spec.ts` driving the route of the use case: 401 without a credential, 403 without the permission, the documented status with it; for a command, one more test asserts the trace of the request, exact on names and structure, with `installTestTracing()` and `expectSpanTree(storyOf(trace), [...])` of `@ddd-ts-kit/tracing/testing` (`POST /invoices`, then `command IssueInvoiceCommand`, then `repository InvoiceRepository.save`, and after it, for a command that gives birth to an aggregate born with `--birth`, `unit-of-work before-commit` and `domain-event <name>` of its birth event, a note naming what already reacts to it). A use case no route reaches, started by an integration event handler of the context, gets a spec that publishes the upstream event, built from its declaration, with `application.publish([event])`, awaits `application.settled()` and leaves `it.todo` for what a client observes (the `GET` routes of the context, or the events it publishes with `collectEvents`); the handler that sends `<UseCase>Command` is found in `application/integration/handlers/`, and `--event billing.invoice.issued` names the event when handlers of several send it, or when the handler does not send it yet. Needs the route, or that handler |
824
+ | `e2e` | `<context> <UseCaseName> [--event <eventType> \| --job <JobName>]` | `test/e2e/<use-case>.e2e.spec.ts` driving the route of the use case: 401 without a credential, 403 without the permission, the documented status with it; for a command, one more test asserts the trace of the request, exact on names and structure, with `installTestTracing()` and `expectSpanTree(storyOf(trace), [...])` of `@ddd-ts-kit/tracing/testing` (`POST /invoices`, then `command IssueInvoiceCommand`, then `repository InvoiceRepository.save`, and after it, for a command that gives birth to an aggregate born with `--birth`, `unit-of-work before-commit` and `domain-event <name>` of its birth event, a note naming what already reacts to it). A use case no route reaches, started by an integration event handler of the context, gets a spec that publishes the upstream event, built from its declaration, with `application.publish([event])`, awaits `application.settled()` and leaves `it.todo` for what a client observes (the `GET` routes of the context, or the events it publishes with `collectEvents`); the handler that sends `<UseCase>Command` is found in `application/integration/handlers/`, and `--event billing.invoice.issued` names the event when handlers of several send it, or when the handler does not send it yet. A use case only a job sends the command of gets one test per job: `await application.runJob('<context>.<job>')` for a scheduled job (`application/scheduling/`), and, for a background job (`application/background/`), the request that enqueues it left to write, `const ran = await application.runDueJobs()`, which runs what is due on the queues as the worker would, and the assertion that the job is among `ran`; each then awaits `application.settled()`. `--job VoidInvoice` names one job, by its class or by the name it runs under (`billing.void-invoice`), also for a use case a route reaches, and writes `test/e2e/<use-case>-<job>.e2e.spec.ts`. Needs the route, that handler, or a job that sends the command |
823
825
  | `acceptance` | `<story> ["<title>"]` | `test/acceptance/<story>.acceptance.spec.ts`, written before the code: an `it.todo` per acceptance criterion of `docs/architecture/stories/<story>.md`, or per slice row of the story in `docs/architecture/slices.md` when it states none |
824
826
  | `policy` | `<context> <Name> --permission <aggregate>.<action> [--module <module>]` | `application/authorization/<name>.policy.ts`, spec; declared: the class carries `@Policy(permission, { name })` and nothing else is written; explicit: registration in `platform/auth/authorization/access-policies.ts` |
825
827
  | `gateway` | `<context> <upstreamContext> <Name> [--module <module>]` | the read contract in the upstream's published language (`<name>.contract.ts`, an abstract class and the token of the upstream value), the port `application/ports/<name>-gateway.port.ts`, an in-process adapter in `infrastructure/external/` bound `.as('gateway')`, a fake, one contract suite; refused unless the upstream is declared |
@@ -1 +1 @@
1
- {"version":3,"file":"tenancy-docs.d.ts","sourceRoot":"","sources":["../../../src/check/explain/tenancy-docs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAEjD,eAAO,MAAM,YAAY,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAmC1D,CAAC"}
1
+ {"version":3,"file":"tenancy-docs.d.ts","sourceRoot":"","sources":["../../../src/check/explain/tenancy-docs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAEjD,eAAO,MAAM,YAAY,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAqC1D,CAAC"}
@@ -1,6 +1,6 @@
1
1
  export const TENANCY_DOCS = {
2
2
  'tenancy/scoped-statement': {
3
- why: 'On shared tables, one statement without its tenant condition reads or overwrites the data of every tenant: the most common and the most damaging leak of a multi-tenant application. The kit puts the condition in one place, the helpers of the ORM package, which read the tenant from the execution scope, refuse work that names none, widen reads only under an audited elevation and never widen writes. A table reached straight from the executor bypasses all of it. Judged in a project whose "stack.tenancy" is not "none": the infrastructure of the contexts, tests aside, but a context declared the control plane of the tenants ("contexts.<name>.tenancy": "control-plane", a deviation recorded in "deviations"), whose tables belong to no tenant since it decides who belongs to which (the identity preset declares its context so). Checked by text, statement by statement: on Knex the executor used other than as the argument of a helper, and raw SQL that may reach rows by itself: a word that reads or writes rows (`select`, `from`, `join`, `insert`, `update`, `delete`, `values`, `call`...) or starts a statement (`table`, `with`, `do`...), a call to a function that is not a known expression (an aggregate, a cast, arithmetic, text), a text that is not a literal or a template that interpolates; a statement of the schema (`create`, `alter`, `drop`, `comment`) with no word of rows, and an aggregate in a select, reach no row by themselves; on Drizzle a read, update or delete whose where carries no tenant condition (inline or in the local it is given), an insert whose row names no tenant, a relational query or a raw execute; on Prisma a statement on the client whose where spreads no `tenantWhere` (a read) or `ownTenantWhere` (an update, a delete), a create whose data spreads no `tenantScopeOf`, `findUnique` and `upsert`, which reach a row by its key when the tenant is never part of the key, raw SQL, and the client held in a variable; on TypeORM the same on the manager (`find*`, `count*`, `update`, `delete`, `insert`, a query builder whose where carries no condition, `insertIgnoringConflict` given a row that names no tenant, `save` and `upsert`, `query`); on the four, a read model store built without its tenant option. The condition has to be a conjunct of the statement, since SQL binds `and` before `or` and an alternative beside it is outside it: on Knex no `.orWhere*` or `.or` at the top of a statement of `tenantTable`, `ownTenantTable` or `whereTenant`, and no `clearWhere()` or `clear(\'where\')`, on the chain, on a local, on what a function of the file answers or in a `modify` (`tenantTable`, `ownTenantTable` and `whereTenant` also refuse them when the statement is built, `UngroupedOrError` and `ClearedTenantConditionError`, and hold the text of a `whereRaw`, or a `knex.raw` given to a where, as one conjunct in parentheses; an `orHaving` applies after the where, and is free); on Drizzle the condition is a direct argument of `where` or of `and`, never under `or`, `not` or a `sql` template; on Prisma the helper is spread at the top of the where or in its `AND`, never under `OR`, `NOT` or a relation; on TypeORM the same, a where array spreads it in each entry, a query builder has no `orWhere` at its top, and the condition stands in its last `where` or an `andWhere` after it, since a `where` resets what comes before it. What is in a group beside the condition is correct and accepted: a callback of a Knex `where`, an `or` given to the `and` of Drizzle, an `OR` beside the Prisma spread, `new Brackets(...)` in a TypeORM `andWhere`. A where built by another function is not followed: inline it, or record a deviation.',
3
+ why: 'On shared tables, one statement without its tenant condition reads or overwrites the data of every tenant: the most common and the most damaging leak of a multi-tenant application. The kit puts the condition in one place, the helpers of the ORM package, which read the tenant from the execution scope, refuse work that names none, widen reads only under an audited elevation and never widen writes. A table reached straight from the executor bypasses all of it. Judged in a project whose "stack.tenancy" is not "none": the infrastructure of the contexts, tests aside, but a context declared the control plane of the tenants ("contexts.<name>.tenancy": "control-plane", a deviation recorded in "deviations"), whose tables belong to no tenant since it decides who belongs to which (the identity preset declares its context so). Checked by text, statement by statement: on Knex the executor used other than as the argument of a helper, and raw SQL that may reach rows by itself: a word that reads or writes rows (`select`, `from`, `join`, `insert`, `update`, `delete`, `values`, `call`...) or starts a statement (`table`, `with`, `do`...), a call to a function that is not a known expression (an aggregate, a cast, arithmetic, text), a text that is not a literal or a template that interpolates; a statement of the schema (`create`, `alter`, `drop`, `comment`) with no word of rows, and an aggregate in a select, reach no row by themselves; on Drizzle a read, update or delete whose where carries no tenant condition (inline or in the local it is given), an insert whose row names no tenant, a relational query or a raw execute; on Prisma a statement on the client whose where spreads no `tenantWhere` (a read) or `ownTenantWhere` (an update, a delete), a create whose data spreads no `tenantScopeOf`, `findUnique` and `upsert`, which reach a row by its key when the tenant is never part of the key, raw SQL, and the client held in a variable; on TypeORM the same on the manager (`find*`, `count*`, `update`, `delete`, `insert`, a query builder whose where carries no condition, `insertIgnoringConflict` given a row that names no tenant, `save` and `upsert`, `query`); on the four, a read model store built without its tenant option. The condition has to be a conjunct of the statement, since SQL binds `and` before `or` and an alternative beside it is outside it: on Knex no `.orWhere*` or `.or` at the top of a statement of `tenantTable`, `ownTenantTable` or `whereTenant`, and no `clearWhere()` or `clear(\'where\')`, on the chain, on a local, on what a function of the file answers or in a `modify` (`tenantTable`, `ownTenantTable` and `whereTenant` also refuse them when the statement is built, `UngroupedOrError` and `ClearedTenantConditionError`, and hold the text of a `whereRaw`, or a `knex.raw` given to a where, as one conjunct in parentheses; an `orHaving` applies after the where, and is free); on Drizzle the condition is a direct argument of `where` or of `and`, never under `or`, `not` or a `sql` template; on Prisma the helper is spread at the top of the where or in its `AND`, never under `OR`, `NOT` or a relation; on TypeORM the same, a where array spreads it in each entry, a query builder has no `orWhere` at its top, and the condition stands in its last `where` or an `andWhere` after it, since a `where` resets what comes before it. What is in a group beside the condition is correct and accepted: a callback of a Knex `where`, an `or` given to the `and` of Drizzle, an `OR` beside the Prisma spread, `new Brackets(...)` in a TypeORM `andWhere`. A where built by another function is not followed: inline it, or record a deviation. A lock on a business key (count then insert, the next number of a sequence) is taken with `advisoryLock(context, key, { tenant: scope })` or `tryAdvisoryLock` of the ORM package, which is given the context and never the executor: a raw `pg_advisory_xact_lock` is raw SQL, reported with a message that names the helper.',
4
4
  bad: `// infrastructure/persistence/knex-invoice.repository.ts
5
5
  const row = await this.database.executor()<InvoiceRow, InvoiceRow[]>('invoices').where({ id }).first();
6
6
  const all = await this.database.executor().from('invoices').where({ status }); // the executor chained
@@ -13,6 +13,7 @@ await this.database.client().billingInvoice.updateMany({ where: { id, version },
13
13
  // infrastructure/persistence/type-orm-invoice.repository.ts
14
14
  await this.database.manager().findOneBy(invoices, { id });
15
15
  await this.database.manager().save(invoices, row); // writes by the key alone
16
+ await this.database.executor().raw('select pg_advisory_xact_lock(hashtext(?))', [key]); // a lock by hand: one key for every tenant
16
17
  // the tenant is not a conjunct: \`and\` binds first, or the condition holds for one branch alone
17
18
  await tenantTable<InvoiceRow>(this.database, this.scope, INVOICES).where({ id }).orWhere({ reference: id });
18
19
  await this.database.executor().select().from(invoices).where(or(eq(invoices.id, id), tenantCondition(invoices.tenantId, this.scope)));
@@ -27,6 +28,7 @@ const found = await this.database.client().billingInvoice.findFirst({ where: { i
27
28
  await this.database.client().billingInvoice.updateMany({ where: { id, version, ...ownTenantWhere(this.scope) }, data });
28
29
  await this.database.manager().findOneBy(invoices, { id, ...tenantWhere(this.scope) });
29
30
  await this.database.manager().update(invoices, { id, version, ...ownTenantWhere(this.scope) }, row);
31
+ await advisoryLock(this.database, 'invoice-number', { tenant: this.scope }); // held until the unit of work ends
30
32
  // alternatives in a group beside the condition
31
33
  await tenantTable<InvoiceRow>(this.database, this.scope, INVOICES).where((either) => either.where({ id }).orWhere({ reference: id }));
32
34
  await this.database.executor().select().from(invoices).where(and(tenantCondition(invoices.tenantId, this.scope), or(eq(invoices.id, id), eq(invoices.reference, id))));
@@ -1 +1 @@
1
- {"version":3,"file":"tenancy-docs.js","sourceRoot":"","sources":["../../../src/check/explain/tenancy-docs.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,YAAY,GAAsC;IAC7D,0BAA0B,EAAE;QAC1B,GAAG,EAAE,qkHAAqkH;QAC1kH,GAAG,EAAE;;;;;;;;;;;;;;;;kHAgByG;QAC9G,IAAI,EAAE;;;;;;;;;;;;;8IAaoI;KAC3I;CACF,CAAC"}
1
+ {"version":3,"file":"tenancy-docs.js","sourceRoot":"","sources":["../../../src/check/explain/tenancy-docs.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,YAAY,GAAsC;IAC7D,0BAA0B,EAAE;QAC1B,GAAG,EAAE,o4HAAo4H;QACz4H,GAAG,EAAE;;;;;;;;;;;;;;;;;kHAiByG;QAC9G,IAAI,EAAE;;;;;;;;;;;;;;8IAcoI;KAC3I;CACF,CAAC"}
@@ -0,0 +1,9 @@
1
+ import type { Fixture } from './fixture.js';
2
+ import { TENANCY_ADAPTERS } from './tenancy-adapters.js';
3
+ type Orm = keyof typeof TENANCY_ADAPTERS;
4
+ /** A lock by hand on each ORM: raw SQL, which the rule reports with the name of the helper. */
5
+ export declare const ADVISORY_LOCKS_BY_HAND: Readonly<Record<Orm, string>>;
6
+ /** The lock on a business key: accepted through `advisoryLock` and `tryAdvisoryLock`, reported as a raw statement. */
7
+ export declare const ADVISORY_LOCK_FIXTURES: readonly Fixture[];
8
+ export {};
9
+ //# sourceMappingURL=tenancy-advisory-lock-fixtures.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tenancy-advisory-lock-fixtures.d.ts","sourceRoot":"","sources":["../../../src/check/fixtures/tenancy-advisory-lock-fixtures.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD,KAAK,GAAG,GAAG,MAAM,OAAO,gBAAgB,CAAC;AASzC,+FAA+F;AAC/F,eAAO,MAAM,sBAAsB,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,CAKhE,CAAC;AAIF,sHAAsH;AACtH,eAAO,MAAM,sBAAsB,EAAE,SAAS,OAAO,EAGnD,CAAC"}
@@ -0,0 +1,45 @@
1
+ import { project } from './project.js';
2
+ import { TENANCY_ADAPTERS } from './tenancy-adapters.js';
3
+ import { tenancyBypass } from './tenancy-bypass.js';
4
+ import { tenancyConfig } from './tenancy-config.js';
5
+ const IMPORTED = {
6
+ knex: '@ddd-ts-kit/knex',
7
+ drizzle: '@ddd-ts-kit/drizzle/postgres',
8
+ prisma: '@ddd-ts-kit/prisma',
9
+ typeorm: '@ddd-ts-kit/typeorm',
10
+ };
11
+ /** A lock by hand on each ORM: raw SQL, which the rule reports with the name of the helper. */
12
+ export const ADVISORY_LOCKS_BY_HAND = {
13
+ knex: "await this.database.executor().raw('select pg_advisory_xact_lock(hashtext(?))', [key]);",
14
+ drizzle: 'await this.database.executor().execute(sql`select pg_advisory_xact_lock(hashtext(${key}))`);',
15
+ prisma: 'await this.database.client().$executeRaw`select pg_try_advisory_xact_lock(hashtext(${key}))`;',
16
+ typeorm: "await this.database.manager().query('select pg_advisory_lock(hashtext($1))', [key]);",
17
+ };
18
+ const ORMS = ['knex', 'drizzle', 'prisma', 'typeorm'];
19
+ /** The lock on a business key: accepted through `advisoryLock` and `tryAdvisoryLock`, reported as a raw statement. */
20
+ export const ADVISORY_LOCK_FIXTURES = ORMS.flatMap((orm) => [
21
+ throughTheHelper(orm),
22
+ tenancyBypass(orm, 'an advisory lock taken by a raw statement', ADVISORY_LOCKS_BY_HAND[orm]),
23
+ ]);
24
+ function throughTheHelper(orm) {
25
+ const { file, owner } = TENANCY_ADAPTERS[orm];
26
+ const source = `import { advisoryLock, tryAdvisoryLock } from '${IMPORTED[orm]}';
27
+
28
+ export class ${owner} {
29
+ async nextNumber(): Promise<void> {
30
+ await advisoryLock(this.database, 'invoice-number', { tenant: this.scope });
31
+ }
32
+
33
+ alone(): Promise<boolean> {
34
+ return tryAdvisoryLock(this.database, 'invoice-closing', { tenant: this.scope });
35
+ }
36
+ }
37
+ `;
38
+ return {
39
+ ruleId: 'tenancy/scoped-statement',
40
+ name: `${orm}: an advisory lock taken through the helper of the package`,
41
+ expect: 'pass',
42
+ files: project({ [file]: source }, tenancyConfig(orm)),
43
+ };
44
+ }
45
+ //# sourceMappingURL=tenancy-advisory-lock-fixtures.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tenancy-advisory-lock-fixtures.js","sourceRoot":"","sources":["../../../src/check/fixtures/tenancy-advisory-lock-fixtures.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAIjD,MAAM,QAAQ,GAAkC;IAC9C,IAAI,EAAE,kBAAkB;IACxB,OAAO,EAAE,8BAA8B;IACvC,MAAM,EAAE,oBAAoB;IAC5B,OAAO,EAAE,qBAAqB;CAC/B,CAAC;AAEF,+FAA+F;AAC/F,MAAM,CAAC,MAAM,sBAAsB,GAAkC;IACnE,IAAI,EAAE,yFAAyF;IAC/F,OAAO,EAAE,8FAA8F;IACvG,MAAM,EAAE,+FAA+F;IACvG,OAAO,EAAE,sFAAsF;CAChG,CAAC;AAEF,MAAM,IAAI,GAAmB,CAAC,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;AAEtE,sHAAsH;AACtH,MAAM,CAAC,MAAM,sBAAsB,GAAuB,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;IAC9E,gBAAgB,CAAC,GAAG,CAAC;IACrB,aAAa,CAAC,GAAG,EAAE,2CAA2C,EAAE,sBAAsB,CAAC,GAAG,CAAC,CAAC;CAC7F,CAAC,CAAC;AAEH,SAAS,gBAAgB,CAAC,GAAQ;IAChC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAE9C,MAAM,MAAM,GAAG,kDAAkD,QAAQ,CAAC,GAAG,CAAC;;eAEjE,KAAK;;;;;;;;;CASnB,CAAC;IAEA,OAAO;QACL,MAAM,EAAE,0BAA0B;QAClC,IAAI,EAAE,GAAG,GAAG,4DAA4D;QACxE,MAAM,EAAE,MAAM;QACd,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC;KACvD,CAAC;AACJ,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"tenancy-fixtures.d.ts","sourceRoot":"","sources":["../../../src/check/fixtures/tenancy-fixtures.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAuFzC,eAAO,MAAM,gBAAgB,EAAE,SAAS,OAAO,EAiI9C,CAAC"}
1
+ {"version":3,"file":"tenancy-fixtures.d.ts","sourceRoot":"","sources":["../../../src/check/fixtures/tenancy-fixtures.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAuFzC,eAAO,MAAM,gBAAgB,EAAE,SAAS,OAAO,EAkI9C,CAAC"}
@@ -1,3 +1,4 @@
1
+ import { ADVISORY_LOCK_FIXTURES } from './tenancy-advisory-lock-fixtures.js';
1
2
  import { PATHS } from './paths.js';
2
3
  import { project } from './project.js';
3
4
  import { controlPlaneFixtures } from './control-plane-fixtures.js';
@@ -148,6 +149,7 @@ export const TENANCY_FIXTURES = [
148
149
  readModel('built without its tenant', 'export class KnexInvoiceTotals extends KnexReadModelStore<Total> {\n constructor(context: KnexContext) {\n super(context, { table: TABLE });\n }\n}\n', { file: READ_MODEL }),
149
150
  readModel('built with new and without its tenant', 'export class KnexInvoiceTotals {\n private readonly rows = new KnexReadModelTable<Total>(this.context, { table: TABLE });\n\n constructor(private readonly context: KnexContext) {}\n}\n', { file: READ_MODEL }),
150
151
  readModel('built with its tenant', 'export class KnexInvoiceTotals extends KnexReadModelStore<Total> {\n constructor(context: KnexContext, scope: ExecutionScope) {\n super(context, { table: TABLE, tenant: scope });\n }\n}\n', 'pass'),
152
+ ...ADVISORY_LOCK_FIXTURES,
151
153
  {
152
154
  ruleId: RULE,
153
155
  name: 'a project of one customer, which says nothing of tenancy',
@@ -1 +1 @@
1
- {"version":3,"file":"tenancy-fixtures.js","sourceRoot":"","sources":["../../../src/check/fixtures/tenancy-fixtures.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAEtE,MAAM,IAAI,GAAG,0BAA0B,CAAC;AACxC,MAAM,YAAY,GAAG,GAAG,KAAK,CAAC,OAAO,wDAAwD,CAAC;AAC9F,MAAM,eAAe,GAAG,GAAG,KAAK,CAAC,OAAO,2DAA2D,CAAC;AAEpG,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KACF;IACD,aAAa,CACX,SAAS,EACT,gCAAgC,EAChC,iEAAiE,CAClE;IACD,aAAa,CAAC,SAAS,EAAE,oBAAoB,EAAE,4DAA4D,CAAC;IAC5G,aAAa,CAAC,SAAS,EAAE,SAAS,EAAE,uEAAuE,CAAC;IAC5G,SAAS,CACP,0BAA0B,EAC1B,4JAA4J,EAC5J,EAAE,IAAI,EAAE,UAAU,EAAE,CACrB;IACD,SAAS,CACP,uCAAuC,EACvC,4LAA4L,EAC5L,EAAE,IAAI,EAAE,UAAU,EAAE,CACrB;IACD,SAAS,CACP,uBAAuB,EACvB,kMAAkM,EAClM,MAAM,CACP;IACD,GAAG,sBAAsB;IACzB;QACE,MAAM,EAAE,IAAI;QACZ,IAAI,EAAE,0DAA0D;QAChE,MAAM,EAAE,MAAM;QACd,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,YAAY,CAAC,EAAE,aAAa,EAAE,EAAE,aAAa,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;KACjF;CACF,CAAC"}
@@ -69,6 +69,6 @@ function unsealed(file, columns) {
69
69
  function undeclared(report, kept, { term, declarations }) {
70
70
  const column = kept.names[0] ?? '';
71
71
  const where = declarations.find((declaration) => declaration.context === kept.context)?.file;
72
- return report(kept, `The column ${column} of ${kept.context} is named like personal data (${term}), and no personalFields declaration of ${kept.context} names it: the erasure, the export and the register of personal data do not reach it.`, `Name it in the fields of the declaration of its table (${where ?? `infrastructure/persistence/<aggregate>${SUFFIX}`}, which \`ddd-ts-kit generate repository ${kept.context} <Aggregate> --personal <column>,...\` writes). A column that holds nothing of a person in this project is recorded: \`// ddd-ts-kit-disable-next-line privacy/declared-field -- ADR-NNNN: <why>\` above it, or the word in \`privacy.allow\` of ddd-ts-kit.config.json.`);
72
+ return report(kept, `The column ${column} of ${kept.context} is named like personal data (${term}), and no personalFields declaration of ${kept.context} names it: the erasure, the export and the register of personal data do not reach it.`, `Name it in the fields of the declaration of its table (${where ?? `infrastructure/persistence/<aggregate>${SUFFIX}`}, which \`ddd-ts-kit generate repository ${kept.context} <Aggregate> --personal <column>,...\` writes; for a table no aggregate owns, \`ddd-ts-kit generate personal-fields ${kept.context} <table> --personal <column>,... --subject <column>\`). A column that holds nothing of a person in this project is recorded: \`// ddd-ts-kit-disable-next-line privacy/declared-field -- ADR-NNNN: <why>\` above it, or the word in \`privacy.allow\` of ddd-ts-kit.config.json.`);
73
73
  }
74
74
  //# sourceMappingURL=privacy-declared-field.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"privacy-declared-field.js","sourceRoot":"","sources":["../../../src/check/rules/privacy-declared-field.ts"],"names":[],"mappings":"AAIA,OAAO,EAAyB,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAC9F,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAA8B,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AACzG,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAE/C,MAAM,MAAM,GAAG,qBAAqB,CAAC;AACrC,gHAAgH;AAChH,MAAM,MAAM,GAAG,4CAA4C,CAAC;AAU5D;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAS;IACxC,EAAE,EAAE,wBAAwB;IAC5B,WAAW,EACT,+JAA+J;IACjK,KAAK,EAAE,SAAS;IAChB,GAAG,CAAC,OAAO;QACT,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE,CAAC;YAC5B,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,UAAU,GAAG,YA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
1
+ {"version":3,"file":"tenancy-scoped-statement.d.ts","sourceRoot":"","sources":["../../../src/check/rules/tenancy-scoped-statement.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAqB1C,eAAO,MAAM,sBAAsB,EAAE,IAcpC,CAAC"}
@@ -6,11 +6,14 @@ import { knexUnscoped } from '../tenancy/knex-unscoped.js';
6
6
  import { prismaUnscoped } from '../tenancy/prisma-unscoped.js';
7
7
  import { typeormUnscoped } from '../tenancy/typeorm-unscoped.js';
8
8
  import { unscopedReadModels } from '../tenancy/unscoped-read-models.js';
9
- const FIX = 'Reach tenant data through the helpers of the ORM package: `tenantTable` to read and `ownTenantTable` to write (Knex), `tenantCondition` and `ownTenantCondition` in the where of each statement and `tenantScopeOf` in each inserted row (Drizzle), `tenantWhere` and `ownTenantWhere` spread into the where of each statement and `tenantScopeOf` into each created row (Prisma, TypeORM), the `tenant` option of a read model store. The condition is a conjunct of the statement, since SQL binds `and` before `or`: alternatives go in a group beside it, `.where((either) => either.where(a).orWhere(b))` (Knex), `.where(and(tenantCondition(...), or(a, b)))` (Drizzle), an `OR` beside the top-level spread (Prisma), `new Brackets(...)` in an `andWhere` and a where array whose every entry spreads the helper (TypeORM). A context whose tables belong to no tenant (the control plane of the tenants) is declared so, `"contexts.<name>.tenancy": "control-plane"` recorded in "deviations"; one table that holds no tenant data is a deviation: `// ddd-ts-kit-disable-next-line tenancy/scoped-statement -- ADR-NNNN: <why>`.';
9
+ const FIX = 'Reach tenant data through the helpers of the ORM package: `tenantTable` to read and `ownTenantTable` to write (Knex), `tenantCondition` and `ownTenantCondition` in the where of each statement and `tenantScopeOf` in each inserted row (Drizzle), `tenantWhere` and `ownTenantWhere` spread into the where of each statement and `tenantScopeOf` into each created row (Prisma, TypeORM), the `tenant` option of a read model store. The condition is a conjunct of the statement, since SQL binds `and` before `or`: alternatives go in a group beside it, `.where((either) => either.where(a).orWhere(b))` (Knex), `.where(and(tenantCondition(...), or(a, b)))` (Drizzle), an `OR` beside the top-level spread (Prisma), `new Brackets(...)` in an `andWhere` and a where array whose every entry spreads the helper (TypeORM). A context whose tables belong to no tenant (the control plane of the tenants) is declared so, `"contexts.<name>.tenancy": "control-plane"` recorded in "deviations"; a lock on a business key is taken with `advisoryLock(context, key, { tenant: scope })` or `tryAdvisoryLock` of the ORM package, never with a raw `pg_advisory_xact_lock`; one table that holds no tenant data is a deviation: `// ddd-ts-kit-disable-next-line tenancy/scoped-statement -- ADR-NNNN: <why>`.';
10
+ const LOCK_BY_HAND = 'An advisory lock is taken by a raw statement: take it with `advisoryLock(context, key, { tenant: scope })` or `tryAdvisoryLock` of the ORM package, which keeps the key of two tenants apart and refuses outside a unit of work.';
11
+ /** The advisory lock functions of PostgreSQL, of the transaction or of the session, waiting or not. */
12
+ const ADVISORY_LOCK = /\bpg_(?:try_)?advisory_(?:xact_)?lock(?:_shared)?\b/i;
10
13
  const READ_MODEL = 'A read model store is built without the `tenant` option: its rows are shared by every tenant.';
11
14
  export const tenancyScopedStatement = {
12
15
  id: 'tenancy/scoped-statement',
13
- description: 'In a multi-tenant project ("stack.tenancy" other than "none"), a persistence adapter of a context that is not the control plane of the tenants confines every statement to the tenant of the work through the helpers of its ORM package: never the executor, client or manager used straight, raw SQL, a relational query, a row reached by its key alone, or a read model store without its tenant. The condition is a conjunct of the statement: never beside an `or` at its top, or under an `or`, a `not` or a `sql` template.',
16
+ description: 'In a multi-tenant project ("stack.tenancy" other than "none"), a persistence adapter of a context that is not the control plane of the tenants confines every statement to the tenant of the work through the helpers of its ORM package: never the executor, client or manager used straight, raw SQL, a relational query, a row reached by its key alone, or a read model store without its tenant; a lock on a business key is taken with `advisoryLock` or `tryAdvisoryLock` of the ORM package. The condition is a conjunct of the statement: never beside an `or` at its top, or under an `or`, a `not` or a `sql` template.',
14
17
  scope: 'file',
15
18
  run(project) {
16
19
  const { tenancy, orm } = project.config.stack;
@@ -36,8 +39,13 @@ function unscoped(file, orm) {
36
39
  const readModels = unscopedReadModels(file).map((offset) => ({ offset, message: READ_MODEL }));
37
40
  return [...statements, ...readModels].map(({ offset, message }) => ({
38
41
  line: file.scan.lineAt(offset),
39
- message,
42
+ message: ADVISORY_LOCK.test(statementAt(file, offset)) ? LOCK_BY_HAND : message,
40
43
  fix: FIX,
41
44
  }));
42
45
  }
46
+ /** The source of the statement reported at `offset`, its SQL included, up to its end. */
47
+ function statementAt(file, offset) {
48
+ const end = file.scan.code.indexOf(';', offset);
49
+ return file.text.slice(offset, end === -1 ? file.text.length : end);
50
+ }
43
51
  //# sourceMappingURL=tenancy-scoped-statement.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tenancy-scoped-statement.js","sourceRoot":"","sources":["../../../src/check/rules/tenancy-scoped-statement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAe,MAAM,cAAc,CAAC;AAI3D,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAErE,MAAM,GAAG,GACP,8kCAA8kC,CAAC;AAEjlC,MAAM,UAAU,GAAG,+FAA+F,CAAC;AAEnH,MAAM,CAAC,MAAM,sBAAsB,GAAS;IAC1C,EAAE,EAAE,0BAA0B;IAC9B,WAAW,EACT,qgBAAqgB;IACvgB,KAAK,EAAE,MAAM;IACb,GAAG,CAAC,OAAO;QACT,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC;QAE9C,IAAI,OA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,GAAG;KACT,CAAC,CAAC,CAAC;AACN,CAAC;AAED,yFAAyF;AACzF,SAAS,WAAW,CAAC,IAAgB,EAAE,MAAc;IACnD,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAEhD,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AACtE,CAAC"}
@@ -121,6 +121,7 @@ const TEXT_FLAGS = [
121
121
  'cron',
122
122
  'phase',
123
123
  'event',
124
+ 'job',
124
125
  'group',
125
126
  'prefix',
126
127
  'role',
@@ -143,6 +144,7 @@ function flagsOf(args) {
143
144
  term: args.many('term'),
144
145
  value: args.many('value'),
145
146
  transition: args.many('transition'),
147
+ field: args.many('field'),
146
148
  ...switchesOf(args),
147
149
  };
148
150
  }