@warlock.js/core 4.15.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/CHANGELOG.md +43 -2
  2. package/bin/warlock.js +154 -1
  3. package/esm/application/application.d.mts +65 -1
  4. package/esm/application/application.d.mts.map +1 -1
  5. package/esm/application/application.mjs +62 -0
  6. package/esm/application/application.mjs.map +1 -1
  7. package/esm/application/index.d.mts +1 -1
  8. package/esm/cli/cli-commands.manager.mjs +60 -10
  9. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  10. package/esm/cli/commands/dev-server.command.mjs +1 -0
  11. package/esm/cli/commands/dev-server.command.mjs.map +1 -1
  12. package/esm/cli/commands/doctor/checks/handler-signature.check.mjs +40 -0
  13. package/esm/cli/commands/doctor/checks/handler-signature.check.mjs.map +1 -0
  14. package/esm/cli/commands/doctor/checks/index.mjs +4 -2
  15. package/esm/cli/commands/doctor/checks/index.mjs.map +1 -1
  16. package/esm/commands/cli-command.d.mts +1 -1
  17. package/esm/commands/cli-command.d.mts.map +1 -1
  18. package/esm/commands/cli-command.mjs.map +1 -1
  19. package/esm/commands/types.d.mts +10 -2
  20. package/esm/commands/types.d.mts.map +1 -1
  21. package/esm/config/config-handlers.d.mts +1 -2
  22. package/esm/config/config-handlers.d.mts.map +1 -1
  23. package/esm/config/config-handlers.mjs +3 -2
  24. package/esm/config/config-handlers.mjs.map +1 -1
  25. package/esm/config/locale-configuration.mjs +29 -0
  26. package/esm/config/locale-configuration.mjs.map +1 -0
  27. package/esm/connectors/assert-no-reserved-connector-names.d.mts +7 -0
  28. package/esm/connectors/assert-no-reserved-connector-names.d.mts.map +1 -0
  29. package/esm/connectors/assert-no-reserved-connector-names.mjs +44 -0
  30. package/esm/connectors/assert-no-reserved-connector-names.mjs.map +1 -0
  31. package/esm/connectors/assert-unique-connector-names.d.mts +7 -0
  32. package/esm/connectors/assert-unique-connector-names.d.mts.map +1 -0
  33. package/esm/connectors/assert-unique-connector-names.mjs +20 -0
  34. package/esm/connectors/assert-unique-connector-names.mjs.map +1 -0
  35. package/esm/connectors/connectors-manager.d.mts +38 -0
  36. package/esm/connectors/connectors-manager.d.mts.map +1 -1
  37. package/esm/connectors/connectors-manager.mjs +45 -12
  38. package/esm/connectors/connectors-manager.mjs.map +1 -1
  39. package/esm/connectors/describe-server-address.mjs +75 -0
  40. package/esm/connectors/describe-server-address.mjs.map +1 -0
  41. package/esm/connectors/http-connector.d.mts.map +1 -1
  42. package/esm/connectors/http-connector.mjs +6 -3
  43. package/esm/connectors/http-connector.mjs.map +1 -1
  44. package/esm/connectors/index.d.mts +4 -1
  45. package/esm/connectors/index.mjs +4 -1
  46. package/esm/connectors/register-configured-connectors.d.mts +14 -0
  47. package/esm/connectors/register-configured-connectors.d.mts.map +1 -0
  48. package/esm/connectors/register-configured-connectors.mjs +99 -0
  49. package/esm/connectors/register-configured-connectors.mjs.map +1 -0
  50. package/esm/connectors/socket-connector.d.mts.map +1 -1
  51. package/esm/connectors/socket-connector.mjs +4 -1
  52. package/esm/connectors/socket-connector.mjs.map +1 -1
  53. package/esm/connectors/types.d.mts +76 -1
  54. package/esm/connectors/types.d.mts.map +1 -1
  55. package/esm/connectors/types.mjs.map +1 -1
  56. package/esm/database/models/database-log/database-log.d.mts +50 -2
  57. package/esm/database/models/database-log/database-log.d.mts.map +1 -1
  58. package/esm/database/utils.d.mts +2 -2
  59. package/esm/database/utils.d.mts.map +1 -1
  60. package/esm/dev-server/development-server.mjs +1 -0
  61. package/esm/dev-server/development-server.mjs.map +1 -1
  62. package/esm/dev-server/layer-executor.mjs +2 -1
  63. package/esm/dev-server/layer-executor.mjs.map +1 -1
  64. package/esm/dev-server/read-config-ast.mjs +48 -0
  65. package/esm/dev-server/read-config-ast.mjs.map +1 -0
  66. package/esm/dev-server/run-typings-generation.mjs +18 -0
  67. package/esm/dev-server/run-typings-generation.mjs.map +1 -0
  68. package/esm/dev-server/type-generator.mjs +30 -39
  69. package/esm/dev-server/type-generator.mjs.map +1 -1
  70. package/esm/generations/add-command.action.mjs +169 -1
  71. package/esm/generations/add-command.action.mjs.map +1 -1
  72. package/esm/generations/stubs.mjs +93 -1
  73. package/esm/generations/stubs.mjs.map +1 -1
  74. package/esm/http/context/request-context.d.mts +14 -3
  75. package/esm/http/context/request-context.d.mts.map +1 -1
  76. package/esm/http/context/request-context.mjs +11 -1
  77. package/esm/http/context/request-context.mjs.map +1 -1
  78. package/esm/http/context/request-memo.d.mts +21 -0
  79. package/esm/http/context/request-memo.d.mts.map +1 -0
  80. package/esm/http/context/request-memo.mjs +48 -0
  81. package/esm/http/context/request-memo.mjs.map +1 -0
  82. package/esm/http/database/RequestLog.d.mts +164 -2
  83. package/esm/http/database/RequestLog.d.mts.map +1 -1
  84. package/esm/http/index.d.mts +6 -5
  85. package/esm/http/index.mjs +2 -1
  86. package/esm/http/middleware/cache-response-middleware.d.mts +2 -2
  87. package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
  88. package/esm/http/middleware/cache-response-middleware.mjs +1 -1
  89. package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
  90. package/esm/http/middleware/concurrency-limit.middleware.mjs +1 -1
  91. package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
  92. package/esm/http/middleware/idempotency.middleware.mjs +1 -1
  93. package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
  94. package/esm/http/middleware/index.d.mts +1 -1
  95. package/esm/http/middleware/index.mjs +1 -1
  96. package/esm/http/middleware/inject-request-context.d.mts +1 -8
  97. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  98. package/esm/http/middleware/inject-request-context.mjs +9 -22
  99. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  100. package/esm/http/middleware/ip-filter.middleware.d.mts +6 -3
  101. package/esm/http/middleware/ip-filter.middleware.d.mts.map +1 -1
  102. package/esm/http/middleware/ip-filter.middleware.mjs +7 -4
  103. package/esm/http/middleware/ip-filter.middleware.mjs.map +1 -1
  104. package/esm/http/middleware/maintenance.middleware.mjs +1 -1
  105. package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
  106. package/esm/http/middleware/max-body-size.middleware.mjs +1 -1
  107. package/esm/http/middleware/max-body-size.middleware.mjs.map +1 -1
  108. package/esm/http/middleware/rate-limit.middleware.mjs +1 -1
  109. package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
  110. package/esm/http/middleware/utils/idempotency-key.d.mts +0 -14
  111. package/esm/http/middleware/utils/idempotency-key.d.mts.map +1 -1
  112. package/esm/http/middleware/utils/idempotency-key.mjs +19 -1
  113. package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
  114. package/esm/http/request.d.mts +149 -44
  115. package/esm/http/request.d.mts.map +1 -1
  116. package/esm/http/request.mjs +132 -43
  117. package/esm/http/request.mjs.map +1 -1
  118. package/esm/http/response.mjs +1 -1
  119. package/esm/http/response.mjs.map +1 -1
  120. package/esm/http/server.d.mts.map +1 -1
  121. package/esm/http/server.mjs.map +1 -1
  122. package/esm/http/types.d.mts +58 -1
  123. package/esm/http/types.d.mts.map +1 -1
  124. package/esm/http/uploaded-file.d.mts +51 -19
  125. package/esm/http/uploaded-file.d.mts.map +1 -1
  126. package/esm/http/uploaded-file.mjs +36 -8
  127. package/esm/http/uploaded-file.mjs.map +1 -1
  128. package/esm/index.d.mts +17 -9
  129. package/esm/index.mjs +10 -4
  130. package/esm/production/build-contributions.mjs +115 -0
  131. package/esm/production/build-contributions.mjs.map +1 -0
  132. package/esm/production/production-builder.mjs +97 -2
  133. package/esm/production/production-builder.mjs.map +1 -1
  134. package/esm/production/resolve-build-config.d.mts +25 -0
  135. package/esm/production/resolve-build-config.d.mts.map +1 -0
  136. package/esm/production/resolve-build-config.mjs +43 -1
  137. package/esm/production/resolve-build-config.mjs.map +1 -1
  138. package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts +1 -1
  139. package/esm/repositories/adapters/cascade/filter-applicator.mjs +20 -9
  140. package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
  141. package/esm/restful/restful.d.mts +29 -8
  142. package/esm/restful/restful.d.mts.map +1 -1
  143. package/esm/restful/restful.mjs +31 -13
  144. package/esm/restful/restful.mjs.map +1 -1
  145. package/esm/router/describe-route-for-log.mjs +29 -0
  146. package/esm/router/describe-route-for-log.mjs.map +1 -0
  147. package/esm/router/index.d.mts +3 -1
  148. package/esm/router/index.mjs +2 -0
  149. package/esm/router/log-request-lifecycle.mjs +38 -0
  150. package/esm/router/log-request-lifecycle.mjs.map +1 -0
  151. package/esm/router/positional-handler-diagnostics.d.mts +90 -0
  152. package/esm/router/positional-handler-diagnostics.d.mts.map +1 -0
  153. package/esm/router/positional-handler-diagnostics.mjs +247 -0
  154. package/esm/router/positional-handler-diagnostics.mjs.map +1 -0
  155. package/esm/router/route-registry.d.mts +34 -0
  156. package/esm/router/route-registry.d.mts.map +1 -0
  157. package/esm/router/router.d.mts.map +1 -1
  158. package/esm/router/router.mjs +87 -63
  159. package/esm/router/router.mjs.map +1 -1
  160. package/esm/router/types.d.mts +23 -5
  161. package/esm/router/types.d.mts.map +1 -1
  162. package/esm/storage/storage.d.mts.map +1 -1
  163. package/esm/storage/storage.mjs +1 -1
  164. package/esm/storage/storage.mjs.map +1 -1
  165. package/esm/storage/utils/safe-fetch.d.mts +11 -1
  166. package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
  167. package/esm/storage/utils/safe-fetch.mjs +51 -4
  168. package/esm/storage/utils/safe-fetch.mjs.map +1 -1
  169. package/esm/tests/vitest-setup.mjs +1 -1
  170. package/esm/utils/load-environment.mjs +33 -2
  171. package/esm/utils/load-environment.mjs.map +1 -1
  172. package/esm/utils/types.d.mts +4 -0
  173. package/esm/utils/types.d.mts.map +1 -1
  174. package/esm/validation/validateAll.mjs +4 -1
  175. package/esm/validation/validateAll.mjs.map +1 -1
  176. package/esm/validation/validators/file-validator.d.mts +25 -1
  177. package/esm/validation/validators/file-validator.d.mts.map +1 -1
  178. package/esm/warlock-config/index.mjs +1 -1
  179. package/esm/warlock-config/normalize-build-config.mjs.map +1 -1
  180. package/esm/warlock-config/types.d.mts +36 -2
  181. package/esm/warlock-config/types.d.mts.map +1 -1
  182. package/llms-full.txt +179 -23
  183. package/llms.txt +1 -1
  184. package/package.json +23 -20
  185. package/skills/request-memo/SKILL.md +142 -0
  186. package/skills/use-middleware/SKILL.md +12 -1
  187. package/skills/use-request-locals/SKILL.md +144 -0
@@ -1 +1 @@
1
- {"version":3,"file":"normalize-build-config.mjs","names":[],"sources":["../../../../../../../core/src/warlock-config/normalize-build-config.ts"],"sourcesContent":["import type { WarlockConfig } from \"./types\";\n\ntype BuildConfig = NonNullable<WarlockConfig[\"build\"]>;\n\n/**\n * Fold the `outDirectory` alias into the canonical `outdir`.\n *\n * `outDirectory` is the name the documentation used for several releases\n * while the code only ever read `outdir`, so a config written from the docs\n * was silently ignored and the bundle still landed in `dist/`. Accepting both\n * keeps those configs working; `outdir` wins when both are set, since that is\n * the name esbuild uses and the one we tell people to prefer.\n *\n * Returns the input untouched when there is nothing to fold, so the common\n * case allocates nothing.\n */\nexport function normalizeBuildConfig<T extends BuildConfig>(build: T): T {\n if (!build.outDirectory || build.outdir) {\n return build;\n }\n\n return { ...build, outdir: build.outDirectory };\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAAgB,qBAA4C,OAAa;CACvE,IAAI,CAAC,MAAM,gBAAgB,MAAM,QAC/B,OAAO;CAGT,OAAO;EAAE,GAAG;EAAO,QAAQ,MAAM;CAAa;AAChD"}
1
+ {"version":3,"file":"normalize-build-config.mjs","names":[],"sources":["../../../../../../../core/src/warlock-config/normalize-build-config.ts"],"sourcesContent":["import type { WarlockConfig } from \"./types\";\n\ntype BuildConfig = NonNullable<WarlockConfig[\"build\"]>;\n\n/**\n * Fold the `outDirectory` alias into the canonical `outdir`.\n *\n * `outDirectory` is the name the documentation used for several releases\n * while the code only ever read `outdir`, so a config written from the docs\n * was silently ignored and the bundle still landed in `dist/`. Accepting both\n * keeps those configs working; `outdir` wins when both are set, since that is\n * the name esbuild uses and the one we tell people to prefer.\n *\n * Returns the input untouched when there is nothing to fold, so the common\n * case allocates nothing.\n */\nexport function normalizeBuildConfig<T extends BuildConfig>(\n build: T,\n): T & Pick<BuildConfig, \"outdir\"> {\n if (!build.outDirectory || build.outdir) {\n return build;\n }\n\n return { ...build, outdir: build.outDirectory };\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAAgB,qBACd,OACiC;CACjC,IAAI,CAAC,MAAM,gBAAgB,MAAM,QAC/B,OAAO;CAGT,OAAO;EAAE,GAAG;EAAO,QAAQ,MAAM;CAAa;AAChD"}
@@ -1,5 +1,6 @@
1
- import { CLICommand } from "../commands/cli-command.mjs";
2
1
  import { FileHealthCheckerContract } from "../dev-server/health-checker/file-health-checker.contract.mjs";
2
+ import { Connector } from "../connectors/types.mjs";
3
+ import { CLICommand } from "../commands/cli-command.mjs";
3
4
  import { MigrationConstructor } from "@warlock.js/cascade";
4
5
  import { BuildOptions } from "esbuild";
5
6
 
@@ -20,8 +21,16 @@ type WarlockConfig = {
20
21
  };
21
22
  /**
22
23
  * Build configuration
24
+ *
25
+ * `tsconfig` and `tsconfigRaw` are deliberately omitted alongside
26
+ * `entryPoints`. Either one applies the app's compiler options to EVERY
27
+ * file esbuild touches, workspace packages included — so an app-level
28
+ * `verbatimModuleSyntax: true` is imposed on package sources that were
29
+ * never written for it, and the bundle dies at import time with
30
+ * `Class extends value undefined`. The builder derives what it needs from
31
+ * the app's tsconfig itself (see `buildAliasMapFromTsconfig`).
23
32
  */
24
- build?: Omit<BuildOptions, 'entryPoints'> & {
33
+ build?: Omit<BuildOptions, "entryPoints" | "tsconfig" | "tsconfigRaw"> & {
25
34
  /**
26
35
  * Output directory
27
36
  *
@@ -91,6 +100,31 @@ type WarlockConfig = {
91
100
  */
92
101
  sourcemap?: boolean | "inline" | "linked";
93
102
  };
103
+ /**
104
+ * Connectors this application adds beyond the built-in ones.
105
+ *
106
+ * ONE key drives both halves of a connector's life:
107
+ *
108
+ * - `warlock build` reads this array STATICALLY and drains each
109
+ * connector's `build` contribution. It never calls `boot()`/`start()` —
110
+ * listing a connector here does not run it.
111
+ * - `warlock dev` and the generated production entry register the same
112
+ * array with the connectors manager, which is what actually boots it.
113
+ *
114
+ * A second key ("built for X" beside "boots X") was rejected precisely
115
+ * because the two would drift, and that drift is silent: a green build
116
+ * with no client bundle.
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * import { webConnector } from "@warlock.js/web/connector";
121
+ *
122
+ * export default defineConfig({
123
+ * connectors: [webConnector({ pagesDirectory: "pages" })],
124
+ * });
125
+ * ```
126
+ */
127
+ connectors?: Connector[];
94
128
  /**
95
129
  * CLI configuration
96
130
  */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/warlock-config/types.ts"],"mappings":";;;;;;;;AAUA;;;KAAY,aAAA;EAaF;;;EATR,MAAA;IACE,IAAA;IACA,IAAA;IACA,cAAA;EAAA;EAFA;;;EAQF,KAAA,GAAQ,IAAA,CAAK,YAAA;IAAL;;;;;IAMN,MAAA;IAkDA;;;;;;;;;;IAvCA,YAAA;IAqFiB;;;;;IA/EjB,OAAA;IAwIA;;;;;;;AAuBO;;;;;;;;;IA9IP,YAAA;;;;;;;;;;;;;;;;IAgBA,OAAA;;;;;;IAMA,MAAA;;;;;;IAMA,SAAA;EAAA;;;;EAMF,GAAA;IACE,QAAA,GAAW,UAAA;EAAA;;;;EAMb,SAAA;;;;IAIE,KAAA;;;;;;MAME,OAAA;;;;;;MAMA,OAAA;IAAA;;;;IAKF,cAAA,GAAiB,yBAAA;;;;;IAKjB,eAAA;;;;;;;;;IASA,eAAA;;;;;;;;;IASA,qBAAA;;;;;;;;;;IAUA,mBAAA;EAAA;;;;EAMF,QAAA;;;;;;;;;;;;;;;;;;IAkBE,UAAA,GAAa,KAAA,CAAM,oBAAA;EAAA;;;;;;;EASrB,OAAA;;;;;;;IAOE,OAAA;;;;;;IAOA,OAAA;EAAA;AAAA"}
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/warlock-config/types.ts"],"mappings":";;;;;;;;;AAWA;;;KAAY,aAAA;EAqBF;;;EAjBR,MAAA;IACE,IAAA;IACA,IAAA;IACA,cAAA;EAAA;EAHF;;;;;;;;;;;EAiBA,KAAA,GAAQ,IAAA,CAAK,YAAA;IA8DX;;;;;IAxDA,MAAA;IA+FW;;;;;;;;;;IApFX,YAAA;IAsJF;;;;;IAhJE,OAAA;IAyLA;;AAAO;;;;;;;;;;;;;;IAxKP,YAAA;;;;;;;;;;;;;;;;IAgBA,OAAA;;;;;;IAMA,MAAA;;;;;;IAMA,SAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;EA2BF,UAAA,GAAa,SAAA;;;;EAKb,GAAA;IACE,QAAA,GAAW,UAAA;EAAA;;;;EAMb,SAAA;;;;IAIE,KAAA;;;;;;MAME,OAAA;;;;;;MAMA,OAAA;IAAA;;;;IAKF,cAAA,GAAiB,yBAAA;;;;;IAKjB,eAAA;;;;;;;;;IASA,eAAA;;;;;;;;;IASA,qBAAA;;;;;;;;;;IAUA,mBAAA;EAAA;;;;EAMF,QAAA;;;;;;;;;;;;;;;;;;IAkBE,UAAA,GAAa,KAAA,CAAM,oBAAA;EAAA;;;;;;;EASrB,OAAA;;;;;;;IAOE,OAAA;;;;;;IAOA,OAAA;EAAA;AAAA"}
package/llms-full.txt CHANGED
@@ -4692,7 +4692,7 @@ export default defineConfig({
4692
4692
  plugins: [lowerStage3Decorators(), mongezVite()],
4693
4693
  test: {
4694
4694
  globalSetup: "./src/test-global-setup.ts", // ← starts the HTTP server
4695
- setupFiles: ["./src/test-setup.ts"], // ← per-worker setupTest (see test-service skill)
4695
+ setupFiles: ["./src/test-setup.ts"], // ← setupTest + afterAll(teardownTest), per test file
4696
4696
  environment: "node",
4697
4697
  globals: false,
4698
4698
  include: ["src/app/**/*.test.ts"],
@@ -4700,7 +4700,13 @@ export default defineConfig({
4700
4700
  });
4701
4701
  ```
4702
4702
 
4703
- Both files (and this config, with `lowerStage3Decorators()` first so decorated models load) are created by `warlock add test`. The split is intentional: `globalSetup` runs ONCE in the main vitest process; `setupFiles` runs per worker thread.
4703
+ Both files (and this config, with `lowerStage3Decorators()` first so decorated models load) are created by `warlock add test`. The split is intentional: `globalSetup` runs **ONCE** in the main vitest process; `setupFiles` runs **before every test file**.
4704
+
4705
+ ⚠ **Corrected in 4.14.0.** This line previously said `setupFiles` runs "per worker thread". **It does not** — Vitest runs it before each test file, and the setup module's registry is rebuilt every time. Measured across all four `pool` × `isolate` combinations.
4706
+
4707
+ **So the service-layer framework is file-scoped: bootstrapped by `setupTest` and closed by the `afterAll(teardownTest)` the setup file registers, once per test file.** ⚠ **`setupTest` alone is not the whole wiring — the paired teardown is mandatory from 4.14.0**; see the `test-service` skill.
4708
+
4709
+ **HTTP is the exception and stays in `globalSetup`**, which genuinely does run once in the main vitest process and owns a real port. **That split is the point:** one server for the whole run, one framework per test file.
4704
4710
 
4705
4711
  ## HTTP request helpers
4706
4712
 
@@ -4901,14 +4907,22 @@ This is fine for normal test flow. It bites when you're inside a transaction the
4901
4907
 
4902
4908
  ---
4903
4909
  name: test-service
4904
- description: 'Pure unit tests against services, repositories, models, and use-cases — `setupTest({ connectors })` bootstraps each Vitest worker with its own DB/cache connections so you can call your code directly. Triggers: `setupTest`, `src/test-setup.ts`, `tests.connectors`, `Application.setEnvironment`; "unit-test a service", "test a repository query", "vitest setupFiles", "skip connectors for pure-logic tests"; typical import `import { setupTest } from "@warlock.js/core/tests"`. Skip: HTTP integration — `@warlock.js/core/test-http/SKILL.md`; warlock add test scaffold — `@warlock.js/core/write-cli-command/SKILL.md`; competing tooling: jest direct, `supertest`, `nock`.'
4910
+ description: 'Pure unit tests against services, repositories, models, and use-cases — `setupTest({ connectors })` bootstraps the framework with its own DB/cache connections so you can call your code directly, and `teardownTest()` closes it. Triggers: `setupTest`, `teardownTest`, `src/test-setup.ts`, `tests.connectors`, `tests.setupTimeout`, `Application.setEnvironment`; "unit-test a service", "test a repository query", "vitest setupFiles", "skip connectors for pure-logic tests"; typical import `import { setupTest, teardownTest } from "@warlock.js/core/tests"`. Skip: HTTP integration — `@warlock.js/core/test-http/SKILL.md`; warlock add test scaffold — `@warlock.js/core/write-cli-command/SKILL.md`; competing tooling: jest direct, `supertest`, `nock`.'
4905
4911
  ---
4906
4912
 
4907
4913
  # Warlock — test a service
4908
4914
 
4909
- For unit tests, you import the thing under test and call it directly. No HTTP, no fetch, no controllers. Framework testing in Warlock is about getting your **service layer** under test efficiently — and that means each Vitest worker needs its own bootstrapped framework with a DB connection.
4915
+ For unit tests, you import the thing under test and call it directly. No HTTP, no fetch, no controllers. Framework testing in Warlock is about getting your **service layer** under test efficiently — and that means your tests need a bootstrapped framework with a DB connection.
4916
+
4917
+ `setupTest()` is the one-call bootstrap that provides that environment; `teardownTest()` closes it.
4918
+
4919
+ ⚠ **Corrected in 4.14.0 — `setupTest` is CALLED once per TEST FILE, not once per worker.** Every version of this skill through 4.13.0 said "per worker", the generated `src/test-setup.ts` carries a `Per-Worker Test Setup` comment saying the same thing, and **both were wrong.** Vitest runs `setupFiles` before **each test file**, and the setup module's registry is rebuilt every time — measured across all four `pool` × `isolate` combinations.
4910
4920
 
4911
- `setupTest()` is the one-call bootstrap that gives each worker that environment.
4921
+ ⛔ **If your project was generated before 4.14.0, fix BOTH the comment and the call.** The comment is false, **and** the generated `setupTest({ connectors: true })` is now an *explicit* value that overrides your `src/config/tests.ts`. **Bare `setupTest()` is the correct call.**
4922
+
4923
+ **The lifetime is FILE-SCOPED, on purpose.** Your setup file bootstraps the framework and its `afterAll(teardownTest)` closes it, once per test file. **One owner, one pairing — correct under every pool, every isolation setting, and watch mode.**
4924
+
4925
+ ⚠ **A worker-scoped lifetime is possible and is deliberately not shipped yet.** Lifecycle state now lives in the worker runtime, so leaving the framework running would let every file in a worker share one bootstrap. Two things block claiming it: under `pool: "threads"` we cannot observe whether Node reclaims a torn-down thread's sockets and pools, and **in watch mode Vitest reuses workers between reruns, so there is no recycle and no cleanup owner.** It gets taken when the real cost is measured and the integration is chosen, not inherited. See *Lifecycle and repeated calls* below.
4912
4926
 
4913
4927
  ⚠ **Changed in 4.13.0 — the import is a subpath now.** `setupTest` used to be re-exported from the package root; it is not any more, because that put the test helpers into every application's production module graph. `import { setupTest } from "@warlock.js/core"` now fails with *"has no exported member"* — **add `/tests` to the specifier and nothing else changes.**
4914
4928
 
@@ -4935,9 +4949,9 @@ describe("registerUserService", () => {
4935
4949
  });
4936
4950
  ```
4937
4951
 
4938
- No `beforeAll(setupTest)` in this file — the project's `src/test-setup.ts` (registered as `setupFiles` in `vite.config.ts`) already ran it once per worker before any test executed.
4952
+ No `beforeAll(setupTest)` in this file — the project's `src/test-setup.ts` (registered as `setupFiles` in `vite.config.ts`) already ran it **before this file's tests executed**, as it does before every test file.
4939
4953
 
4940
- ## `setupTest({ connectors })` — the worker bootstrap
4954
+ ## `setupTest({ connectors })` — the bootstrap
4941
4955
 
4942
4956
  ```ts
4943
4957
  import { setupTest } from "@warlock.js/core/tests";
@@ -4952,10 +4966,10 @@ What it does (in order):
4952
4966
  3. Runs `bootstrap()` — env, app, prestart hooks.
4953
4967
  4. Initializes the `filesOrchestrator` (module/route/config discovery, no file watching).
4954
4968
  5. Loads all `src/config/*.ts` files.
4955
- 6. Reads `tests.connectors` from config (overrides the parameter if set).
4969
+ 6. Resolves the connector selection — **an explicit parameter wins, then `tests.connectors` from config, then the `true` default.** See *Selecting connectors* below.
4956
4970
  7. Starts the chosen connectors — but **never `http`** when you pass a boolean. HTTP is the global-setup's job.
4957
4971
 
4958
- The result: each worker has its own DB/cache/logger/storage connections. Models save, repositories query, services run. Same code as production, just isolated to the test process.
4972
+ The result: DB/cache/logger/storage connections your code can use. Models save, repositories query, services run. Same code as production, just isolated to the test process.
4959
4973
 
4960
4974
  ### The `connectors` parameter
4961
4975
 
@@ -4965,9 +4979,9 @@ The result: each worker has its own DB/cache/logger/storage connections. Models
4965
4979
  | `false` | None | Pure logic tests with no DB / cache touches (parsers, validators, util functions). |
4966
4980
  | `["database", "cache"]` | Just those, in that order | A test that only needs DB but not, say, the storage driver. |
4967
4981
 
4968
- The default `true` is the sane choice. Reach for `false` when the unit you're testing genuinely doesn't talk to any framework subsystem — pulling up a DB connection per worker just to test a string parser is wasted setup time.
4982
+ The default `true` is the sane choice. Reach for `false` when the unit you're testing genuinely doesn't talk to any framework subsystem — pulling up a DB connection **for every file** just to test a string parser is wasted setup time.
4969
4983
 
4970
- ### Override via config — `src/config/tests.ts`
4984
+ ### Selecting connectors — `src/config/tests.ts`
4971
4985
 
4972
4986
  ```ts title="src/config/tests.ts"
4973
4987
  const testsConfigurations = {
@@ -4977,7 +4991,33 @@ const testsConfigurations = {
4977
4991
  export default testsConfigurations;
4978
4992
  ```
4979
4993
 
4980
- If `tests.connectors` is set, **it wins over the `setupTest({ connectors })` parameter**. Use this when every test file in the project agrees on the same minimal connector list saves repeating the explicit array in `test-setup.ts`.
4994
+ **BREAKING in 4.14.0 — the precedence flipped.**
4995
+
4996
+ | | Order |
4997
+ |---|---|
4998
+ | **4.13.0 and earlier** | `tests.connectors` config **>** `setupTest({ connectors })` parameter **>** `true` |
4999
+ | **4.14.0 onward** | **explicit `setupTest({ connectors })` parameter** **>** `tests.connectors` config **>** `true` |
5000
+
5001
+ **An explicit call-site value now beats project config.** If your project sets `tests.connectors` *and* some test file passes `connectors` explicitly, **that file will start a different connector set after upgrading.** Search for `setupTest({` across your tests before you upgrade — a call passing `connectors` was previously ignored and is now honoured.
5002
+
5003
+ **"Explicit" means you supplied a non-`undefined` value.** Both of these fall through to config:
5004
+
5005
+ ```ts
5006
+ await setupTest(); // → tests.connectors, else true
5007
+ await setupTest({}); // → tests.connectors, else true
5008
+ await setupTest({ connectors: undefined }); // → tests.connectors, else true — NOT "start none"
5009
+ ```
5010
+
5011
+ The `undefined` rule is deliberate: an optional variable that happens to be `undefined` must not silently erase your project config.
5012
+
5013
+ ```ts
5014
+ await setupTest({ connectors: false }); // → none, even if config says otherwise
5015
+ await setupTest({ connectors: ["database"] }); // → exactly that, even if config differs
5016
+ ```
5017
+
5018
+ ⚠ **The generated `src/test-setup.ts` calls `setupTest()` with no argument, on purpose.** If you "helpfully" change it to `setupTest({ connectors: true })`, you have made it explicit and **erased the `tests.connectors` layer for the whole project.**
5019
+
5020
+ Use `tests.connectors` when every test file agrees on the same minimal list — it saves repeating the array, and individual files can still override it.
4981
5021
 
4982
5022
  ## Project wiring — `src/test-setup.ts` + `vite.config.ts`
4983
5023
 
@@ -4985,14 +5025,22 @@ The `warlock add test` feature creates both files. The standard wiring:
4985
5025
 
4986
5026
  ```ts title="src/test-setup.ts"
4987
5027
  /**
4988
- * Per-Worker Test Setup
4989
- * Runs in EACH Vitest worker thread before tests execute.
5028
+ * Test Setup
5029
+ * Runs before EACH test file not once per worker.
4990
5030
  */
4991
- import { setupTest } from "@warlock.js/core/tests";
5031
+ import { afterAll } from "vitest";
5032
+ import { setupTest, teardownTest } from "@warlock.js/core/tests";
4992
5033
 
4993
- await setupTest({ connectors: true });
5034
+ await setupTest();
5035
+ afterAll(teardownTest);
4994
5036
  ```
4995
5037
 
5038
+ ⛔ **Three things changed here in 4.14.0. If you generated this file earlier, replace all three — it is not a comment fix.**
5039
+
5040
+ 1. **`afterAll(teardownTest)` is new and mandatory.** Nothing else closes the framework your tests started. This is what makes the lifetime file-scoped and owned rather than left running.
5041
+ 2. **The call is now bare `setupTest()`, not `setupTest({ connectors: true })`.** Under the flipped precedence, passing `true` is an *explicit* value and would override `tests.connectors` for **every file in the project.** Bare means "whatever this project configured, else the default".
5042
+ 3. **The comment used to say `Per-Worker Test Setup` / "Runs in EACH Vitest worker thread".** False — see the top of this skill.
5043
+
4996
5044
  ```ts title="vite.config.ts"
4997
5045
  import { lowerStage3Decorators } from "@warlock.js/core/vite";
4998
5046
  import mongezVite from "@mongez/vite";
@@ -5002,7 +5050,7 @@ export default defineConfig({
5002
5050
  plugins: [lowerStage3Decorators(), mongezVite()],
5003
5051
  test: {
5004
5052
  globalSetup: "./src/test-global-setup.ts", // ← HTTP server (see test-http skill)
5005
- setupFiles: ["./src/test-setup.ts"], // ← runs setupTest per worker
5053
+ setupFiles: ["./src/test-setup.ts"], // ← runs setupTest before EACH test file
5006
5054
  environment: "node",
5007
5055
  globals: false,
5008
5056
  include: ["src/app/**/*.test.ts"],
@@ -5107,7 +5155,9 @@ afterEach(async () => {
5107
5155
  });
5108
5156
  ```
5109
5157
 
5110
- Vitest runs tests in a single worker file sequentially, so an `afterEach` truncate gives each test a clean slate. For cross-file isolation, run the suite with `vitest --pool=forks --maxWorkers=N` and rely on the per-worker connection — each file's data stays within its worker until the run ends.
5158
+ Vitest runs the tests within one file sequentially, so an `afterEach` truncate gives each test a clean slate.
5159
+
5160
+ ⚠ **Cross-*file* isolation is not solved by this.** Separate workers get separate **connections**, not separate **rows** — two files pointed at the same database see each other's committed data regardless of pool or worker count. **Truncate what your file wrote; don't assume the worker boundary did it for you.** Real data isolation (DB-per-worker, transaction-per-test) is a separate piece of work and is not in this release.
5111
5161
 
5112
5162
  ### Skipping connectors for pure logic tests
5113
5163
 
@@ -5127,14 +5177,109 @@ describe("slugify", () => {
5127
5177
  });
5128
5178
  ```
5129
5179
 
5130
- `setupTest` is idempotent per worker (`isSetupComplete` flag) — calling it again with different options after `src/test-setup.ts` already ran is a no-op. **That includes a `connectors: false` call: if `src/test-setup.ts` already ran `setupTest()` in this worker, the example above changes nothing.** To genuinely skip connectors, either set `tests.connectors: false` in config (project-wide) or rely on the default in `src/test-setup.ts` being what you want most of the time.
5180
+ **BREAKING in 4.14.0 the example above now REJECTS if your project has a `src/test-setup.ts`.**
5181
+
5182
+ Through 4.13.0 a second `setupTest` call with different options was a **silent no-op** — you asked for no connectors, got all of them, and nothing told you. In 4.14.0 a conflicting call **rejects with an error naming both the active and the requested selection**, because silently ignoring what you asked for is worse than failing.
5183
+
5184
+ **If `src/test-setup.ts` already ran `setupTest()` in this file, use one of these instead:**
5185
+
5186
+ ```ts
5187
+ // 1. Tear down first, then set up differently — and PUT IT BACK when the file ends.
5188
+ import { afterAll, beforeAll } from "vitest";
5189
+ import { setupTest, teardownTest } from "@warlock.js/core/tests";
5190
+
5191
+ beforeAll(async () => {
5192
+ await teardownTest();
5193
+ await setupTest({ connectors: false });
5194
+ });
5195
+
5196
+ afterAll(async () => {
5197
+ await teardownTest(); // ← REQUIRED, see below
5198
+ });
5199
+ ```
5200
+
5201
+ ⛔ **The `afterAll` is not optional** — without it you leave a `connectors: false` runtime ready when the file ends.
5131
5202
 
5132
- ⚠ **Config beats the parameter.** If `tests.connectors` is set at all, `setupTest({ connectors })` cannot override it the config value wins. That is the current contract, not an accident; a per-call override is under discussion for a later release.
5203
+ ⚠ **This pattern interacts with the `afterAll(teardownTest)` in your setup file, and the relative ordering of the two has not been verified.** `teardownTest` is idempotent, so whichever runs second finds an idle lifecycle and no-ops but **do not build anything on a particular order until someone has measured it.** This is the strongest argument for option 2 below.
5204
+
5205
+ ```ts
5206
+ // 2. Or don't call setupTest at all — a pure-logic test needs nothing from it.
5207
+ // The connectors your setup file started are already running; you simply don't use them.
5208
+ ```
5209
+
5210
+ **3. Or set `tests.connectors: false` in `src/config/tests.ts`** if no test file in the project needs connectors.
5211
+
5212
+ **Option 2 is usually right, and option 1 is easy to get wrong.** Tearing down and re-bootstrapping costs a full framework startup — twice, once for your file and once for the next — to avoid a DB connection you were never going to use. **Reach for option 1 only when a connector's mere presence breaks the thing you're testing**, not to save setup time.
5213
+
5214
+ ## Lifecycle and repeated calls
5215
+
5216
+ `setupTest` / `teardownTest` are a pair. **The harness that calls one owns calling the other in the same context.**
5217
+
5218
+ | Call | Behaviour |
5219
+ |---|---|
5220
+ | `setupTest(x)` while idle | bootstraps |
5221
+ | `setupTest(x)` while already ready with the **same** effective options | no-op |
5222
+ | `setupTest(y)` while ready or starting with **different** effective options | ⛔ **rejects**, naming active vs requested |
5223
+ | two concurrent `setupTest(x)` calls | share one startup |
5224
+ | `setupTest` after a failed setup | allowed — a failed setup unwinds and returns to idle |
5225
+ | `teardownTest()` while idle | no-op |
5226
+ | two concurrent `teardownTest()` calls | share one shutdown |
5227
+ | `setupTest(y)` after a **successful** teardown | allowed, different options fine |
5228
+
5229
+ **"Same options" is compared by meaning, not by literal value** — connector arrays are deduplicated and compared as sets, so `["cache", "database"]` and `["database", "cache", "cache"]` are the same selection.
5230
+
5231
+ ⚠ **A failed shutdown poisons the lifecycle.** If `teardownTest()` rejects because the shutdown layer reported a failure, later `setupTest` calls **refuse until the Vitest worker is recycled** or a retried teardown fully succeeds. This is deliberate: a cleared flag does not prove that ports, sockets, pools or timers actually closed, and pretending otherwise hands you a "clean" run built on a leaked runtime.
5232
+
5233
+ ⚠ **What it cannot detect:** `connectorsManager.shutdown()` catches and logs individual connector failures internally. Those never reach this lifecycle, so they never poison it. It surfaces what that layer reports — no more.
5234
+
5235
+ ### `tests.setupTimeout` — the setup attempt is bounded
5236
+
5237
+ **New in 4.14.0.** A setup attempt that never settles used to leave the lifecycle stuck in `starting` and take the worker down with an out-of-memory crash. It is now bounded.
5238
+
5239
+ ```ts title="src/config/tests.ts"
5240
+ const testsConfigurations = {
5241
+ connectors: ["database", "logger"],
5242
+ setupTimeout: 120000, // milliseconds — this is the default
5243
+ };
5244
+
5245
+ export default testsConfigurations;
5246
+ ```
5247
+
5248
+ **Default: `120000` (two minutes)** — far above a healthy cold start, below the point where you'd stop watching the terminal. When it expires:
5249
+
5250
+ ```
5251
+ setupTest() did not finish within 120000ms and is stuck in the "starting" state. The
5252
+ lifecycle is now poisoned: whatever that attempt had already started is not known to be
5253
+ closed, so later setupTest() calls refuse until the Vitest worker is recycled. If your
5254
+ cold start is legitimately slower than this, raise the bound with `tests.setupTimeout`
5255
+ in `src/config/tests.ts` — milliseconds, default 120000.
5256
+ ```
5257
+
5258
+ 1. **It bounds the setup ATTEMPT, not teardown separately.** `teardownTest()` awaits the same attempt, so it inherits the bound — **one timer, not two.** A second teardown-side deadline was tried and rejected: it re-introduced the unbounded re-entry this whole guard exists to remove.
5259
+ 2. **Expiry poisons the lifecycle**, it does not return to `idle`. The attempt may have started connectors nobody can now account for, so pretending the runtime is clean would be worse than refusing.
5260
+ 3. **⛔ An invalid `setupTimeout` throws, naming the bad value.** Zero, negative and non-numeric all fail loudly rather than falling back to the default — a silent fallback would hide a typo behind a working suite.
5261
+ 4. **The bound is measured from when the attempt started**, not from when config was read. `tests.setupTimeout` is only readable after `loadConfigFiles()`, which happens *inside* the window being bounded; re-arming naively would give you the default plus your configured value.
5262
+
5263
+ ⚠ **What is proven and what is not.** The nine guards above were each seen to fail under their own mutation. **But every spec injects its scheduler**, so the default *value* is tested while the production timer — and whether its `unref` actually releases the worker — is not. **And no spec observes a real hang**: the stuck attempt is a mock gate, not a socket that never returns. These prove what the lifecycle *decides*, not what a genuinely wedged connector does.
5264
+
5265
+ ### State is per worker runtime, not per module
5266
+
5267
+ The lifecycle state lives in the worker runtime, not in a module variable. That matters because **Vitest rebuilds the module registry between test files while the worker itself keeps running** — so a module-level flag resets exactly where live DB connections and pools survive. Scope:
5268
+
5269
+ - **`pool: "forks"`** — state is per worker **process**.
5270
+ - **`pool: "threads"`** — state is per worker **thread**. It does **not** cross threads; `globalThis` is per realm, not per process.
5271
+
5272
+ In both cases the guard's scope matches the resource's scope, which is the point.
5273
+
5274
+ ⚠ **Not guaranteed:** under `threads` with `isolate: true`, Vitest tears the thread down while the process lives on. **Whether Node reclaims that thread's sockets and pools is unmeasured**, and nothing in this lifecycle can observe it.
5133
5275
 
5134
5276
  ## Gotchas
5135
5277
 
5136
- - **`setupTest` is idempotent per worker.** Second + later calls early-return. You can't "swap" the connector set mid-run the first call wins, including the one in `src/test-setup.ts`. Choose your worker default carefully.
5137
- - **Per-worker connections are separate from the HTTP server's connections.** A row inserted by a service-level test is on the worker's connection; the HTTP test server has its own. They don't see each other unless they're both pointing at the same physical DB and the inserting test has already committed.
5278
+ - **`setupTest` runs per test file, not per worker** every version of this skill through 4.13.0 said otherwise. **You pay one framework bootstrap per test file**, which is what 4.13.0 already cost; the difference is that it is now a chosen lifetime rather than a side effect of a module flag resetting.
5279
+ - **Never delete the `afterAll(teardownTest)` from your setup file.** Without it nothing closes what `setupTest` opened, and the connectors outlive the file that started them.
5280
+ - ⛔ **You can't swap the connector set by calling `setupTest` again — it rejects now.** Through 4.13.0 the second call was silently ignored. Tear down first, or don't call it.
5281
+ - **These connections are separate from the HTTP test server's.** A row inserted by a service-level test is on this connection; the HTTP test server has its own. They only see each other if both point at the same physical DB **and** the inserting test has committed.
5282
+ - **`setupTest` takes over the process's `connectorsManager` for its lifetime.** Teardown is manager-wide, so **mixing `setupTest` with manually started connectors is unsupported** — teardown may close yours too.
5138
5283
  - **`NODE_ENV` is set to `"test"`** by `setupTest`. Code that branches on `Application.isProduction` / `Application.isDevelopment` sees `false` for both. If your tests need production-like config (cookies, CORS), set those values in `src/config/*.ts` explicitly under the test branch — don't rely on the env flag.
5139
5284
  - **No HTTP from this layer.** `setupTest({ connectors: true })` never starts the HTTP connector by design. Don't try to `request.app.http` your way to a fetch test — use the `test-http` skill instead.
5140
5285
  - **Don't import `vitest-setup` from `@warlock.js/core/src/...`.** The public surface is `import { setupTest } from "@warlock.js/core/tests"`. Reaching into source paths breaks when the package layout shifts.
@@ -6308,7 +6453,18 @@ export default {
6308
6453
 
6309
6454
  `deny` wins over `allow`. If the IP can't be read (empty / unparseable), the request is rejected with 403. Reads via `request.detectIp()`.
6310
6455
 
6311
- ⚠ **Since 4.13.0 `http.trustProxy` defaults to `false`**, so `request.detectIp()` returns the socket address and **`X-Real-IP` / `X-Forwarded-For` are ignored unless you opt in.** Set `trustProxy: true` **only when you are genuinely behind a proxy that overwrites those headers** — before 4.13.0 the default was `true`, which meant any client could set its own forwarding header and be believed.
6456
+ ⚠ **Since 4.13.0 `http.trustProxy` defaults to `false`**, so `request.detectIp()` returns the socket address and **`X-Real-IP` / `X-Forwarded-For` are ignored unless you opt in.** Before 4.13.0 the default was `true`, which meant any client could set its own forwarding header and be believed.
6457
+
6458
+ ⚠ **Opt in with the narrowest shape your topology allows, not with `true`.** Since 4.15.0 `http.trustProxy` takes a hop count or a trusted-proxy list, and `detectIp()` resolves the chain the same way Fastify's `request.ip` does:
6459
+
6460
+ | `http.trustProxy` | Client IP |
6461
+ | --- | --- |
6462
+ | `false` *(default)* | Socket peer address |
6463
+ | `2` | Walks past the 2 rightmost `X-Forwarded-For` hops — for an edge that **appends** (the usual case: nginx, ALB, most CDNs) |
6464
+ | `"10.0.0.0/8"` / `["10.0.0.0/8", "192.168.0.0/16"]` | Walks left while each hop is a listed proxy |
6465
+ | `true` | Trusts the whole chain — the leftmost hop, i.e. **whatever the client put there** if your edge appends rather than overwrites |
6466
+
6467
+ With `true`, any client that can reach the process directly picks its own IP and this allowlist is decorative. `X-Real-IP` is honoured only under `true` — it carries no chain to check a hop count or proxy list against — so if your edge sets only that header, have it set `X-Forwarded-For` too.
6312
6468
 
6313
6469
  ```ts
6314
6470
  import { middleware } from "@warlock.js/core";
package/llms.txt CHANGED
@@ -27,7 +27,7 @@
27
27
  - [send-response](@warlock.js/core/send-response/SKILL.md): Send HTTP responses via @warlock.js/core's Response helpers — success/error variants, status helpers, redirects, files, streams, and SSE. Picking the right helper carries the HTTP semantic without manual status codes. Triggers: `response.success`, `response.successCreate`, `response.notFound`, `response.forbidden`, `response.badRequest`, `response.sendFile`, `response.stream`, `response.sse`, `response.replay`, `ResourceNotFoundError`, `ForbiddenError`; "return a 201 from a controller", "send a file", "stream Server-Sent Events", "throw HTTP-shaped errors from services"; typical import `import type { RequestHandler, Response } from "@warlock.js/core"`. Skip: controller shape — `@warlock.js/core/create-controller/SKILL.md`; route registration — `@warlock.js/core/register-route/SKILL.md`; competing patterns: hand-rolled status codes via `reply.code(404).send(...)`, raw Fastify reply.
28
28
  - [store-file](@warlock.js/core/store-file/SKILL.md): Read/write/delete files via the `storage` singleton — disks, drivers (local/S3/R2/DO Spaces), `storage.use(name)`, `StorageFile` handles, presigned URLs. Triggers: `storage.put`, `storage.get`, `storage.use`, `StorageFile`, `storageConfigurations`, `getPresignedUrl`, `getPresignedUploadUrl`; "save an uploaded file", "switch between local and S3", "generate a presigned URL", "read file metadata"; typical import `import { storage } from "@warlock.js/core"`. Skip: multipart parsing + image chain — `@warlock.js/core/upload-file/SKILL.md`; image transforms — `@warlock.js/core/process-image/SKILL.md`; storage config shape — `@warlock.js/core/configure-app/SKILL.md`; competing libs `@aws-sdk/client-s3`, `multer`, `formidable`.
29
29
  - [test-http](@warlock.js/core/test-http/SKILL.md): Integration tests against a real HTTP server — `startHttpTestServer()` boots one shared server in globalSetup, then `testGet` / `testPost` / `expectJson` make typed requests against it. Triggers: `startHttpTestServer`, `startHttpTestServer({ port })`, `stopHttpTestServer`, `testGet`, `testPost`, `testPut`, `testPatch`, `testDelete`, `expectJson`, `getTestServerUrl`, `testRequest`, `PortInUseError`, `assertPortIsAvailable`, `isPortAvailable`; "integration-test a controller", "end-to-end HTTP test", "globalSetup HTTP server", "assert status and body shape", "test server port already in use", "EADDRINUSE while running tests", "run tests while the dev server is up"; typical import `import { testGet, testPost, expectJson } from "@warlock.js/core/tests"`. Skip: pure unit tests — `@warlock.js/core/test-service/SKILL.md`; controller shape — `@warlock.js/core/create-controller/SKILL.md`; competing libs `supertest`, `light-my-request`, `nock`.
30
- - [test-service](@warlock.js/core/test-service/SKILL.md): Pure unit tests against services, repositories, models, and use-cases — `setupTest({ connectors })` bootstraps each Vitest worker with its own DB/cache connections so you can call your code directly. Triggers: `setupTest`, `src/test-setup.ts`, `tests.connectors`, `Application.setEnvironment`; "unit-test a service", "test a repository query", "vitest setupFiles", "skip connectors for pure-logic tests"; typical import `import { setupTest } from "@warlock.js/core/tests"`. Skip: HTTP integration — `@warlock.js/core/test-http/SKILL.md`; warlock add test scaffold — `@warlock.js/core/write-cli-command/SKILL.md`; competing tooling: jest direct, `supertest`, `nock`.
30
+ - [test-service](@warlock.js/core/test-service/SKILL.md): Pure unit tests against services, repositories, models, and use-cases — `setupTest({ connectors })` bootstraps the framework with its own DB/cache connections so you can call your code directly, and `teardownTest()` closes it. Triggers: `setupTest`, `teardownTest`, `src/test-setup.ts`, `tests.connectors`, `tests.setupTimeout`, `Application.setEnvironment`; "unit-test a service", "test a repository query", "vitest setupFiles", "skip connectors for pure-logic tests"; typical import `import { setupTest, teardownTest } from "@warlock.js/core/tests"`. Skip: HTTP integration — `@warlock.js/core/test-http/SKILL.md`; warlock add test scaffold — `@warlock.js/core/write-cli-command/SKILL.md`; competing tooling: jest direct, `supertest`, `nock`.
31
31
  - [update-packages](@warlock.js/core/update-packages/SKILL.md): Keep a project current with `warlock update` — bump every `@warlock.js/*` dependency in package.json to its latest published version (range operator preserved), then run the lockfile-detected package manager install. Also covers the `warlock dev` update notice, its `u` update-and-restart keyboard shortcut, and the `devServer.checkForUpdates` toggle. Triggers: `warlock update`, `--no-install`, `--dry-run`, `--check`, `checkForUpdates`, `fetchLatestVersion`, `isNewerVersion`; "update warlock packages", "upgrade the framework", "is there a new warlock version", "update notice in the dev server", "press u to update", "dev server keyboard shortcut", "update check offline", "bump @warlock.js/* to latest"; typical CLI `warlock update`. Skip: dev/build/start runtime — `@warlock.js/core/run-app/SKILL.md`; writing a custom command — `@warlock.js/core/write-cli-command/SKILL.md`; installing a NEW feature package (auth, mail, storage) — that is `warlock add`; releasing/publishing the framework — workspace release tooling, not this command.
32
32
  - [upload-file](@warlock.js/core/upload-file/SKILL.md): Handle multipart file uploads — read via `request.file()` or `request.validated()`, validate with `v.file()`, save via `UploadedFile.save()` or the storage layer, transform images inline. Triggers: `UploadedFile`, `request.file`, `v.file`, `.save`, `.saveAs`, `.resize`, `.format`, `.quality`, `.image`, `.mimeType`, `.maxSize`; "accept a file upload", "validate file size and mime", "save to S3 or local disk", "resize an uploaded image on save"; typical import `import type { UploadedFile, RequestHandler } from "@warlock.js/core"`. Skip: storage drivers + presigned URLs — `@warlock.js/core/store-file/SKILL.md`; image-only transforms — `@warlock.js/core/process-image/SKILL.md`; schema rules — `@warlock.js/core/validate-input/SKILL.md`; competing libs `multer`, `formidable`, `busboy`.
33
33
  - [use-app-context](@warlock.js/core/use-app-context/SKILL.md): Read app-wide context — the `Application` static class (env, version, uptime, runtime strategy, boot lifecycle) plus the `app` runtime accessor (live Fastify, socket.io, router, database via the DI container). Triggers: `Application.isProduction`, `Application.environment`, `Application.runtimeStrategy`, `Application.uptime`, `Application.version`, `Application.onceBooted`, `Application.whenBooted`, `Application.isBooted`, `Application.onShutdown`, `Application.isShuttingDown`, `app.http`, `app.socket`, `app.database`, `app.router`; "branch on environment", "reach the live Fastify instance", "framework version in health endpoint", "dev vs production runtime check", "run code once the app is fully booted", "after all connectors started", "app booted hook", "run cleanup before shutdown", "graceful shutdown hook"; typical import `import { Application, app } from "@warlock.js/core"`. Skip: path helpers — `@warlock.js/core/resolve-path/SKILL.md`; connector start order — `@warlock.js/core/add-connector/SKILL.md`; competing patterns: bare `process.env.NODE_ENV`, ad-hoc Fastify imports.
package/package.json CHANGED
@@ -1,6 +1,9 @@
1
1
  {
2
2
  "name": "@warlock.js/core",
3
3
  "description": "A robust nodejs framework for building blazing fast applications",
4
+ "warlock": {
5
+ "environment": "server"
6
+ },
4
7
  "bin": {
5
8
  "warlock": "bin/warlock.js"
6
9
  },
@@ -11,24 +14,24 @@
11
14
  "@fastify/multipart": "^9.3.0",
12
15
  "@fastify/rate-limit": "^10.3.0",
13
16
  "@fastify/static": "^8.3.0",
14
- "@mongez/concat-route": "^1.1.4",
15
- "@mongez/config": "^1.1.4",
17
+ "@mongez/concat-route": "^1.2.0",
18
+ "@mongez/config": "^1.2.1",
16
19
  "@mongez/copper": "^2.1.2",
17
- "@mongez/dotenv": "^1.3.1",
18
- "@mongez/events": "^2.2.6",
19
- "@mongez/http": "^3.3.8",
20
- "@mongez/localization": "^3.4.6",
21
- "@mongez/reinforcements": "^3.3.0",
20
+ "@mongez/dotenv": "^1.3.2",
21
+ "@mongez/events": "^2.2.7",
22
+ "@mongez/http": "^3.5.0",
23
+ "@mongez/localization": "^3.4.7",
24
+ "@mongez/reinforcements": "^4.0.1",
22
25
  "@mongez/slug": "^1.0.7",
23
- "@mongez/supportive-is": "^2.1.3",
26
+ "@mongez/supportive-is": "^2.1.4",
24
27
  "@mongez/time-wizard": "^1.0.6",
25
- "@warlock.js/auth": "4.15.0",
26
- "@warlock.js/cache": "4.15.0",
27
- "@warlock.js/cascade": "4.15.0",
28
- "@warlock.js/context": "4.15.0",
29
- "@warlock.js/logger": "4.15.0",
30
- "@warlock.js/seal": "4.15.0",
31
- "@warlock.js/fs": "4.15.0",
28
+ "@warlock.js/auth": "5.0.0",
29
+ "@warlock.js/cache": "5.0.0",
30
+ "@warlock.js/cascade": "5.0.0",
31
+ "@warlock.js/context": "5.0.0",
32
+ "@warlock.js/logger": "5.0.0",
33
+ "@warlock.js/seal": "5.0.0",
34
+ "@warlock.js/fs": "5.0.0",
32
35
  "chokidar": "^5.0.0",
33
36
  "dayjs": "^1.11.19",
34
37
  "es-module-lexer": "^2.0.0",
@@ -54,10 +57,10 @@
54
57
  "react": "^19.2.3",
55
58
  "react-dom": "^19.2.3",
56
59
  "@react-email/render": "^2.0.5",
57
- "@warlock.js/herald": "4.15.0",
58
- "@warlock.js/ai": "4.15.0",
59
- "@warlock.js/access": "4.15.0",
60
- "@warlock.js/notifications": "4.15.0"
60
+ "@warlock.js/herald": "5.0.0",
61
+ "@warlock.js/ai": "5.0.0",
62
+ "@warlock.js/access": "5.0.0",
63
+ "@warlock.js/notifications": "5.0.0"
61
64
  },
62
65
  "peerDependenciesMeta": {
63
66
  "sharp": {
@@ -120,7 +123,7 @@
120
123
  ],
121
124
  "author": "hassanzohdy",
122
125
  "license": "MIT",
123
- "version": "4.15.0",
126
+ "version": "5.0.0",
124
127
  "type": "module",
125
128
  "main": "./esm/index.mjs",
126
129
  "module": "./esm/index.mjs",
@@ -0,0 +1,142 @@
1
+ ---
2
+ name: request-memo
3
+ description: 'Memoize async work for one HTTP request with `requestMemo<T>(key, fn)` — the v5 replacement for removed `fromRequest`, with single-flight promise sharing, settled-success reuse, rejection eviction, and no cross-request fallback. Triggers: `requestMemo`, `fromRequest`, `fromRequest removed`, `request-scoped cache`, `single-flight`, `current request memo`; "migrate off fromRequest", "load this once per request", "deduplicate concurrent loaders", "cache a repository lookup during one request"; typical import `import { requestMemo } from "@warlock.js/core"`. Skip: middleware-written request state — `@warlock.js/core/use-request-locals/SKILL.md`; process-wide or cross-request caching — `@warlock.js/core/use-middleware/SKILL.md`; competing patterns: dynamic `request[key]` properties, module-global `Map`, payload `request.get()` / `request.set()`.'
4
+ ---
5
+
6
+ # Warlock — memoize work for one request
7
+
8
+ `requestMemo()` is the v5 replacement for the removed `fromRequest()`. Use it when several code paths in the same HTTP request may need the same asynchronously computed value and the work should run once.
9
+
10
+ ## The exact signature
11
+
12
+ From `core/src/http/context/request-memo.ts`:
13
+
14
+ ```ts
15
+ export function requestMemo<T>(key: string, fn: () => Promise<T>): Promise<T>
16
+ ```
17
+
18
+ Import it from the package root:
19
+
20
+ ```ts
21
+ import { requestMemo } from "@warlock.js/core";
22
+ ```
23
+
24
+ `fn` takes no arguments and must return a promise. Close over the current request or the inputs needed by the loader.
25
+
26
+ ## Migrate from v4 to v5
27
+
28
+ ### Before — v4 `fromRequest()`
29
+
30
+ ```ts title="src/app/tenants/utils/current-tenant.ts"
31
+ import { fromRequest, type Request } from "@warlock.js/core";
32
+
33
+ type Tenant = { id: string };
34
+
35
+ async function loadTenant(id: string): Promise<Tenant> {
36
+ return { id };
37
+ }
38
+
39
+ export function currentTenant(request: Request): Promise<Tenant> {
40
+ const tenantId = String(request.header("x-tenant-id") ?? "");
41
+
42
+ return fromRequest("tenants.current", () => loadTenant(tenantId));
43
+ }
44
+ ```
45
+
46
+ ### After — v5 `requestMemo()`
47
+
48
+ ```ts title="src/app/tenants/utils/current-tenant.ts"
49
+ import { requestMemo, type Request } from "@warlock.js/core";
50
+
51
+ type Tenant = { id: string };
52
+
53
+ async function loadTenant(id: string): Promise<Tenant> {
54
+ return { id };
55
+ }
56
+
57
+ export function currentTenant(request: Request): Promise<Tenant> {
58
+ const tenantId = String(request.header("x-tenant-id") ?? "");
59
+
60
+ return requestMemo("tenants.current", () => loadTenant(tenantId));
61
+ }
62
+ ```
63
+
64
+ The call-site migration is usually the import and function name. The complete v5 example above also shows the callback-shape migration: if a v4 callback used the `Request` argument supplied by `fromRequest`, capture the surrounding `request` variable because `requestMemo`'s `fn` receives no arguments.
65
+
66
+ ## Single-flight behavior
67
+
68
+ Within one request, the first call for a key invokes `fn` and stores its promise. Every concurrent caller using that key receives that exact promise, so parallel consumers do not duplicate the work. After the promise resolves, later calls during the same request keep receiving the cached successful promise.
69
+
70
+ ```ts title="src/app/catalog/controllers/show-product.controller.ts"
71
+ import { requestMemo, type RequestHandler } from "@warlock.js/core";
72
+
73
+ let loads = 0;
74
+
75
+ async function loadProduct(): Promise<{ id: string }> {
76
+ loads += 1;
77
+ return { id: "product-1" };
78
+ }
79
+
80
+ export const showProductController: RequestHandler = async ({ response }) => {
81
+ const first = requestMemo("catalog.product", loadProduct);
82
+ const second = requestMemo("catalog.product", loadProduct);
83
+ const [product, sameProduct] = await Promise.all([first, second]);
84
+
85
+ return response.success({ product, sameProduct, loads });
86
+ };
87
+ ```
88
+
89
+ For that request, `first === second` and `loads` is `1`.
90
+
91
+ A rejection is not cached. The rejected entry is deleted immediately, so a later call with the same key retries `fn`. Callers already sharing the rejected promise all observe that rejection.
92
+
93
+ ## Lifetime and isolation
94
+
95
+ The memo table is attached indirectly to the current request-context store through a `WeakMap`. Each incoming request gets a fresh store, so:
96
+
97
+ - two concurrent requests never share entries, even when they use the same key;
98
+ - resolved values live only for the request's context lifetime;
99
+ - the store and its memo entries are eligible for garbage collection after the request ends;
100
+ - no value is written onto the `Request` object.
101
+
102
+ Calling `requestMemo()` outside the HTTP request pipeline throws synchronously. It deliberately has no process-global fallback. For data meant to survive across requests, use an explicit application cache instead.
103
+
104
+ ## Why it replaces `fromRequest()`
105
+
106
+ `fromRequest()` memoized through dynamic `request[key]` properties. That only type-checked because v4's `Request` had a `[key: string]: any` index signature. v5 removed both the unsafe index signature and `fromRequest()`; `requestMemo()` keeps the one-request lifetime without mutating `Request` or turning values into `any`.
107
+
108
+ The new helper also provides real single-flight behavior: it stores the in-flight promise. The old helper awaited its callback before writing the result onto `Request`, so concurrent v4 callers could run the same callback more than once.
109
+
110
+ ## Key design
111
+
112
+ Keys share one string namespace within a request. Use stable, namespaced keys and include every input that changes the result:
113
+
114
+ ```ts
115
+ import { requestMemo } from "@warlock.js/core";
116
+
117
+ type Product = { id: string };
118
+
119
+ async function findProduct(id: string): Promise<Product> {
120
+ return { id };
121
+ }
122
+
123
+ export function productById(id: string): Promise<Product> {
124
+ return requestMemo(`catalog.product:${id}`, () => findProduct(id));
125
+ }
126
+ ```
127
+
128
+ Reusing one key for different result types is a caller bug: TypeScript cannot compare the generic type arguments used at separate call sites.
129
+
130
+ ## Gotchas
131
+
132
+ - **Do not call it during bootstrap, in a CLI command, or from a background job.** There is no active HTTP request context there, so it throws.
133
+ - **Do not omit result-changing inputs from the key.** `catalog.product` is wrong when different IDs may be loaded during one request; use `catalog.product:${id}`.
134
+ - **Do not use `request.set()` as a replacement.** It writes to the request input payload read by `all()`, `input()`, and `validated()`.
135
+ - **Failures retry.** If repeated failures must also be cached, this primitive is not that policy; catch and convert the failure into a successful result deliberately, or use another cache.
136
+ - **Use `request.locals` for state written by middleware and read downstream.** Memoization and request attachment are separate jobs.
137
+
138
+ ## See also
139
+
140
+ - [`use-request-locals/SKILL.md`](../use-request-locals/SKILL.md) — typed per-request data written by middleware.
141
+ - [`write-middleware/SKILL.md`](../write-middleware/SKILL.md) — authoring and registering middleware.
142
+ - [`create-controller/SKILL.md`](../create-controller/SKILL.md) — consuming request-scoped values from controllers.