@warlock.js/core 5.34.3 → 5.35.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 (244) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/esm/cli/cli-commands.manager.mjs +1 -1
  3. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  4. package/esm/cli/commands/add.command.mjs +1 -0
  5. package/esm/cli/commands/add.command.mjs.map +1 -1
  6. package/esm/cli/commands/build.command.mjs +30 -3
  7. package/esm/cli/commands/build.command.mjs.map +1 -1
  8. package/esm/cli/commands/check/check-command.action.mjs +1 -0
  9. package/esm/cli/commands/check/check-command.action.mjs.map +1 -1
  10. package/esm/cli/commands/check.command.mjs +5 -0
  11. package/esm/cli/commands/check.command.mjs.map +1 -1
  12. package/esm/cli/commands/explain/explain-command.action.mjs +21 -0
  13. package/esm/cli/commands/explain/explain-command.action.mjs.map +1 -1
  14. package/esm/cli/commands/explain.command.mjs +14 -4
  15. package/esm/cli/commands/explain.command.mjs.map +1 -1
  16. package/esm/cli/commands/generate/generate.command.mjs +19 -1
  17. package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
  18. package/esm/cli/commands/generate/generators/endpoint.generator.mjs +1 -1
  19. package/esm/cli/commands/generate/generators/endpoint.generator.mjs.map +1 -1
  20. package/esm/cli/commands/generate/generators/web.generator.mjs +169 -0
  21. package/esm/cli/commands/generate/generators/web.generator.mjs.map +1 -0
  22. package/esm/cli/commands/generate/templates/web-stubs.mjs +231 -0
  23. package/esm/cli/commands/generate/templates/web-stubs.mjs.map +1 -0
  24. package/esm/cli/commands/inspect/inspect-command.action.mjs +4 -3
  25. package/esm/cli/commands/inspect/inspect-command.action.mjs.map +1 -1
  26. package/esm/cli/commands/inspect.command.mjs +13 -8
  27. package/esm/cli/commands/inspect.command.mjs.map +1 -1
  28. package/esm/cli/commands/mcp/mcp-command.action.mjs +1 -1
  29. package/esm/cli/commands/mcp/mcp-command.action.mjs.map +1 -1
  30. package/esm/config/config-loader.d.mts.map +1 -1
  31. package/esm/config/config-loader.mjs +2 -0
  32. package/esm/config/config-loader.mjs.map +1 -1
  33. package/esm/config/load-config-files.mjs +4 -0
  34. package/esm/config/load-config-files.mjs.map +1 -1
  35. package/esm/dev-server/file-event-handler.mjs +11 -1
  36. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  37. package/esm/dev-server/file-manager.d.mts +1 -1
  38. package/esm/dev-server/file-manager.d.mts.map +1 -1
  39. package/esm/dev-server/file-manager.mjs.map +1 -1
  40. package/esm/dev-server/files-orchestrator.mjs +16 -1
  41. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  42. package/esm/dev-server/files-watcher.mjs +13 -4
  43. package/esm/dev-server/files-watcher.mjs.map +1 -1
  44. package/esm/dev-server/loader/loader-port-acks.mjs +21 -9
  45. package/esm/dev-server/loader/loader-port-acks.mjs.map +1 -1
  46. package/esm/dev-server/loader/register-loader.mjs +31 -12
  47. package/esm/dev-server/loader/register-loader.mjs.map +1 -1
  48. package/esm/dev-server/module-loader.mjs +14 -0
  49. package/esm/dev-server/module-loader.mjs.map +1 -1
  50. package/esm/dev-server/special-file-patterns.mjs +4 -1
  51. package/esm/dev-server/special-file-patterns.mjs.map +1 -1
  52. package/esm/e2e/index.d.mts +2 -2
  53. package/esm/e2e/page.d.mts +6 -1
  54. package/esm/e2e/page.d.mts.map +1 -1
  55. package/esm/e2e/page.mjs +36 -1
  56. package/esm/e2e/page.mjs.map +1 -1
  57. package/esm/e2e/types.d.mts +31 -0
  58. package/esm/e2e/types.d.mts.map +1 -1
  59. package/esm/e2e/types.mjs.map +1 -1
  60. package/esm/errors/error-codes.d.mts +48 -0
  61. package/esm/errors/error-codes.d.mts.map +1 -1
  62. package/esm/errors/error-codes.mjs +48 -0
  63. package/esm/errors/error-codes.mjs.map +1 -1
  64. package/esm/errors/index.d.mts +2 -2
  65. package/esm/errors/index.mjs +2 -2
  66. package/esm/generations/add-command.action.mjs +2 -0
  67. package/esm/generations/add-command.action.mjs.map +1 -1
  68. package/esm/generations/design-system-payload.mjs +53 -0
  69. package/esm/generations/design-system-payload.mjs.map +1 -0
  70. package/esm/generations/features/design-system.feature.mjs +38 -0
  71. package/esm/generations/features/design-system.feature.mjs.map +1 -0
  72. package/esm/generations/features/index.mjs +3 -1
  73. package/esm/generations/features/index.mjs.map +1 -1
  74. package/esm/generations/features/notifications.feature.mjs +13 -2
  75. package/esm/generations/features/notifications.feature.mjs.map +1 -1
  76. package/esm/generations/features/test.feature.mjs +48 -13
  77. package/esm/generations/features/test.feature.mjs.map +1 -1
  78. package/esm/generations/stubs.mjs +9 -5
  79. package/esm/generations/stubs.mjs.map +1 -1
  80. package/esm/http/error-mapper.d.mts +1 -1
  81. package/esm/http/error-mapper.mjs +3 -3
  82. package/esm/http/error-mapper.mjs.map +1 -1
  83. package/esm/http/error-response.d.mts +3 -0
  84. package/esm/http/error-response.d.mts.map +1 -1
  85. package/esm/http/error-response.mjs +8 -2
  86. package/esm/http/error-response.mjs.map +1 -1
  87. package/esm/http/errors/errors.d.mts +8 -0
  88. package/esm/http/errors/errors.d.mts.map +1 -1
  89. package/esm/http/errors/errors.mjs +13 -1
  90. package/esm/http/errors/errors.mjs.map +1 -1
  91. package/esm/http/index.d.mts +3 -2
  92. package/esm/http/index.mjs +3 -2
  93. package/esm/http/list-endpoint.d.mts +35 -0
  94. package/esm/http/list-endpoint.d.mts.map +1 -0
  95. package/esm/http/list-endpoint.mjs +28 -0
  96. package/esm/http/list-endpoint.mjs.map +1 -0
  97. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  98. package/esm/http/middleware/inject-request-context.mjs +12 -2
  99. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  100. package/esm/http/server.mjs +1 -1
  101. package/esm/index.d.mts +8 -6
  102. package/esm/index.mjs +3 -2
  103. package/esm/openapi/security.mjs +12 -4
  104. package/esm/openapi/security.mjs.map +1 -1
  105. package/esm/openapi/types.d.mts +2 -0
  106. package/esm/openapi/types.d.mts.map +1 -1
  107. package/esm/production/build-budgets.d.mts +46 -0
  108. package/esm/production/build-budgets.d.mts.map +1 -0
  109. package/esm/production/build-budgets.mjs +109 -0
  110. package/esm/production/build-budgets.mjs.map +1 -0
  111. package/esm/production/production-builder.mjs +13 -1
  112. package/esm/production/production-builder.mjs.map +1 -1
  113. package/esm/production/resolve-build-config.d.mts +1 -1
  114. package/esm/production/resolve-build-config.d.mts.map +1 -1
  115. package/esm/production/resolve-build-config.mjs.map +1 -1
  116. package/esm/restful/restful.d.mts +1 -1
  117. package/esm/tests/fakes/storage-fake.d.mts +3 -1
  118. package/esm/tests/fakes/storage-fake.d.mts.map +1 -1
  119. package/esm/tests/fakes/storage-fake.mjs +3 -3
  120. package/esm/tests/fakes/storage-fake.mjs.map +1 -1
  121. package/esm/tests/fakes/test-fakes.d.mts +3 -1
  122. package/esm/tests/fakes/test-fakes.d.mts.map +1 -1
  123. package/esm/tests/fakes/test-fakes.mjs +3 -2
  124. package/esm/tests/fakes/test-fakes.mjs.map +1 -1
  125. package/esm/tests/index.d.mts +4 -2
  126. package/esm/tests/index.mjs +3 -1
  127. package/esm/tests/load-unit-config.mjs +24 -0
  128. package/esm/tests/load-unit-config.mjs.map +1 -0
  129. package/esm/tests/response-contract.d.mts +32 -0
  130. package/esm/tests/response-contract.d.mts.map +1 -0
  131. package/esm/tests/response-contract.mjs +116 -0
  132. package/esm/tests/response-contract.mjs.map +1 -0
  133. package/esm/tests/start-http-development-server.d.mts.map +1 -1
  134. package/esm/tests/start-http-development-server.mjs +10 -2
  135. package/esm/tests/start-http-development-server.mjs.map +1 -1
  136. package/esm/tests/test-lifecycle-state.mjs.map +1 -1
  137. package/esm/tests/test-locales.mjs +33 -0
  138. package/esm/tests/test-locales.mjs.map +1 -0
  139. package/esm/tests/test-runtime-scope.d.mts +15 -0
  140. package/esm/tests/test-runtime-scope.d.mts.map +1 -0
  141. package/esm/tests/test-runtime-scope.mjs +80 -0
  142. package/esm/tests/test-runtime-scope.mjs.map +1 -0
  143. package/esm/tests/vitest-setup.d.mts +13 -3
  144. package/esm/tests/vitest-setup.d.mts.map +1 -1
  145. package/esm/tests/vitest-setup.mjs +146 -18
  146. package/esm/tests/vitest-setup.mjs.map +1 -1
  147. package/esm/tooling/check/affected-files.d.mts +5 -0
  148. package/esm/tooling/check/affected-files.d.mts.map +1 -0
  149. package/esm/tooling/check/affected-files.mjs +56 -0
  150. package/esm/tooling/check/affected-files.mjs.map +1 -0
  151. package/esm/tooling/check/changed-files.d.mts +2 -0
  152. package/esm/tooling/check/changed-files.d.mts.map +1 -1
  153. package/esm/tooling/check/changed-files.mjs +2 -2
  154. package/esm/tooling/check/changed-files.mjs.map +1 -1
  155. package/esm/tooling/check/conventions-step.d.mts +2 -1
  156. package/esm/tooling/check/conventions-step.d.mts.map +1 -1
  157. package/esm/tooling/check/conventions-step.mjs +48 -6
  158. package/esm/tooling/check/conventions-step.mjs.map +1 -1
  159. package/esm/tooling/check/fixes.d.mts +8 -0
  160. package/esm/tooling/check/fixes.d.mts.map +1 -0
  161. package/esm/tooling/check/fixes.mjs +31 -0
  162. package/esm/tooling/check/fixes.mjs.map +1 -0
  163. package/esm/tooling/check/index.d.mts +12 -0
  164. package/esm/tooling/check/index.mjs +3 -2
  165. package/esm/tooling/check/run-check.d.mts +2 -0
  166. package/esm/tooling/check/run-check.d.mts.map +1 -1
  167. package/esm/tooling/check/run-check.mjs +20 -4
  168. package/esm/tooling/check/run-check.mjs.map +1 -1
  169. package/esm/tooling/check/run-tests.mjs +1 -1
  170. package/esm/tooling/check/source-ast.d.mts +1 -0
  171. package/esm/tooling/check/web-conventions.d.mts +10 -0
  172. package/esm/tooling/check/web-conventions.d.mts.map +1 -0
  173. package/esm/tooling/check/web-conventions.mjs +126 -0
  174. package/esm/tooling/check/web-conventions.mjs.map +1 -0
  175. package/esm/tooling/index.d.mts +7 -2
  176. package/esm/tooling/index.mjs +4 -2
  177. package/esm/tooling/inspect/collect-files.mjs +172 -0
  178. package/esm/tooling/inspect/collect-files.mjs.map +1 -0
  179. package/esm/tooling/inspect/collect-pages.mjs +3 -2
  180. package/esm/tooling/inspect/collect-pages.mjs.map +1 -1
  181. package/esm/tooling/inspect/collect-routes.mjs +1 -1
  182. package/esm/tooling/inspect/collect-routes.mjs.map +1 -1
  183. package/esm/tooling/inspect/explain-file.d.mts +12 -0
  184. package/esm/tooling/inspect/explain-file.d.mts.map +1 -0
  185. package/esm/tooling/inspect/explain-file.mjs +45 -0
  186. package/esm/tooling/inspect/explain-file.mjs.map +1 -0
  187. package/esm/tooling/inspect/index.d.mts +3 -2
  188. package/esm/tooling/inspect/index.mjs +2 -1
  189. package/esm/tooling/inspect/inspect-app.d.mts.map +1 -1
  190. package/esm/tooling/inspect/inspect-app.mjs +9 -3
  191. package/esm/tooling/inspect/inspect-app.mjs.map +1 -1
  192. package/esm/tooling/inspect/inspect-report.schema.mjs +34 -1
  193. package/esm/tooling/inspect/inspect-report.schema.mjs.map +1 -1
  194. package/esm/tooling/inspect/inspect-report.types.d.mts +17 -1
  195. package/esm/tooling/inspect/inspect-report.types.d.mts.map +1 -1
  196. package/esm/tooling/inspect/inspect-report.types.mjs +2 -1
  197. package/esm/tooling/inspect/inspect-report.types.mjs.map +1 -1
  198. package/esm/tooling/mcp/mcp-tools.d.mts.map +1 -1
  199. package/esm/tooling/mcp/mcp-tools.mjs +8 -2
  200. package/esm/tooling/mcp/mcp-tools.mjs.map +1 -1
  201. package/esm/tooling/problem.d.mts +4 -0
  202. package/esm/tooling/problem.d.mts.map +1 -1
  203. package/esm/tooling/problem.mjs +1 -0
  204. package/esm/tooling/problem.mjs.map +1 -1
  205. package/esm/tooling/syntax/ast.d.mts +2 -0
  206. package/esm/tooling/typecheck/run-typecheck.mjs +5 -1
  207. package/esm/tooling/typecheck/run-typecheck.mjs.map +1 -1
  208. package/esm/vite/index.d.mts +3 -1
  209. package/esm/vite/index.mjs +3 -1
  210. package/esm/vite/test-setup-reporter.d.mts +16 -0
  211. package/esm/vite/test-setup-reporter.d.mts.map +1 -0
  212. package/esm/vite/test-setup-reporter.mjs +55 -0
  213. package/esm/vite/test-setup-reporter.mjs.map +1 -0
  214. package/esm/vite/test-workers.d.mts +5 -0
  215. package/esm/vite/test-workers.d.mts.map +1 -0
  216. package/esm/vite/test-workers.mjs +38 -0
  217. package/esm/vite/test-workers.mjs.map +1 -0
  218. package/esm/warlock-config/index.d.mts +2 -1
  219. package/esm/warlock-config/types.d.mts +3 -0
  220. package/esm/warlock-config/types.d.mts.map +1 -1
  221. package/llms-full.txt +763 -9
  222. package/llms.txt +2 -0
  223. package/package.json +15 -14
  224. package/schemas/inspect-report.schema.json +47 -1
  225. package/skills/build-budgets/SKILL.md +51 -0
  226. package/skills/build-restful/SKILL.md +56 -0
  227. package/skills/configure-app/SKILL.md +7 -0
  228. package/skills/create-module/SKILL.md +9 -0
  229. package/skills/generate-web-ui/SKILL.md +71 -0
  230. package/skills/index.md +2 -2
  231. package/skills/run-app/SKILL.md +1 -1
  232. package/skills/send-mail/SKILL.md +25 -0
  233. package/skills/send-response/SKILL.md +50 -0
  234. package/skills/test-browser/SKILL.md +53 -0
  235. package/skills/test-http/SKILL.md +91 -0
  236. package/skills/test-service/SKILL.md +161 -3
  237. package/skills/upgrade-from-5-29/SKILL.md +18 -0
  238. package/skills/use-localization/SKILL.md +21 -0
  239. package/skills/warlock-check/SKILL.md +72 -1
  240. package/skills/warlock-inspect/SKILL.md +45 -2
  241. package/skills/warlock-mcp/SKILL.md +4 -0
  242. package/skills/write-cli-command/SKILL.md +18 -0
  243. package/esm/production/build-app-production.mjs +0 -14
  244. package/esm/production/build-app-production.mjs.map +0 -1
@@ -1,3 +1,5 @@
1
+ import { config } from "../config/config-getter.mjs";
2
+ import "../config/index.mjs";
1
3
  import { Application } from "../application/application.mjs";
2
4
  import { bootstrap } from "../bootstrap.mjs";
3
5
  import { connectorsManager } from "../connectors/connectors-manager.mjs";
@@ -7,17 +9,21 @@ import { setAppModuleImporter } from "../loader/app-module-importer.mjs";
7
9
  import { filesOrchestrator } from "../dev-server/files-orchestrator.mjs";
8
10
  import { loadConfigFiles } from "../config/load-config-files.mjs";
9
11
  import { installTestFakes, restoreTestFakes } from "./fakes/test-fakes.mjs";
12
+ import { loadTestLocales } from "./test-locales.mjs";
13
+ import { loadUnitConfig } from "./load-unit-config.mjs";
14
+ import { finishTestProfile, selectTestLifetime, testRuntimeScope, timeTestStep } from "./test-runtime-scope.mjs";
10
15
  import { describeConnectorsSelection, isSameConnectorsSelection, normalizeConnectorNames, readRequestedConnectors, resolveEffectiveConnectors } from "./test-connectors-selection.mjs";
11
16
  import { getTestLifecycleRegistry } from "./test-lifecycle-state.mjs";
12
17
  import { DEFAULT_TEST_SETUP_TIMEOUT, describeExpiredSetup, readConfiguredSetupTimeout, scheduleRealTimeout } from "./test-setup-timeout.mjs";
18
+ import { performance } from "node:perf_hooks";
13
19
 
14
20
  //#region ../../packages/core/src/tests/vitest-setup.ts
15
21
  /**
16
22
  * Worker test lifecycle — `setupTest` / `teardownTest`.
17
23
  *
18
24
  * Implements `contracts/2026-08-12-test-worker-lifecycle.md`. The pair is
19
- * context-scoped, not "once per worker": Vitest runs `setupFiles` before EVERY
20
- * test file and rebuilds the module registry each time, so the harness that
25
+ * File-scoped by default, optionally worker-scoped. Vitest runs `setupFiles`
26
+ * before every test file. With isolation enabled it rebuilds the module registry. The harness that
21
27
  * calls `setupTest` owns pairing it with `teardownTest` in the same runtime
22
28
  * context.
23
29
  *
@@ -56,13 +62,13 @@ var TestLifecycleError = class extends Error {
56
62
  this.name = "TestLifecycleError";
57
63
  }
58
64
  };
59
- const POISONED_MESSAGE = "setupTest() refuses to start a test runtime: an earlier teardownTest() reported a shutdown failure, so the connectors, ports and pools it owned are not known to be closed. Restart the Vitest worker before setting up again, or call teardownTest() to retry the shutdown — the lifecycle only returns to idle on a fully successful retry.";
65
+ const POISONED_MESSAGE = "setupTest() refuses to start a test runtime: an earlier teardownTest() or per-file reset reported a failure, so the connectors, ports and pools it owned are not known to be closed. Restart the Vitest worker before setting up again, or call teardownTest() to retry the shutdown — the lifecycle only returns to idle on a fully successful retry.";
60
66
  /**
61
67
  * Bootstrap the test runtime and start the selected connectors.
62
68
  *
63
- * ⚠ Runs once per TEST FILE, not once per worker: `setupFiles` is executed for
64
- * every file and its module registry is rebuilt with it, measured across both
65
- * pools with isolation on and off. The lifecycle state lives on the runtime
69
+ * By default boots once per TEST FILE. With tests.lifetime: "worker", the runner
70
+ * owns shutdown and requires a shared module graph. `setupFiles` executes for
71
+ * every file. The lifecycle state lives on the runtime
66
72
  * context rather than in this module precisely so that a rebuild cannot hide a
67
73
  * runtime that is still up.
68
74
  *
@@ -85,6 +91,36 @@ const POISONED_MESSAGE = "setupTest() refuses to start a test runtime: an earlie
85
91
  * await setupTest({ connectors: false });
86
92
  */
87
93
  async function setupTest(options) {
94
+ const scope = testRuntimeScope();
95
+ const mode = options?.mode ?? "integration";
96
+ if (scope.fileOpen && scope.mode !== mode) throw new TestLifecycleError("Cannot mix unit and integration runtimes in one file.");
97
+ if (scope.mode && scope.mode !== mode && getTestLifecycleRegistry().state !== "idle") throw new TestLifecycleError("Cannot change mode while a test runtime is active.");
98
+ scope.mode = mode;
99
+ if (mode === "unit") {
100
+ if (!options?.importModule) throw new TestLifecycleError("setupTest({ mode: 'unit' }) requires importModule from Vitest's module graph.");
101
+ if (scope.fileOpen) return;
102
+ scope.profile = {
103
+ file: options.file ?? "unknown",
104
+ steps: {}
105
+ };
106
+ await timeTestStep("environment", () => Application.setEnvironment("test"));
107
+ const importModule = options.importModule;
108
+ scope.unitConfig ??= timeTestStep("config", async () => {
109
+ await warlockConfigManager.load();
110
+ await loadUnitConfig(importModule);
111
+ });
112
+ try {
113
+ await scope.unitConfig;
114
+ } catch (error) {
115
+ scope.unitConfig = void 0;
116
+ scope.profile = void 0;
117
+ throw error;
118
+ }
119
+ if (!profileEnabled()) scope.profile = void 0;
120
+ scope.files += 1;
121
+ scope.fileOpen = true;
122
+ return;
123
+ }
88
124
  warnMissingImportModule(options?.importModule);
89
125
  const registry = getTestLifecycleRegistry();
90
126
  const requested = readRequestedConnectors(options?.connectors);
@@ -95,6 +131,27 @@ async function setupTest(options) {
95
131
  }
96
132
  if (registry.state === "ready") {
97
133
  assertReadySelectionMatches(registry.activeSelection, requested);
134
+ if (scope.lifetime === "worker" && !scope.fileOpen) {
135
+ scope.boundary ??= Promise.resolve().then(async () => {
136
+ beginFileProfile(options?.file);
137
+ try {
138
+ await timeTestStep("reset", async () => {
139
+ await restoreTestFakes();
140
+ await installTestFakes(options?.fakes, { isolatedStorage: true });
141
+ await resetBetweenFiles();
142
+ });
143
+ scope.fileOpen = true;
144
+ scope.files += 1;
145
+ } catch (error) {
146
+ registry.state = "poisoned";
147
+ finishTestProfile();
148
+ throw error;
149
+ } finally {
150
+ scope.boundary = void 0;
151
+ }
152
+ });
153
+ await scope.boundary;
154
+ }
98
155
  return;
99
156
  }
100
157
  if (registry.state === "starting" && registry.setupAttempt) {
@@ -104,7 +161,7 @@ async function setupTest(options) {
104
161
  }
105
162
  setAppModuleImporter(options?.importModule);
106
163
  try {
107
- return await startTestRuntime(requested, options?.fakes);
164
+ return await startTestRuntime(requested, options?.fakes, options);
108
165
  } finally {
109
166
  setAppModuleImporter(void 0);
110
167
  }
@@ -127,11 +184,33 @@ async function setupTest(options) {
127
184
  * poison anything. This lifecycle can only surface what that layer reports.
128
185
  */
129
186
  async function teardownTest() {
187
+ const scope = testRuntimeScope();
188
+ if (scope.mode === "unit") {
189
+ scope.fileOpen = false;
190
+ await timeTestStep("teardown", () => Promise.resolve());
191
+ finishTestProfile();
192
+ return;
193
+ }
194
+ if (scope.lifetime === "worker") {
195
+ if (scope.boundary) await settled(scope.boundary);
196
+ scope.fileOpen = false;
197
+ await timeTestStep("teardown", () => Promise.resolve());
198
+ finishTestProfile();
199
+ return;
200
+ }
201
+ try {
202
+ await timeTestStep("teardown", () => teardownFileRuntime());
203
+ } finally {
204
+ scope.fileOpen = false;
205
+ finishTestProfile();
206
+ }
207
+ }
208
+ async function teardownFileRuntime() {
130
209
  const registry = getTestLifecycleRegistry();
131
210
  if (registry.state === "stopping" && registry.teardownAttempt) return registry.teardownAttempt;
132
211
  if (registry.state === "starting" && registry.setupAttempt) {
133
212
  await settled(registry.setupAttempt.completion);
134
- return teardownTest();
213
+ return teardownFileRuntime();
135
214
  }
136
215
  if (registry.state === "idle") return;
137
216
  registry.state = "stopping";
@@ -215,7 +294,7 @@ async function awaitSetupWithinBound(attempt, bound, registry) {
215
294
  /**
216
295
  * Open a new setup attempt and publish it before it runs.
217
296
  */
218
- function startTestRuntime(requested, fakes) {
297
+ function startTestRuntime(requested, fakes, options) {
219
298
  const registry = getTestLifecycleRegistry();
220
299
  let publishEffectiveSelection = () => void 0;
221
300
  let failEffectiveSelection = () => void 0;
@@ -225,7 +304,7 @@ function startTestRuntime(requested, fakes) {
225
304
  });
226
305
  effectiveSelection.catch(() => void 0);
227
306
  const bound = armSetupBound(registry);
228
- const attempt = Promise.resolve().then(() => runTestRuntimeStartup(requested, publishEffectiveSelection, failEffectiveSelection, bound, fakes));
307
+ const attempt = Promise.resolve().then(() => runTestRuntimeStartup(requested, publishEffectiveSelection, failEffectiveSelection, bound, fakes, options));
229
308
  attempt.catch(() => void 0);
230
309
  const completion = awaitSetupWithinBound(attempt, bound, registry);
231
310
  registry.state = "starting";
@@ -243,22 +322,44 @@ function startTestRuntime(requested, fakes) {
243
322
  * unchanged. A cleanup failure is a secondary diagnostic and never replaces the
244
323
  * cause the caller needs to read.
245
324
  */
246
- async function runTestRuntimeStartup(requested, publishEffectiveSelection, failEffectiveSelection, bound, fakes) {
325
+ async function runTestRuntimeStartup(requested, publishEffectiveSelection, failEffectiveSelection, bound, fakes, options) {
247
326
  const registry = getTestLifecycleRegistry();
248
327
  try {
249
- Application.setEnvironment("test");
250
- await warlockConfigManager.load();
251
- await bootstrap();
252
- await filesOrchestrator.init();
253
- await loadConfigFiles(true);
328
+ const steps = {};
329
+ const scope = testRuntimeScope();
330
+ scope.profile = {
331
+ file: options?.file ?? "unknown",
332
+ steps
333
+ };
334
+ await timeTestStep("environment", () => Application.setEnvironment("test"));
335
+ await timeTestStep("config", () => warlockConfigManager.load());
336
+ scope.bootstraps += 1;
337
+ await timeTestStep("bootstrap", () => bootstrap());
338
+ await timeTestStep("orchestrator", () => filesOrchestrator.init({ skipLoader: Boolean(process.env.VITEST && options?.importModule) }));
339
+ await timeTestStep("appConfig", () => loadConfigFiles(true));
340
+ registry.cleanupLocales = await timeTestStep("locales", () => loadTestLocales());
341
+ if (!profileEnabled()) scope.profile = void 0;
342
+ scope.lifetime = selectTestLifetime(readRuntimeConfiguration().lifetime);
343
+ scope.shutdown = async () => {
344
+ const started = performance.now();
345
+ try {
346
+ await teardownFileRuntime();
347
+ } finally {
348
+ scope.shutdownMs = performance.now() - started;
349
+ scope.fileOpen = false;
350
+ }
351
+ };
254
352
  const configuredTimeout = readConfiguredSetupTimeout();
255
353
  if (configuredTimeout !== void 0) bound.rearm(configuredTimeout);
256
354
  const effectiveSelection = resolveEffectiveConnectors(requested);
257
355
  if (!bound.hasExpired()) registry.activeSelection = effectiveSelection;
258
356
  publishEffectiveSelection(effectiveSelection);
259
- await startSelectedConnectors(effectiveSelection);
260
- await installTestFakes(fakes);
357
+ await timeTestStep("connectors", () => startSelectedConnectors(effectiveSelection));
358
+ await timeTestStep("fakes", () => installTestFakes(fakes, { isolatedStorage: scope.lifetime === "worker" }));
359
+ if (scope.lifetime === "worker") await timeTestStep("reset", () => resetBetweenFiles());
261
360
  if (!bound.hasExpired()) {
361
+ scope.fileOpen = true;
362
+ scope.files += 1;
262
363
  registry.state = "ready";
263
364
  registry.setupAttempt = void 0;
264
365
  }
@@ -270,6 +371,11 @@ async function runTestRuntimeStartup(requested, publishEffectiveSelection, failE
270
371
  registry.activeSelection = void 0;
271
372
  registry.setupAttempt = void 0;
272
373
  }
374
+ const scope = testRuntimeScope();
375
+ scope.lifetime = "file";
376
+ scope.fileOpen = false;
377
+ if (profileEnabled()) finishTestProfile();
378
+ else scope.profile = void 0;
273
379
  console.error("[vitest-setup] Failed to setup test environment:", error);
274
380
  throw error;
275
381
  }
@@ -294,6 +400,8 @@ async function startSelectedConnectors(selection) {
294
400
  * step is attempted independently.
295
401
  */
296
402
  async function unwindPartialStartup() {
403
+ getTestLifecycleRegistry().cleanupLocales?.();
404
+ getTestLifecycleRegistry().cleanupLocales = void 0;
297
405
  await attemptCleanupStep("test fakes", () => restoreTestFakes());
298
406
  await attemptCleanupStep("application shutdown hooks", () => Application.runShutdownHooks());
299
407
  await attemptCleanupStep("connectors shutdown", () => connectorsManager.shutdown());
@@ -323,6 +431,8 @@ async function runTestRuntimeShutdown() {
323
431
  await connectorsManager.shutdown();
324
432
  shutdownSucceeded = true;
325
433
  } finally {
434
+ getTestLifecycleRegistry().cleanupLocales?.();
435
+ getTestLifecycleRegistry().cleanupLocales = void 0;
326
436
  registry.activeSelection = void 0;
327
437
  registry.setupAttempt = void 0;
328
438
  registry.teardownAttempt = void 0;
@@ -362,6 +472,24 @@ function assertSelectionsMatch(activeSelection, requestedSelection) {
362
472
  function settled(attempt) {
363
473
  return attempt.catch(() => void 0);
364
474
  }
475
+ function profileEnabled() {
476
+ return process.env.WARLOCK_TEST_PROFILE === "1" || readRuntimeConfiguration().profileSetup === true;
477
+ }
478
+ function beginFileProfile(file) {
479
+ if (profileEnabled()) testRuntimeScope().profile = {
480
+ file: file ?? "unknown",
481
+ steps: {}
482
+ };
483
+ }
484
+ async function resetBetweenFiles() {
485
+ const reset = readRuntimeConfiguration().resetBetweenFiles;
486
+ if (reset === void 0 || reset === null) return;
487
+ if (typeof reset !== "function") throw new TestLifecycleError("tests.resetBetweenFiles must be a function.");
488
+ await reset();
489
+ }
490
+ function readRuntimeConfiguration() {
491
+ return config.get("tests", {}) ?? {};
492
+ }
365
493
 
366
494
  //#endregion
367
495
  export { TestLifecycleError, setupTest, teardownTest, warnMissingImportModule };
@@ -1 +1 @@
1
- {"version":3,"file":"vitest-setup.mjs","names":[],"sources":["../../../../../../../../packages/core/src/tests/vitest-setup.ts"],"sourcesContent":["/**\n * Worker test lifecycle — `setupTest` / `teardownTest`.\n *\n * Implements `contracts/2026-08-12-test-worker-lifecycle.md`. The pair is\n * context-scoped, not \"once per worker\": Vitest runs `setupFiles` before EVERY\n * test file and rebuilds the module registry each time, so the harness that\n * calls `setupTest` owns pairing it with `teardownTest` in the same runtime\n * context.\n *\n * Ownership, stated once because teardown is wider than it looks:\n *\n * - the runtime assumes exclusive ownership of the process-local\n * `connectorsManager` for its lifetime;\n * - it owns the framework bootstrap, the application shutdown hooks, and the\n * connectors it starts — including the `connectors: false` case, where\n * bootstrap still registers hooks;\n * - teardown is MANAGER-WIDE. `connectorsManager.shutdown()` has no selective\n * ownership handle, so a lifecycle that started two connectors still closes\n * every connector the manager holds. Mixing `setupTest` with manual connector\n * startup in the same process is unsupported for exactly that reason.\n * - HTTP global setup stays separately owned by `startHttpTestServer` /\n * `stopHttpTestServer`.\n */\nimport { Application } from \"../application/application\";\nimport { bootstrap } from \"../bootstrap\";\nimport { setAppModuleImporter } from \"../loader/app-module-importer\";\nimport type { AppModuleImporter } from \"../loader/app-module-importer\";\nimport { loadConfigFiles } from \"../config/load-config-files\";\nimport { connectorsManager } from \"../connectors\";\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { installTestFakes, restoreTestFakes } from \"./fakes/test-fakes\";\nimport type { TestFakesSelection } from \"./fakes/test-fakes\";\nimport {\n describeConnectorsSelection,\n isSameConnectorsSelection,\n normalizeConnectorNames,\n readRequestedConnectors,\n resolveEffectiveConnectors,\n} from \"./test-connectors-selection\";\nimport type { RequestedTestConnectors, TestConnectorsSelection } from \"./test-connectors-selection\";\nimport { getTestLifecycleRegistry } from \"./test-lifecycle-state\";\nimport type { TestLifecycleRegistry, TestSetupAttempt } from \"./test-lifecycle-state\";\nimport {\n DEFAULT_TEST_SETUP_TIMEOUT,\n describeExpiredSetup,\n readConfiguredSetupTimeout,\n scheduleRealTimeout,\n} from \"./test-setup-timeout\";\nimport type { TestTimeoutHandle } from \"./test-setup-timeout\";\n\nexport type { TestConnectorsSelection } from \"./test-connectors-selection\";\n\nexport type TestSetupOptions = {\n /**\n * Which connectors to start.\n *\n * Precedence is `explicit non-undefined option > tests.connectors config >\n * true`. Omitting the property, or passing `undefined`, lets project config\n * apply — so an optional variable that happens to be `undefined` cannot erase\n * it.\n */\n connectors?: TestConnectorsSelection;\n /**\n * Import hook for APPLICATION modules (config, routes, events, ...).\n *\n * Pass `(file) => import(file)` from your `src/test-setup.ts`: that file is\n * app code, so Vitest handles the `import()` and app modules land in the same\n * module graph as your test files. Without it Warlock imports them natively,\n * one worker holds two copies of every class (`User`, ...), and `instanceof`\n * fails. Defaults to native import.\n */\n importModule?: AppModuleImporter;\n /**\n * Which test fakes to install once the connectors are up: mail, queue,\n * cache, storage, clock, ids and secrets (see `installTestFakes`).\n *\n * Precedence is `explicit option > tests.fakes config > true`, so every fake\n * is on unless the project or this call opts out. `false` keeps the real\n * drivers; `{ cache: false }` keeps only the real cache. Teardown restores\n * them.\n */\n fakes?: TestFakesSelection;\n};\n\nconst IMPORT_MODULE_WARNED_KEY = Symbol.for(\"warlock.core.importModuleWarned\");\n\n/**\n * Warn — once per process — that app modules are loaded outside Vitest's graph.\n */\nexport function warnMissingImportModule(importModule: AppModuleImporter | undefined): void {\n if (importModule || !process.env.VITEST) return;\n\n const holder = globalThis as Record<symbol, unknown>;\n\n if (holder[IMPORT_MODULE_WARNED_KEY]) return;\n\n holder[IMPORT_MODULE_WARNED_KEY] = true;\n\n console.warn(\n \"[warlock] Warlock loads app modules outside Vitest's module graph, so classes like User exist twice and instanceof fails. Pass importModule: (file) => import(file) to setupTest().\",\n );\n}\n\n/**\n * Raised by the lifecycle itself, never by the runtime it manages — a conflict\n * between two calls, or a refusal to reuse a runtime that did not close.\n */\nexport class TestLifecycleError extends Error {\n public constructor(message: string) {\n super(message);\n\n this.name = \"TestLifecycleError\";\n }\n}\n\nconst POISONED_MESSAGE =\n \"setupTest() refuses to start a test runtime: an earlier teardownTest() reported a shutdown failure, so the connectors, ports and pools it owned are not known to be closed. Restart the Vitest worker before setting up again, or call teardownTest() to retry the shutdown — the lifecycle only returns to idle on a fully successful retry.\";\n\n/**\n * Bootstrap the test runtime and start the selected connectors.\n *\n * ⚠ Runs once per TEST FILE, not once per worker: `setupFiles` is executed for\n * every file and its module registry is rebuilt with it, measured across both\n * pools with isolation on and off. The lifecycle state lives on the runtime\n * context rather than in this module precisely so that a rebuild cannot hide a\n * runtime that is still up.\n *\n * Repeated calls:\n *\n * - concurrent calls with the same effective selection share one startup;\n * - while ready, the same effective selection is a no-op;\n * - while starting or ready, a DIFFERENT effective selection rejects and leaves\n * the live runtime untouched;\n * - a failed setup unwinds and returns to idle, so a clean retry is allowed;\n * - after a successful `teardownTest`, a later setup may use a different\n * selection.\n *\n * @example\n * // let project config decide, falling back to the default set\n * await setupTest();\n *\n * @example\n * // bootstrap only — no connectors, whatever config says\n * await setupTest({ connectors: false });\n */\nexport async function setupTest(options?: TestSetupOptions): Promise<void> {\n warnMissingImportModule(options?.importModule);\n\n const registry = getTestLifecycleRegistry();\n const requested = readRequestedConnectors(options?.connectors);\n\n if (registry.state === \"poisoned\") {\n throw new TestLifecycleError(POISONED_MESSAGE);\n }\n\n if (registry.state === \"stopping\" && registry.teardownAttempt) {\n await settled(registry.teardownAttempt);\n\n return setupTest(options);\n }\n\n if (registry.state === \"ready\") {\n assertReadySelectionMatches(registry.activeSelection, requested);\n\n return;\n }\n\n if (registry.state === \"starting\" && registry.setupAttempt) {\n const attempt = registry.setupAttempt;\n\n await assertPendingSetupMatches(attempt, requested);\n\n return attempt.completion;\n }\n\n // Scoped to this startup: the loaders read it while app modules import, and\n // it is cleared whatever the outcome so it never leaks past setup.\n setAppModuleImporter(options?.importModule);\n\n try {\n return await startTestRuntime(requested, options?.fakes);\n } finally {\n setAppModuleImporter(undefined);\n }\n}\n\n/**\n * Shut the test runtime down and release the lifecycle.\n *\n * - idle is a no-op;\n * - concurrent calls share one attempt;\n * - a call made while setup is still running waits for that attempt to settle,\n * then closes the runtime if it succeeded;\n * - the local \"ready\" state is always cleared, including when shutdown rejects;\n * - a shutdown rejection is surfaced, never swallowed, and poisons the\n * lifecycle — a reported close failure is not proof that anything closed, so\n * later `setupTest` calls refuse until the worker is restarted or a retry\n * fully succeeds.\n *\n * ⚠ Individual connector shutdown failures are caught and logged inside\n * `connectorsManager.shutdown()`, so they never reach this function and never\n * poison anything. This lifecycle can only surface what that layer reports.\n */\nexport async function teardownTest(): Promise<void> {\n const registry = getTestLifecycleRegistry();\n\n if (registry.state === \"stopping\" && registry.teardownAttempt) {\n return registry.teardownAttempt;\n }\n\n if (registry.state === \"starting\" && registry.setupAttempt) {\n // A runtime that is still opening cannot be closed halfway. Wait for the\n // attempt to settle: a failed one has already unwound itself and left the\n // lifecycle idle, which the re-entry below then reads as \"nothing to do\".\n await settled(registry.setupAttempt.completion);\n\n return teardownTest();\n }\n\n if (registry.state === \"idle\") {\n return;\n }\n\n registry.state = \"stopping\";\n\n // Deferred by a microtask so the registry is fully published before the\n // attempt's first line runs — a synchronous throw would otherwise reach the\n // `finally` below, and reset the state, before this function had recorded\n // that a teardown was in flight at all.\n const attempt = Promise.resolve().then(() => runTestRuntimeShutdown());\n\n registry.teardownAttempt = attempt;\n\n return attempt;\n}\n\n/**\n * The setup attempt's hang guard, as the lifecycle consumes it.\n *\n * The bound's POLICY — the default, the config key, the message — lives in\n * `test-setup-timeout.ts`. What expiry MEANS lives here.\n *\n * @internal\n */\ntype SetupBound = {\n /**\n * Rejects with the expiry error. Never resolves: the attempt is the only side\n * of the race that can succeed.\n */\n readonly expiry: Promise<never>;\n\n /**\n * Re-aim the bound at `next` ms measured from when the ATTEMPT STARTED, once\n * config has made `tests.setupTimeout` readable.\n */\n rearm(next: number): void;\n\n /** The race is over — cancel whatever timer is still pending. */\n settle(): void;\n\n /** Whether the bound, rather than the attempt, won the race. */\n hasExpired(): boolean;\n};\n\n/**\n * Arm the hang guard for one setup attempt.\n *\n * Armed at the default BEFORE the attempt runs, because `tests.setupTimeout` is\n * not readable until the attempt has loaded config — and loading config is\n * itself one of the steps that can hang. `rearm` then narrows or widens it the\n * moment config arrives.\n */\nfunction armSetupBound(registry: TestLifecycleRegistry): SetupBound {\n const schedule = registry.scheduleTimeout ?? scheduleRealTimeout;\n const armedAt = Date.now();\n\n let handle: TestTimeoutHandle | undefined;\n let expired = false;\n let closed = false;\n let expire: (error: unknown) => void = () => undefined;\n\n const expiry = new Promise<never>((_resolve, reject) => {\n expire = reject;\n });\n\n // Only `awaitSetupWithinBound` observes this, and only until the attempt wins\n // — after that nobody is listening, and an unobserved rejection surfaces as an\n // unhandled rejection that fails an unrelated test file. Same reason as the\n // `effectiveSelection` barrier below.\n expiry.catch(() => undefined);\n\n const expireNow = (bound: number): void => {\n if (closed) {\n return;\n }\n\n closed = true;\n expired = true;\n\n handle?.cancel();\n handle = undefined;\n\n expire(new TestLifecycleError(describeExpiredSetup(bound)));\n };\n\n const armFor = (bound: number, delay: number): void => {\n if (closed) {\n return;\n }\n\n handle?.cancel();\n\n // Already overdue. A bound the attempt has ALREADY exceeded must fire now,\n // not be rescheduled for time that was spent before it was known.\n if (delay <= 0) {\n expireNow(bound);\n\n return;\n }\n\n handle = schedule(delay, () => expireNow(bound));\n };\n\n const initialBound = registry.setupTimeoutOverride ?? DEFAULT_TEST_SETUP_TIMEOUT;\n\n armFor(initialBound, initialBound);\n\n return {\n expiry,\n\n // Measured from `armedAt`, never from now: adding a configured bound to the\n // time already spent would make the real bound default-plus-configured, and\n // a project that lowered the key would get a LONGER guard than the default.\n rearm: (next) => armFor(next, next - (Date.now() - armedAt)),\n\n settle: () => {\n closed = true;\n\n handle?.cancel();\n handle = undefined;\n },\n\n hasExpired: () => expired,\n };\n}\n\n/**\n * Race one setup attempt against its bound.\n *\n * The losing attempt is NOT cancellable — nothing here can interrupt a bootstrap\n * stuck in a socket connect — so when the bound wins, the lifecycle is poisoned\n * and every later state write from that abandoned attempt is dropped. That\n * dropping happens in `runTestRuntimeStartup`, guarded on `hasExpired()`;\n * without it the still-running attempt would quietly overwrite `poisoned` with\n * `ready` or `idle` and hand the next caller a runtime nobody owns.\n */\nasync function awaitSetupWithinBound(\n attempt: Promise<void>,\n bound: SetupBound,\n registry: TestLifecycleRegistry,\n): Promise<void> {\n try {\n await Promise.race([attempt, bound.expiry]);\n } catch (error) {\n if (bound.hasExpired()) {\n registry.state = \"poisoned\";\n registry.activeSelection = undefined;\n registry.setupAttempt = undefined;\n }\n\n throw error;\n } finally {\n bound.settle();\n }\n}\n\n/**\n * Open a new setup attempt and publish it before it runs.\n */\nfunction startTestRuntime(\n requested: RequestedTestConnectors,\n fakes: TestFakesSelection | undefined,\n): Promise<void> {\n const registry = getTestLifecycleRegistry();\n\n let publishEffectiveSelection: (selection: TestConnectorsSelection) => void = () => undefined;\n let failEffectiveSelection: (error: unknown) => void = () => undefined;\n\n const effectiveSelection = new Promise<TestConnectorsSelection>((resolve, reject) => {\n publishEffectiveSelection = resolve;\n failEffectiveSelection = reject;\n });\n\n // Only the mixed explicit/config comparison ever awaits this barrier, so its\n // rejection is usually unobserved — and an unobserved rejection would surface\n // as an unhandled rejection and fail an unrelated test file.\n effectiveSelection.catch(() => undefined);\n\n const bound = armSetupBound(registry);\n\n const attempt = Promise.resolve().then(() =>\n runTestRuntimeStartup(\n requested,\n publishEffectiveSelection,\n failEffectiveSelection,\n bound,\n fakes,\n ),\n );\n\n // The attempt outlives a bound that beat it, and by then `completion` has\n // already rejected with the expiry error — so the attempt's own late rejection\n // has no observer. Same unhandled-rejection hazard as above.\n attempt.catch(() => undefined);\n\n // `teardownTest` waits on this same promise, which is how a teardown requested\n // during setup inherits the bound. There is deliberately no second timer and\n // no separate teardown deadline.\n const completion = awaitSetupWithinBound(attempt, bound, registry);\n\n registry.state = \"starting\";\n registry.setupAttempt = { requested, effectiveSelection, completion };\n\n return completion;\n}\n\n/**\n * The startup attempt itself.\n *\n * On failure: best-effort unwind, reset bookkeeping, rethrow the ORIGINAL error\n * unchanged. A cleanup failure is a secondary diagnostic and never replaces the\n * cause the caller needs to read.\n */\nasync function runTestRuntimeStartup(\n requested: RequestedTestConnectors,\n publishEffectiveSelection: (selection: TestConnectorsSelection) => void,\n failEffectiveSelection: (error: unknown) => void,\n bound: SetupBound,\n fakes: TestFakesSelection | undefined,\n): Promise<void> {\n const registry = getTestLifecycleRegistry();\n\n try {\n Application.setEnvironment(\"test\");\n\n await warlockConfigManager.load();\n await bootstrap();\n\n await filesOrchestrator.init();\n await loadConfigFiles(true);\n\n // The first point at which `tests.setupTimeout` is readable at all. An\n // invalid value throws from here and takes the normal failure path — falling\n // back to the default would silently erase what the project configured.\n const configuredTimeout = readConfiguredSetupTimeout();\n\n if (configuredTimeout !== undefined) {\n bound.rearm(configuredTimeout);\n }\n\n // Resolved here and not at call time: the config layer is only readable once\n // the four steps above have run.\n const effectiveSelection = resolveEffectiveConnectors(requested);\n\n // Every state write below is conditional on this attempt still being the one\n // the lifecycle is waiting for. Once the bound has expired the lifecycle is\n // poisoned and this attempt is abandoned — it may still be running, but it\n // no longer speaks for the runtime.\n if (!bound.hasExpired()) {\n registry.activeSelection = effectiveSelection;\n }\n\n publishEffectiveSelection(effectiveSelection);\n\n await startSelectedConnectors(effectiveSelection);\n\n // After the connectors, so the cache and storage fakes replace drivers\n // that are already configured instead of being replaced by them.\n await installTestFakes(fakes);\n\n if (!bound.hasExpired()) {\n registry.state = \"ready\";\n registry.setupAttempt = undefined;\n }\n } catch (error) {\n failEffectiveSelection(error);\n\n await unwindPartialStartup();\n\n if (!bound.hasExpired()) {\n registry.state = \"idle\";\n registry.activeSelection = undefined;\n registry.setupAttempt = undefined;\n }\n\n console.error(\"[vitest-setup] Failed to setup test environment:\", error);\n\n throw error;\n }\n}\n\n/**\n * `false` means none at all. Everything else starts something: an array starts\n * exactly those, and `true` starts the default set — all but http, which is the\n * global setup's job and shared across every worker.\n */\nasync function startSelectedConnectors(selection: TestConnectorsSelection): Promise<void> {\n if (selection === false) {\n return;\n }\n\n if (Array.isArray(selection)) {\n await connectorsManager.start(normalizeConnectorNames(selection));\n\n return;\n }\n\n await connectorsManager.startWithout([\"http\"]);\n}\n\n/**\n * Best-effort teardown of whatever a failed startup managed to start.\n *\n * Runs while an error is already in flight, so no step here may throw and every\n * step is attempted independently.\n */\nasync function unwindPartialStartup(): Promise<void> {\n // Two steps rather than one: `connectorsManager.shutdown()` runs the\n // application hooks itself, but it runs them FIRST and does not isolate their\n // rejection — so a hook that rejects would take the connector teardown down\n // with it and leave every connector up. Both calls are idempotent, so running\n // the hooks on their own first costs nothing and means neither failure can\n // skip the other step.\n await attemptCleanupStep(\"test fakes\", () => restoreTestFakes());\n await attemptCleanupStep(\"application shutdown hooks\", () => Application.runShutdownHooks());\n await attemptCleanupStep(\"connectors shutdown\", () => connectorsManager.shutdown());\n}\n\n/**\n * Run one cleanup step, isolating its failure so the next step still runs.\n */\nasync function attemptCleanupStep(step: string, run: () => Promise<void>): Promise<void> {\n try {\n await run();\n } catch (error) {\n // Reported, not thrown — it is secondary to the startup error about to be\n // rethrown, and losing that one to this would be the worse outcome.\n console.error(`[vitest-setup] Cleanup after a failed setup did not complete (${step}):`, error);\n }\n}\n\n/**\n * The teardown attempt itself.\n */\nasync function runTestRuntimeShutdown(): Promise<void> {\n const registry = getTestLifecycleRegistry();\n let shutdownSucceeded = false;\n\n try {\n // Manager-wide, and deliberately called whatever the selection was: with\n // `connectors: false` nothing was started, but bootstrap still registered\n // application shutdown hooks, and the manager runs those first (see\n // `connectors-manager.ts` — `Application.runShutdownHooks()` is its first\n // line). Skipping the call to \"match\" an empty selection would leak them.\n //\n // Fakes go first, while the real drivers they put back are still\n // connected. A fake that fails to restore is reported, never allowed to\n // keep the connectors open.\n try {\n await restoreTestFakes();\n } catch (error) {\n console.error(\"[vitest-setup] Restoring the test fakes did not complete:\", error);\n }\n\n await connectorsManager.shutdown();\n\n shutdownSucceeded = true;\n } finally {\n // In a `finally`, not after the `await`: a rejected shutdown must not leave\n // the lifecycle claiming a runtime it no longer owns. Poisoned rather than\n // idle, because a cleared flag does not prove that ports, sockets, pools or\n // timers closed.\n registry.activeSelection = undefined;\n registry.setupAttempt = undefined;\n registry.teardownAttempt = undefined;\n registry.state = shutdownSucceeded ? \"idle\" : \"poisoned\";\n }\n}\n\n/**\n * Reject when a ready runtime was set up with a different selection.\n */\nfunction assertReadySelectionMatches(\n activeSelection: TestConnectorsSelection | undefined,\n requested: RequestedTestConnectors,\n): void {\n if (activeSelection === undefined) {\n return;\n }\n\n // Config is loaded by the time anything is ready, so the config-derived layer\n // is resolvable right here.\n const requestedSelection = resolveEffectiveConnectors(requested);\n\n assertSelectionsMatch(activeSelection, requestedSelection);\n}\n\n/**\n * Reject when an in-flight setup attempt is starting a different selection.\n */\nasync function assertPendingSetupMatches(\n attempt: TestSetupAttempt,\n requested: RequestedTestConnectors,\n): Promise<void> {\n const pending = attempt.requested;\n\n // Two calls that both defer to project config resolve to the same thing by\n // construction — knowable without waiting for config to load.\n if (!pending.isExplicit && !requested.isExplicit) {\n return;\n }\n\n if (pending.isExplicit && requested.isExplicit) {\n assertSelectionsMatch(pending.selection, requested.selection);\n\n return;\n }\n\n // Mixed: one side is config-derived and config is not readable until the\n // running attempt has loaded it, so wait for that barrier first.\n const activeSelection = await attempt.effectiveSelection;\n const requestedSelection = resolveEffectiveConnectors(requested);\n\n assertSelectionsMatch(activeSelection, requestedSelection);\n}\n\n/**\n * Name both selections: a caller looking at this message has to be able to tell\n * which call to change without reading the framework's source.\n */\nfunction assertSelectionsMatch(\n activeSelection: TestConnectorsSelection,\n requestedSelection: TestConnectorsSelection,\n): void {\n if (isSameConnectorsSelection(activeSelection, requestedSelection)) {\n return;\n }\n\n throw new TestLifecycleError(\n `setupTest() is already using ${describeConnectorsSelection(activeSelection)}, and this call asked for ${describeConnectorsSelection(requestedSelection)}. One test runtime serves one connector selection — call teardownTest() before setting up a different one.`,\n );\n}\n\n/**\n * Await an attempt for its state transition only, not its result.\n */\nfunction settled(attempt: Promise<void>): Promise<void> {\n return attempt.catch(() => undefined);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,MAAM,2BAA2B,OAAO,IAAI,iCAAiC;;;;AAK7E,SAAgB,wBAAwB,cAAmD;CACzF,IAAI,gBAAgB,CAAC,QAAQ,IAAI,QAAQ;CAEzC,MAAM,SAAS;CAEf,IAAI,OAAO,2BAA2B;CAEtC,OAAO,4BAA4B;CAEnC,QAAQ,KACN,qLACF;AACF;;;;;AAMA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,AAAO,YAAY,SAAiB;EAClC,MAAM,OAAO;EAEb,KAAK,OAAO;CACd;AACF;AAEA,MAAM,mBACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BF,eAAsB,UAAU,SAA2C;CACzE,wBAAwB,SAAS,YAAY;CAE7C,MAAM,WAAW,yBAAyB;CAC1C,MAAM,YAAY,wBAAwB,SAAS,UAAU;CAE7D,IAAI,SAAS,UAAU,YACrB,MAAM,IAAI,mBAAmB,gBAAgB;CAG/C,IAAI,SAAS,UAAU,cAAc,SAAS,iBAAiB;EAC7D,MAAM,QAAQ,SAAS,eAAe;EAEtC,OAAO,UAAU,OAAO;CAC1B;CAEA,IAAI,SAAS,UAAU,SAAS;EAC9B,4BAA4B,SAAS,iBAAiB,SAAS;EAE/D;CACF;CAEA,IAAI,SAAS,UAAU,cAAc,SAAS,cAAc;EAC1D,MAAM,UAAU,SAAS;EAEzB,MAAM,0BAA0B,SAAS,SAAS;EAElD,OAAO,QAAQ;CACjB;CAIA,qBAAqB,SAAS,YAAY;CAE1C,IAAI;EACF,OAAO,MAAM,iBAAiB,WAAW,SAAS,KAAK;CACzD,UAAU;EACR,qBAAqB,MAAS;CAChC;AACF;;;;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WACe;CACf,MAAM,UAAU,QAAQ;CAIxB,IAAI,CAAC,QAAQ,cAAc,CAAC,UAAU,YACpC;CAGF,IAAI,QAAQ,cAAc,UAAU,YAAY;EAC9C,sBAAsB,QAAQ,WAAW,UAAU,SAAS;EAE5D;CACF;CAOA,sBAAsB,MAHQ,QAAQ,oBACX,2BAA2B,SAEE,CAAC;AAC3D;;;;;AAMA,SAAS,sBACP,iBACA,oBACM;CACN,IAAI,0BAA0B,iBAAiB,kBAAkB,GAC/D;CAGF,MAAM,IAAI,mBACR,gCAAgC,4BAA4B,eAAe,EAAE,4BAA4B,4BAA4B,kBAAkB,EAAE,2GAC3J;AACF;;;;AAKA,SAAS,QAAQ,SAAuC;CACtD,OAAO,QAAQ,YAAY,MAAS;AACtC"}
1
+ {"version":3,"file":"vitest-setup.mjs","names":[],"sources":["../../../../../../../../packages/core/src/tests/vitest-setup.ts"],"sourcesContent":["import { loadTestLocales } from \"./test-locales\";\n\n/**\n * Worker test lifecycle — `setupTest` / `teardownTest`.\n *\n * Implements `contracts/2026-08-12-test-worker-lifecycle.md`. The pair is\n * File-scoped by default, optionally worker-scoped. Vitest runs `setupFiles`\n * before every test file. With isolation enabled it rebuilds the module registry. The harness that\n * calls `setupTest` owns pairing it with `teardownTest` in the same runtime\n * context.\n *\n * Ownership, stated once because teardown is wider than it looks:\n *\n * - the runtime assumes exclusive ownership of the process-local\n * `connectorsManager` for its lifetime;\n * - it owns the framework bootstrap, the application shutdown hooks, and the\n * connectors it starts — including the `connectors: false` case, where\n * bootstrap still registers hooks;\n * - teardown is MANAGER-WIDE. `connectorsManager.shutdown()` has no selective\n * ownership handle, so a lifecycle that started two connectors still closes\n * every connector the manager holds. Mixing `setupTest` with manual connector\n * startup in the same process is unsupported for exactly that reason.\n * - HTTP global setup stays separately owned by `startHttpTestServer` /\n * `stopHttpTestServer`.\n */\nimport { performance } from \"node:perf_hooks\";\nimport { config } from \"../config\";\nimport { loadUnitConfig } from \"./load-unit-config\";\nimport {\n testRuntimeScope,\n selectTestLifetime,\n timeTestStep,\n finishTestProfile,\n} from \"./test-runtime-scope\";\nimport { Application } from \"../application/application\";\nimport { bootstrap } from \"../bootstrap\";\nimport { setAppModuleImporter } from \"../loader/app-module-importer\";\nimport type { AppModuleImporter } from \"../loader/app-module-importer\";\nimport { loadConfigFiles } from \"../config/load-config-files\";\nimport { connectorsManager } from \"../connectors\";\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { installTestFakes, restoreTestFakes } from \"./fakes/test-fakes\";\nimport type { TestFakesSelection } from \"./fakes/test-fakes\";\nimport {\n describeConnectorsSelection,\n isSameConnectorsSelection,\n normalizeConnectorNames,\n readRequestedConnectors,\n resolveEffectiveConnectors,\n} from \"./test-connectors-selection\";\nimport type { RequestedTestConnectors, TestConnectorsSelection } from \"./test-connectors-selection\";\nimport { getTestLifecycleRegistry } from \"./test-lifecycle-state\";\nimport type { TestLifecycleRegistry, TestSetupAttempt } from \"./test-lifecycle-state\";\nimport {\n DEFAULT_TEST_SETUP_TIMEOUT,\n describeExpiredSetup,\n readConfiguredSetupTimeout,\n scheduleRealTimeout,\n} from \"./test-setup-timeout\";\nimport type { TestTimeoutHandle } from \"./test-setup-timeout\";\n\nexport type { TestConnectorsSelection } from \"./test-connectors-selection\";\n\nexport type TestRuntimeConfiguration = {\n lifetime?: \"file\" | \"worker\";\n profileSetup?: boolean;\n /** Runs before fixtures in every worker-lifetime file, including the first. Use a worker-specific database. */\n resetBetweenFiles?: () => void | Promise<void>;\n};\n\nexport type TestSetupOptions = {\n /** Unit mode loads config values without hooks, connectors or native loaders. Requires importModule. */\n mode?: \"unit\" | \"integration\";\n /** File label for setup profiling. Pass expect.getState().testPath from Vitest. */\n file?: string;\n /**\n * Which connectors to start.\n *\n * Precedence is `explicit non-undefined option > tests.connectors config >\n * true`. Omitting the property, or passing `undefined`, lets project config\n * apply — so an optional variable that happens to be `undefined` cannot erase\n * it.\n */\n connectors?: TestConnectorsSelection;\n /**\n * Import hook for APPLICATION modules (config, routes, events, ...).\n *\n * Pass `(file) => import(file)` from your `src/test-setup.ts`: that file is\n * app code, so Vitest handles the `import()` and app modules land in the same\n * module graph as your test files. Without it Warlock imports them natively,\n * one worker holds two copies of every class (`User`, ...), and `instanceof`\n * fails. Defaults to native import.\n */\n importModule?: AppModuleImporter;\n /**\n * Which test fakes to install once the connectors are up: mail, queue,\n * cache, storage, clock, ids and secrets (see `installTestFakes`).\n *\n * Precedence is `explicit option > tests.fakes config > true`, so every fake\n * is on unless the project or this call opts out. `false` keeps the real\n * drivers; `{ cache: false }` keeps only the real cache. Teardown restores\n * them.\n */\n fakes?: TestFakesSelection;\n};\n\nconst IMPORT_MODULE_WARNED_KEY = Symbol.for(\"warlock.core.importModuleWarned\");\n\n/**\n * Warn — once per process — that app modules are loaded outside Vitest's graph.\n */\nexport function warnMissingImportModule(importModule: AppModuleImporter | undefined): void {\n if (importModule || !process.env.VITEST) return;\n\n const holder = globalThis as Record<symbol, unknown>;\n\n if (holder[IMPORT_MODULE_WARNED_KEY]) return;\n\n holder[IMPORT_MODULE_WARNED_KEY] = true;\n\n console.warn(\n \"[warlock] Warlock loads app modules outside Vitest's module graph, so classes like User exist twice and instanceof fails. Pass importModule: (file) => import(file) to setupTest().\",\n );\n}\n\n/**\n * Raised by the lifecycle itself, never by the runtime it manages — a conflict\n * between two calls, or a refusal to reuse a runtime that did not close.\n */\nexport class TestLifecycleError extends Error {\n public constructor(message: string) {\n super(message);\n\n this.name = \"TestLifecycleError\";\n }\n}\n\nconst POISONED_MESSAGE =\n \"setupTest() refuses to start a test runtime: an earlier teardownTest() or per-file reset reported a failure, so the connectors, ports and pools it owned are not known to be closed. Restart the Vitest worker before setting up again, or call teardownTest() to retry the shutdown — the lifecycle only returns to idle on a fully successful retry.\";\n\n/**\n * Bootstrap the test runtime and start the selected connectors.\n *\n * By default boots once per TEST FILE. With tests.lifetime: \"worker\", the runner\n * owns shutdown and requires a shared module graph. `setupFiles` executes for\n * every file. The lifecycle state lives on the runtime\n * context rather than in this module precisely so that a rebuild cannot hide a\n * runtime that is still up.\n *\n * Repeated calls:\n *\n * - concurrent calls with the same effective selection share one startup;\n * - while ready, the same effective selection is a no-op;\n * - while starting or ready, a DIFFERENT effective selection rejects and leaves\n * the live runtime untouched;\n * - a failed setup unwinds and returns to idle, so a clean retry is allowed;\n * - after a successful `teardownTest`, a later setup may use a different\n * selection.\n *\n * @example\n * // let project config decide, falling back to the default set\n * await setupTest();\n *\n * @example\n * // bootstrap only — no connectors, whatever config says\n * await setupTest({ connectors: false });\n */\nexport async function setupTest(options?: TestSetupOptions): Promise<void> {\n const scope = testRuntimeScope();\n const mode = options?.mode ?? \"integration\";\n if (scope.fileOpen && scope.mode !== mode) {\n throw new TestLifecycleError(\"Cannot mix unit and integration runtimes in one file.\");\n }\n if (scope.mode && scope.mode !== mode && getTestLifecycleRegistry().state !== \"idle\") {\n throw new TestLifecycleError(\"Cannot change mode while a test runtime is active.\");\n }\n scope.mode = mode;\n if (mode === \"unit\") {\n if (!options?.importModule)\n throw new TestLifecycleError(\n \"setupTest({ mode: 'unit' }) requires importModule from Vitest's module graph.\",\n );\n if (scope.fileOpen) return;\n scope.profile = { file: options.file ?? \"unknown\", steps: {} };\n await timeTestStep(\"environment\", () => Application.setEnvironment(\"test\"));\n const importModule = options.importModule;\n scope.unitConfig ??= timeTestStep(\"config\", async () => {\n await warlockConfigManager.load();\n await loadUnitConfig(importModule);\n });\n try {\n await scope.unitConfig;\n } catch (error) {\n scope.unitConfig = undefined;\n scope.profile = undefined;\n throw error;\n }\n if (!profileEnabled()) scope.profile = undefined;\n scope.files += 1;\n scope.fileOpen = true;\n return;\n }\n warnMissingImportModule(options?.importModule);\n\n const registry = getTestLifecycleRegistry();\n const requested = readRequestedConnectors(options?.connectors);\n\n if (registry.state === \"poisoned\") {\n throw new TestLifecycleError(POISONED_MESSAGE);\n }\n\n if (registry.state === \"stopping\" && registry.teardownAttempt) {\n await settled(registry.teardownAttempt);\n\n return setupTest(options);\n }\n\n if (registry.state === \"ready\") {\n assertReadySelectionMatches(registry.activeSelection, requested);\n if (scope.lifetime === \"worker\" && !scope.fileOpen) {\n scope.boundary ??= Promise.resolve().then(async () => {\n beginFileProfile(options?.file);\n try {\n await timeTestStep(\"reset\", async () => {\n await restoreTestFakes();\n await installTestFakes(options?.fakes, { isolatedStorage: true });\n await resetBetweenFiles();\n });\n scope.fileOpen = true;\n scope.files += 1;\n } catch (error) {\n registry.state = \"poisoned\";\n finishTestProfile();\n throw error;\n } finally {\n scope.boundary = undefined;\n }\n });\n await scope.boundary;\n }\n return;\n }\n\n if (registry.state === \"starting\" && registry.setupAttempt) {\n const attempt = registry.setupAttempt;\n\n await assertPendingSetupMatches(attempt, requested);\n\n return attempt.completion;\n }\n\n // Scoped to this startup: the loaders read it while app modules import, and\n // it is cleared whatever the outcome so it never leaks past setup.\n setAppModuleImporter(options?.importModule);\n\n try {\n return await startTestRuntime(requested, options?.fakes, options);\n } finally {\n setAppModuleImporter(undefined);\n }\n}\n\n/**\n * Shut the test runtime down and release the lifecycle.\n *\n * - idle is a no-op;\n * - concurrent calls share one attempt;\n * - a call made while setup is still running waits for that attempt to settle,\n * then closes the runtime if it succeeded;\n * - the local \"ready\" state is always cleared, including when shutdown rejects;\n * - a shutdown rejection is surfaced, never swallowed, and poisons the\n * lifecycle — a reported close failure is not proof that anything closed, so\n * later `setupTest` calls refuse until the worker is restarted or a retry\n * fully succeeds.\n *\n * ⚠ Individual connector shutdown failures are caught and logged inside\n * `connectorsManager.shutdown()`, so they never reach this function and never\n * poison anything. This lifecycle can only surface what that layer reports.\n */\nexport async function teardownTest(): Promise<void> {\n const scope = testRuntimeScope();\n if (scope.mode === \"unit\") {\n scope.fileOpen = false;\n await timeTestStep(\"teardown\", () => Promise.resolve());\n finishTestProfile();\n return;\n }\n if (scope.lifetime === \"worker\") {\n if (scope.boundary) await settled(scope.boundary);\n scope.fileOpen = false;\n // The runner owns actual shutdown; afterAll marks the file boundary.\n await timeTestStep(\"teardown\", () => Promise.resolve());\n finishTestProfile();\n return;\n }\n try {\n await timeTestStep(\"teardown\", () => teardownFileRuntime());\n } finally {\n scope.fileOpen = false;\n finishTestProfile();\n }\n}\n\nasync function teardownFileRuntime(): Promise<void> {\n const registry = getTestLifecycleRegistry();\n\n if (registry.state === \"stopping\" && registry.teardownAttempt) {\n return registry.teardownAttempt;\n }\n\n if (registry.state === \"starting\" && registry.setupAttempt) {\n // A runtime that is still opening cannot be closed halfway. Wait for the\n // attempt to settle: a failed one has already unwound itself and left the\n // lifecycle idle, which the re-entry below then reads as \"nothing to do\".\n await settled(registry.setupAttempt.completion);\n\n return teardownFileRuntime();\n }\n\n if (registry.state === \"idle\") {\n return;\n }\n\n registry.state = \"stopping\";\n\n // Deferred by a microtask so the registry is fully published before the\n // attempt's first line runs — a synchronous throw would otherwise reach the\n // `finally` below, and reset the state, before this function had recorded\n // that a teardown was in flight at all.\n const attempt = Promise.resolve().then(() => runTestRuntimeShutdown());\n\n registry.teardownAttempt = attempt;\n\n return attempt;\n}\n\n/**\n * The setup attempt's hang guard, as the lifecycle consumes it.\n *\n * The bound's POLICY — the default, the config key, the message — lives in\n * `test-setup-timeout.ts`. What expiry MEANS lives here.\n *\n * @internal\n */\ntype SetupBound = {\n /**\n * Rejects with the expiry error. Never resolves: the attempt is the only side\n * of the race that can succeed.\n */\n readonly expiry: Promise<never>;\n\n /**\n * Re-aim the bound at `next` ms measured from when the ATTEMPT STARTED, once\n * config has made `tests.setupTimeout` readable.\n */\n rearm(next: number): void;\n\n /** The race is over — cancel whatever timer is still pending. */\n settle(): void;\n\n /** Whether the bound, rather than the attempt, won the race. */\n hasExpired(): boolean;\n};\n\n/**\n * Arm the hang guard for one setup attempt.\n *\n * Armed at the default BEFORE the attempt runs, because `tests.setupTimeout` is\n * not readable until the attempt has loaded config — and loading config is\n * itself one of the steps that can hang. `rearm` then narrows or widens it the\n * moment config arrives.\n */\nfunction armSetupBound(registry: TestLifecycleRegistry): SetupBound {\n const schedule = registry.scheduleTimeout ?? scheduleRealTimeout;\n const armedAt = Date.now();\n\n let handle: TestTimeoutHandle | undefined;\n let expired = false;\n let closed = false;\n let expire: (error: unknown) => void = () => undefined;\n\n const expiry = new Promise<never>((_resolve, reject) => {\n expire = reject;\n });\n\n // Only `awaitSetupWithinBound` observes this, and only until the attempt wins\n // — after that nobody is listening, and an unobserved rejection surfaces as an\n // unhandled rejection that fails an unrelated test file. Same reason as the\n // `effectiveSelection` barrier below.\n expiry.catch(() => undefined);\n\n const expireNow = (bound: number): void => {\n if (closed) {\n return;\n }\n\n closed = true;\n expired = true;\n\n handle?.cancel();\n handle = undefined;\n\n expire(new TestLifecycleError(describeExpiredSetup(bound)));\n };\n\n const armFor = (bound: number, delay: number): void => {\n if (closed) {\n return;\n }\n\n handle?.cancel();\n\n // Already overdue. A bound the attempt has ALREADY exceeded must fire now,\n // not be rescheduled for time that was spent before it was known.\n if (delay <= 0) {\n expireNow(bound);\n\n return;\n }\n\n handle = schedule(delay, () => expireNow(bound));\n };\n\n const initialBound = registry.setupTimeoutOverride ?? DEFAULT_TEST_SETUP_TIMEOUT;\n\n armFor(initialBound, initialBound);\n\n return {\n expiry,\n\n // Measured from `armedAt`, never from now: adding a configured bound to the\n // time already spent would make the real bound default-plus-configured, and\n // a project that lowered the key would get a LONGER guard than the default.\n rearm: (next) => armFor(next, next - (Date.now() - armedAt)),\n\n settle: () => {\n closed = true;\n\n handle?.cancel();\n handle = undefined;\n },\n\n hasExpired: () => expired,\n };\n}\n\n/**\n * Race one setup attempt against its bound.\n *\n * The losing attempt is NOT cancellable — nothing here can interrupt a bootstrap\n * stuck in a socket connect — so when the bound wins, the lifecycle is poisoned\n * and every later state write from that abandoned attempt is dropped. That\n * dropping happens in `runTestRuntimeStartup`, guarded on `hasExpired()`;\n * without it the still-running attempt would quietly overwrite `poisoned` with\n * `ready` or `idle` and hand the next caller a runtime nobody owns.\n */\nasync function awaitSetupWithinBound(\n attempt: Promise<void>,\n bound: SetupBound,\n registry: TestLifecycleRegistry,\n): Promise<void> {\n try {\n await Promise.race([attempt, bound.expiry]);\n } catch (error) {\n if (bound.hasExpired()) {\n registry.state = \"poisoned\";\n registry.activeSelection = undefined;\n registry.setupAttempt = undefined;\n }\n\n throw error;\n } finally {\n bound.settle();\n }\n}\n\n/**\n * Open a new setup attempt and publish it before it runs.\n */\nfunction startTestRuntime(\n requested: RequestedTestConnectors,\n fakes: TestFakesSelection | undefined,\n options?: TestSetupOptions,\n): Promise<void> {\n const registry = getTestLifecycleRegistry();\n\n let publishEffectiveSelection: (selection: TestConnectorsSelection) => void = () => undefined;\n let failEffectiveSelection: (error: unknown) => void = () => undefined;\n\n const effectiveSelection = new Promise<TestConnectorsSelection>((resolve, reject) => {\n publishEffectiveSelection = resolve;\n failEffectiveSelection = reject;\n });\n\n // Only the mixed explicit/config comparison ever awaits this barrier, so its\n // rejection is usually unobserved — and an unobserved rejection would surface\n // as an unhandled rejection and fail an unrelated test file.\n effectiveSelection.catch(() => undefined);\n\n const bound = armSetupBound(registry);\n\n const attempt = Promise.resolve().then(() =>\n runTestRuntimeStartup(\n requested,\n publishEffectiveSelection,\n failEffectiveSelection,\n bound,\n fakes,\n options,\n ),\n );\n\n // The attempt outlives a bound that beat it, and by then `completion` has\n // already rejected with the expiry error — so the attempt's own late rejection\n // has no observer. Same unhandled-rejection hazard as above.\n attempt.catch(() => undefined);\n\n // `teardownTest` waits on this same promise, which is how a teardown requested\n // during setup inherits the bound. There is deliberately no second timer and\n // no separate teardown deadline.\n const completion = awaitSetupWithinBound(attempt, bound, registry);\n\n registry.state = \"starting\";\n registry.setupAttempt = { requested, effectiveSelection, completion };\n\n return completion;\n}\n\n/**\n * The startup attempt itself.\n *\n * On failure: best-effort unwind, reset bookkeeping, rethrow the ORIGINAL error\n * unchanged. A cleanup failure is a secondary diagnostic and never replaces the\n * cause the caller needs to read.\n */\nasync function runTestRuntimeStartup(\n requested: RequestedTestConnectors,\n publishEffectiveSelection: (selection: TestConnectorsSelection) => void,\n failEffectiveSelection: (error: unknown) => void,\n bound: SetupBound,\n fakes: TestFakesSelection | undefined,\n options?: TestSetupOptions,\n): Promise<void> {\n const registry = getTestLifecycleRegistry();\n\n try {\n const steps: Record<string, number> = {};\n const scope = testRuntimeScope();\n // Collect cold-start timings before profileSetup becomes readable.\n scope.profile = { file: options?.file ?? \"unknown\", steps };\n await timeTestStep(\"environment\", () => Application.setEnvironment(\"test\"));\n await timeTestStep(\"config\", () => warlockConfigManager.load());\n scope.bootstraps += 1;\n await timeTestStep(\"bootstrap\", () => bootstrap());\n await timeTestStep(\"orchestrator\", () =>\n filesOrchestrator.init({ skipLoader: Boolean(process.env.VITEST && options?.importModule) }),\n );\n await timeTestStep(\"appConfig\", () => loadConfigFiles(true));\n registry.cleanupLocales = await timeTestStep(\"locales\", () => loadTestLocales());\n if (!profileEnabled()) scope.profile = undefined;\n scope.lifetime = selectTestLifetime(readRuntimeConfiguration().lifetime);\n scope.shutdown = async () => {\n const started = performance.now();\n try {\n await teardownFileRuntime();\n } finally {\n scope.shutdownMs = performance.now() - started;\n scope.fileOpen = false;\n }\n };\n\n // The first point at which `tests.setupTimeout` is readable at all. An\n // invalid value throws from here and takes the normal failure path — falling\n // back to the default would silently erase what the project configured.\n const configuredTimeout = readConfiguredSetupTimeout();\n\n if (configuredTimeout !== undefined) {\n bound.rearm(configuredTimeout);\n }\n\n // Resolved here and not at call time: the config layer is only readable once\n // the four steps above have run.\n const effectiveSelection = resolveEffectiveConnectors(requested);\n\n // Every state write below is conditional on this attempt still being the one\n // the lifecycle is waiting for. Once the bound has expired the lifecycle is\n // poisoned and this attempt is abandoned — it may still be running, but it\n // no longer speaks for the runtime.\n if (!bound.hasExpired()) {\n registry.activeSelection = effectiveSelection;\n }\n\n publishEffectiveSelection(effectiveSelection);\n\n await timeTestStep(\"connectors\", () => startSelectedConnectors(effectiveSelection));\n\n // After the connectors, so the cache and storage fakes replace drivers\n // that are already configured instead of being replaced by them.\n await timeTestStep(\"fakes\", () =>\n installTestFakes(fakes, { isolatedStorage: scope.lifetime === \"worker\" }),\n );\n if (scope.lifetime === \"worker\") await timeTestStep(\"reset\", () => resetBetweenFiles());\n\n if (!bound.hasExpired()) {\n scope.fileOpen = true;\n scope.files += 1;\n registry.state = \"ready\";\n registry.setupAttempt = undefined;\n }\n } catch (error) {\n failEffectiveSelection(error);\n\n await unwindPartialStartup();\n\n if (!bound.hasExpired()) {\n registry.state = \"idle\";\n registry.activeSelection = undefined;\n registry.setupAttempt = undefined;\n }\n\n const scope = testRuntimeScope();\n scope.lifetime = \"file\";\n scope.fileOpen = false;\n if (profileEnabled()) finishTestProfile();\n else scope.profile = undefined;\n console.error(\"[vitest-setup] Failed to setup test environment:\", error);\n\n throw error;\n }\n}\n\n/**\n * `false` means none at all. Everything else starts something: an array starts\n * exactly those, and `true` starts the default set — all but http, which is the\n * global setup's job and shared across every worker.\n */\nasync function startSelectedConnectors(selection: TestConnectorsSelection): Promise<void> {\n if (selection === false) {\n return;\n }\n\n if (Array.isArray(selection)) {\n await connectorsManager.start(normalizeConnectorNames(selection));\n\n return;\n }\n\n await connectorsManager.startWithout([\"http\"]);\n}\n\n/**\n * Best-effort teardown of whatever a failed startup managed to start.\n *\n * Runs while an error is already in flight, so no step here may throw and every\n * step is attempted independently.\n */\nasync function unwindPartialStartup(): Promise<void> {\n getTestLifecycleRegistry().cleanupLocales?.();\n getTestLifecycleRegistry().cleanupLocales = undefined;\n // Two steps rather than one: `connectorsManager.shutdown()` runs the\n // application hooks itself, but it runs them FIRST and does not isolate their\n // rejection — so a hook that rejects would take the connector teardown down\n // with it and leave every connector up. Both calls are idempotent, so running\n // the hooks on their own first costs nothing and means neither failure can\n // skip the other step.\n await attemptCleanupStep(\"test fakes\", () => restoreTestFakes());\n await attemptCleanupStep(\"application shutdown hooks\", () => Application.runShutdownHooks());\n await attemptCleanupStep(\"connectors shutdown\", () => connectorsManager.shutdown());\n}\n\n/**\n * Run one cleanup step, isolating its failure so the next step still runs.\n */\nasync function attemptCleanupStep(step: string, run: () => Promise<void>): Promise<void> {\n try {\n await run();\n } catch (error) {\n // Reported, not thrown — it is secondary to the startup error about to be\n // rethrown, and losing that one to this would be the worse outcome.\n console.error(`[vitest-setup] Cleanup after a failed setup did not complete (${step}):`, error);\n }\n}\n\n/**\n * The teardown attempt itself.\n */\nasync function runTestRuntimeShutdown(): Promise<void> {\n const registry = getTestLifecycleRegistry();\n let shutdownSucceeded = false;\n\n try {\n // Manager-wide, and deliberately called whatever the selection was: with\n // `connectors: false` nothing was started, but bootstrap still registered\n // application shutdown hooks, and the manager runs those first (see\n // `connectors-manager.ts` — `Application.runShutdownHooks()` is its first\n // line). Skipping the call to \"match\" an empty selection would leak them.\n //\n // Fakes go first, while the real drivers they put back are still\n // connected. A fake that fails to restore is reported, never allowed to\n // keep the connectors open.\n try {\n await restoreTestFakes();\n } catch (error) {\n console.error(\"[vitest-setup] Restoring the test fakes did not complete:\", error);\n }\n\n await connectorsManager.shutdown();\n\n shutdownSucceeded = true;\n } finally {\n // In a `finally`, not after the `await`: a rejected shutdown must not leave\n // the lifecycle claiming a runtime it no longer owns. Poisoned rather than\n // idle, because a cleared flag does not prove that ports, sockets, pools or\n // timers closed.\n getTestLifecycleRegistry().cleanupLocales?.();\n getTestLifecycleRegistry().cleanupLocales = undefined;\n registry.activeSelection = undefined;\n registry.setupAttempt = undefined;\n registry.teardownAttempt = undefined;\n registry.state = shutdownSucceeded ? \"idle\" : \"poisoned\";\n }\n}\n\n/**\n * Reject when a ready runtime was set up with a different selection.\n */\nfunction assertReadySelectionMatches(\n activeSelection: TestConnectorsSelection | undefined,\n requested: RequestedTestConnectors,\n): void {\n if (activeSelection === undefined) {\n return;\n }\n\n // Config is loaded by the time anything is ready, so the config-derived layer\n // is resolvable right here.\n const requestedSelection = resolveEffectiveConnectors(requested);\n\n assertSelectionsMatch(activeSelection, requestedSelection);\n}\n\n/**\n * Reject when an in-flight setup attempt is starting a different selection.\n */\nasync function assertPendingSetupMatches(\n attempt: TestSetupAttempt,\n requested: RequestedTestConnectors,\n): Promise<void> {\n const pending = attempt.requested;\n\n // Two calls that both defer to project config resolve to the same thing by\n // construction — knowable without waiting for config to load.\n if (!pending.isExplicit && !requested.isExplicit) {\n return;\n }\n\n if (pending.isExplicit && requested.isExplicit) {\n assertSelectionsMatch(pending.selection, requested.selection);\n\n return;\n }\n\n // Mixed: one side is config-derived and config is not readable until the\n // running attempt has loaded it, so wait for that barrier first.\n const activeSelection = await attempt.effectiveSelection;\n const requestedSelection = resolveEffectiveConnectors(requested);\n\n assertSelectionsMatch(activeSelection, requestedSelection);\n}\n\n/**\n * Name both selections: a caller looking at this message has to be able to tell\n * which call to change without reading the framework's source.\n */\nfunction assertSelectionsMatch(\n activeSelection: TestConnectorsSelection,\n requestedSelection: TestConnectorsSelection,\n): void {\n if (isSameConnectorsSelection(activeSelection, requestedSelection)) {\n return;\n }\n\n throw new TestLifecycleError(\n `setupTest() is already using ${describeConnectorsSelection(activeSelection)}, and this call asked for ${describeConnectorsSelection(requestedSelection)}. One test runtime serves one connector selection — call teardownTest() before setting up a different one.`,\n );\n}\n\n/**\n * Await an attempt for its state transition only, not its result.\n */\nfunction settled(attempt: Promise<void>): Promise<void> {\n return attempt.catch(() => undefined);\n}\n\nfunction profileEnabled(): boolean {\n return (\n process.env.WARLOCK_TEST_PROFILE === \"1\" || readRuntimeConfiguration().profileSetup === true\n );\n}\n\nfunction beginFileProfile(file?: string): void {\n if (profileEnabled()) testRuntimeScope().profile = { file: file ?? \"unknown\", steps: {} };\n}\n\nasync function resetBetweenFiles(): Promise<void> {\n const reset = readRuntimeConfiguration().resetBetweenFiles;\n if (reset === undefined || reset === null) return;\n if (typeof reset !== \"function\")\n throw new TestLifecycleError(\"tests.resetBetweenFiles must be a function.\");\n await reset();\n}\n\nfunction readRuntimeConfiguration(): {\n lifetime?: unknown;\n profileSetup?: unknown;\n resetBetweenFiles?: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ling/check/affected-files.d.ts
2
+ /** Transitive reverse import closure, including re-exports and type-only imports. */
3
+ export declare function affectedFiles(cwd: string, changed: readonly string[], project?: string): Promise<string[]>;
4
+ //#endregion
5
+ //# sourceMappingURL=affected-files.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"affected-files.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/affected-files.ts"],"mappings":";;wBAQsB,cACpB,aACA,4BACA,mBACC"}
@@ -0,0 +1,56 @@
1
+ import { importSpecifiers } from "../syntax/imports.mjs";
2
+ import { CompilerSession } from "../typescript/compiler.mjs";
3
+ import { resolveSpecifier } from "./conventions-step.mjs";
4
+ import { listSourceFiles, listTestFiles } from "./source-files.mjs";
5
+ import path from "node:path";
6
+ import { existsSync, readFileSync } from "node:fs";
7
+
8
+ //#region ../../packages/core/src/tooling/check/affected-files.ts
9
+ /** Transitive reverse import closure, including re-exports and type-only imports. */
10
+ async function affectedFiles(cwd, changed, project = "tsconfig.json") {
11
+ if (!changed.length) return [];
12
+ const selected = new Set(changed.map((file) => path.resolve(cwd, file)));
13
+ const session = existsSync(path.resolve(cwd, project)) ? new CompilerSession(cwd, path.resolve(cwd, project)) : void 0;
14
+ try {
15
+ const edges = [.../* @__PURE__ */ new Set([
16
+ ...await listSourceFiles(cwd),
17
+ ...await listTestFiles(cwd),
18
+ ...(session?.fileNames ?? []).filter((file) => file.startsWith(cwd + path.sep) && !file.includes(`${path.sep}node_modules${path.sep}`)).map((file) => path.relative(cwd, file))
19
+ ])].map((file) => {
20
+ const absolute = path.resolve(cwd, file);
21
+ return {
22
+ absolute,
23
+ imports: [...session?.importFiles(absolute) ?? [], ...importSpecifiers(file, readFileSync(absolute, "utf8")).flatMap(({ specifier }) => {
24
+ const target = resolveSpecifier(specifier, file, cwd);
25
+ if (!target && (specifier.startsWith(".") || specifier.startsWith("app/"))) {
26
+ const base = specifier.startsWith(".") ? path.resolve(cwd, path.dirname(file), specifier) : path.resolve(cwd, "src", specifier);
27
+ return [base, ...[
28
+ ".ts",
29
+ ".tsx",
30
+ ".js",
31
+ ".jsx",
32
+ "/index.ts",
33
+ "/index.tsx"
34
+ ].map((extension) => base + extension)].filter((candidate) => selected.has(candidate));
35
+ }
36
+ return target ? [path.resolve(cwd, target)] : [];
37
+ })]
38
+ };
39
+ });
40
+ let added = true;
41
+ while (added) {
42
+ added = false;
43
+ for (const edge of edges) if (!selected.has(edge.absolute) && edge.imports.some((file) => selected.has(path.resolve(file)))) {
44
+ selected.add(edge.absolute);
45
+ added = true;
46
+ }
47
+ }
48
+ return [...selected].filter((file) => existsSync(file)).map((file) => path.relative(cwd, file).split(path.sep).join("/")).sort();
49
+ } finally {
50
+ session?.close();
51
+ }
52
+ }
53
+
54
+ //#endregion
55
+ export { affectedFiles };
56
+ //# sourceMappingURL=affected-files.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"affected-files.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/affected-files.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { CompilerSession } from \"../typescript/compiler\";\nimport { importSpecifiers } from \"../syntax/imports\";\nimport { resolveSpecifier } from \"./conventions-step\";\nimport { listSourceFiles, listTestFiles } from \"./source-files\";\n\n/** Transitive reverse import closure, including re-exports and type-only imports. */\nexport async function affectedFiles(\n cwd: string,\n changed: readonly string[],\n project = \"tsconfig.json\",\n): Promise<string[]> {\n if (!changed.length) return [];\n const selected = new Set(changed.map((file) => path.resolve(cwd, file)));\n const session = existsSync(path.resolve(cwd, project))\n ? new CompilerSession(cwd, path.resolve(cwd, project))\n : undefined;\n try {\n const files = new Set([\n ...(await listSourceFiles(cwd)),\n ...(await listTestFiles(cwd)),\n ...(session?.fileNames ?? [])\n .filter(\n (file) =>\n file.startsWith(cwd + path.sep) && !file.includes(`${path.sep}node_modules${path.sep}`),\n )\n .map((file) => path.relative(cwd, file)),\n ]);\n const edges = [...files].map((file) => {\n const absolute = path.resolve(cwd, file);\n const imports = [\n ...(session?.importFiles(absolute) ?? []),\n ...importSpecifiers(file, readFileSync(absolute, \"utf8\")).flatMap(({ specifier }) => {\n const target = resolveSpecifier(specifier, file, cwd);\n if (!target && (specifier.startsWith(\".\") || specifier.startsWith(\"app/\"))) {\n const base = specifier.startsWith(\".\")\n ? path.resolve(cwd, path.dirname(file), specifier)\n : path.resolve(cwd, \"src\", specifier);\n const candidates = [\n base,\n ...[\".ts\", \".tsx\", \".js\", \".jsx\", \"/index.ts\", \"/index.tsx\"].map(\n (extension) => base + extension,\n ),\n ];\n return candidates.filter((candidate) => selected.has(candidate));\n }\n return target ? [path.resolve(cwd, target)] : [];\n }),\n ];\n return { absolute, imports };\n });\n let added = true;\n while (added) {\n added = false;\n for (const edge of edges)\n if (\n !selected.has(edge.absolute) &&\n edge.imports.some((file) => selected.has(path.resolve(file)))\n ) {\n selected.add(edge.absolute);\n added = true;\n }\n }\n return [...selected]\n .filter((file) => existsSync(file))\n .map((file) => path.relative(cwd, file).split(path.sep).join(\"/\"))\n .sort();\n } finally {\n session?.close();\n }\n}\n"],"mappings":";;;;;;;;;AAQA,eAAsB,cACpB,KACA,SACA,UAAU,iBACS;CACnB,IAAI,CAAC,QAAQ,QAAQ,OAAO,CAAC;CAC7B,MAAM,WAAW,IAAI,IAAI,QAAQ,KAAK,SAAS,KAAK,QAAQ,KAAK,IAAI,CAAC,CAAC;CACvE,MAAM,UAAU,WAAW,KAAK,QAAQ,KAAK,OAAO,CAAC,IACjD,IAAI,gBAAgB,KAAK,KAAK,QAAQ,KAAK,OAAO,CAAC,IACnD;CACJ,IAAI;EAWF,MAAM,QAAQ,CAAC,mBAAG,IAVA,IAAI;GACpB,GAAI,MAAM,gBAAgB,GAAG;GAC7B,GAAI,MAAM,cAAc,GAAG;GAC3B,IAAI,SAAS,aAAa,CAAC,EAAC,CACzB,QACE,SACC,KAAK,WAAW,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,SAAS,GAAG,KAAK,I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CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CACjE,KAAK;CACV,UAAU;EACR,SAAS,MAAM;CACjB;AACF"}
@@ -22,6 +22,8 @@ export declare function listChangedFiles(options: {
22
22
  cwd: string;
23
23
  base?: string;
24
24
  git?: GitRunner;
25
+ /** Keep deleted paths as seeds for reverse dependency selection. */
26
+ includeDeleted?: boolean;
25
27
  }): Promise<{
26
28
  files: string[];
27
29
  } | {
@@ -1 +1 @@
1
- {"version":3,"file":"changed-files.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/changed-files.ts"],"mappings":";;;YAMY;EAAc;EAAc;EAAgB;;;YAG5C,aAAa,yBAAyB,gBAAgB,QAAQ;;qBAG7D,QAAQ;;;;;;;;;wBAoCC,iBAAiB;EACrC;EACA;EACA,MAAM;IACJ;EAAU;;EAAsB,SAAS"}
1
+ {"version":3,"file":"changed-files.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/changed-files.ts"],"mappings":";;;YAMY;EAAc;EAAc;EAAgB;;;YAG5C,aAAa,yBAAyB,gBAAgB,QAAQ;;qBAG7D,QAAQ;;;;;;;;;wBAoCC,iBAAiB;EACrC;EACA;EACA,MAAM;;EAEN;IACE;EAAU;;EAAsB,SAAS"}
@@ -55,7 +55,7 @@ async function listChangedFiles(options) {
55
55
  "diff",
56
56
  "--name-only",
57
57
  "--relative",
58
- "--diff-filter=ACMR",
58
+ options.includeDeleted ? "--diff-filter=ACMRD" : "--diff-filter=ACMR",
59
59
  ref
60
60
  ], options.cwd);
61
61
  if (diff.code !== 0) return { problem: gitProblem(`git diff against ${ref} failed: ${diff.stderr.trim() || `exit ${diff.code}`}`) };
@@ -65,7 +65,7 @@ async function listChangedFiles(options) {
65
65
  "--exclude-standard"
66
66
  ], options.cwd);
67
67
  if (untracked.code !== 0) return { problem: gitProblem(`git ls-files failed: ${untracked.stderr.trim() || `exit ${untracked.code}`}`) };
68
- return { files: [.../* @__PURE__ */ new Set([...lines(diff.stdout), ...lines(untracked.stdout)])].map((file) => file.split(path.sep).join("/")).filter((file) => SOURCE_FILE.test(file) && existsSync(path.join(options.cwd, file))).sort() };
68
+ return { files: [.../* @__PURE__ */ new Set([...lines(diff.stdout), ...lines(untracked.stdout)])].map((file) => file.split(path.sep).join("/")).filter((file) => SOURCE_FILE.test(file) && (options.includeDeleted || existsSync(path.join(options.cwd, file)))).sort() };
69
69
  }
70
70
 
71
71
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"changed-files.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/changed-files.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { createProblem, type ToolingProblem } from \"../problem\";\n\n/** The result of one git invocation. */\nexport type GitResult = { code: number; stdout: string; stderr: string };\n\n/** Runs `git <args>` in `cwd`. Injectable so tests need no repository. */\nexport type GitRunner = (args: readonly string[], cwd: string) => Promise<GitResult>;\n\n/** The default {@link GitRunner}: the `git` on PATH. */\nexport const runGit: GitRunner = (args, cwd) =>\n new Promise((resolve) => {\n execFile(\n \"git\",\n [...args],\n { cwd, encoding: \"utf8\", windowsHide: true, maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n const code = error === null ? 0 : typeof error.code === \"number\" ? error.code : 127;\n\n resolve({ code, stdout, stderr: stderr || (error?.message ?? \"\") });\n },\n );\n });\n\n/** Files `warlock check --changed` considers: JavaScript and TypeScript sources. */\nconst SOURCE_FILE = /\\.(?:[cm]?[jt]sx?)$/i;\n\nfunction lines(output: string): string[] {\n return output\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n}\n\nfunction gitProblem(message: string): ToolingProblem {\n return createProblem({ code: \"WL8006\", source: \"environment\", message });\n}\n\n/**\n * The source files changed in the working tree — tracked changes against\n * `base` (or HEAD) plus untracked files — relative to `cwd`, existing only.\n *\n * With `base`, the comparison point is `git merge-base <base> HEAD`, so a\n * branch is compared with where it left `base` rather than with `base`'s tip.\n * A git failure is a `WL8006` environment problem.\n */\nexport async function listChangedFiles(options: {\n cwd: string;\n base?: string;\n git?: GitRunner;\n}): Promise<{ files: string[] } | { problem: ToolingProblem }> {\n const git = options.git ?? runGit;\n let ref = \"HEAD\";\n\n if (options.base) {\n const mergeBase = await git([\"merge-base\", options.base, \"HEAD\"], options.cwd);\n\n if (mergeBase.code !== 0) {\n return {\n problem: gitProblem(\n `git merge-base ${options.base} HEAD failed: ${mergeBase.stderr.trim() || `exit ${mergeBase.code}`}`,\n ),\n };\n }\n\n ref = mergeBase.stdout.trim();\n }\n\n // `--relative` makes the paths relative to cwd and limits them to it.\n const diff = await git(\n [\"diff\", \"--name-only\", \"--relative\", \"--diff-filter=ACMR\", ref],\n options.cwd,\n );\n\n if (diff.code !== 0) {\n return {\n problem: gitProblem(\n `git diff against ${ref} failed: ${diff.stderr.trim() || `exit ${diff.code}`}`,\n ),\n };\n }\n\n const untracked = await git([\"ls-files\", \"--others\", \"--exclude-standard\"], options.cwd);\n\n if (untracked.code !== 0) {\n return {\n problem: gitProblem(\n `git ls-files failed: ${untracked.stderr.trim() || `exit ${untracked.code}`}`,\n ),\n };\n }\n\n const files = [...new Set([...lines(diff.stdout), ...lines(untracked.stdout)])]\n .map((file) => file.split(path.sep).join(\"/\"))\n .filter((file) => SOURCE_FILE.test(file) && existsSync(path.join(options.cwd, file)))\n .sort();\n\n return { files };\n}\n"],"mappings":";;;;;;;AAYA,MAAa,UAAqB,MAAM,QACtC,IAAI,SAAS,YAAY;CACvB,SACE,OACA,CAAC,GAAG,IAAI,GACR;EAAE;EAAK,UAAU;EAAQ,aAAa;EAAM,WAAW;CAAiB,IACvE,OAAO,QAAQ,WAAW;EAGzB,QAAQ;GAAE,MAFG,UAAU,OAAO,IAAI,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;GAEhE;GAAQ,QAAQ,WAAW,OAAO,WAAW;EAAI,CAAC;CAC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GAAG,CAAC,CAAC,CAC7C,QAAQ,SAAS,YAAY,KAAK,IAAI,KAAK,WAAW,KAAK,KAAK,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,CACpF,KAEU,EAAE;AACjB"}
1
+ {"version":3,"file":"changed-files.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/changed-files.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { createProblem, type ToolingProblem } from \"../problem\";\n\n/** The result of one git invocation. */\nexport type GitResult = { code: number; stdout: string; stderr: string };\n\n/** Runs `git <args>` in `cwd`. Injectable so tests need no repository. */\nexport type GitRunner = (args: readonly string[], cwd: string) => Promise<GitResult>;\n\n/** The default {@link GitRunner}: the `git` on PATH. */\nexport const runGit: GitRunner = (args, cwd) =>\n new Promise((resolve) => {\n execFile(\n \"git\",\n [...args],\n { cwd, encoding: \"utf8\", windowsHide: true, maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n const code = error === null ? 0 : typeof error.code === \"number\" ? error.code : 127;\n\n resolve({ code, stdout, stderr: stderr || (error?.message ?? \"\") });\n },\n );\n });\n\n/** Files `warlock check --changed` considers: JavaScript and TypeScript sources. */\nconst SOURCE_FILE = /\\.(?:[cm]?[jt]sx?)$/i;\n\nfunction lines(output: string): string[] {\n return output\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n}\n\nfunction gitProblem(message: string): ToolingProblem {\n return createProblem({ code: \"WL8006\", source: \"environment\", message });\n}\n\n/**\n * The source files changed in the working tree — tracked changes against\n * `base` (or HEAD) plus untracked files — relative to `cwd`, existing only.\n *\n * With `base`, the comparison point is `git merge-base <base> HEAD`, so a\n * branch is compared with where it left `base` rather than with `base`'s tip.\n * A git failure is a `WL8006` environment problem.\n */\nexport async function listChangedFiles(options: {\n cwd: string;\n base?: string;\n git?: GitRunner;\n /** Keep deleted paths as seeds for reverse dependency selection. */\n includeDeleted?: boolean;\n}): Promise<{ files: string[] } | { problem: ToolingProblem }> {\n const git = options.git ?? runGit;\n let ref = \"HEAD\";\n\n if (options.base) {\n const mergeBase = await git([\"merge-base\", options.base, \"HEAD\"], options.cwd);\n\n if (mergeBase.code !== 0) {\n return {\n problem: gitProblem(\n `git merge-base ${options.base} HEAD failed: ${mergeBase.stderr.trim() || `exit ${mergeBase.code}`}`,\n ),\n };\n }\n\n ref = mergeBase.stdout.trim();\n }\n\n // `--relative` makes the paths relative to cwd and limits them to it.\n const diff = await git(\n [\n \"diff\",\n \"--name-only\",\n \"--relative\",\n options.includeDeleted ? \"--diff-filter=ACMRD\" : \"--diff-filter=ACMR\",\n ref,\n ],\n options.cwd,\n );\n\n if (diff.code !== 0) {\n return {\n problem: gitProblem(\n `git diff against ${ref} failed: ${diff.stderr.trim() || `exit ${diff.code}`}`,\n ),\n };\n }\n\n const untracked = await git([\"ls-files\", \"--others\", \"--exclude-standard\"], options.cwd);\n\n if (untracked.code !== 0) {\n return {\n problem: gitProblem(\n `git ls-files failed: ${untracked.stderr.trim() || `exit ${untracked.code}`}`,\n ),\n };\n }\n\n const files = [...new Set([...lines(diff.stdout), ...lines(untracked.stdout)])]\n .map((file) => file.split(path.sep).join(\"/\"))\n .filter(\n (file) =>\n SOURCE_FILE.test(file) &&\n (options.includeDeleted || existsSync(path.join(options.cwd, file))),\n )\n .sort();\n\n return { files };\n}\n"],"mappings":";;;;;;;AAYA,MAAa,UAAqB,MAAM,QACtC,IAAI,SAAS,YAAY;CACvB,SACE,OACA,CAAC,GAAG,IAAI,GACR;EAAE;EAAK,UAAU;EAAQ,aAAa;EAAM,WAAW;CAAiB,IACvE,OAAO,QAAQ,WAAW;EAGzB,QAAQ;GAAE,MAFG,UAAU,OAAO,IAAI,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;GAEhE;GAAQ,QAAQ,WAAW,OAAO,WAAW;EAAI,CAAC;CACpE,CACF;AACF,CAAC;;AAGH,MAAM,cAAc;AA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E,SACC,YAAY,KAAK,IAAI,MACpB,QAAQ,kBAAkB,WAAW,KAAK,KAAK,QAAQ,KAAK,IAAI,CAAC,EACtE,CAAC,CACA,KAEU,EAAE;AACjB"}
@@ -1,4 +1,5 @@
1
1
  import { ToolingProblem } from "../problem.mjs";
2
+ import { ConventionOptions } from "./web-conventions.mjs";
2
3
  //#region ../../packages/core/src/tooling/check/conventions-step.d.ts
3
4
  /** Matches a project-relative path of a file the framework loads by itself. */
4
5
  export declare function isAutoLoadedFile(relativePath: string): boolean;
@@ -20,7 +21,7 @@ export declare function isAutoLoadedFile(relativePath: string): boolean;
20
21
  * A `// warlock-check-ignore WL9006` comment on the problem's line or the line
21
22
  * above silences that code there; without codes it silences every one.
22
23
  */
23
- export declare function checkFileConventions(relativePath: string, source: string, cwd: string): ToolingProblem[];
24
+ export declare function checkFileConventions(relativePath: string, source: string, cwd: string, options?: ConventionOptions): ToolingProblem[];
24
25
  /** `WL9004` when the project tsconfig turns on legacy decorators. */
25
26
  export declare function checkTsconfigConventions(cwd: string, project?: string): ToolingProblem[];
26
27
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"conventions-step.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/conventions-step.ts"],"mappings":";;;wBAiBgB,iBAAiB;;;;;;;;;;;;;;;;;;;wBAiKjB,qBACd,sBACA,gBACA,cACC;;wBAmBa,yBAAyB,aAAa,mBAA4B;;;;;wBAyClE,eACd,aACA,0BACA,mBACC"}
1
+ {"version":3,"file":"conventions-step.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/conventions-step.ts"],"mappings":";;;;wBAoBgB,iBAAiB;;;;;;;;;;;;;;;;;;;wBAuKjB,qBACd,sBACA,gBACA,aACA,UAAS,oBACR;;wBAgCa,yBAAyB,aAAa,mBAA4B;;;;;wBAyClE,eACd,aACA,0BACA,mBACC"}