@warlock.js/core 5.32.0 → 5.33.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 (125) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/esm/application/application-config-types.d.mts +8 -0
  3. package/esm/application/application-config-types.d.mts.map +1 -1
  4. package/esm/application/boot-signal.d.mts +8 -8
  5. package/esm/application/boot-signal.d.mts.map +1 -1
  6. package/esm/application/boot-signal.mjs +15 -9
  7. package/esm/application/boot-signal.mjs.map +1 -1
  8. package/esm/cli/commands/ai/ai-command.action.mjs +140 -0
  9. package/esm/cli/commands/ai/ai-command.action.mjs.map +1 -0
  10. package/esm/cli/commands/ai.command.mjs +50 -0
  11. package/esm/cli/commands/ai.command.mjs.map +1 -0
  12. package/esm/cli/commands/check/check-command.action.mjs +3 -0
  13. package/esm/cli/commands/check/check-command.action.mjs.map +1 -1
  14. package/esm/cli/commands/check.command.mjs +6 -1
  15. package/esm/cli/commands/check.command.mjs.map +1 -1
  16. package/esm/cli/commands/pm2/pm2-command.action.mjs +91 -0
  17. package/esm/cli/commands/pm2/pm2-command.action.mjs.map +1 -0
  18. package/esm/cli/commands/pm2/pm2-config.mjs +115 -0
  19. package/esm/cli/commands/pm2/pm2-config.mjs.map +1 -0
  20. package/esm/cli/commands/pm2.command.mjs +53 -0
  21. package/esm/cli/commands/pm2.command.mjs.map +1 -0
  22. package/esm/cli/framework-cli-commands.mjs +4 -0
  23. package/esm/cli/framework-cli-commands.mjs.map +1 -1
  24. package/esm/connectors/connectors-manager.d.mts.map +1 -1
  25. package/esm/connectors/connectors-manager.mjs +1 -4
  26. package/esm/connectors/connectors-manager.mjs.map +1 -1
  27. package/esm/connectors/shutdown-timeout.mjs +7 -0
  28. package/esm/connectors/shutdown-timeout.mjs.map +1 -0
  29. package/esm/connectors/socket-connector.d.mts.map +1 -1
  30. package/esm/connectors/socket-connector.mjs +8 -1
  31. package/esm/connectors/socket-connector.mjs.map +1 -1
  32. package/esm/dev-server/health-checker/checkers/eslint-health-checker.mjs +6 -8
  33. package/esm/dev-server/health-checker/checkers/eslint-health-checker.mjs.map +1 -1
  34. package/esm/dev-server/health-checker/default-health-checkers.mjs +6 -15
  35. package/esm/dev-server/health-checker/default-health-checkers.mjs.map +1 -1
  36. package/esm/dev-server/health-checker/eslint-support.mjs +27 -0
  37. package/esm/dev-server/health-checker/eslint-support.mjs.map +1 -0
  38. package/esm/dev-server/health-checker/file-health-checker.contract.d.mts +2 -1
  39. package/esm/dev-server/health-checker/file-health-checker.contract.d.mts.map +1 -1
  40. package/esm/dev-server/health-checker/workers/eslint-health.worker.mjs +2 -11
  41. package/esm/dev-server/health-checker/workers/eslint-health.worker.mjs.map +1 -1
  42. package/esm/generations/features/index.mjs +2 -0
  43. package/esm/generations/features/index.mjs.map +1 -1
  44. package/esm/generations/features/process.feature.mjs +65 -0
  45. package/esm/generations/features/process.feature.mjs.map +1 -0
  46. package/esm/http/port-preflight.d.mts.map +1 -1
  47. package/esm/http/port-preflight.mjs +2 -0
  48. package/esm/http/port-preflight.mjs.map +1 -1
  49. package/esm/index.d.mts +7 -2
  50. package/esm/index.mjs +7 -2
  51. package/esm/secrets/errors.d.mts +9 -0
  52. package/esm/secrets/errors.d.mts.map +1 -0
  53. package/esm/secrets/errors.mjs +22 -0
  54. package/esm/secrets/errors.mjs.map +1 -0
  55. package/esm/secrets/file-backend.mjs +167 -0
  56. package/esm/secrets/file-backend.mjs.map +1 -0
  57. package/esm/secrets/index.d.mts +6 -0
  58. package/esm/secrets/index.mjs +6 -0
  59. package/esm/secrets/keyring-backend.mjs +50 -0
  60. package/esm/secrets/keyring-backend.mjs.map +1 -0
  61. package/esm/secrets/memory-backend.d.mts +12 -0
  62. package/esm/secrets/memory-backend.d.mts.map +1 -0
  63. package/esm/secrets/memory-backend.mjs +28 -0
  64. package/esm/secrets/memory-backend.mjs.map +1 -0
  65. package/esm/secrets/secret-store.d.mts +25 -0
  66. package/esm/secrets/secret-store.d.mts.map +1 -0
  67. package/esm/secrets/secret-store.mjs +117 -0
  68. package/esm/secrets/secret-store.mjs.map +1 -0
  69. package/esm/secrets/secrets.d.mts +11 -0
  70. package/esm/secrets/secrets.d.mts.map +1 -0
  71. package/esm/secrets/secrets.mjs +63 -0
  72. package/esm/secrets/secrets.mjs.map +1 -0
  73. package/esm/secrets/types.d.mts +22 -0
  74. package/esm/secrets/types.d.mts.map +1 -0
  75. package/esm/socket/index.d.mts +2 -2
  76. package/esm/socket/index.mjs +2 -2
  77. package/esm/socket/utils.d.mts +7 -0
  78. package/esm/socket/utils.d.mts.map +1 -1
  79. package/esm/socket/utils.mjs +12 -1
  80. package/esm/socket/utils.mjs.map +1 -1
  81. package/esm/tests/fakes/index.d.mts +2 -1
  82. package/esm/tests/fakes/index.mjs +2 -1
  83. package/esm/tests/fakes/secrets-fake.d.mts +13 -0
  84. package/esm/tests/fakes/secrets-fake.d.mts.map +1 -0
  85. package/esm/tests/fakes/secrets-fake.mjs +50 -0
  86. package/esm/tests/fakes/secrets-fake.mjs.map +1 -0
  87. package/esm/tests/fakes/test-fakes.d.mts +2 -2
  88. package/esm/tests/fakes/test-fakes.d.mts.map +1 -1
  89. package/esm/tests/fakes/test-fakes.mjs +5 -2
  90. package/esm/tests/fakes/test-fakes.mjs.map +1 -1
  91. package/esm/tests/index.d.mts +2 -1
  92. package/esm/tests/index.mjs +2 -1
  93. package/esm/tests/vitest-setup.d.mts +1 -1
  94. package/esm/tests/vitest-setup.mjs.map +1 -1
  95. package/esm/tooling/check/lint-step.d.mts +2 -8
  96. package/esm/tooling/check/lint-step.d.mts.map +1 -1
  97. package/esm/tooling/check/lint-step.mjs +14 -11
  98. package/esm/tooling/check/lint-step.mjs.map +1 -1
  99. package/esm/tooling/check/run-check.d.mts +2 -0
  100. package/esm/tooling/check/run-check.d.mts.map +1 -1
  101. package/esm/tooling/check/run-check.mjs +2 -2
  102. package/esm/tooling/check/run-check.mjs.map +1 -1
  103. package/esm/upgrade/codemods/index.mjs +2 -0
  104. package/esm/upgrade/codemods/index.mjs.map +1 -1
  105. package/esm/upgrade/codemods/oxc-toolchain.mjs +142 -0
  106. package/esm/upgrade/codemods/oxc-toolchain.mjs.map +1 -0
  107. package/esm/upgrade/codemods/toolchain-templates.mjs +244 -0
  108. package/esm/upgrade/codemods/toolchain-templates.mjs.map +1 -0
  109. package/esm/upgrade/run-upgrade.mjs +25 -6
  110. package/esm/upgrade/run-upgrade.mjs.map +1 -1
  111. package/esm/warlock-config/types.d.mts +2 -1
  112. package/esm/warlock-config/types.d.mts.map +1 -1
  113. package/llms-full.txt +326 -19
  114. package/llms.txt +3 -2
  115. package/package.json +23 -13
  116. package/skills/README.md +2 -1
  117. package/skills/index.md +1 -1
  118. package/skills/run-app/SKILL.md +114 -5
  119. package/skills/store-secrets/SKILL.md +102 -0
  120. package/skills/test-fakes/SKILL.md +13 -11
  121. package/skills/upgrade-from-5-29/SKILL.md +39 -2
  122. package/skills/warlock-check/SKILL.md +5 -1
  123. package/skills/warlock-doctor/SKILL.md +9 -0
  124. package/skills/wire-socket/SKILL.md +19 -0
  125. package/skills/write-cli-command/SKILL.md +21 -0
@@ -7,7 +7,18 @@ import { container } from "../container/index.mjs";
7
7
  function getSocketServer() {
8
8
  return container.tryGet("socket") ?? null;
9
9
  }
10
+ /**
11
+ * Broadcast through the socket connector's configured adapter. Returns false
12
+ * without a socket server; true means dispatched, not acknowledged by clients.
13
+ * Socket.IO 4.8.3's BroadcastOperator.emit calls adapter.broadcast (installed
14
+ * socket.io/dist/broadcast-operator.js); do not use `io.local` here.
15
+ */
16
+ function broadcastSocketEvent(event, ...args) {
17
+ const socket = getSocketServer();
18
+ if (!socket) return false;
19
+ return socket.emit(event, ...args);
20
+ }
10
21
 
11
22
  //#endregion
12
- export { getSocketServer };
23
+ export { broadcastSocketEvent, getSocketServer };
13
24
  //# sourceMappingURL=utils.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../../packages/core/src/socket/utils.ts"],"sourcesContent":["import { type Server } from \"socket.io\";\nimport { container } from \"../container\";\n\n/**\n * Get socket server instance\n */\nexport function getSocketServer(): Server | null {\n return container.tryGet(\"socket\") ?? null;\n}\n"],"mappings":";;;;;;AAMA,SAAgB,kBAAiC;CAC/C,OAAO,UAAU,OAAO,QAAQ,KAAK;AACvC"}
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../../packages/core/src/socket/utils.ts"],"sourcesContent":["import { type Server } from \"socket.io\";\nimport { container } from \"../container\";\n\n/**\n * Get socket server instance\n */\nexport function getSocketServer(): Server | null {\n return container.tryGet(\"socket\") ?? null;\n}\n\n/**\n * Broadcast through the socket connector's configured adapter. Returns false\n * without a socket server; true means dispatched, not acknowledged by clients.\n * Socket.IO 4.8.3's BroadcastOperator.emit calls adapter.broadcast (installed\n * socket.io/dist/broadcast-operator.js); do not use `io.local` here.\n */\nexport function broadcastSocketEvent(event: string, ...args: unknown[]): boolean {\n const socket = getSocketServer();\n if (!socket) return false;\n return socket.emit(event, ...args);\n}\n"],"mappings":";;;;;;AAMA,SAAgB,kBAAiC;CAC/C,OAAO,UAAU,OAAO,QAAQ,KAAK;AACvC;;;;;;;AAQA,SAAgB,qBAAqB,OAAe,GAAG,MAA0B;CAC/E,MAAM,SAAS,gBAAgB;CAC/B,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO,OAAO,KAAK,OAAO,GAAG,IAAI;AACnC"}
@@ -6,4 +6,5 @@ import { idsFake } from "./ids-fake.mjs";
6
6
  import { MailMatcher, mailFake } from "./mail-fake.mjs";
7
7
  import { JobReference, PushedJob, PushedJobMatcher, queueFake } from "./queue-fake.mjs";
8
8
  import { storageFake } from "./storage-fake.mjs";
9
- export { DEFAULT_FAKE_NOW, FakeAssertionError, JobReference, MailMatcher, PushedJob, PushedJobMatcher, TEST_FAKE_NAMES, TestFakeName, TestFakesSelection, cacheFake, clockFake, describeRecorded, idsFake, installTestFakes, installedTestFakes, mailFake, queueFake, readConfiguredFakes, resolveTestFakes, restoreTestFakes, storageFake };
9
+ import { secretsFake } from "./secrets-fake.mjs";
10
+ export { DEFAULT_FAKE_NOW, FakeAssertionError, JobReference, MailMatcher, PushedJob, PushedJobMatcher, TEST_FAKE_NAMES, TestFakeName, TestFakesSelection, cacheFake, clockFake, describeRecorded, idsFake, installTestFakes, installedTestFakes, mailFake, queueFake, readConfiguredFakes, resolveTestFakes, restoreTestFakes, secretsFake, storageFake };
@@ -4,7 +4,8 @@ import { DEFAULT_FAKE_NOW, clockFake } from "./clock-fake.mjs";
4
4
  import { idsFake } from "./ids-fake.mjs";
5
5
  import { mailFake } from "./mail-fake.mjs";
6
6
  import { queueFake } from "./queue-fake.mjs";
7
+ import { secretsFake } from "./secrets-fake.mjs";
7
8
  import { storageFake } from "./storage-fake.mjs";
8
9
  import { TEST_FAKE_NAMES, installTestFakes, installedTestFakes, readConfiguredFakes, resolveTestFakes, restoreTestFakes } from "./test-fakes.mjs";
9
10
 
10
- export { DEFAULT_FAKE_NOW, FakeAssertionError, TEST_FAKE_NAMES, cacheFake, clockFake, describeRecorded, idsFake, installTestFakes, installedTestFakes, mailFake, queueFake, readConfiguredFakes, resolveTestFakes, restoreTestFakes, storageFake };
11
+ export { DEFAULT_FAKE_NOW, FakeAssertionError, TEST_FAKE_NAMES, cacheFake, clockFake, describeRecorded, idsFake, installTestFakes, installedTestFakes, mailFake, queueFake, readConfiguredFakes, resolveTestFakes, restoreTestFakes, secretsFake, storageFake };
@@ -0,0 +1,13 @@
1
+ //#region ../../packages/core/src/tests/fakes/secrets-fake.d.ts
2
+ /** The default test-kit secret backend. Assertion failures never reveal stored values. */
3
+ export declare const secretsFake: {
4
+ install(): void;
5
+ restore(): void;
6
+ isInstalled(): boolean;
7
+ clear(): void;
8
+ assertHas(name: string): Promise<void>;
9
+ assertMissing(name: string): Promise<void>;
10
+ assertStored(name: string, value: string): Promise<void>;
11
+ };
12
+ //#endregion
13
+ //# sourceMappingURL=secrets-fake.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets-fake.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/secrets-fake.ts"],"mappings":";;qBAaa;EACX;EAQA;EAMA;EAGA;EAGM,UAAS,eAAgB;EAMzB,cAAa,eAAgB;EAM7B,aAAY,cAAa,gBAAkB"}
@@ -0,0 +1,50 @@
1
+ import { MemorySecretBackend } from "../../secrets/memory-backend.mjs";
2
+ import { replaceSecretsBackend, secrets } from "../../secrets/secrets.mjs";
3
+ import { FakeAssertionError } from "./fake-assertion-error.mjs";
4
+
5
+ //#region ../../packages/core/src/tests/fakes/secrets-fake.ts
6
+ let backend;
7
+ let restore;
8
+ function installed() {
9
+ if (!backend) throw new FakeAssertionError("secretsFake is not installed.");
10
+ return backend;
11
+ }
12
+ /** The default test-kit secret backend. Assertion failures never reveal stored values. */
13
+ const secretsFake = {
14
+ install() {
15
+ if (backend) {
16
+ backend.clear();
17
+ return;
18
+ }
19
+ backend = new MemorySecretBackend();
20
+ restore = replaceSecretsBackend(backend);
21
+ },
22
+ restore() {
23
+ restore?.();
24
+ restore = void 0;
25
+ backend?.clear();
26
+ backend = void 0;
27
+ },
28
+ isInstalled() {
29
+ return backend !== void 0;
30
+ },
31
+ clear() {
32
+ installed().clear();
33
+ },
34
+ async assertHas(name) {
35
+ installed();
36
+ if (!await secrets.has(name)) throw new FakeAssertionError("Expected the secret to be present.");
37
+ },
38
+ async assertMissing(name) {
39
+ installed();
40
+ if (await secrets.has(name)) throw new FakeAssertionError("Expected the secret to be absent.");
41
+ },
42
+ async assertStored(name, value) {
43
+ installed();
44
+ if (await secrets.get(name) !== value) throw new FakeAssertionError("The stored secret does not match the expected value.");
45
+ }
46
+ };
47
+
48
+ //#endregion
49
+ export { secretsFake };
50
+ //# sourceMappingURL=secrets-fake.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets-fake.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/secrets-fake.ts"],"sourcesContent":["import { MemorySecretBackend } from \"../../secrets/memory-backend\";\nimport { replaceSecretsBackend, secrets } from \"../../secrets/secrets\";\nimport { FakeAssertionError } from \"./fake-assertion-error\";\n\nlet backend: MemorySecretBackend | undefined;\nlet restore: (() => void) | undefined;\n\nfunction installed(): MemorySecretBackend {\n if (!backend) throw new FakeAssertionError(\"secretsFake is not installed.\");\n return backend;\n}\n\n/** The default test-kit secret backend. Assertion failures never reveal stored values. */\nexport const secretsFake = {\n install(): void {\n if (backend) {\n backend.clear();\n return;\n }\n backend = new MemorySecretBackend();\n restore = replaceSecretsBackend(backend);\n },\n restore(): void {\n restore?.();\n restore = undefined;\n backend?.clear();\n backend = undefined;\n },\n isInstalled(): boolean {\n return backend !== undefined;\n },\n clear(): void {\n installed().clear();\n },\n async assertHas(name: string): Promise<void> {\n installed();\n if (!(await secrets.has(name))) {\n throw new FakeAssertionError(\"Expected the secret to be present.\");\n }\n },\n async assertMissing(name: string): Promise<void> {\n installed();\n if (await secrets.has(name)) {\n throw new FakeAssertionError(\"Expected the secret to be absent.\");\n }\n },\n async assertStored(name: string, value: string): Promise<void> {\n installed();\n if ((await secrets.get(name)) !== value) {\n throw new FakeAssertionError(\"The stored secret does not match the expected value.\");\n }\n },\n};\n"],"mappings":";;;;;AAIA,IAAI;AACJ,IAAI;AAEJ,SAAS,YAAiC;CACxC,IAAI,CAAC,SAAS,MAAM,IAAI,mBAAmB,+BAA+B;CAC1E,OAAO;AACT;;AAGA,MAAa,cAAc;CACzB,UAAgB;EACd,IAAI,SAAS;GACX,QAAQ,MAAM;GACd;EACF;EACA,UAAU,IAAI,oBAAoB;EAClC,UAAU,sBAAsB,OAAO;CACzC;CACA,UAAgB;EACd,UAAU;EACV,UAAU;EACV,SAAS,MAAM;EACf,UAAU;CACZ;CACA,cAAuB;EACrB,OAAO,YAAY;CACrB;CACA,QAAc;EACZ,UAAU,CAAC,CAAC,MAAM;CACpB;CACA,MAAM,UAAU,MAA6B;EAC3C,UAAU;EACV,IAAI,CAAE,MAAM,QAAQ,IAAI,IAAI,GAC1B,MAAM,IAAI,mBAAmB,oCAAoC;CAErE;CACA,MAAM,cAAc,MAA6B;EAC/C,UAAU;EACV,IAAI,MAAM,QAAQ,IAAI,IAAI,GACxB,MAAM,IAAI,mBAAmB,mCAAmC;CAEpE;CACA,MAAM,aAAa,MAAc,OAA8B;EAC7D,UAAU;EACV,IAAK,MAAM,QAAQ,IAAI,IAAI,MAAO,OAChC,MAAM,IAAI,mBAAmB,sDAAsD;CAEvF;AACF"}
@@ -1,12 +1,12 @@
1
1
  //#region ../../packages/core/src/tests/fakes/test-fakes.d.ts
2
2
  /** The fakes the test kit installs. */
3
- export declare const TEST_FAKE_NAMES: readonly ["mail", "queue", "cache", "storage", "clock", "ids"];
3
+ export declare const TEST_FAKE_NAMES: readonly ["mail", "queue", "cache", "storage", "clock", "ids", "secrets"];
4
4
  export type TestFakeName = (typeof TEST_FAKE_NAMES)[number];
5
5
  /**
6
6
  * Which fakes to install.
7
7
  *
8
8
  * - `true` (the default) — all of them.
9
- * - `false` — none: real drivers, real clock, real ids.
9
+ * - `false` — none: real drivers, real clock, real ids, real secret storage.
10
10
  * - an object — all of them except the ones set to `false`, e.g.
11
11
  * `{ cache: false }` keeps the configured cache driver.
12
12
  */
@@ -1 +1 @@
1
- {"version":3,"file":"test-fakes.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/test-fakes.ts"],"mappings":";;qBAUa;YAED,uBAAuB;;;;;;;;;YAUvB,+BAA+B,QAAQ,OAAO;;wBAiB1C,uBAAuB;;;;;;wBA0CvB,iBAAiB,WAAW,qBAAqB;;;;;;;;wBAiB3C,iBAAiB,WAAW,qBAAqB,QAAQ;;;;;wBAgBzD,oBAAoB;;wBAiB1B,sBAAsB"}
1
+ {"version":3,"file":"test-fakes.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/test-fakes.ts"],"mappings":";;qBAWa;YAUD,uBAAuB;;;;;;;;;YAUvB,+BAA+B,QAAQ,OAAO;;wBAkB1C,uBAAuB;;;;;;wBA0CvB,iBAAiB,WAAW,qBAAqB;;;;;;;;wBAiB3C,iBAAiB,WAAW,qBAAqB,QAAQ;;;;;wBAgBzD,oBAAoB;;wBAiB1B,sBAAsB"}
@@ -5,6 +5,7 @@ import { clockFake } from "./clock-fake.mjs";
5
5
  import { idsFake } from "./ids-fake.mjs";
6
6
  import { mailFake } from "./mail-fake.mjs";
7
7
  import { queueFake } from "./queue-fake.mjs";
8
+ import { secretsFake } from "./secrets-fake.mjs";
8
9
  import { storageFake } from "./storage-fake.mjs";
9
10
 
10
11
  //#region ../../packages/core/src/tests/fakes/test-fakes.ts
@@ -15,7 +16,8 @@ const TEST_FAKE_NAMES = [
15
16
  "cache",
16
17
  "storage",
17
18
  "clock",
18
- "ids"
19
+ "ids",
20
+ "secrets"
19
21
  ];
20
22
  const fakes = {
21
23
  mail: mailFake,
@@ -23,7 +25,8 @@ const fakes = {
23
25
  cache: cacheFake,
24
26
  storage: storageFake,
25
27
  clock: clockFake,
26
- ids: idsFake
28
+ ids: idsFake,
29
+ secrets: secretsFake
27
30
  };
28
31
  let active = [];
29
32
  /** Read `tests.fakes` from `src/config/tests.ts`, or `undefined` when unset. */
@@ -1 +1 @@
1
- {"version":3,"file":"test-fakes.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/test-fakes.ts"],"sourcesContent":["import type { GenericObject } from \"@mongez/reinforcements\";\nimport { config } from \"../../config\";\nimport { cacheFake } from \"./cache-fake\";\nimport { clockFake } from \"./clock-fake\";\nimport { idsFake } from \"./ids-fake\";\nimport { mailFake } from \"./mail-fake\";\nimport { queueFake } from \"./queue-fake\";\nimport { storageFake } from \"./storage-fake\";\n\n/** The fakes the test kit installs. */\nexport const TEST_FAKE_NAMES = [\"mail\", \"queue\", \"cache\", \"storage\", \"clock\", \"ids\"] as const;\n\nexport type TestFakeName = (typeof TEST_FAKE_NAMES)[number];\n\n/**\n * Which fakes to install.\n *\n * - `true` (the default) — all of them.\n * - `false` — none: real drivers, real clock, real ids.\n * - an object — all of them except the ones set to `false`, e.g.\n * `{ cache: false }` keeps the configured cache driver.\n */\nexport type TestFakesSelection = boolean | Partial<Record<TestFakeName, boolean>>;\n\nconst fakes: Record<\n TestFakeName,\n { install(): void | Promise<void>; restore(): void | Promise<void> }\n> = {\n mail: mailFake,\n queue: queueFake,\n cache: cacheFake,\n storage: storageFake,\n clock: clockFake,\n ids: idsFake,\n};\n\nlet active: TestFakeName[] = [];\n\n/** Read `tests.fakes` from `src/config/tests.ts`, or `undefined` when unset. */\nexport function readConfiguredFakes(): TestFakesSelection | undefined {\n // `config.get` resolves an absent key to `null`, not to its default's shape.\n const testsConfig = config.get<GenericObject>(\"tests\", {}) ?? {};\n\n return validateSelection(testsConfig.fakes as unknown, \"tests.fakes\");\n}\n\nfunction validateSelection(value: unknown, source: string): TestFakesSelection | undefined {\n if (value === undefined || typeof value === \"boolean\") return value;\n\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(\n `${source} must be true, false, or an object such as { cache: false }; got ${JSON.stringify(value)}.`,\n );\n }\n\n const selection: Partial<Record<TestFakeName, boolean>> = {};\n\n for (const [key, flag] of Object.entries(value)) {\n const name = TEST_FAKE_NAMES.find((candidate) => candidate === key);\n\n if (!name) {\n throw new Error(\n `${source} has an unknown fake \"${key}\". Known fakes: ${TEST_FAKE_NAMES.join(\", \")}.`,\n );\n }\n\n if (typeof flag !== \"boolean\") {\n throw new Error(`${source}.${key} must be true or false; got ${JSON.stringify(flag)}.`);\n }\n\n selection[name] = flag;\n }\n\n return selection;\n}\n\n/**\n * The fakes to install. Precedence: an explicit selection (the `fakes`\n * option of `setupTest()` / `startHttpTestServer()`) > `tests.fakes` in\n * `src/config/tests.ts` > all on.\n */\nexport function resolveTestFakes(explicit?: TestFakesSelection): TestFakeName[] {\n const selection =\n explicit !== undefined ? validateSelection(explicit, \"fakes\") : readConfiguredFakes();\n\n if (selection === undefined || selection === true) return [...TEST_FAKE_NAMES];\n if (selection === false) return [];\n\n return TEST_FAKE_NAMES.filter((name) => selection[name] !== false);\n}\n\n/**\n * Install the selected fakes. Called by `setupTest()` and\n * `startHttpTestServer()` once their connectors are up; call it yourself only\n * when you bootstrap the framework without them.\n *\n * @returns the fakes that are now installed.\n */\nexport async function installTestFakes(explicit?: TestFakesSelection): Promise<TestFakeName[]> {\n const selected = resolveTestFakes(explicit);\n\n for (const name of selected) {\n await fakes[name].install();\n }\n\n active = [...new Set([...active, ...selected])];\n\n return selected;\n}\n\n/**\n * Restore every installed fake, in reverse order. Every fake is restored even\n * when one fails; the failures are rethrown together afterwards.\n */\nexport async function restoreTestFakes(): Promise<void> {\n const errors: unknown[] = [];\n\n for (const name of [...active].reverse()) {\n try {\n await fakes[name].restore();\n } catch (error) {\n errors.push(error);\n }\n }\n\n active = [];\n\n if (errors.length > 0) throw new AggregateError(errors, \"Restoring the test fakes failed.\");\n}\n\n/** The fakes installed right now. */\nexport function installedTestFakes(): TestFakeName[] {\n return [...active];\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,kBAAkB;CAAC;CAAQ;CAAS;CAAS;CAAW;CAAS;AAAK;AAcnF,MAAM,QAGF;CACF,MAAM;CACN,OAAO;CACP,OAAO;CACP,SAAS;CACT,OAAO;CACP,KAAK;AACP;AAEA,IAAI,SAAyB,CAAC;;AAG9B,SAAgB,sBAAsD;CAIpE,OAAO,mBAFa,OAAO,IAAmB,SAAS,CAAC,CAAC,KAAK,CAAC,EAE3B,CAAC,OAAkB,aAAa;AACtE;AAEA,SAAS,kBAAkB,OAAgB,QAAgD;CACzF,IAAI,UAAU,UAAa,OAAO,UAAU,WAAW,OAAO;CAE9D,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MACR,GAAG,OAAO,mEAAmE,KAAK,UAAU,KAAK,EAAE,EACrG;CAGF,MAAM,YAAoD,CAAC;CAE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 {"version":3,"file":"test-fakes.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/test-fakes.ts"],"sourcesContent":["import type { GenericObject } from \"@mongez/reinforcements\";\nimport { config } from \"../../config\";\nimport { cacheFake } from \"./cache-fake\";\nimport { clockFake } from \"./clock-fake\";\nimport { idsFake } from \"./ids-fake\";\nimport { mailFake } from \"./mail-fake\";\nimport { queueFake } from \"./queue-fake\";\nimport { secretsFake } from \"./secrets-fake\";\nimport { storageFake } from \"./storage-fake\";\n\n/** The fakes the test kit installs. */\nexport const TEST_FAKE_NAMES = [\n \"mail\",\n \"queue\",\n \"cache\",\n \"storage\",\n \"clock\",\n \"ids\",\n \"secrets\",\n] as const;\n\nexport type TestFakeName = (typeof TEST_FAKE_NAMES)[number];\n\n/**\n * Which fakes to install.\n *\n * - `true` (the default) — all of them.\n * - `false` — none: real drivers, real clock, real ids, real secret storage.\n * - an object — all of them except the ones set to `false`, e.g.\n * `{ cache: false }` keeps the configured cache driver.\n */\nexport type TestFakesSelection = boolean | Partial<Record<TestFakeName, boolean>>;\n\nconst fakes: Record<\n TestFakeName,\n { install(): void | Promise<void>; restore(): void | Promise<void> }\n> = {\n mail: mailFake,\n queue: queueFake,\n cache: cacheFake,\n storage: storageFake,\n clock: clockFake,\n ids: idsFake,\n secrets: secretsFake,\n};\n\nlet active: TestFakeName[] = [];\n\n/** Read `tests.fakes` from `src/config/tests.ts`, or `undefined` when unset. */\nexport function readConfiguredFakes(): TestFakesSelection | undefined {\n // `config.get` resolves an absent key to `null`, not to its default's shape.\n const testsConfig = config.get<GenericObject>(\"tests\", {}) ?? {};\n\n return validateSelection(testsConfig.fakes as unknown, \"tests.fakes\");\n}\n\nfunction validateSelection(value: unknown, source: string): TestFakesSelection | undefined {\n if (value === undefined || typeof value === \"boolean\") return value;\n\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(\n `${source} must be true, false, or an object such as { cache: false }; got ${JSON.stringify(value)}.`,\n );\n }\n\n const selection: Partial<Record<TestFakeName, boolean>> = {};\n\n for (const [key, flag] of Object.entries(value)) {\n const name = TEST_FAKE_NAMES.find((candidate) => candidate === key);\n\n if (!name) {\n throw new Error(\n `${source} has an unknown fake \"${key}\". Known fakes: ${TEST_FAKE_NAMES.join(\", \")}.`,\n );\n }\n\n if (typeof flag !== \"boolean\") {\n throw new Error(`${source}.${key} must be true or false; got ${JSON.stringify(flag)}.`);\n }\n\n selection[name] = flag;\n }\n\n return selection;\n}\n\n/**\n * The fakes to install. Precedence: an explicit selection (the `fakes`\n * option of `setupTest()` / `startHttpTestServer()`) > `tests.fakes` in\n * `src/config/tests.ts` > all on.\n */\nexport function resolveTestFakes(explicit?: TestFakesSelection): TestFakeName[] {\n const selection =\n explicit !== undefined ? validateSelection(explicit, \"fakes\") : readConfiguredFakes();\n\n if (selection === undefined || selection === true) return [...TEST_FAKE_NAMES];\n if (selection === false) return [];\n\n return TEST_FAKE_NAMES.filter((name) => selection[name] !== false);\n}\n\n/**\n * Install the selected fakes. Called by `setupTest()` and\n * `startHttpTestServer()` once their connectors are up; call it yourself only\n * when you bootstrap the framework without them.\n *\n * @returns the fakes that are now installed.\n */\nexport async function installTestFakes(explicit?: TestFakesSelection): Promise<TestFakeName[]> {\n const selected = resolveTestFakes(explicit);\n\n for (const name of selected) {\n await fakes[name].install();\n }\n\n active = [...new Set([...active, ...selected])];\n\n return selected;\n}\n\n/**\n * Restore every installed fake, in reverse order. Every fake is restored even\n * when one fails; the failures are rethrown together afterwards.\n */\nexport async function restoreTestFakes(): Promise<void> {\n const errors: unknown[] = [];\n\n for (const name of [...active].reverse()) {\n try {\n await fakes[name].restore();\n } catch (error) {\n errors.push(error);\n }\n }\n\n active = [];\n\n if (errors.length > 0) throw new AggregateError(errors, \"Restoring the test fakes failed.\");\n}\n\n/** The fakes installed right now. */\nexport function installedTestFakes(): TestFakeName[] {\n return [...active];\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,kBAAkB;CAC7B;CACA;CACA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,MAAM,QAAQ,UACjB,MAAM,MAAM,KAAK,CAAC,QAAQ;CAG5B,SAAS,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,QAAQ,GAAG,QAAQ,CAAC,CAAC;CAE9C,OAAO;AACT;;;;;AAMA,eAAsB,mBAAkC;CACtD,MAAM,SAAoB,CAAC;CAE3B,KAAK,MAAM,QAAQ,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,GACrC,IAAI;EACF,MAAM,MAAM,KAAK,CAAC,QAAQ;CAC5B,SAAS,OAAO;EACd,OAAO,KAAK,KAAK;CACnB;CAGF,SAAS,CAAC;CAEV,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,eAAe,QAAQ,kCAAkC;AAC5F;;AAGA,SAAgB,qBAAqC;CACnD,OAAO,CAAC,GAAG,MAAM;AACnB"}
@@ -12,8 +12,9 @@ import { idsFake } from "./fakes/ids-fake.mjs";
12
12
  import { MailMatcher, mailFake } from "./fakes/mail-fake.mjs";
13
13
  import { JobReference, PushedJob, PushedJobMatcher, queueFake } from "./fakes/queue-fake.mjs";
14
14
  import { storageFake } from "./fakes/storage-fake.mjs";
15
+ import { secretsFake } from "./fakes/secrets-fake.mjs";
15
16
  import "./fakes/index.mjs";
16
17
  import { Factory, FactoryAttributes, FactoryOverrides, FactorySeed, FactoryState, defineFactory, resetFactorySequences } from "./factories.mjs";
17
18
  import { CreateTestHttpServerOptions, TestHttpServer, createTestHttpServer } from "./test-http-server.mjs";
18
19
  import { REDACTED, ResponseSnapshot, SnapshotResponseOptions, snapshotResponse } from "./snapshot-response.mjs";
19
- export { AuthenticatedTestClient, CreateTestHttpServerOptions, DEFAULT_FAKE_NOW, Factory, FactoryAttributes, FactoryOverrides, FactorySeed, FactoryState, FakeAssertionError, JobReference, MailMatcher, PushedJob, PushedJobMatcher, REDACTED, ResponseSnapshot, SnapshotResponseOptions, StartHttpTestServerOptions, TEST_FAKE_NAMES, TestAuthenticableUser, type TestConnectorsSelection, TestFakeName, TestFakesSelection, TestHttpServer, TestLifecycleError, TestRequestClient, TestSetupOptions, actingAs, assertPortIsAvailable, cacheFake, clockFake, createTestHttpServer, createTestRequestClient, defineFactory, describeRecorded, expectJson, getTestServerUrl, idsFake, installTestFakes, installedTestFakes, isPortAvailable, isTestServerRunning, mailFake, parseJsonResponse, queueFake, readConfiguredFakes, resetFactorySequences, resolveTestFakes, restoreTestFakes, setupTest, snapshotResponse, startHttpTestServer, stopHttpTestServer, storageFake, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest, warnMissingImportModule };
20
+ export { AuthenticatedTestClient, CreateTestHttpServerOptions, DEFAULT_FAKE_NOW, Factory, FactoryAttributes, FactoryOverrides, FactorySeed, FactoryState, FakeAssertionError, JobReference, MailMatcher, PushedJob, PushedJobMatcher, REDACTED, ResponseSnapshot, SnapshotResponseOptions, StartHttpTestServerOptions, TEST_FAKE_NAMES, TestAuthenticableUser, type TestConnectorsSelection, TestFakeName, TestFakesSelection, TestHttpServer, TestLifecycleError, TestRequestClient, TestSetupOptions, actingAs, assertPortIsAvailable, cacheFake, clockFake, createTestHttpServer, createTestRequestClient, defineFactory, describeRecorded, expectJson, getTestServerUrl, idsFake, installTestFakes, installedTestFakes, isPortAvailable, isTestServerRunning, mailFake, parseJsonResponse, queueFake, readConfiguredFakes, resetFactorySequences, resolveTestFakes, restoreTestFakes, secretsFake, setupTest, snapshotResponse, startHttpTestServer, stopHttpTestServer, storageFake, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest, warnMissingImportModule };
@@ -5,6 +5,7 @@ import { DEFAULT_FAKE_NOW, clockFake } from "./fakes/clock-fake.mjs";
5
5
  import { idsFake } from "./fakes/ids-fake.mjs";
6
6
  import { mailFake } from "./fakes/mail-fake.mjs";
7
7
  import { queueFake } from "./fakes/queue-fake.mjs";
8
+ import { secretsFake } from "./fakes/secrets-fake.mjs";
8
9
  import { storageFake } from "./fakes/storage-fake.mjs";
9
10
  import { TEST_FAKE_NAMES, installTestFakes, installedTestFakes, readConfiguredFakes, resolveTestFakes, restoreTestFakes } from "./fakes/test-fakes.mjs";
10
11
  import { isTestServerRunning, startHttpTestServer, stopHttpTestServer } from "./start-http-development-server.mjs";
@@ -16,4 +17,4 @@ import { defineFactory, resetFactorySequences } from "./factories.mjs";
16
17
  import { createTestHttpServer } from "./test-http-server.mjs";
17
18
  import { REDACTED, snapshotResponse } from "./snapshot-response.mjs";
18
19
 
19
- export { DEFAULT_FAKE_NOW, FakeAssertionError, REDACTED, TEST_FAKE_NAMES, TestLifecycleError, actingAs, assertPortIsAvailable, cacheFake, clockFake, createTestHttpServer, createTestRequestClient, defineFactory, describeRecorded, expectJson, getTestServerUrl, idsFake, installTestFakes, installedTestFakes, isPortAvailable, isTestServerRunning, mailFake, parseJsonResponse, queueFake, readConfiguredFakes, resetFactorySequences, resolveTestFakes, restoreTestFakes, setupTest, snapshotResponse, startHttpTestServer, stopHttpTestServer, storageFake, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest, warnMissingImportModule };
20
+ export { DEFAULT_FAKE_NOW, FakeAssertionError, REDACTED, TEST_FAKE_NAMES, TestLifecycleError, actingAs, assertPortIsAvailable, cacheFake, clockFake, createTestHttpServer, createTestRequestClient, defineFactory, describeRecorded, expectJson, getTestServerUrl, idsFake, installTestFakes, installedTestFakes, isPortAvailable, isTestServerRunning, mailFake, parseJsonResponse, queueFake, readConfiguredFakes, resetFactorySequences, resolveTestFakes, restoreTestFakes, secretsFake, setupTest, snapshotResponse, startHttpTestServer, stopHttpTestServer, storageFake, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest, warnMissingImportModule };
@@ -24,7 +24,7 @@ export type TestSetupOptions = {
24
24
  importModule?: AppModuleImporter;
25
25
  /**
26
26
  * Which test fakes to install once the connectors are up: mail, queue,
27
- * cache, storage, clock and ids (see `installTestFakes`).
27
+ * cache, storage, clock, ids and secrets (see `installTestFakes`).
28
28
  *
29
29
  * Precedence is `explicit option > tests.fakes config > true`, so every fake
30
30
  * is on unless the project or this call opts out. `false` keeps the real
@@ -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 and ids (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;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AAC3D;;;;AAKA,eAAe,0BACb,SACA,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":["/**\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,U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MAAM,iEAAiE,KAAK,KAAK,KAAK;CAChG;AACF;;;;AAKA,eAAe,yBAAwC;CACrD,MAAM,WAAW,yBAAyB;CAC1C,IAAI,oBAAoB;CAExB,IAAI;EAUF,IAAI;GACF,MAAM,iBAAiB;EACzB,SAAS,OAAO;GACd,QAAQ,MAAM,6DAA6D,KAAK;EAClF;EAEA,MAAM,kBAAkB,SAAS;EAEjC,oBAAoB;CACtB,UAAU;EAKR,SAAS,kBAAkB;EAC3B,SAAS,eAAe;EACxB,SAAS,kBAAkB;EAC3B,SAAS,QAAQ,oBAAoB,SAAS;CAChD;AACF;;;;AAKA,SAAS,4BACP,iBACA,WACM;CACN,IAAI,oBAAoB,QACtB;CAOF,sBAAsB,iBAFK,2BAA2B,SAEE,CAAC;AAC3D;;;;AAKA,eAAe,0BACb,SACA,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"}
@@ -6,13 +6,7 @@ export type LintOutcome = {
6
6
  /** The linters that ran (`eslint`, `oxlint`); empty when the app configures none. */
7
7
  linters: string[];
8
8
  };
9
- /**
10
- * Lint `files` (project-relative) with the linters the app configures, the
11
- * same ones `warlock dev` runs in the background: ESLint when an
12
- * `eslint.config.*` exists, oxlint when an oxlint config exists and the app
13
- * has the `oxlint` package. A config without its tool is a `WL8002`
14
- * environment problem.
15
- */
16
- export declare function runLint(cwd: string, files: readonly string[]): Promise<LintOutcome>;
9
+ /** Oxlint by default. ESLint requires an explicit selection and a flat config. */
10
+ export declare function runLint(cwd: string, files: readonly string[], selection?: "oxlint" | "eslint"): Promise<LintOutcome>;
17
11
  //#endregion
18
12
  //# sourceMappingURL=lint-step.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"lint-step.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/lint-step.ts"],"mappings":";;;YAWY;EACV,UAAU;;EAEV;;;;;;;;;wBAuFoB,QAAQ,aAAa,2BAA2B,QAAQ"}
1
+ {"version":3,"file":"lint-step.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/lint-step.ts"],"mappings":";;;YAWY;EACV,UAAU;;EAEV;;;wBAiFoB,QACpB,aACA,0BACA,kCACC,QAAQ"}
@@ -1,5 +1,5 @@
1
+ import { hasEslint, warnEslintDeprecation } from "../../dev-server/health-checker/eslint-support.mjs";
1
2
  import { OxlintRunner, findOxlint, hasOxlintConfig } from "../../dev-server/health-checker/oxlint-runner.mjs";
2
- import { hasEslint } from "../../dev-server/health-checker/default-health-checkers.mjs";
3
3
  import { createProblem } from "../problem.mjs";
4
4
  import path from "node:path";
5
5
  import { ESLint } from "eslint";
@@ -65,14 +65,8 @@ async function runOxlint(cwd, files) {
65
65
  await runner.shutdown();
66
66
  }
67
67
  }
68
- /**
69
- * Lint `files` (project-relative) with the linters the app configures, the
70
- * same ones `warlock dev` runs in the background: ESLint when an
71
- * `eslint.config.*` exists, oxlint when an oxlint config exists and the app
72
- * has the `oxlint` package. A config without its tool is a `WL8002`
73
- * environment problem.
74
- */
75
- async function runLint(cwd, files) {
68
+ /** Oxlint by default. ESLint requires an explicit selection and a flat config. */
69
+ async function runLint(cwd, files, selection = "oxlint") {
76
70
  const lintable = files.filter((file) => LINTABLE.test(file));
77
71
  const problems = [];
78
72
  const linters = [];
@@ -80,7 +74,16 @@ async function runLint(cwd, files) {
80
74
  problems,
81
75
  linters
82
76
  };
83
- if (hasEslint(cwd)) {
77
+ if (selection === "eslint") {
78
+ warnEslintDeprecation();
79
+ if (!hasEslint(cwd)) return {
80
+ linters: ["eslint"],
81
+ problems: [createProblem({
82
+ code: "WL8002",
83
+ source: "environment",
84
+ message: "Cannot find ESLint flat config in the app."
85
+ })]
86
+ };
84
87
  linters.push("eslint");
85
88
  try {
86
89
  problems.push(...await runEslint(cwd, lintable));
@@ -88,7 +91,7 @@ async function runLint(cwd, files) {
88
91
  problems.push(toolFailure("ESLint", error));
89
92
  }
90
93
  }
91
- if (hasOxlintConfig(cwd)) {
94
+ if (selection === "oxlint" && hasOxlintConfig(cwd)) {
92
95
  linters.push("oxlint");
93
96
  if (!findOxlint(cwd)) problems.push(createProblem({
94
97
  code: "WL8002",
@@ -1 +1 @@
1
- {"version":3,"file":"lint-step.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/lint-step.ts"],"sourcesContent":["import { ESLint } from \"eslint\";\nimport path from \"node:path\";\nimport { hasEslint } from \"../../dev-server/health-checker/default-health-checkers\";\nimport {\n findOxlint,\n hasOxlintConfig,\n OxlintRunner,\n} from \"../../dev-server/health-checker/oxlint-runner\";\nimport { createProblem, type ToolingProblem } from \"../problem\";\n\n/** What the lint step found, and which linters ran. */\nexport type LintOutcome = {\n problems: ToolingProblem[];\n /** The linters that ran (`eslint`, `oxlint`); empty when the app configures none. */\n linters: string[];\n};\n\nconst LINTABLE = /\\.[cm]?[jt]sx?$/i;\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** A missing package/plugin is the machine's install; anything else is the tool crashing. */\nfunction toolFailure(tool: string, error: unknown): ToolingProblem {\n const message = errorMessage(error);\n const missing = /cannot find (?:module|package)|ERR_MODULE_NOT_FOUND/i.test(message);\n\n return createProblem({\n code: missing ? \"WL8002\" : \"WL8007\",\n source: \"environment\",\n message: `${tool} could not run: ${message.split(\"\\n\")[0]}`,\n });\n}\n\nasync function runEslint(cwd: string, files: readonly string[]): Promise<ToolingProblem[]> {\n // The same flat-config lookup the dev server's ESLint checker uses.\n const eslint = new ESLint({ cwd, errorOnUnmatchedPattern: false, warnIgnored: false });\n const results = await eslint.lintFiles([...files]);\n const problems: ToolingProblem[] = [];\n\n for (const result of results) {\n const file = path.relative(cwd, result.filePath).split(path.sep).join(\"/\");\n\n for (const message of result.messages) {\n const error = message.severity === 2 || message.fatal === true;\n\n problems.push(\n createProblem({\n code: error ? \"WL7201\" : \"WL7202\",\n source: \"eslint\",\n severity: error ? \"error\" : \"warning\",\n message: message.message,\n file,\n line: message.line || null,\n column: message.column || null,\n rule: message.ruleId ?? null,\n }),\n );\n }\n }\n\n return problems;\n}\n\nasync function runOxlint(cwd: string, files: readonly string[]): Promise<ToolingProblem[]> {\n const runner = new OxlintRunner();\n\n runner.initialize(cwd);\n\n try {\n const results = await runner.checkFiles(\n files.map((file) => ({ path: path.join(cwd, file), relativePath: file })),\n );\n\n return results.flatMap((result) =>\n [...result.errors, ...result.warnings].map((message) =>\n createProblem({\n code: message.type === \"error\" ? \"WL7201\" : \"WL7202\",\n source: \"oxlint\",\n severity: message.type,\n message: message.message,\n file: message.relativePath,\n line: message.lineNumber,\n column: message.columnNumber,\n rule: message.ruleId ?? null,\n }),\n ),\n );\n } finally {\n await runner.shutdown();\n }\n}\n\n/**\n * Lint `files` (project-relative) with the linters the app configures, the\n * same ones `warlock dev` runs in the background: ESLint when an\n * `eslint.config.*` exists, oxlint when an oxlint config exists and the app\n * has the `oxlint` package. A config without its tool is a `WL8002`\n * environment problem.\n */\nexport async function runLint(cwd: string, files: readonly string[]): Promise<LintOutcome> {\n const lintable = files.filter((file) => LINTABLE.test(file));\n const problems: ToolingProblem[] = [];\n const linters: string[] = [];\n\n // ESLint lints the whole directory when handed no pattern; nothing to lint\n // means nothing to run.\n if (lintable.length === 0) return { problems, linters };\n\n if (hasEslint(cwd)) {\n linters.push(\"eslint\");\n\n try {\n problems.push(...(await runEslint(cwd, lintable)));\n } catch (error) {\n problems.push(toolFailure(\"ESLint\", error));\n }\n }\n\n if (hasOxlintConfig(cwd)) {\n linters.push(\"oxlint\");\n\n if (!findOxlint(cwd)) {\n problems.push(\n createProblem({\n code: \"WL8002\",\n source: \"environment\",\n message: \"An oxlint config exists but the oxlint package is not installed in the app.\",\n }),\n );\n } else {\n try {\n problems.push(...(await runOxlint(cwd, lintable)));\n } catch (error) {\n problems.push(toolFailure(\"oxlint\", error));\n }\n }\n }\n\n return { problems, linters };\n}\n"],"mappings":";;;;;;;AAiBA,MAAM,WAAW;AAEjB,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;AAGA,SAAS,YAAY,MAAc,OAAgC;CACjE,MAAM,UAAU,aAAa,KAAK;CAClC,MAAM,UAAU,uDAAuD,KAAK,OAAO;CAEnF,OAAO,cAAc;EACnB,MAAM,UAAU,WAAW;EAC3B,QAAQ;EACR,SAAS,GAAG,KAAK,kBAAkB,QAAQ,MAAM,IAAI,CAAC,CAAC;CACzD,CAAC;AACH;AAEA,eAAe,UAAU,KAAa,OAAqD;CAGzF,MAAM,UAAU,MAAM,IADH,OAAO;EAAE;EAAK,yBAAyB;EAAO,aAAa;CAAM,CACzD,CAAC,CAAC,UAAU,CAAC,GAAG,KAAK,CAAC;CACjD,MAAM,WAA6B,CAAC;CAEpC,KAAK,MAAM,UAAU,SAAS;EAC5B,MAAM,OAAO,KAAK,SAAS,KAAK,OAAO,QAAQ,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;EAEzE,KAAK,MAAM,WAAW,OAAO,UAAU;GACrC,MAAM,QAAQ,QAAQ,aAAa,KAAK,QAAQ,UAAU;GAE1D,SAAS,KACP,cAAc;IACZ,MAAM,QAAQ,WAAW;IACzB,QAAQ;IACR,UAAU,QAAQ,UAAU;IAC5B,SAAS,QAAQ;IACjB;IACA,MAAM,Q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OAEA,IAAI;GACF,SAAS,KAAK,GAAI,MAAM,UAAU,KAAK,QAAQ,CAAE;EACnD,SAAS,OAAO;GACd,SAAS,KAAK,YAAY,UAAU,KAAK,CAAC;EAC5C;CAEJ;CAEA,OAAO;EAAE;EAAU;CAAQ;AAC7B"}
1
+ {"version":3,"file":"lint-step.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/lint-step.ts"],"sourcesContent":["import { ESLint } from \"eslint\";\nimport path from \"node:path\";\nimport { hasEslint, warnEslintDeprecation } from \"../../dev-server/health-checker/eslint-support\";\nimport {\n findOxlint,\n hasOxlintConfig,\n OxlintRunner,\n} from \"../../dev-server/health-checker/oxlint-runner\";\nimport { createProblem, type ToolingProblem } from \"../problem\";\n\n/** What the lint step found, and which linters ran. */\nexport type LintOutcome = {\n problems: ToolingProblem[];\n /** The linters that ran (`eslint`, `oxlint`); empty when the app configures none. */\n linters: string[];\n};\n\nconst LINTABLE = /\\.[cm]?[jt]sx?$/i;\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** A missing package/plugin is the machine's install; anything else is the tool crashing. */\nfunction toolFailure(tool: string, error: unknown): ToolingProblem {\n const message = errorMessage(error);\n const missing = /cannot find (?:module|package)|ERR_MODULE_NOT_FOUND/i.test(message);\n\n return createProblem({\n code: missing ? \"WL8002\" : \"WL8007\",\n source: \"environment\",\n message: `${tool} could not run: ${message.split(\"\\n\")[0]}`,\n });\n}\n\nasync function runEslint(cwd: string, files: readonly string[]): Promise<ToolingProblem[]> {\n // The same flat-config lookup the dev server's ESLint checker uses.\n const eslint = new ESLint({ cwd, errorOnUnmatchedPattern: false, warnIgnored: false });\n const results = await eslint.lintFiles([...files]);\n const problems: ToolingProblem[] = [];\n\n for (const result of results) {\n const file = path.relative(cwd, result.filePath).split(path.sep).join(\"/\");\n\n for (const message of result.messages) {\n const error = message.severity === 2 || message.fatal === true;\n\n problems.push(\n createProblem({\n code: error ? \"WL7201\" : \"WL7202\",\n source: \"eslint\",\n severity: error ? \"error\" : \"warning\",\n message: message.message,\n file,\n line: message.line || null,\n column: message.column || null,\n rule: message.ruleId ?? null,\n }),\n );\n }\n }\n\n return problems;\n}\n\nasync function runOxlint(cwd: string, files: readonly string[]): Promise<ToolingProblem[]> {\n const runner = new OxlintRunner();\n\n runner.initialize(cwd);\n\n try {\n const results = await runner.checkFiles(\n files.map((file) => ({ path: path.join(cwd, file), relativePath: file })),\n );\n\n return results.flatMap((result) =>\n [...result.errors, ...result.warnings].map((message) =>\n createProblem({\n code: message.type === \"error\" ? \"WL7201\" : \"WL7202\",\n source: \"oxlint\",\n severity: message.type,\n message: message.message,\n file: message.relativePath,\n line: message.lineNumber,\n column: message.columnNumber,\n rule: message.ruleId ?? null,\n }),\n ),\n );\n } finally {\n await runner.shutdown();\n }\n}\n\n/** Oxlint by default. ESLint requires an explicit selection and a flat config. */\nexport async function runLint(\n cwd: string,\n files: readonly string[],\n selection: \"oxlint\" | \"eslint\" = \"oxlint\",\n): Promise<LintOutcome> {\n const lintable = files.filter((file) => LINTABLE.test(file));\n const problems: ToolingProblem[] = [];\n const linters: string[] = [];\n\n // ESLint lints the whole directory when handed no pattern; nothing to lint\n // means nothing to run.\n if (lintable.length === 0) return { problems, linters };\n\n if (selection === \"eslint\") {\n warnEslintDeprecation();\n if (!hasEslint(cwd)) {\n return {\n linters: [\"eslint\"],\n problems: [\n createProblem({\n code: \"WL8002\",\n source: \"environment\",\n message: \"Cannot find ESLint flat config in the app.\",\n }),\n ],\n };\n }\n linters.push(\"eslint\");\n\n try {\n problems.push(...(await runEslint(cwd, lintable)));\n } catch (error) {\n problems.push(toolFailure(\"ESLint\", error));\n }\n }\n\n if (selection === \"oxlint\" && hasOxlintConfig(cwd)) {\n linters.push(\"oxlint\");\n\n if (!findOxlint(cwd)) {\n problems.push(\n createProblem({\n code: \"WL8002\",\n source: \"environment\",\n message: \"An oxlint config exists but the oxlint package is not installed in the app.\",\n }),\n );\n } else {\n try {\n probl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OAAO;GACd,SAAS,KAAK,YAAY,UAAU,KAAK,CAAC;EAC5C;CAEJ;CAEA,OAAO;EAAE;EAAU;CAAQ;AAC7B"}
@@ -9,6 +9,8 @@ export type TypecheckRunner = (options: TypecheckOptions) => Promise<TypecheckRe
9
9
  export type CheckOptions = {
10
10
  /** Project root. Default: `process.cwd()`. */
11
11
  cwd?: string;
12
+ /** Oxlint by default; ESLint is deprecated and requires explicit selection. */
13
+ lint?: "oxlint" | "eslint";
12
14
  /** Limit every step to the files changed against `base` (default HEAD) plus untracked files. */
13
15
  changed?: boolean;
14
16
  /** Compare with `git merge-base <base> HEAD` instead of HEAD. Implies `changed`. */
@@ -1 +1 @@
1
- {"version":3,"file":"run-check.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/run-check.ts"],"mappings":";;;;;;YA8BY,mBACV,SAAS,qBACN,QAAQ,mBAAmB;;YAGpB;;EAEV;;EAEA;;EAEA;;EAEA,gBAAgB;;EAEhB;;EAEA,MAAM;;EAEN,YAAY;;EAEZ,SAAS;;EAET;;EAEA;;;;;;;;;;;;wBA4BoB,SAAS,UAAS,eAAoB,QAAQ"}
1
+ {"version":3,"file":"run-check.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/run-check.ts"],"mappings":";;;;;;YA8BY,mBACV,SAAS,qBACN,QAAQ,mBAAmB;;YAGpB;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA,gBAAgB;;EAEhB;;EAEA,MAAM;;EAEN,YAAY;;EAEZ,SAAS;;EAET;;EAEA;;;;;;;;;;;;wBA4BoB,SAAS,UAAS,eAAoB,QAAQ"}
@@ -119,10 +119,10 @@ async function runCheck(options = {}) {
119
119
  detail: "no files to lint",
120
120
  problems: []
121
121
  };
122
- const { linters, problems: found } = await runLint(cwd, lintFiles);
122
+ const { linters, problems: found } = await runLint(cwd, lintFiles, options.lint);
123
123
  if (linters.length === 0) return {
124
124
  status: "skipped",
125
- detail: "no ESLint or oxlint config",
125
+ detail: "no Oxlint config (ESLint requires --lint eslint)",
126
126
  problems: []
127
127
  };
128
128
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"run-check.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/run-check.ts"],"sourcesContent":["import path from \"node:path\";\nimport { createProblem, type ToolingProblem } from \"../problem\";\nimport {\n runTypecheck,\n type TypecheckOptions,\n type TypecheckResult,\n} from \"../typecheck/run-typecheck\";\nimport { type GitRunner, listChangedFiles } from \"./changed-files\";\nimport {\n CHECK_STEPS,\n type CheckReport,\n type CheckStep,\n type CheckStepName,\n type CheckStepStatus,\n checkExitCode,\n} from \"./check-report.types\";\nimport { runConventions } from \"./conventions-step\";\nimport { checkNodeVersion } from \"./environment-step\";\nimport { runLint } from \"./lint-step\";\nimport { listSourceFiles, listTestFiles } from \"./source-files\";\nimport {\n findVitest,\n parseVitestReport,\n runVitest,\n type VitestRunner,\n vitestArguments,\n vitestRunFailure,\n} from \"./tests-step\";\n\n/** Runs the typecheck step. The CLI swaps in a child process so a heap overflow cannot end `check`. */\nexport type TypecheckRunner = (\n options: TypecheckOptions,\n) => Promise<TypecheckResult> | TypecheckResult;\n\n/** Inputs of {@link runCheck}. */\nexport type CheckOptions = {\n /** Project root. Default: `process.cwd()`. */\n cwd?: string;\n /** Limit every step to the files changed against `base` (default HEAD) plus untracked files. */\n changed?: boolean;\n /** Compare with `git merge-base <base> HEAD` instead of HEAD. Implies `changed`. */\n base?: string;\n /** Steps not to run. */\n skip?: readonly CheckStepName[];\n /** tsconfig path, relative to `cwd`. Default: `tsconfig.json`. */\n project?: string;\n /** How git is run. */\n git?: GitRunner;\n /** How the typecheck runs. Default: in this process. */\n typecheck?: TypecheckRunner;\n /** How vitest runs. */\n vitest?: VitestRunner;\n /** Where the app's vitest CLI is. Default: resolved from the app root. */\n vitestBinary?: string | null;\n /** The Node.js version to check. Default: the running one. */\n nodeVersion?: string;\n};\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction statusOf(problems: readonly ToolingProblem[]): CheckStepStatus {\n const errors = problems.filter((problem) => problem.severity === \"error\");\n\n if (errors.some((problem) => problem.category === \"environment\")) return \"blocked\";\n\n return errors.length > 0 ? \"failed\" : \"passed\";\n}\n\n/** Bundles one step's timing, status and problems. */\ntype StepOutcome = { status?: CheckStepStatus; detail: string | null; problems: ToolingProblem[] };\n\n/**\n * The single verify command: typecheck, lint, the tests affected by the\n * change, and the framework's convention checks, as one report with one entry\n * per problem and an exit code that tells \"your code\" (1) from \"this machine\"\n * (2).\n *\n * Every step runs even when an earlier one failed, so one run lists every\n * problem. The only exception: with `changed`, a git failure leaves no file\n * list, and every step after `environment` is `blocked`.\n */\nexport async function runCheck(options: CheckOptions = {}): Promise<CheckReport> {\n const cwd = path.resolve(options.cwd ?? process.cwd());\n const changed = options.changed === true || options.base !== undefined;\n const skip = new Set(options.skip ?? []);\n const steps: CheckStep[] = [];\n const problems: ToolingProblem[] = [];\n let files: string[] | null = null;\n let filesBlocked = false;\n\n const run = async (name: CheckStepName, body: () => Promise<StepOutcome> | StepOutcome) => {\n const startedAt = Date.now();\n\n if (skip.has(name)) {\n steps.push({ name, status: \"skipped\", durationMs: 0, detail: \"skipped with --skip\" });\n return;\n }\n\n if (filesBlocked && name !== \"environment\") {\n steps.push({\n name,\n status: \"blocked\",\n durationMs: 0,\n detail: \"the changed files could not be listed\",\n });\n return;\n }\n\n let outcome: StepOutcome;\n\n try {\n outcome = await body();\n } catch (error) {\n outcome = {\n detail: null,\n problems: [\n createProblem({\n code: \"WL8007\",\n source: \"environment\",\n message: `The ${name} step crashed: ${errorMessage(error)}`,\n }),\n ],\n };\n }\n\n problems.push(...outcome.problems);\n steps.push({\n name,\n status: outcome.status ?? statusOf(outcome.problems),\n durationMs: Date.now() - startedAt,\n detail: outcome.detail,\n });\n };\n\n await run(\"environment\", async () => {\n const found = checkNodeVersion(cwd, options.nodeVersion);\n\n if (changed) {\n const listed = await listChangedFiles({ cwd, base: options.base, git: options.git });\n\n if (\"problem\" in listed) {\n filesBlocked = true;\n found.push(listed.problem);\n } else {\n files = listed.files;\n }\n }\n\n return {\n detail: `Node ${options.nodeVersion ?? process.versions.node}${files ? `, ${files.length} changed file(s)` : \"\"}`,\n problems: found,\n };\n });\n\n const targets = async (): Promise<string[]> => files ?? (await listSourceFiles(cwd));\n\n await run(\"typecheck\", async () => {\n if (files !== null && files.length === 0) {\n return { status: \"skipped\", detail: \"no changed files\", problems: [] };\n }\n\n const typecheck = options.typecheck ?? runTypecheck;\n const result = await typecheck({\n cwd,\n project: options.project,\n ...(files !== null ? { files } : {}),\n });\n\n return {\n detail: `${result.checkedFiles} file(s) checked in ${result.durationMs}ms`,\n problems: result.problems,\n };\n });\n\n await run(\"lint\", async () => {\n const lintFiles = await targets();\n\n if (lintFiles.length === 0) {\n return { status: \"skipped\", detail: \"no files to lint\", problems: [] };\n }\n\n const { linters, problems: found } = await runLint(cwd, lintFiles);\n\n if (linters.length === 0) {\n return { status: \"skipped\", detail: \"no ESLint or oxlint config\", problems: [] };\n }\n\n return { detail: `${linters.join(\" + \")} over ${lintFiles.length} file(s)`, problems: found };\n });\n\n await run(\"tests\", async () => {\n if (files !== null && files.length === 0) {\n return { status: \"skipped\", detail: \"no changed files\", problems: [] };\n }\n\n const binary = options.vitestBinary === undefined ? findVitest(cwd) : options.vitestBinary;\n\n if (!binary) {\n if ((await listTestFiles(cwd)).length === 0) {\n return { status: \"skipped\", detail: \"no test files\", problems: [] };\n }\n\n return {\n detail: null,\n problems: [\n createProblem({\n code: \"WL8002\",\n source: \"environment\",\n message: \"The project has test files but vitest is not installed in the app.\",\n }),\n ],\n };\n }\n\n const vitest = options.vitest ?? runVitest;\n const outcome = await vitest(binary, vitestArguments(files), cwd);\n const found =\n outcome.report === undefined\n ? vitestRunFailure(outcome)\n : parseVitestReport(outcome.report, cwd);\n const total =\n typeof outcome.report === \"object\" && outcome.report !== null\n ? Reflect.get(outcome.report, \"numTotalTests\")\n : undefined;\n\n return {\n detail: typeof total === \"number\" ? `${total} test(s) ran` : null,\n problems: found,\n };\n });\n\n await run(\"conventions\", async () => {\n const conventionFiles = await targets();\n\n return {\n detail: `${conventionFiles.length} file(s) checked`,\n problems: runConventions(cwd, conventionFiles, options.project),\n };\n });\n\n // Keep the declared order even if a future step is added out of sequence.\n steps.sort((first, second) => CHECK_STEPS.indexOf(first.name) - CHECK_STEPS.indexOf(second.name));\n\n const exitCode = checkExitCode(problems);\n const errors = problems.filter((problem) => problem.severity === \"error\");\n\n return {\n schemaVersion: 1,\n ok: exitCode === 0,\n exitCode,\n changed,\n files,\n steps,\n problems,\n summary: {\n errors: errors.length,\n warnings: problems.length - errors.length,\n code: errors.filter((problem) => problem.category === \"code\").length,\n environment: errors.filter((problem) => problem.category === \"environment\").length,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AA0DA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAS,SAAS,UAAsD;CACtE,MAAM,SAAS,SAAS,QAAQ,YAAY,QAAQ,aAAa,OAAO;CAExE,IAAI,OAAO,MAAM,YAAY,QAAQ,aAAa,aAAa,GAAG,OAAO;CAEzE,OAAO,OAAO,SAAS,IAAI,WAAW;AACxC;;;;;;;;;;;AAeA,eAAsB,SAAS,UAAwB,CAAC,GAAyB;CAC/E,MAAM,MAAM,KAAK,QAAQ,QAAQ,OAAO,QAAQ,IAAI,CAAC;CACrD,MAAM,UAAU,QAAQ,YAAY,QAAQ,QAAQ,SAAS;CAC7D,MAAM,OAAO,IAAI,IAAI,QAAQ,QAAQ,CAAC,CAAC;CACvC,MAAM,QAAqB,CAAC;CAC5B,MAAM,WAA6B,CAAC;CACpC,IAAI,QAAyB;CAC7B,IAAI,eAAe;CAEnB,MAAM,MAAM,OAAO,MAAqB,SAAmD;EACzF,MAAM,YAAY,KAAK,IAAI;EAE3B,IAAI,KAAK,IAAI,IAAI,GAAG;GAClB,M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Q,WAAW,OACrD,QAAQ,IAAI,QAAQ,QAAQ,eAAe,IAC3C;EAEN,OAAO;GACL,QAAQ,OAAO,UAAU,WAAW,GAAG,MAAM,gBAAgB;GAC7D,UAAU;EACZ;CACF,CAAC;CAED,MAAM,IAAI,eAAe,YAAY;EACnC,MAAM,kBAAkB,MAAM,QAAQ;EAEtC,OAAO;GACL,QAAQ,GAAG,gBAAgB,OAAO;GAClC,UAAU,eAAe,KAAK,iBAAiB,QAAQ,OAAO;EAChE;CACF,CAAC;CAGD,MAAM,MAAM,OAAO,WAAW,YAAY,QAAQ,MAAM,IAAI,IAAI,YAAY,QAAQ,OAAO,IAAI,CAAC;CAEhG,MAAM,WAAW,cAAc,QAAQ;CACvC,MAAM,SAAS,SAAS,QAAQ,YAAY,QAAQ,aAAa,OAAO;CAExE,OAAO;EACL,eAAe;EACf,IAAI,aAAa;EACjB;EACA;EACA;EACA;EACA;EACA,SAAS;GACP,QAAQ,OAAO;GACf,UAAU,SAAS,SAAS,OAAO;GACnC,MAAM,OAAO,QAAQ,YAAY,QAAQ,aAAa,MAAM,CAAC,CAAC;GAC9D,aAAa,OAAO,QAAQ,YAAY,QAAQ,aAAa,aAAa,CAAC,CAAC;EAC9E;CACF;AACF"}
1
+ {"version":3,"file":"run-check.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tooling/check/run-check.ts"],"sourcesContent":["import path from \"node:path\";\nimport { createProblem, type ToolingProblem } from \"../problem\";\nimport {\n runTypecheck,\n type TypecheckOptions,\n type TypecheckResult,\n} from \"../typecheck/run-typecheck\";\nimport { type GitRunner, listChangedFiles } from \"./changed-files\";\nimport {\n CHECK_STEPS,\n type CheckReport,\n type CheckStep,\n type CheckStepName,\n type CheckStepStatus,\n checkExitCode,\n} from \"./check-report.types\";\nimport { runConventions } from \"./conventions-step\";\nimport { checkNodeVersion } from \"./environment-step\";\nimport { runLint } from \"./lint-step\";\nimport { listSourceFiles, listTestFiles } from \"./source-files\";\nimport {\n findVitest,\n parseVitestReport,\n runVitest,\n type VitestRunner,\n vitestArguments,\n vitestRunFailure,\n} from \"./tests-step\";\n\n/** Runs the typecheck step. The CLI swaps in a child process so a heap overflow cannot end `check`. */\nexport type TypecheckRunner = (\n options: TypecheckOptions,\n) => Promise<TypecheckResult> | TypecheckResult;\n\n/** Inputs of {@link runCheck}. */\nexport type CheckOptions = {\n /** Project root. Default: `process.cwd()`. */\n cwd?: string;\n /** Oxlint by default; ESLint is deprecated and requires explicit selection. */\n lint?: \"oxlint\" | \"eslint\";\n /** Limit every step to the files changed against `base` (default HEAD) plus untracked files. */\n changed?: boolean;\n /** Compare with `git merge-base <base> HEAD` instead of HEAD. Implies `changed`. */\n base?: string;\n /** Steps not to run. */\n skip?: readonly CheckStepName[];\n /** tsconfig path, relative to `cwd`. Default: `tsconfig.json`. */\n project?: string;\n /** How git is run. */\n git?: GitRunner;\n /** How the typecheck runs. Default: in this process. */\n typecheck?: TypecheckRunner;\n /** How vitest runs. */\n vitest?: VitestRunner;\n /** Where the app's vitest CLI is. Default: resolved from the app root. */\n vitestBinary?: string | null;\n /** The Node.js version to check. Default: the running one. */\n nodeVersion?: string;\n};\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction statusOf(problems: readonly ToolingProblem[]): CheckStepStatus {\n const errors = problems.filter((problem) => problem.severity === \"error\");\n\n if (errors.some((problem) => problem.category === \"environment\")) return \"blocked\";\n\n return errors.length > 0 ? \"failed\" : \"passed\";\n}\n\n/** Bundles one step's timing, status and problems. */\ntype StepOutcome = { status?: CheckStepStatus; detail: string | null; problems: ToolingProblem[] };\n\n/**\n * The single verify command: typecheck, lint, the tests affected by the\n * change, and the framework's convention checks, as one report with one entry\n * per problem and an exit code that tells \"your code\" (1) from \"this machine\"\n * (2).\n *\n * Every step runs even when an earlier one failed, so one run lists every\n * problem. The only exception: with `changed`, a git failure leaves no file\n * list, and every step after `environment` is `blocked`.\n */\nexport async function runCheck(options: CheckOptions = {}): Promise<CheckReport> {\n const cwd = path.resolve(options.cwd ?? process.cwd());\n const changed = options.changed === true || options.base !== undefined;\n const skip = new Set(options.skip ?? []);\n const steps: CheckStep[] = [];\n const problems: ToolingProblem[] = [];\n let files: string[] | null = null;\n let filesBlocked = false;\n\n const run = async (name: CheckStepName, body: () => Promise<StepOutcome> | StepOutcome) => {\n const startedAt = Date.now();\n\n if (skip.has(name)) {\n steps.push({ name, status: \"skipped\", durationMs: 0, detail: \"skipped with --skip\" });\n return;\n }\n\n if (filesBlocked && name !== \"environment\") {\n steps.push({\n name,\n status: \"blocked\",\n durationMs: 0,\n detail: \"the changed files could not be listed\",\n });\n return;\n }\n\n let outcome: StepOutcome;\n\n try {\n outcome = await body();\n } catch (error) {\n outcome = {\n detail: null,\n problems: [\n createProblem({\n code: \"WL8007\",\n source: \"environment\",\n message: `The ${name} step crashed: ${errorMessage(error)}`,\n }),\n ],\n };\n }\n\n problems.push(...outcome.problems);\n steps.push({\n name,\n status: outcome.status ?? statusOf(outcome.problems),\n durationMs: Date.now() - startedAt,\n detail: outcome.detail,\n });\n };\n\n await run(\"environment\", async () => {\n const found = checkNodeVersion(cwd, options.nodeVersion);\n\n if (changed) {\n const listed = await listChangedFiles({ cwd, base: options.base, git: options.git });\n\n if (\"problem\" in listed) {\n filesBlocked = true;\n found.push(listed.problem);\n } else {\n files = listed.files;\n }\n }\n\n return {\n detail: `Node ${options.nodeVersion ?? process.versions.node}${files ? `, ${files.length} changed file(s)` : \"\"}`,\n problems: found,\n };\n });\n\n const targets = async (): Promise<string[]> => files ?? (await listSourceFiles(cwd));\n\n await run(\"typecheck\", async () => {\n if (files !== null && files.length === 0) {\n return { status: \"skipped\", detail: \"no changed files\", problems: [] };\n }\n\n const typecheck = options.typecheck ?? runTypecheck;\n const result = await typecheck({\n cwd,\n project: options.project,\n ...(files !== null ? { files } : {}),\n });\n\n return {\n detail: `${result.checkedFiles} file(s) checked in ${result.durationMs}ms`,\n problems: result.problems,\n };\n });\n\n await run(\"lint\", async () => {\n const lintFiles = await targets();\n\n if (lintFiles.length === 0) {\n return { status: \"skipped\", detail: \"no files to lint\", problems: [] };\n }\n\n const { linters, problems: found } = await runLint(cwd, lintFiles, options.lint);\n\n if (linters.length === 0) {\n return {\n status: \"skipped\",\n detail: \"no Oxlint config (ESLint requires --lint eslint)\",\n problems: [],\n };\n }\n\n return { detail: `${linters.join(\" + \")} over ${lintFiles.length} file(s)`, problems: found };\n });\n\n await run(\"tests\", async () => {\n if (files !== null && files.length === 0) {\n return { status: \"skipped\", detail: \"no changed files\", problems: [] };\n }\n\n const binary = options.vitestBinary === undefined ? findVitest(cwd) : options.vitestBinary;\n\n if (!binary) {\n if ((await listTestFiles(cwd)).length === 0) {\n return { status: \"skipped\", detail: \"no test files\", problems: [] };\n }\n\n return {\n detail: null,\n problems: [\n createProblem({\n code: \"WL8002\",\n source: \"environment\",\n message: \"The project has test files but vitest is not installed in the app.\",\n }),\n ],\n };\n }\n\n const vitest = options.vitest ?? runVitest;\n const outcome = await vitest(binary, vitestArguments(files), cwd);\n const found =\n outcome.report === undefined\n ? vitestRunFailure(outcome)\n : parseVitestReport(outcome.report, cwd);\n const total =\n typeof outcome.report === \"object\" && outcome.report !== null\n ? Reflect.get(outcome.report, \"numTotalTests\")\n : undefined;\n\n return {\n detail: typeof total === \"number\" ? `${total} test(s) ran` : null,\n problems: found,\n };\n });\n\n await run(\"conventions\", async () => {\n const conventionFiles = await targets();\n\n return {\n detail: `${conventionFiles.length} file(s) checked`,\n problems: runConventions(cwd, conventionFiles, options.project),\n };\n });\n\n // Keep the declared order even if a future step is added out of sequence.\n steps.sort((first, second) => CHECK_STEPS.indexOf(first.name) - CHECK_STEPS.indexOf(second.name));\n\n const exitCode = checkExitCode(problems);\n const errors = problems.filter((problem) => problem.severity === \"error\");\n\n return {\n schemaVersion: 1,\n ok: exitCode === 0,\n exitCode,\n changed,\n files,\n steps,\n problems,\n summary: {\n errors: errors.length,\n warnings: problems.length - errors.length,\n code: errors.filter((problem) => problem.category === \"code\").length,\n environment: errors.filter((problem) => problem.category === \"environment\").length,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AA4DA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAS,SAAS,UAAsD;CACtE,MAAM,SAAS,SAAS,QAAQ,YAAY,QAAQ,aAAa,OAAO;CAExE,IAAI,OAAO,MAAM,YAAY,QAAQ,aAAa,aAAa,GAAG,OAAO;CAEzE,OAAO,OAAO,SAAS,IAAI,WAAW;AACxC;;;;;;;;;;;AAeA,eAAsB,SAAS,UAAwB,CAAC,GAAyB;CAC/E,MAAM,MAAM,KAAK,QAAQ,QAAQ,OAAO,QAAQ,IAAI,CAAC;CACrD,MAAM,UAAU,QAAQ,YAAY,QAAQ,QAAQ,SAAS;CAC7D,MAAM,OAAO,IAAI,IAAI,QAAQ,QAAQ,CAAC,CAAC;CACvC,MAAM,QAAqB,CAAC;CAC5B,MAAM,WAA6B,CAAC;CACpC,IAAI,QAAyB;CAC7B,IAAI,eAAe;CAEnB,MAAM,MAAM,OAAO,MAAqB,SAAmD;EACzF,MAAM,YAAY,KAAK,IAAI;EAE3B,IAAI,KAAK,IAAI,IAAI,GAAG;GAClB,MAAM,KAAK;IAAE;IAAM,QAAQ;IAAW,YAAY;IAAG,QAAQ;GAAsB,CAAC;GACpF;EACF;EAEA,IAAI,gBAAgB,SAAS,eAAe;GAC1C,MAAM,KAAK;IACT;IACA,QAAQ;IACR,YAAY;IACZ,QAAQ;GACV,CAAC;GACD;EACF;EAEA,IAAI;EAEJ,IAAI;GACF,UAAU,MAAM,KAAK;EACvB,SAAS,OAAO;GACd,UAAU;IACR,QAAQ;IACR,UAAU,CACR,cAAc;KACZ,MAAM;KACN,QAAQ;KACR,SAAS,OAAO,KAAK,iBAAiB,aAAa,KAAK;IAC1D,CAAC,CACH;GACF;EACF;EAEA,SAAS,KAAK,GAAG,QAAQ,QAAQ;EACjC,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