@smoothbricks/nx-plugin 0.4.25 → 0.4.27

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 (348) hide show
  1. package/README.md +1078 -98
  2. package/dist/bin/smoo-nx-bound-failures.d.ts +3 -0
  3. package/dist/bin/smoo-nx-bound-failures.d.ts.map +1 -0
  4. package/dist/bin/smoo-nx-bound-failures.js +31 -0
  5. package/dist/bin/smoo-nx-cargo-hash.js +28 -3
  6. package/dist/bin/smoo-nx-exec.js +16 -85
  7. package/dist/bin/smoo-nx-failures.d.ts +3 -0
  8. package/dist/bin/smoo-nx-failures.d.ts.map +1 -0
  9. package/dist/bin/smoo-nx-failures.js +3 -0
  10. package/dist/bin/smoo-nx-nextest-extract.js +3 -2
  11. package/dist/bin/smoo-nx-test-walks.d.ts +3 -0
  12. package/dist/bin/smoo-nx-test-walks.d.ts.map +1 -0
  13. package/dist/bin/smoo-nx-test-walks.js +34 -0
  14. package/dist/bounded-test-policy.d.ts +7 -1
  15. package/dist/bounded-test-policy.d.ts.map +1 -1
  16. package/dist/bounded-test-policy.js +101 -40
  17. package/dist/build-state-output-policy.d.ts +25 -0
  18. package/dist/build-state-output-policy.d.ts.map +1 -0
  19. package/dist/build-state-output-policy.js +64 -0
  20. package/dist/cargo-closure-input.d.ts +16 -17
  21. package/dist/cargo-closure-input.d.ts.map +1 -1
  22. package/dist/cargo-closure-input.js +37 -44
  23. package/dist/cargo-dev-profile.d.ts +37 -0
  24. package/dist/cargo-dev-profile.d.ts.map +1 -0
  25. package/dist/cargo-dev-profile.js +108 -0
  26. package/dist/cargo-source-hash.d.ts +50 -8
  27. package/dist/cargo-source-hash.d.ts.map +1 -1
  28. package/dist/cargo-source-hash.js +691 -71
  29. package/dist/cargo-toolchain-policy.d.ts +4 -0
  30. package/dist/cargo-toolchain-policy.d.ts.map +1 -1
  31. package/dist/cargo-toolchain-policy.js +5 -0
  32. package/dist/cargo-workspace.d.ts +108 -12
  33. package/dist/cargo-workspace.d.ts.map +1 -1
  34. package/dist/cargo-workspace.js +299 -18
  35. package/dist/cross-check-policy.d.ts +21 -3
  36. package/dist/cross-check-policy.d.ts.map +1 -1
  37. package/dist/cross-check-policy.js +24 -6
  38. package/dist/disk-command-policy.d.ts +7 -0
  39. package/dist/disk-command-policy.d.ts.map +1 -0
  40. package/dist/disk-command-policy.js +98 -0
  41. package/dist/ensure-built-receipt.d.ts +25 -0
  42. package/dist/ensure-built-receipt.d.ts.map +1 -0
  43. package/dist/ensure-built-receipt.js +261 -0
  44. package/dist/ensure-built-witness.d.ts +57 -0
  45. package/dist/ensure-built-witness.d.ts.map +1 -0
  46. package/dist/ensure-built-witness.js +412 -0
  47. package/dist/ensure-built.d.ts +213 -12
  48. package/dist/ensure-built.d.ts.map +1 -1
  49. package/dist/ensure-built.js +624 -177
  50. package/dist/eslint-file-set.d.ts +7 -0
  51. package/dist/eslint-file-set.d.ts.map +1 -0
  52. package/dist/eslint-file-set.js +12 -0
  53. package/dist/executors/bounded-exec/cpu-pool.d.ts +63 -0
  54. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -0
  55. package/dist/executors/bounded-exec/cpu-pool.js +379 -0
  56. package/dist/executors/bounded-exec/cpu-tokens.d.ts +82 -0
  57. package/dist/executors/bounded-exec/cpu-tokens.d.ts.map +1 -0
  58. package/dist/executors/bounded-exec/cpu-tokens.js +114 -0
  59. package/dist/executors/bounded-exec/disk-lease.d.ts +61 -0
  60. package/dist/executors/bounded-exec/disk-lease.d.ts.map +1 -0
  61. package/dist/executors/bounded-exec/disk-lease.js +91 -0
  62. package/dist/executors/bounded-exec/executor.d.ts +45 -2
  63. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  64. package/dist/executors/bounded-exec/executor.js +447 -52
  65. package/dist/executors/bounded-exec/gateway-lease.d.ts +52 -0
  66. package/dist/executors/bounded-exec/gateway-lease.d.ts.map +1 -0
  67. package/dist/executors/bounded-exec/gateway-lease.js +143 -0
  68. package/dist/executors/bounded-exec/hang-diagnostics.d.ts +35 -0
  69. package/dist/executors/bounded-exec/hang-diagnostics.d.ts.map +1 -0
  70. package/dist/executors/bounded-exec/hang-diagnostics.js +231 -0
  71. package/dist/executors/bounded-exec/progress.d.ts +35 -0
  72. package/dist/executors/bounded-exec/progress.d.ts.map +1 -0
  73. package/dist/executors/bounded-exec/progress.js +79 -0
  74. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts +3 -0
  75. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts.map +1 -0
  76. package/dist/executors/bounded-exec/ram-temp-fixtures.js +12 -0
  77. package/dist/executors/bounded-exec/ram-temp-held.d.ts +91 -0
  78. package/dist/executors/bounded-exec/ram-temp-held.d.ts.map +1 -0
  79. package/dist/executors/bounded-exec/ram-temp-held.js +152 -0
  80. package/dist/executors/bounded-exec/ram-temp.d.ts +223 -0
  81. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -0
  82. package/dist/executors/bounded-exec/ram-temp.js +1528 -0
  83. package/dist/executors/bounded-exec/schema.d.ts +29 -11
  84. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  85. package/dist/executors/bounded-exec/verdict.d.ts +162 -0
  86. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -0
  87. package/dist/executors/bounded-exec/verdict.js +318 -0
  88. package/dist/executors/shard-timings/executor.d.ts +14 -0
  89. package/dist/executors/shard-timings/executor.d.ts.map +1 -0
  90. package/dist/executors/shard-timings/executor.js +25 -0
  91. package/dist/executors/shard-timings/schema.d.ts +4 -0
  92. package/dist/executors/shard-timings/schema.d.ts.map +1 -0
  93. package/dist/executors/shard-timings/schema.js +1 -0
  94. package/dist/failure-summary.d.ts +5 -0
  95. package/dist/failure-summary.d.ts.map +1 -0
  96. package/dist/failure-summary.js +118 -0
  97. package/dist/generators/create-package/generator.d.ts.map +1 -1
  98. package/dist/generators/create-package/generator.js +6 -2
  99. package/dist/index.d.ts +14 -2
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +435 -230
  102. package/dist/managed-assets.d.ts +6 -0
  103. package/dist/managed-assets.d.ts.map +1 -1
  104. package/dist/managed-files/ci-workflow.d.ts +13 -0
  105. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  106. package/dist/managed-files/ci-workflow.js +44 -13
  107. package/dist/managed-files/files.d.ts +7 -1
  108. package/dist/managed-files/files.d.ts.map +1 -1
  109. package/dist/managed-files/files.js +62 -8
  110. package/dist/managed-files/json-edit.d.ts +21 -0
  111. package/dist/managed-files/json-edit.d.ts.map +1 -0
  112. package/dist/managed-files/json-edit.js +295 -0
  113. package/dist/managed-files/managed-format.d.ts +33 -1
  114. package/dist/managed-files/managed-format.d.ts.map +1 -1
  115. package/dist/managed-files/managed-format.js +82 -2
  116. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts +7 -0
  117. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts.map +1 -1
  118. package/dist/managed-files/pr-preview-cleanup-workflow.js +68 -4
  119. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  120. package/dist/managed-files/publish-workflow.js +231 -48
  121. package/dist/managed-files/tree.d.ts +5 -0
  122. package/dist/managed-files/tree.d.ts.map +1 -1
  123. package/dist/managed-files/tree.js +5 -3
  124. package/dist/manifest-hash.js +3 -2
  125. package/dist/nextest-code-bound.d.ts +62 -0
  126. package/dist/nextest-code-bound.d.ts.map +1 -0
  127. package/dist/nextest-code-bound.js +154 -0
  128. package/dist/nextest-extraction.d.ts +24 -8
  129. package/dist/nextest-extraction.d.ts.map +1 -1
  130. package/dist/nextest-extraction.js +42 -7
  131. package/dist/package-target-policy.d.ts.map +1 -1
  132. package/dist/package-target-policy.js +3 -5
  133. package/dist/release-config-policy.d.ts.map +1 -1
  134. package/dist/release-config-policy.js +3 -5
  135. package/dist/runtime-input.d.ts +14 -0
  136. package/dist/runtime-input.d.ts.map +1 -0
  137. package/dist/runtime-input.js +15 -0
  138. package/dist/rust-tokens.d.ts +11 -0
  139. package/dist/rust-tokens.d.ts.map +1 -0
  140. package/dist/rust-tokens.js +81 -0
  141. package/dist/task-results.d.ts +6 -0
  142. package/dist/task-results.d.ts.map +1 -0
  143. package/dist/task-results.js +61 -0
  144. package/dist/test-program.d.ts +54 -0
  145. package/dist/test-program.d.ts.map +1 -0
  146. package/dist/test-program.js +292 -0
  147. package/dist/test-timings.d.ts +71 -0
  148. package/dist/test-timings.d.ts.map +1 -0
  149. package/dist/test-timings.js +393 -0
  150. package/dist/test-walk-policy.d.ts +103 -0
  151. package/dist/test-walk-policy.d.ts.map +1 -0
  152. package/dist/test-walk-policy.js +657 -0
  153. package/dist/testing.d.ts +177 -0
  154. package/dist/testing.d.ts.map +1 -0
  155. package/dist/testing.js +824 -0
  156. package/dist/type-guards.d.ts +3 -0
  157. package/dist/type-guards.d.ts.map +1 -0
  158. package/dist/type-guards.js +4 -0
  159. package/dist/typecheck-test-policy.d.ts +8 -5
  160. package/dist/typecheck-test-policy.d.ts.map +1 -1
  161. package/dist/typecheck-test-policy.js +113 -100
  162. package/dist/workspace-config-policy.d.ts +8 -0
  163. package/dist/workspace-config-policy.d.ts.map +1 -1
  164. package/dist/workspace-config-policy.js +175 -63
  165. package/dist/workspace-index.d.ts +12 -0
  166. package/dist/workspace-index.d.ts.map +1 -0
  167. package/dist/workspace-index.js +17 -0
  168. package/dist/workspace-manifest.d.ts +37 -1
  169. package/dist/workspace-manifest.d.ts.map +1 -1
  170. package/executors.json +5 -0
  171. package/loader.js +13 -11
  172. package/managed/raw/envrc +33 -62
  173. package/managed/raw/git-format-staged.yml +30 -35
  174. package/managed/raw/patches/nx@23.2.1.patch +3484 -0
  175. package/managed/raw/tooling/direnv/apple-developer.sh +83 -0
  176. package/managed/raw/tooling/direnv/developer-links.ts +607 -17
  177. package/managed/raw/tooling/direnv/devenv.smoo.nix +314 -92
  178. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +20 -11
  179. package/managed/raw/tooling/direnv/linked-snapshots.ts +845 -0
  180. package/managed/raw/tooling/direnv/nx-socket-dir.sh +82 -0
  181. package/managed/raw/tooling/direnv/repo-path +14 -2
  182. package/managed/raw/tooling/direnv/setup-environment.ts +1009 -118
  183. package/managed/raw/tooling/direnv/toolchain-stamp.ts +45 -3
  184. package/managed/raw/tooling/direnv/ttsc-env.sh +39 -0
  185. package/managed/raw/tooling/git-hooks/commit-msg.sh +5 -6
  186. package/managed/raw/tooling/git-hooks/pre-commit.sh +7 -6
  187. package/managed/raw/tooling/git-hooks/pre-push.sh +20 -15
  188. package/managed/templates/github/actions/cache-nix-devenv/action.yml +6 -6
  189. package/managed/templates/github/actions/cache-node-modules/action.yml +6 -4
  190. package/managed/templates/github/actions/cache-nx/action.yml +1 -1
  191. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +1 -1
  192. package/managed/templates/github/actions/forgejo-artifact.cjs +99 -0
  193. package/managed/templates/github/actions/forgejo-download-artifact/action.yml +49 -0
  194. package/managed/templates/github/actions/forgejo-download-artifact/index.cjs +7 -0
  195. package/managed/templates/github/actions/forgejo-upload-artifact/action.yml +65 -0
  196. package/managed/templates/github/actions/forgejo-upload-artifact/index.cjs +7 -0
  197. package/managed/templates/github/actions/setup-devenv/action.yml +21 -3
  198. package/managed/templates/github/workflows/managed-files.yml +1 -2
  199. package/nextest.toml +8 -75
  200. package/package.json +75 -13
  201. package/runtime-input.sh +81 -0
  202. package/src/__tests__/counted-cargo-process.ts +286 -0
  203. package/src/__tests__/counted-cargo.ts +730 -0
  204. package/src/__tests__/fixture-cargo-home.ts +36 -0
  205. package/src/__tests__/fixture-nx-env.ts +157 -2
  206. package/src/__tests__/progress-clock.ts +43 -0
  207. package/src/__tests__/runtime-input.ts +23 -0
  208. package/src/bin/smoo-nx-bound-failures.test.ts +127 -0
  209. package/src/bin/smoo-nx-bound-failures.ts +33 -0
  210. package/src/bin/smoo-nx-cargo-hash.ts +28 -3
  211. package/src/bin/smoo-nx-exec.ts +17 -86
  212. package/src/bin/smoo-nx-failures.ts +4 -0
  213. package/src/bin/smoo-nx-nextest-extract.ts +3 -2
  214. package/src/bin/smoo-nx-test-walks.ts +42 -0
  215. package/src/bounded-test-policy.test.ts +268 -22
  216. package/src/bounded-test-policy.ts +114 -42
  217. package/src/build-state-output-policy.test.ts +115 -0
  218. package/src/build-state-output-policy.ts +90 -0
  219. package/src/bun-bootstrap.test.ts +57 -3
  220. package/src/bun-file-packages.test.ts +47 -0
  221. package/src/cargo-closure-input.test.ts +432 -62
  222. package/src/cargo-closure-input.ts +51 -57
  223. package/src/cargo-dev-profile.ts +137 -0
  224. package/src/cargo-resolve-cache.test.ts +1044 -0
  225. package/src/cargo-source-hash.test.ts +203 -93
  226. package/src/cargo-source-hash.ts +762 -75
  227. package/src/cargo-toolchain-policy.ts +6 -0
  228. package/src/cargo-workspace.test.ts +320 -0
  229. package/src/cargo-workspace.ts +344 -18
  230. package/src/cross-check-policy.test.ts +59 -1
  231. package/src/cross-check-policy.ts +25 -6
  232. package/src/disk-command-policy.test.ts +61 -0
  233. package/src/disk-command-policy.ts +107 -0
  234. package/src/ensure-built-receipt.test.ts +184 -0
  235. package/src/ensure-built-receipt.ts +263 -0
  236. package/src/ensure-built-witness.test.ts +344 -0
  237. package/src/ensure-built-witness.ts +252 -0
  238. package/src/ensure-built.test.ts +1043 -483
  239. package/src/ensure-built.ts +870 -197
  240. package/src/eslint-file-set.ts +9 -0
  241. package/src/executors/bounded-exec/cpu-pool.test.ts +454 -0
  242. package/src/executors/bounded-exec/cpu-pool.ts +417 -0
  243. package/src/executors/bounded-exec/cpu-tokens.test.ts +269 -0
  244. package/src/executors/bounded-exec/cpu-tokens.ts +177 -0
  245. package/src/executors/bounded-exec/disk-lease.test.ts +185 -0
  246. package/src/executors/bounded-exec/disk-lease.ts +139 -0
  247. package/src/executors/bounded-exec/executor-host.test.ts +778 -0
  248. package/src/executors/bounded-exec/executor.test.ts +1116 -63
  249. package/src/executors/bounded-exec/executor.ts +565 -67
  250. package/src/executors/bounded-exec/gateway-lease.ts +176 -0
  251. package/src/executors/bounded-exec/hang-diagnostics.test.ts +285 -0
  252. package/src/executors/bounded-exec/hang-diagnostics.ts +283 -0
  253. package/src/executors/bounded-exec/progress.test.ts +79 -0
  254. package/src/executors/bounded-exec/progress.ts +118 -0
  255. package/src/executors/bounded-exec/ram-temp-fixtures.ts +12 -0
  256. package/src/executors/bounded-exec/ram-temp-held.test.ts +264 -0
  257. package/src/executors/bounded-exec/ram-temp-held.ts +242 -0
  258. package/src/executors/bounded-exec/ram-temp-host.test.ts +605 -0
  259. package/src/executors/bounded-exec/ram-temp.test.ts +674 -0
  260. package/src/executors/bounded-exec/ram-temp.ts +1918 -0
  261. package/src/executors/bounded-exec/schema.json +11 -5
  262. package/src/executors/bounded-exec/schema.ts +27 -11
  263. package/src/executors/bounded-exec/verdict.test.ts +440 -0
  264. package/src/executors/bounded-exec/verdict.ts +433 -0
  265. package/src/executors/shard-timings/executor.ts +36 -0
  266. package/src/executors/shard-timings/schema.json +21 -0
  267. package/src/executors/shard-timings/schema.ts +4 -0
  268. package/src/failure-summary.ts +119 -0
  269. package/src/generators/bounded-test-targets/generator.test.ts +4 -4
  270. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  271. package/src/generators/create-package/generator.test.ts +6 -0
  272. package/src/generators/create-package/generator.ts +6 -2
  273. package/src/host-controller-wiring.test.ts +31 -0
  274. package/src/index.test.ts +1070 -360
  275. package/src/index.ts +524 -255
  276. package/src/linked-snapshots.nx.test.ts +172 -0
  277. package/src/managed-assets.ts +12 -0
  278. package/src/managed-files/ci-workflow.ts +54 -13
  279. package/src/managed-files/files.ts +65 -9
  280. package/src/managed-files/forgejo-artifact.test.ts +395 -0
  281. package/src/managed-files/generator.test.ts +60 -1
  282. package/src/managed-files/json-edit.test.ts +216 -0
  283. package/src/managed-files/json-edit.ts +290 -0
  284. package/src/managed-files/managed-format-json.test.ts +308 -0
  285. package/src/managed-files/managed-format.ts +90 -2
  286. package/src/managed-files/pr-preview-cleanup-workflow.ts +69 -3
  287. package/src/managed-files/publish-workflow.ts +285 -67
  288. package/src/managed-files/repo-path.test.ts +129 -0
  289. package/src/managed-files/trace-db-artifact.test.ts +7 -0
  290. package/src/managed-files/tree.ts +11 -3
  291. package/src/manifest-hash.ts +3 -2
  292. package/src/nextest-code-bound.test.ts +155 -0
  293. package/src/nextest-code-bound.ts +195 -0
  294. package/src/nextest-extraction.test.ts +37 -5
  295. package/src/nextest-extraction.ts +51 -9
  296. package/src/nextest-partitions.test.ts +495 -0
  297. package/src/nx-cache-bound.test.ts +109 -0
  298. package/src/nx-cache-restore-mtime.test.ts +170 -0
  299. package/src/nx-daemon-claim.test.ts +277 -0
  300. package/src/nx-daemon-idle-cpu.test.ts +81 -0
  301. package/src/nx-daemon-idle-policy.test.ts +51 -0
  302. package/src/nx-daemon-ignore-files.test.ts +210 -0
  303. package/src/nx-daemon-root-normalization.test.ts +105 -0
  304. package/src/nx-daemon-validity.test.ts +925 -0
  305. package/src/nx-dot-input-policy.test.ts +353 -0
  306. package/src/nx-failure-life-cycles.test.ts +207 -0
  307. package/src/nx-files-archive-racy.test.ts +97 -0
  308. package/src/nx-foreign-workspace-env.test.ts +329 -0
  309. package/src/nx-incomplete-run-summary.test.ts +70 -0
  310. package/src/nx-plugin-load-errors.test.ts +120 -0
  311. package/src/nx-project-resolution-cache.test.ts +176 -0
  312. package/src/nx-raw-inputs.test.ts +166 -0
  313. package/src/nx-resident-graph-workers.test.ts +112 -0
  314. package/src/nx-run-information.test.ts +118 -0
  315. package/src/nx-skipped-task-exit.test.ts +180 -0
  316. package/src/nx-state-location.test.ts +63 -0
  317. package/src/nx-store-resolution.test.ts +99 -0
  318. package/src/nx-task-graph-cycles.test.ts +148 -0
  319. package/src/nx-task-output-lease.test.ts +414 -0
  320. package/src/nx-use-local.test.ts +103 -0
  321. package/src/package-target-policy.ts +3 -6
  322. package/src/release-config-policy.ts +3 -6
  323. package/src/runtime-input.test.ts +215 -0
  324. package/src/runtime-input.ts +17 -0
  325. package/src/rust-tokens.ts +78 -0
  326. package/src/serial-group-wiring.test.ts +326 -0
  327. package/src/task-history-namespace.test.ts +181 -0
  328. package/src/task-results.test.ts +226 -0
  329. package/src/task-results.ts +75 -0
  330. package/src/test-program.test.ts +303 -0
  331. package/src/test-program.ts +341 -0
  332. package/src/test-timings.test.ts +240 -0
  333. package/src/test-timings.ts +311 -0
  334. package/src/test-walk-policy.test.ts +585 -0
  335. package/src/test-walk-policy.ts +731 -0
  336. package/src/testing.test.ts +509 -0
  337. package/src/testing.ts +922 -0
  338. package/src/type-guards.ts +4 -0
  339. package/src/typecheck-test-policy.test.ts +496 -11
  340. package/src/typecheck-test-policy.ts +137 -103
  341. package/src/workspace-config-policy.test.ts +212 -13
  342. package/src/workspace-config-policy.ts +101 -73
  343. package/src/workspace-index.ts +18 -0
  344. package/src/workspace-manifest.ts +41 -1
  345. package/test-timings.json +85 -28
  346. package/managed/raw/tooling/direnv/inherited-devenv.ts +0 -615
  347. package/managed/raw/tooling/direnv/shared-caches.sh +0 -53
  348. package/src/__tests__/in-process-nx-index.ts +0 -9
@@ -0,0 +1,925 @@
1
+ import { expect, it } from 'bun:test';
2
+ import { type ChildProcess, spawn, spawnSync } from 'node:child_process';
3
+ import { watch as fsWatch } from 'node:fs';
4
+ import { mkdir, readdir, readFile, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises';
5
+ import { createRequire } from 'node:module';
6
+ import { createConnection, createServer } from 'node:net';
7
+ import { dirname, join } from 'node:path';
8
+ import { createInterface } from 'node:readline';
9
+ import { setTimeout as sleep } from 'node:timers/promises';
10
+ import { sendMessage } from 'nx/src/daemon/socket-utils.js';
11
+ import { consumeMessagesFromSocket, parseMessage } from 'nx/src/utils/consume-messages-from-socket.js';
12
+ import typia from 'typia';
13
+ import { guardEvent } from './__tests__/counted-cargo.js';
14
+ import { fixtureNxEnv, withNxFixture } from './__tests__/fixture-nx-env.js';
15
+ import { awaitExit, isRunning, type ProcessEntry, processTable, terminate, withDescendants } from './testing.js';
16
+
17
+ /**
18
+ * Guards the event-driven validity hunk of `patches/nx@23.2.1.patch` (upstream nrwl/nx#37113, fixing nrwl/nx#37112).
19
+ * The installed daemon judged its root lockfiles and installed nx version on a 20 ms timer. These regressions preserve
20
+ * the existing socket and process ownership guards while moving lockfile checks to applied watcher events, request
21
+ * boundaries, and a 5 s safety poll for events the watcher ignores or drops.
22
+ *
23
+ * Each test runs a real daemon in a fixture workspace and asserts only what a client, a watcher, or the filesystem can
24
+ * observe. Restarts are awaited on the record directory, and readiness on an actual PING answer, not a filesystem event.
25
+ * The one real-clock observation window is the idle walk in the last test.
26
+ */
27
+
28
+ const repositoryRoot = join(import.meta.dir, '../../..');
29
+ const nxEntry = join(repositoryRoot, 'node_modules', '.bin', 'nx');
30
+ const requireNx = createRequire(join(repositoryRoot, 'package.json'));
31
+ const daemonClient = requireNx.resolve('nx/src/daemon/client/client');
32
+ const daemonStart = requireNx.resolve('nx/src/daemon/server/start.js');
33
+ const daemonServer = join(dirname(daemonStart), 'server.js');
34
+
35
+ /** The root lockfiles the daemon validates. */
36
+ const LOCKFILES = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb', 'bun.lock'] as const;
37
+ /** The fixture's workspace directory under its root, so installed-package copies sit outside the workspace. */
38
+ const FIXTURE_WORKSPACE = 'workspace';
39
+ /** The idle observation window, longer than the 5 s safety poll so one poll would fall inside it. */
40
+ const OBSERVATION_MS = 6_000;
41
+
42
+ interface DaemonRecord {
43
+ readonly processId: number;
44
+ readonly socketPath: string;
45
+ }
46
+
47
+ interface Daemon {
48
+ readonly record: DaemonRecord;
49
+ readonly entry: ProcessEntry;
50
+ }
51
+
52
+ interface Manifest {
53
+ readonly version: string;
54
+ readonly [field: string]: unknown;
55
+ }
56
+
57
+ interface DaemonRequest {
58
+ readonly type: 'PING' | 'REQUEST_PROJECT_GRAPH';
59
+ readonly workspaceRoot: string;
60
+ }
61
+
62
+ /** A served answer, or the reason the daemon did not answer on this connection. */
63
+ type Answer =
64
+ | { readonly answered: true; readonly message: unknown }
65
+ | { readonly answered: false; readonly reason: string };
66
+
67
+ interface RawClient {
68
+ request(message: DaemonRequest, what: string): Promise<Answer>;
69
+ close(): void;
70
+ }
71
+
72
+ interface Listener {
73
+ readonly pid: number;
74
+ stop(): Promise<void>;
75
+ }
76
+
77
+ interface Replacement {
78
+ readonly workspace: string;
79
+ /** The pid the record must stop naming; absent when no daemon has published a record yet. */
80
+ readonly previous?: number;
81
+ /** Runs once the directory watch is open. */
82
+ readonly action?: () => Promise<void>;
83
+ readonly what: string;
84
+ readonly timeoutMs?: number;
85
+ }
86
+
87
+ /** One line per event the watch client saw: its kind, then the tab-separated details. */
88
+ interface WatchEvent {
89
+ readonly kind: string;
90
+ readonly details: readonly string[];
91
+ }
92
+
93
+ const CLIENT = `
94
+ const { writeSync } = require('node:fs');
95
+ const { daemonClient } = require(process.env.NX_DAEMON_CLIENT);
96
+ const say = (...fields) => writeSync(1, fields.join('\\t') + '\\n');
97
+ daemonClient
98
+ .registerFileWatcher({ watchProjects: 'all', includeGlobalWorkspaceFiles: true }, (error, data) => {
99
+ if (error === 'reconnecting' || error === 'closed') {
100
+ say(error);
101
+ process.exit(0);
102
+ }
103
+ if (error !== null) {
104
+ say('error', String(error));
105
+ process.exit(1);
106
+ }
107
+ say('changed', ...data.changedFiles.map(({ path }) => path));
108
+ })
109
+ .then(() => say('ready'), (error) => {
110
+ say('error', String(error));
111
+ process.exit(1);
112
+ });
113
+ `;
114
+
115
+ /**
116
+ * A process that stands in as a successor: it listens on the socket path it is given, and reports so on stdout. The
117
+ * listening server keeps the process alive.
118
+ */
119
+ const LISTENER = [
120
+ "const { createServer } = require('node:net');",
121
+ "createServer(() => {}).listen(process.argv[1], () => process.stdout.write('listening\\n'));",
122
+ ].join('\n');
123
+
124
+ /**
125
+ * Preloaded into the daemon. It records each call that reads a lockfile by name, the record file, or a socket, through
126
+ * the fs functions the old 20 ms loop used. It writes with `writeSync` on a descriptor opened before it wraps anything.
127
+ */
128
+ const PROBE = `
129
+ const fs = require('node:fs');
130
+ const path = require('node:path');
131
+ const locks = ${JSON.stringify(Object.fromEntries(LOCKFILES.map((name) => [name, true])))};
132
+ const sink = fs.openSync(process.env.NX_VALIDITY_LOG, 'a');
133
+ const write = (line) => fs.writeSync(sink, line + '\\n');
134
+ const classify = (file) => {
135
+ if (typeof file !== 'string') return undefined;
136
+ const name = path.basename(file);
137
+ if (locks[name] === true) return 'lock';
138
+ if (name === 'server-process.json') return 'record';
139
+ if (name.endsWith('.sock')) return 'socket';
140
+ return undefined;
141
+ };
142
+ write('attached');
143
+ for (const name of ['existsSync', 'statSync', 'lstatSync', 'readFileSync', 'openSync']) {
144
+ const original = fs[name];
145
+ fs[name] = function (file, ...rest) {
146
+ const kind = classify(file);
147
+ if (kind !== undefined) write(kind + ' ' + name + ' ' + file);
148
+ return original.call(fs, file, ...rest);
149
+ };
150
+ }
151
+ `;
152
+
153
+ function recordPath(workspace: string): string {
154
+ return join(workspace, '.nx', 'workspace-data', 'd', 'server-process.json');
155
+ }
156
+
157
+ /** A missing path (ENOENT) or a socket nothing listens on (ECONNREFUSED): the record or the daemon is absent. */
158
+ function isAbsent(error: unknown): boolean {
159
+ if (typeof error !== 'object' || error === null || !('code' in error)) return false;
160
+ return error.code === 'ENOENT' || error.code === 'ECONNREFUSED';
161
+ }
162
+
163
+ function gone(reason: string): Answer {
164
+ return { answered: false, reason };
165
+ }
166
+
167
+ function ping(workspace: string): DaemonRequest {
168
+ return { type: 'PING', workspaceRoot: workspace };
169
+ }
170
+
171
+ async function daemonRecord(workspace: string): Promise<DaemonRecord | null> {
172
+ let text: string;
173
+ try {
174
+ text = await readFile(recordPath(workspace), 'utf8');
175
+ } catch (error) {
176
+ if (isAbsent(error)) return null;
177
+ throw error;
178
+ }
179
+ return typia.json.assertParse<DaemonRecord>(text);
180
+ }
181
+
182
+ async function recordedPid(workspace: string): Promise<number> {
183
+ const record = await daemonRecord(workspace);
184
+ if (record === null) throw new Error(`no daemon record at ${recordPath(workspace)}`);
185
+ return record.processId;
186
+ }
187
+
188
+ async function installedManifest(): Promise<Manifest> {
189
+ return typia.json.assertParse<Manifest>(
190
+ await readFile(join(repositoryRoot, 'node_modules', 'nx', 'package.json'), 'utf8'),
191
+ );
192
+ }
193
+
194
+ function nx(workspace: string, env: Record<string, string>, ...args: string[]): string {
195
+ const result = spawnSync('bun', [nxEntry, ...args], { cwd: workspace, env, encoding: 'utf8' });
196
+ expect(result.status, `nx ${args.join(' ')} failed:\n${result.stdout}\n${result.stderr}`).toBe(0);
197
+ return result.stdout;
198
+ }
199
+
200
+ /** A fixture-owned `node_modules`: every entry links to the repository's, except `nx`, which links to `nxPackage`. */
201
+ async function linkedModules(workspace: string, nxPackage: string): Promise<void> {
202
+ const modules = join(workspace, 'node_modules');
203
+ await mkdir(modules);
204
+ for (const entry of await readdir(join(repositoryRoot, 'node_modules'))) {
205
+ if (entry !== 'nx') await symlink(join(repositoryRoot, 'node_modules', entry), join(modules, entry), 'dir');
206
+ }
207
+ await symlink(nxPackage, join(modules, 'nx'), 'dir');
208
+ }
209
+
210
+ /** A fixture-owned copy of the installed `nx` package, with `version` in its manifest and the repository's `dist`. */
211
+ async function nxPackageCopy(directory: string, version: string): Promise<void> {
212
+ await mkdir(directory);
213
+ const manifest = await installedManifest();
214
+ await writeFile(join(directory, 'package.json'), JSON.stringify({ ...manifest, version }));
215
+ await symlink(join(repositoryRoot, 'node_modules', 'nx', 'dist'), join(directory, 'dist'), 'dir');
216
+ }
217
+
218
+ /** A project in the workspace; `node_modules` is the repository's, or a fixture-owned copy when `nxPackage` is given. */
219
+ async function fixtureWorkspace(workspace: string, nxPackage?: string): Promise<void> {
220
+ if (nxPackage === undefined) {
221
+ await symlink(join(repositoryRoot, 'node_modules'), join(workspace, 'node_modules'), 'dir');
222
+ } else {
223
+ await linkedModules(workspace, nxPackage);
224
+ }
225
+ await writeFile(join(workspace, 'nx.json'), '{}\n');
226
+ await writeFile(join(workspace, 'package.json'), '{"name":"fixture","private":true}\n');
227
+ await mkdir(join(workspace, 'p'));
228
+ await writeFile(join(workspace, 'p', 'project.json'), '{"name":"p"}\n');
229
+ }
230
+
231
+ async function processEntry(pid: number): Promise<ProcessEntry> {
232
+ const entry = (await processTable()).find((candidate) => candidate.pid === pid);
233
+ if (entry === undefined) throw new Error(`process ${pid} is not in the process table`);
234
+ return entry;
235
+ }
236
+
237
+ async function stopChild(child: ChildProcess): Promise<void> {
238
+ if (child.exitCode !== null || child.signalCode !== null) return;
239
+ const exited = Promise.withResolvers<void>();
240
+ child.once('exit', () => exited.resolve());
241
+ if (child.pid !== undefined) terminate(child.pid);
242
+ await exited.promise;
243
+ }
244
+
245
+ /** A raw IPC connection that stays open, so one client can send across a lockfile change. */
246
+ function openClient(socketPath: string): Promise<RawClient> {
247
+ const socket = createConnection(socketPath);
248
+ const opened = Promise.withResolvers<RawClient>();
249
+ let waiting: ((answer: Answer) => void) | undefined;
250
+ const settle = (answer: Answer): void => {
251
+ const resolve = waiting;
252
+ waiting = undefined;
253
+ resolve?.(answer);
254
+ };
255
+ socket.on(
256
+ 'data',
257
+ consumeMessagesFromSocket(
258
+ (message) => settle({ answered: true, message: parseMessage(message) }),
259
+ (error) => settle(gone(String(error))),
260
+ ),
261
+ );
262
+ socket.once('error', (error) => settle(gone(error.message)));
263
+ socket.once('close', () => settle(gone('the daemon closed the connection')));
264
+ socket.once('connect', () =>
265
+ opened.resolve({
266
+ request(message, what) {
267
+ if (socket.destroyed) return Promise.resolve(gone('the connection was already closed'));
268
+ const answer = Promise.withResolvers<Answer>();
269
+ waiting = answer.resolve;
270
+ sendMessage(socket, message, 'json');
271
+ return guardEvent(answer.promise, what, () => `socket ${socketPath}`);
272
+ },
273
+ close() {
274
+ socket.destroy();
275
+ },
276
+ }),
277
+ );
278
+ socket.once('error', opened.reject);
279
+ return opened.promise;
280
+ }
281
+
282
+ /** One PING or request on a fresh connection. A daemon that is gone answers `gone`. */
283
+ async function requestOnce(socketPath: string, request: DaemonRequest, what: string): Promise<Answer> {
284
+ let client: RawClient;
285
+ try {
286
+ client = await openClient(socketPath);
287
+ } catch (error) {
288
+ if (isAbsent(error)) return gone(`nothing listens on ${socketPath}: ${String(error)}`);
289
+ throw error;
290
+ }
291
+ try {
292
+ return await client.request(request, what);
293
+ } finally {
294
+ client.close();
295
+ }
296
+ }
297
+
298
+ /** Whether a process accepts connections on `socketPath`. */
299
+ async function acceptsConnections(socketPath: string): Promise<boolean> {
300
+ try {
301
+ (await openClient(socketPath)).close();
302
+ return true;
303
+ } catch (error) {
304
+ if (isAbsent(error)) return false;
305
+ throw error;
306
+ }
307
+ }
308
+
309
+ /** A served answer is one that is not an error. A stale daemon must answer with an error, or not at all. */
310
+ function assertNotServed(answer: Answer, what: string): void {
311
+ if (!answer.answered) return;
312
+ if (typeof answer.message === 'object' && answer.message !== null && 'error' in answer.message) return;
313
+ throw new Error(`${what} was served by a daemon that should have stopped: ${JSON.stringify(answer.message)}`);
314
+ }
315
+
316
+ /**
317
+ * Runs `action` once a watch on `directory` is open, then resolves with the first non-null `check`. Each pass runs
318
+ * `check` before it waits, so a change at any point, including while `action` runs, is seen.
319
+ */
320
+ async function watchUntil<T>(
321
+ directory: string,
322
+ what: string,
323
+ check: () => Promise<T | null>,
324
+ action?: () => Promise<void>,
325
+ timeoutMs = 30_000,
326
+ ): Promise<T> {
327
+ await mkdir(directory, { recursive: true });
328
+ let notify: (() => void) | undefined;
329
+ const watcher = fsWatch(directory, () => notify?.());
330
+ try {
331
+ await action?.();
332
+ for (;;) {
333
+ const changed = Promise.withResolvers<void>();
334
+ notify = () => changed.resolve();
335
+ const found = await check();
336
+ if (found !== null) return found;
337
+ await guardEvent(changed.promise, what, () => `no change in ${directory}`, undefined, timeoutMs);
338
+ }
339
+ } finally {
340
+ watcher.close();
341
+ }
342
+ }
343
+
344
+ /** Capture the expected holder and the current record before fixture retirement removes the evidence. */
345
+ async function daemonDiagnostics(workspace: string, expectedPid: number): Promise<string> {
346
+ const [record, table] = await Promise.all([daemonRecord(workspace), processTable()]);
347
+ const expected = table.find(({ pid }) => pid === expectedPid);
348
+ const processes = withDescendants(table, record === null ? [expectedPid] : [expectedPid, record.processId]);
349
+ const logPath = join(dirname(recordPath(workspace)), 'daemon.log');
350
+ let log: string;
351
+ try {
352
+ log = await readFile(logPath, 'utf8');
353
+ } catch (error) {
354
+ log = `unavailable: ${error instanceof Error ? error.message : String(error)}`;
355
+ }
356
+ return [
357
+ `workspace ${workspace}; expected daemon pid ${expectedPid}: ${
358
+ expected === undefined ? 'absent from process table' : `state=${expected.stat} command=${expected.command}`
359
+ }`,
360
+ `current daemon record ${JSON.stringify(record)}`,
361
+ `daemon processes ${JSON.stringify(processes)}`,
362
+ `daemon log tail ${logPath}:\n${log.split('\n').slice(-60).join('\n')}`,
363
+ ].join('\n');
364
+ }
365
+
366
+ /**
367
+ * The record and socket path can exist before a daemon can answer. Binding, listening and closing a connection need not
368
+ * emit another directory event, so readiness probes the protocol itself; only a true PING advances the fixture.
369
+ */
370
+ async function untilServing(record: DaemonRecord, workspace: string): Promise<void> {
371
+ const { socketPath } = record;
372
+ const waiting = new AbortController();
373
+ const serving = async (): Promise<void> => {
374
+ while (!waiting.signal.aborted) {
375
+ const answer = await requestOnce(socketPath, ping(workspace), 'the readiness PING');
376
+ if (answer.answered) {
377
+ if (answer.message === true) return;
378
+ throw new Error(`the daemon on ${socketPath} answered PING with ${JSON.stringify(answer.message)}, not true`);
379
+ }
380
+ await sleep(50, undefined, { signal: waiting.signal });
381
+ }
382
+ };
383
+ try {
384
+ await guardEvent(
385
+ serving(),
386
+ `the daemon on ${socketPath} to answer PING`,
387
+ () => daemonDiagnostics(workspace, record.processId),
388
+ undefined,
389
+ 30_000,
390
+ );
391
+ } finally {
392
+ waiting.abort();
393
+ }
394
+ }
395
+
396
+ async function readyDaemon(workspace: string, record: DaemonRecord): Promise<Daemon> {
397
+ await untilServing(record, workspace);
398
+ return { record, entry: await processEntry(record.processId) };
399
+ }
400
+
401
+ async function startDaemon(workspace: string, env: Record<string, string>): Promise<Daemon> {
402
+ nx(workspace, env, 'daemon', '--start');
403
+ const record = await daemonRecord(workspace);
404
+ if (record === null) throw new Error('nx daemon --start left no daemon record');
405
+ return readyDaemon(workspace, record);
406
+ }
407
+
408
+ /**
409
+ * Runs `action`, then resolves with the record that names a process other than `previous`. The record directory is
410
+ * watched before `action` runs, so a record written at any point is seen.
411
+ */
412
+ function replacementAfter({ workspace, previous, action, what, timeoutMs }: Replacement): Promise<DaemonRecord> {
413
+ return watchUntil(
414
+ dirname(recordPath(workspace)),
415
+ what,
416
+ async () => {
417
+ const record = await daemonRecord(workspace);
418
+ return record !== null && record.processId !== previous ? record : null;
419
+ },
420
+ action,
421
+ timeoutMs,
422
+ );
423
+ }
424
+
425
+ /** Runs `action` under a daemon that must judge the change in place, then awaits the old daemon's exit and the new one. */
426
+ async function restarted(
427
+ workspace: string,
428
+ daemon: Daemon,
429
+ what: string,
430
+ action: () => Promise<void>,
431
+ ): Promise<Daemon> {
432
+ const record = await replacementAfter({
433
+ workspace,
434
+ previous: daemon.record.processId,
435
+ action,
436
+ what: `the daemon to restart after ${what}`,
437
+ });
438
+ await awaitExit([daemon.entry], `daemon ${daemon.record.processId} replaced after ${what}`);
439
+ return readyDaemon(workspace, record);
440
+ }
441
+
442
+ /**
443
+ * A file-watcher client of the workspace's daemon, read one event at a time. The fixture environment turns NX_DAEMON
444
+ * off, so this client turns it back on: its watcher must reach the daemon under test, not an in-process Nx.
445
+ */
446
+ function watchClient(workspace: string, env: Record<string, string>) {
447
+ const child = spawn('node', ['-e', CLIENT], {
448
+ cwd: workspace,
449
+ env: { ...env, NX_DAEMON: 'true', NX_DAEMON_CLIENT: daemonClient },
450
+ stdio: ['ignore', 'pipe', 'pipe'],
451
+ });
452
+ let stderr = '';
453
+ child.stderr.setEncoding('utf8').on('data', (text: string) => {
454
+ stderr += text;
455
+ });
456
+ const seen: WatchEvent[] = [];
457
+ const lines = createInterface({ input: child.stdout })[Symbol.asyncIterator]();
458
+ const exited = Promise.withResolvers<number | null>();
459
+ child.once('exit', (code) => exited.resolve(code));
460
+ return {
461
+ seen,
462
+ async next(what: string): Promise<WatchEvent> {
463
+ const line = await guardEvent(lines.next(), what, () => `events so far ${JSON.stringify(seen)}\n${stderr}`);
464
+ if (line.done) throw new Error(`the watch client ended before ${what}: ${JSON.stringify(seen)}\n${stderr}`);
465
+ const [kind = '', ...details] = line.value.split('\t');
466
+ const event = { kind, details };
467
+ seen.push(event);
468
+ return event;
469
+ },
470
+ async end(): Promise<void> {
471
+ if (child.pid !== undefined && child.exitCode === null && child.signalCode === null) terminate(child.pid);
472
+ await exited.promise;
473
+ },
474
+ };
475
+ }
476
+
477
+ /**
478
+ * Runs `change` under a file-watcher client of the daemon, then writes a marker the watcher must report. Watch events
479
+ * arrive in order, so once the marker is reported the change was judged too. The daemon must still be the same process.
480
+ */
481
+ async function quietAfter(
482
+ workspace: string,
483
+ env: Record<string, string>,
484
+ daemon: Daemon,
485
+ what: string,
486
+ marker: string,
487
+ change: () => Promise<void>,
488
+ ): Promise<void> {
489
+ const client = watchClient(workspace, env);
490
+ try {
491
+ expect(await client.next(`the file watcher registering before ${what}`)).toEqual({ kind: 'ready', details: [] });
492
+ await change();
493
+ await writeFile(join(workspace, 'p', marker), 'marker\n');
494
+ for (;;) {
495
+ const event = await client.next(`the file watcher reporting ${marker} after ${what}`);
496
+ expect(
497
+ event.kind,
498
+ `${what} made the daemon stop instead of judging the change in place: ${JSON.stringify(client.seen)}`,
499
+ ).toBe('changed');
500
+ if (event.details.includes(`p/${marker}`)) break;
501
+ }
502
+ } finally {
503
+ await client.end();
504
+ }
505
+ expect(await recordedPid(workspace), `${what} replaced the daemon`).toBe(daemon.record.processId);
506
+ expect(isRunning(daemon.record.processId), `${what} stopped the daemon`).toBe(true);
507
+ }
508
+
509
+ /** A process that listens on `socketPath`, started after the path is free. */
510
+ async function listeningChild(socketPath: string): Promise<Listener> {
511
+ const child = spawn('node', ['-e', LISTENER, socketPath], { stdio: ['ignore', 'pipe', 'pipe'] });
512
+ const pid = child.pid;
513
+ if (pid === undefined) throw new Error(`could not start the listener for ${socketPath}`);
514
+ let stderr = '';
515
+ child.stderr.setEncoding('utf8').on('data', (text: string) => {
516
+ stderr += text;
517
+ });
518
+ const lines = createInterface({ input: child.stdout })[Symbol.asyncIterator]();
519
+ const first = await guardEvent(lines.next(), `the listener on ${socketPath} to start`, () => `stderr:\n${stderr}`);
520
+ if (first.done || first.value !== 'listening') {
521
+ throw new Error(`the listener on ${socketPath} did not report listening: ${JSON.stringify(first)}\n${stderr}`);
522
+ }
523
+ return { pid, stop: () => stopChild(child) };
524
+ }
525
+
526
+ /** Binds `socketPath` from this process, so the replacement exists before a daemon's exit could remove it. */
527
+ async function listenInProcess(socketPath: string): Promise<() => Promise<void>> {
528
+ const server = createServer(() => {});
529
+ const listening = Promise.withResolvers<void>();
530
+ server.once('error', listening.reject);
531
+ server.listen(socketPath, () => listening.resolve());
532
+ await guardEvent(listening.promise, `this process to listen on ${socketPath}`, () => 'no listen callback');
533
+ return () => {
534
+ const closed = Promise.withResolvers<void>();
535
+ server.close(() => closed.resolve());
536
+ return closed.promise;
537
+ };
538
+ }
539
+
540
+ it('has no 20 ms outdated-check loop or lockfile hashing left in the installed daemon', async () => {
541
+ const source = await readFile(daemonServer, 'utf8');
542
+ for (const removed of [
543
+ 'lockFileHashChanged',
544
+ 'daemonIsOutdated',
545
+ 'existingLockHash',
546
+ 'outdated check interval (20ms)',
547
+ ]) {
548
+ expect(source.includes(removed), `${daemonServer} still contains ${removed}`).toBe(false);
549
+ }
550
+ });
551
+
552
+ it('awaits an answerable daemon after a closed PING without another socket-directory event', async () => {
553
+ await withNxFixture('nx-daemon-validity-readiness-', async ({ socketDirectory, workspace }) => {
554
+ await fixtureWorkspace(workspace);
555
+ await mkdir(socketDirectory, { recursive: true });
556
+ const socketPath = join(socketDirectory, 'readiness.sock');
557
+ let requests = 0;
558
+ const server = createServer((socket) => {
559
+ socket.once('data', () => {
560
+ requests += 1;
561
+ if (requests === 1) socket.end();
562
+ else sendMessage(socket, true, 'json');
563
+ });
564
+ });
565
+ const listening = Promise.withResolvers<void>();
566
+ server.once('error', listening.reject);
567
+ server.listen(socketPath, () => listening.resolve());
568
+ await listening.promise;
569
+ try {
570
+ await untilServing({ processId: process.pid, socketPath }, workspace);
571
+ expect(requests).toBe(2);
572
+ } finally {
573
+ const closed = Promise.withResolvers<void>();
574
+ server.close(() => closed.resolve());
575
+ await closed.promise;
576
+ }
577
+ });
578
+ }, 45_000);
579
+
580
+ /** Valid lockfiles keep the real graph usable while the watcher judges byte changes. */
581
+ async function lockContents(
582
+ lockfile: (typeof LOCKFILES)[number],
583
+ root: string,
584
+ ): Promise<readonly [Buffer, Buffer, Buffer]> {
585
+ let text: string;
586
+ switch (lockfile) {
587
+ case 'package-lock.json':
588
+ text = '{"name":"fixture","lockfileVersion":3,"requires":true,"packages":{"":{"name":"fixture"}}}\n';
589
+ break;
590
+ case 'yarn.lock':
591
+ text = '# yarn lockfile v1\n';
592
+ break;
593
+ case 'pnpm-lock.yaml':
594
+ text = "lockfileVersion: '9.0'\nimporters:\n .: {}\npackages: {}\nsnapshots: {}\n";
595
+ break;
596
+ case 'bun.lock':
597
+ text = '{"lockfileVersion":1,"workspaces":{"":{"name":"fixture"}},"packages":{}}\n';
598
+ break;
599
+ case 'bun.lockb': {
600
+ // Generate the legacy binary with Bun, outside the watched workspace.
601
+ const generator = join(root, 'lock-generator');
602
+ await mkdir(generator);
603
+ await writeFile(join(generator, 'bunfig.toml'), '[install]\nsaveTextLockfile = false\n');
604
+ const generated: Buffer[] = [];
605
+ for (const version of ['1.0.0', '1.0.1', '1.0.2']) {
606
+ const dependency = join(root, `lock-dependency-${version}`);
607
+ await mkdir(dependency);
608
+ await writeFile(
609
+ join(generator, 'package.json'),
610
+ JSON.stringify({
611
+ name: 'fixture',
612
+ dependencies: { 'lock-dependency': `file:../lock-dependency-${version}` },
613
+ }),
614
+ );
615
+ await writeFile(join(dependency, 'package.json'), JSON.stringify({ name: 'lock-dependency', version }));
616
+ await rm(join(generator, 'bun.lockb'), { force: true });
617
+ const result = spawnSync('bun', ['install', '--lockfile-only', '--ignore-scripts', '--offline'], {
618
+ cwd: generator,
619
+ encoding: 'utf8',
620
+ });
621
+ expect(result.status, result.stdout + result.stderr).toBe(0);
622
+ generated.push(await readFile(join(generator, 'bun.lockb')));
623
+ }
624
+ const [one, two, three] = generated;
625
+ if (one === undefined || two === undefined || three === undefined)
626
+ throw new Error('Bun generated fewer than three lockfiles');
627
+ expect(one.equals(two)).toBe(false);
628
+ expect(two.equals(three)).toBe(false);
629
+ return [one, two, three];
630
+ }
631
+ }
632
+ return [Buffer.from(text), Buffer.from(`${text}\n`), Buffer.from(`${text}\n\n`)];
633
+ }
634
+
635
+ for (const lockfile of LOCKFILES) {
636
+ it(`restarts the daemon on ${lockfile} create, change, replace, and delete, and only then`, async () => {
637
+ await withNxFixture(
638
+ 'nx-daemon-validity-lock-',
639
+ async ({ root, socketDirectory, workspace }) => {
640
+ if (lockfile === 'pnpm-lock.yaml') {
641
+ // pnpm's parser requires its hoisting metadata, even with no packages.
642
+ // Keep the installation directory fixture-owned, never write through the repository link.
643
+ await fixtureWorkspace(workspace, join(repositoryRoot, 'node_modules/nx'));
644
+ await writeFile(join(workspace, 'node_modules/.modules.yaml'), 'hoistedDependencies: {}\n');
645
+ } else {
646
+ await fixtureWorkspace(workspace);
647
+ }
648
+ const env = fixtureNxEnv(workspace, socketDirectory);
649
+ const lock = join(workspace, lockfile);
650
+ const [one, two, three] = await lockContents(lockfile, root);
651
+ let daemon = await startDaemon(workspace, env);
652
+ daemon = await restarted(workspace, daemon, `creating ${lockfile}`, () => writeFile(lock, one));
653
+ daemon = await restarted(workspace, daemon, `changing ${lockfile}`, () => writeFile(lock, two));
654
+ daemon = await restarted(workspace, daemon, `replacing ${lockfile} by rename`, async () => {
655
+ await writeFile(`${lock}.next`, three);
656
+ await rename(`${lock}.next`, lock);
657
+ });
658
+ await quietAfter(workspace, env, daemon, `a same-bytes rewrite of ${lockfile}`, 'same-bytes.txt', () =>
659
+ writeFile(lock, three),
660
+ );
661
+ await quietAfter(workspace, env, daemon, `a nested ${lockfile} in p`, 'nested.txt', () =>
662
+ writeFile(join(workspace, 'p', lockfile), one),
663
+ );
664
+ await restarted(workspace, daemon, `deleting ${lockfile}`, () => rm(lock));
665
+ },
666
+ FIXTURE_WORKSPACE,
667
+ );
668
+ }, 180_000);
669
+ }
670
+
671
+ it('does not serve a request sent on a connection opened before a lockfile change', async () => {
672
+ await withNxFixture(
673
+ 'nx-daemon-validity-held-',
674
+ async ({ socketDirectory, workspace }) => {
675
+ await fixtureWorkspace(workspace);
676
+ const lock = join(workspace, 'yarn.lock');
677
+ await writeFile(lock, 'lock one\n');
678
+ const env = fixtureNxEnv(workspace, socketDirectory);
679
+ const daemon = await startDaemon(workspace, env);
680
+ const held = await openClient(daemon.record.socketPath);
681
+ try {
682
+ expect(await held.request(ping(workspace), 'the first PING on the held connection')).toEqual({
683
+ answered: true,
684
+ message: true,
685
+ });
686
+ await writeFile(lock, 'lock two\n');
687
+ assertNotServed(
688
+ await held.request(
689
+ { type: 'REQUEST_PROJECT_GRAPH', workspaceRoot: workspace },
690
+ 'the graph request sent right after the lockfile change',
691
+ ),
692
+ 'a graph request on a connection opened before the lockfile change',
693
+ );
694
+ } finally {
695
+ held.close();
696
+ }
697
+ await awaitExit([daemon.entry], `daemon ${daemon.record.processId} after the held lockfile change`);
698
+ await replacementAfter({
699
+ workspace,
700
+ previous: daemon.record.processId,
701
+ what: 'the daemon to restart after the held lockfile change',
702
+ });
703
+ },
704
+ FIXTURE_WORKSPACE,
705
+ );
706
+ }, 180_000);
707
+
708
+ it('stops a daemon at the next request after an ignored lockfile changes, then its successor within its safety poll with no request', async () => {
709
+ await withNxFixture(
710
+ 'nx-daemon-validity-ignored-',
711
+ async ({ socketDirectory, workspace }) => {
712
+ await fixtureWorkspace(workspace);
713
+ await writeFile(join(workspace, '.gitignore'), 'yarn.lock\n');
714
+ const lock = join(workspace, 'yarn.lock');
715
+ await writeFile(lock, 'lock one\n');
716
+ const env = fixtureNxEnv(workspace, socketDirectory);
717
+ const daemon = await startDaemon(workspace, env);
718
+ // The watcher never reports an ignored lockfile; the next request is what judges this change.
719
+ await writeFile(lock, 'lock two\n');
720
+ assertNotServed(
721
+ await requestOnce(daemon.record.socketPath, ping(workspace), 'a PING sent after the ignored lockfile changed'),
722
+ 'a PING sent after the ignored lockfile changed',
723
+ );
724
+ await awaitExit(
725
+ [daemon.entry],
726
+ `daemon ${daemon.record.processId} after the ignored lockfile changed and a PING followed`,
727
+ );
728
+ const record = await replacementAfter({
729
+ workspace,
730
+ previous: daemon.record.processId,
731
+ what: 'the daemon to restart after the ignored lockfile changed and a PING followed',
732
+ });
733
+ // The successor booted with 'lock two' on disk, so that is its baseline; a daemon answers a PING only when its
734
+ // check finds the lock unchanged, and nothing requests this one afterwards.
735
+ const successor = await readyDaemon(workspace, record);
736
+ expect(
737
+ await recordedPid(workspace),
738
+ 'the successor was replaced before the lockfile changed again, so no replacement could show the safety poll',
739
+ ).toBe(successor.record.processId);
740
+ // Nothing requests the successor after this write and its watcher ignores the file, so only the 5 s safety
741
+ // poll can judge 'lock three'.
742
+ await replacementAfter({
743
+ workspace,
744
+ previous: successor.record.processId,
745
+ action: () => writeFile(lock, 'lock three\n'),
746
+ what: 'a replacement of the successor within the 5 s safety poll after an ignored lockfile change',
747
+ timeoutMs: 20_000,
748
+ });
749
+ await awaitExit(
750
+ [successor.entry],
751
+ `successor ${successor.record.processId} after the ignored lockfile changed with no request`,
752
+ );
753
+ },
754
+ FIXTURE_WORKSPACE,
755
+ );
756
+ }, 180_000);
757
+
758
+ it('stops a daemon, refusing its next request, once the installed nx version changes in place', async () => {
759
+ await withNxFixture(
760
+ 'nx-daemon-validity-version-',
761
+ async ({ root, socketDirectory, workspace }) => {
762
+ const installed = join(root, 'installed-nx');
763
+ const manifest = await installedManifest();
764
+ await nxPackageCopy(installed, manifest.version);
765
+ await fixtureWorkspace(workspace, installed);
766
+ const env = fixtureNxEnv(workspace, socketDirectory);
767
+ const daemon = await startDaemon(workspace, env);
768
+ await writeFile(
769
+ join(installed, 'package.json'),
770
+ JSON.stringify({ ...manifest, version: `${manifest.version}-validity` }),
771
+ );
772
+ assertNotServed(
773
+ await requestOnce(
774
+ daemon.record.socketPath,
775
+ ping(workspace),
776
+ 'a PING sent after the installed nx version changed',
777
+ ),
778
+ 'a PING sent after the installed nx version changed',
779
+ );
780
+ await awaitExit([daemon.entry], `daemon ${daemon.record.processId} after the installed nx version changed`);
781
+ },
782
+ FIXTURE_WORKSPACE,
783
+ );
784
+ }, 180_000);
785
+
786
+ it('stops a daemon once the workspace nx link points at a different version', async () => {
787
+ await withNxFixture(
788
+ 'nx-daemon-validity-link-',
789
+ async ({ root, socketDirectory, workspace }) => {
790
+ const first = join(root, 'installed-nx');
791
+ const second = join(root, 'replacement-nx');
792
+ const manifest = await installedManifest();
793
+ await nxPackageCopy(first, manifest.version);
794
+ await nxPackageCopy(second, `${manifest.version}-validity`);
795
+ await fixtureWorkspace(workspace, first);
796
+ const env = fixtureNxEnv(workspace, socketDirectory);
797
+ const daemon = await startDaemon(workspace, env);
798
+ const link = join(workspace, 'node_modules', 'nx');
799
+ await unlink(link);
800
+ await symlink(second, link, 'dir');
801
+ assertNotServed(
802
+ await requestOnce(daemon.record.socketPath, ping(workspace), 'a PING sent after the nx link changed'),
803
+ 'a PING sent after the nx link changed',
804
+ );
805
+ await awaitExit([daemon.entry], `daemon ${daemon.record.processId} after the nx link changed`);
806
+ },
807
+ FIXTURE_WORKSPACE,
808
+ );
809
+ }, 180_000);
810
+
811
+ it('leaves a successor record and socket in place when another process takes the record', async () => {
812
+ await withNxFixture(
813
+ 'nx-daemon-validity-successor-',
814
+ async ({ socketDirectory, workspace }) => {
815
+ await fixtureWorkspace(workspace);
816
+ const env = fixtureNxEnv(workspace, socketDirectory);
817
+ const old = await startDaemon(workspace, env);
818
+ const successorSocket = join(socketDirectory, 'successor.sock');
819
+ const successor = await listeningChild(successorSocket);
820
+ try {
821
+ const record = {
822
+ processId: successor.pid,
823
+ socketPath: successorSocket,
824
+ nxVersion: (await installedManifest()).version,
825
+ workspaceRoot: workspace,
826
+ };
827
+ await writeFile(recordPath(workspace), `${JSON.stringify(record)}\n`);
828
+ await awaitExit([old.entry], `daemon ${old.record.processId} whose record now names ${successor.pid}`);
829
+ expect(await daemonRecord(workspace), 'the record after the displaced daemon exited').toMatchObject({
830
+ processId: successor.pid,
831
+ socketPath: successorSocket,
832
+ });
833
+ expect(
834
+ await acceptsConnections(successorSocket),
835
+ 'the successor socket after the displaced daemon exited',
836
+ ).toBe(true);
837
+ } finally {
838
+ await successor.stop();
839
+ }
840
+ },
841
+ FIXTURE_WORKSPACE,
842
+ );
843
+ }, 180_000);
844
+
845
+ it("leaves a replacement socket in place when the daemon's own socket path is replaced", async () => {
846
+ await withNxFixture(
847
+ 'nx-daemon-validity-socket-',
848
+ async ({ socketDirectory, workspace }) => {
849
+ await fixtureWorkspace(workspace);
850
+ const env = fixtureNxEnv(workspace, socketDirectory);
851
+ const daemon = await startDaemon(workspace, env);
852
+ await unlink(daemon.record.socketPath);
853
+ const closeReplacement = await listenInProcess(daemon.record.socketPath);
854
+ try {
855
+ await awaitExit([daemon.entry], `daemon ${daemon.record.processId} whose socket path was replaced`);
856
+ expect(
857
+ await acceptsConnections(daemon.record.socketPath),
858
+ 'the replacement socket after the daemon exited',
859
+ ).toBe(true);
860
+ } finally {
861
+ await closeReplacement();
862
+ }
863
+ },
864
+ FIXTURE_WORKSPACE,
865
+ );
866
+ }, 180_000);
867
+
868
+ it('stops a daemon whose own socket path is removed with nothing taking its place', async () => {
869
+ await withNxFixture(
870
+ 'nx-daemon-validity-unlinked-',
871
+ async ({ socketDirectory, workspace }) => {
872
+ await fixtureWorkspace(workspace);
873
+ const env = fixtureNxEnv(workspace, socketDirectory);
874
+ const daemon = await startDaemon(workspace, env);
875
+ await unlink(daemon.record.socketPath);
876
+ await awaitExit([daemon.entry], `daemon ${daemon.record.processId} after its socket path was removed`);
877
+ expect(await acceptsConnections(daemon.record.socketPath), 'the socket path after the daemon exited').toBe(false);
878
+ },
879
+ FIXTURE_WORKSPACE,
880
+ );
881
+ }, 180_000);
882
+
883
+ it('keeps an idle daemon off the lockfiles, record, and socket between its safety polls', async () => {
884
+ await withNxFixture(
885
+ 'nx-daemon-validity-idle-',
886
+ async ({ root, socketDirectory, workspace }) => {
887
+ await fixtureWorkspace(workspace);
888
+ const log = join(root, 'validity-probe.log');
889
+ const probe = join(root, 'validity-probe.cjs');
890
+ await writeFile(probe, PROBE);
891
+ const env = { ...fixtureNxEnv(workspace, socketDirectory), NX_VALIDITY_LOG: log };
892
+ const daemonProcess = spawn(process.execPath, ['--preload', probe, daemonStart], {
893
+ cwd: workspace,
894
+ env,
895
+ stdio: ['ignore', 'ignore', 'ignore'],
896
+ });
897
+ try {
898
+ const record = await replacementAfter({ workspace, what: 'the directly started daemon to publish its record' });
899
+ const daemon = await readyDaemon(workspace, record);
900
+ const before = (await readFile(log, 'utf8')).split('\n').filter((line) => line !== '');
901
+ // The one real-clock wait. The daemon is a separate OS process whose idle behaviour exists only in wall-clock
902
+ // time, so no injected or fake clock can reach it; the window has to be measured against the real clock.
903
+ const observation = Promise.withResolvers<void>();
904
+ setTimeout(observation.resolve, OBSERVATION_MS);
905
+ await observation.promise;
906
+ const observed = (await readFile(log, 'utf8'))
907
+ .split('\n')
908
+ .filter((line) => line !== '')
909
+ .slice(before.length);
910
+ expect(
911
+ before.length,
912
+ 'the probe recorded no daemon startup reads, so its instrumentation is dead',
913
+ ).toBeGreaterThan(1);
914
+ expect(
915
+ observed.length,
916
+ `an idle daemon made ${observed.length} lockfile, record, or socket calls in ${OBSERVATION_MS} ms:\n${observed.join('\n')}`,
917
+ ).toBeLessThan(100);
918
+ expect(isRunning(daemon.record.processId), 'the idle daemon stopped').toBe(true);
919
+ } finally {
920
+ await stopChild(daemonProcess);
921
+ }
922
+ },
923
+ FIXTURE_WORKSPACE,
924
+ );
925
+ }, 120_000);