@smoothbricks/nx-plugin 0.5.6 → 0.6.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 (440) hide show
  1. package/README.md +1095 -360
  2. package/dist/.build-inputs.json +138 -0
  3. package/dist/bin/smoo-nx-cargo-toolchain.d.ts +3 -0
  4. package/dist/bin/smoo-nx-cargo-toolchain.d.ts.map +1 -0
  5. package/dist/bin/smoo-nx-cargo-toolchain.js +8 -0
  6. package/dist/bin/smoo-nx-forbidden-spellings.d.ts +3 -0
  7. package/dist/bin/smoo-nx-forbidden-spellings.d.ts.map +1 -0
  8. package/dist/bin/smoo-nx-forbidden-spellings.js +32 -0
  9. package/dist/bin/smoo-nx-nextest-timings.d.ts +3 -0
  10. package/dist/bin/smoo-nx-nextest-timings.d.ts.map +1 -0
  11. package/dist/bin/smoo-nx-nextest-timings.js +28 -0
  12. package/dist/bounded-test-policy.d.ts +1 -1
  13. package/dist/bounded-test-policy.d.ts.map +1 -1
  14. package/dist/bounded-test-policy.js +14 -15
  15. package/dist/build-state-output-policy.d.ts +95 -1
  16. package/dist/build-state-output-policy.d.ts.map +1 -1
  17. package/dist/build-state-output-policy.js +368 -30
  18. package/dist/bun-lock-scope.d.ts +44 -0
  19. package/dist/bun-lock-scope.d.ts.map +1 -0
  20. package/dist/bun-lock-scope.js +97 -0
  21. package/dist/cargo-build-script-env.d.ts +49 -0
  22. package/dist/cargo-build-script-env.d.ts.map +1 -0
  23. package/dist/cargo-build-script-env.js +324 -0
  24. package/dist/cargo-closure-input.d.ts +31 -4
  25. package/dist/cargo-closure-input.d.ts.map +1 -1
  26. package/dist/cargo-closure-input.js +66 -6
  27. package/dist/cargo-retention-hook.d.ts +17 -0
  28. package/dist/cargo-retention-hook.d.ts.map +1 -0
  29. package/dist/cargo-retention-hook.js +85 -0
  30. package/dist/cargo-source-hash.d.ts +25 -7
  31. package/dist/cargo-source-hash.d.ts.map +1 -1
  32. package/dist/cargo-source-hash.js +108 -43
  33. package/dist/cargo-toolchain-paths.d.ts +40 -0
  34. package/dist/cargo-toolchain-paths.d.ts.map +1 -0
  35. package/dist/cargo-toolchain-paths.js +84 -0
  36. package/dist/cargo-toolchain-policy.d.ts +25 -8
  37. package/dist/cargo-toolchain-policy.d.ts.map +1 -1
  38. package/dist/cargo-toolchain-policy.js +39 -5
  39. package/dist/cargo-workspace.d.ts +10 -4
  40. package/dist/cargo-workspace.d.ts.map +1 -1
  41. package/dist/cargo-workspace.js +65 -95
  42. package/dist/cross-check-policy.d.ts +9 -9
  43. package/dist/cross-check-policy.d.ts.map +1 -1
  44. package/dist/cross-check-policy.js +11 -11
  45. package/dist/disk-command-policy.d.ts.map +1 -1
  46. package/dist/disk-command-policy.js +1 -0
  47. package/dist/ensure-built-receipt.d.ts +13 -5
  48. package/dist/ensure-built-receipt.d.ts.map +1 -1
  49. package/dist/ensure-built-receipt.js +126 -47
  50. package/dist/ensure-built-witness.d.ts +27 -8
  51. package/dist/ensure-built-witness.d.ts.map +1 -1
  52. package/dist/ensure-built-witness.js +45 -15
  53. package/dist/ensure-built.d.ts.map +1 -1
  54. package/dist/ensure-built.js +9 -1
  55. package/dist/eslint-config-closure.d.ts +7 -0
  56. package/dist/eslint-config-closure.d.ts.map +1 -0
  57. package/dist/eslint-config-closure.js +346 -0
  58. package/dist/executors/all-verdicts/executor.d.ts +35 -0
  59. package/dist/executors/all-verdicts/executor.d.ts.map +1 -0
  60. package/dist/executors/all-verdicts/executor.js +133 -0
  61. package/dist/executors/all-verdicts/schema.d.ts +10 -0
  62. package/dist/executors/all-verdicts/schema.d.ts.map +1 -0
  63. package/dist/executors/all-verdicts/schema.js +2 -0
  64. package/dist/executors/bounded-exec/bounds.d.ts +56 -0
  65. package/dist/executors/bounded-exec/bounds.d.ts.map +1 -0
  66. package/dist/executors/bounded-exec/bounds.js +43 -0
  67. package/dist/executors/bounded-exec/cpu-pool.d.ts +33 -36
  68. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -1
  69. package/dist/executors/bounded-exec/cpu-pool.js +54 -119
  70. package/dist/executors/bounded-exec/executor.d.ts +19 -12
  71. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  72. package/dist/executors/bounded-exec/executor.js +371 -239
  73. package/dist/executors/bounded-exec/gateway-lease.d.ts +22 -19
  74. package/dist/executors/bounded-exec/gateway-lease.d.ts.map +1 -1
  75. package/dist/executors/bounded-exec/gateway-lease.js +81 -28
  76. package/dist/executors/bounded-exec/hang-diagnostics.d.ts +18 -1
  77. package/dist/executors/bounded-exec/hang-diagnostics.d.ts.map +1 -1
  78. package/dist/executors/bounded-exec/hang-diagnostics.js +148 -30
  79. package/dist/executors/bounded-exec/lease-wait.d.ts +43 -0
  80. package/dist/executors/bounded-exec/lease-wait.d.ts.map +1 -0
  81. package/dist/executors/bounded-exec/lease-wait.js +68 -0
  82. package/dist/executors/bounded-exec/lock-wait.d.ts +51 -0
  83. package/dist/executors/bounded-exec/lock-wait.d.ts.map +1 -0
  84. package/dist/executors/bounded-exec/lock-wait.js +108 -0
  85. package/dist/executors/bounded-exec/owned-subtree.d.ts +84 -0
  86. package/dist/executors/bounded-exec/owned-subtree.d.ts.map +1 -0
  87. package/dist/executors/bounded-exec/owned-subtree.js +178 -0
  88. package/dist/executors/bounded-exec/progress.d.ts +4 -1
  89. package/dist/executors/bounded-exec/progress.d.ts.map +1 -1
  90. package/dist/executors/bounded-exec/progress.js +5 -2
  91. package/dist/executors/bounded-exec/ram-attach.d.ts +19 -0
  92. package/dist/executors/bounded-exec/ram-attach.d.ts.map +1 -0
  93. package/dist/executors/bounded-exec/ram-attach.js +207 -0
  94. package/dist/executors/bounded-exec/ram-detach.d.ts +25 -0
  95. package/dist/executors/bounded-exec/ram-detach.d.ts.map +1 -0
  96. package/dist/executors/bounded-exec/ram-detach.js +207 -0
  97. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts +76 -0
  98. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts.map +1 -1
  99. package/dist/executors/bounded-exec/ram-temp-fixtures.js +296 -0
  100. package/dist/executors/bounded-exec/ram-temp.d.ts +388 -88
  101. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -1
  102. package/dist/executors/bounded-exec/ram-temp.js +1213 -399
  103. package/dist/executors/bounded-exec/run-cpu-pool.d.ts +4 -4
  104. package/dist/executors/bounded-exec/run-cpu-pool.d.ts.map +1 -1
  105. package/dist/executors/bounded-exec/run-cpu-pool.js +20 -30
  106. package/dist/executors/bounded-exec/runner-hook.js +14 -5
  107. package/dist/executors/bounded-exec/runner-lifecycle.d.ts +14 -1
  108. package/dist/executors/bounded-exec/runner-lifecycle.d.ts.map +1 -1
  109. package/dist/executors/bounded-exec/runner-lifecycle.js +27 -6
  110. package/dist/executors/bounded-exec/{cpu-tokens.d.ts → runner-sizing.d.ts} +14 -42
  111. package/dist/executors/bounded-exec/runner-sizing.d.ts.map +1 -0
  112. package/dist/executors/bounded-exec/{cpu-tokens.js → runner-sizing.js} +5 -35
  113. package/dist/executors/bounded-exec/runtime-pin.d.ts +73 -0
  114. package/dist/executors/bounded-exec/runtime-pin.d.ts.map +1 -0
  115. package/dist/executors/bounded-exec/runtime-pin.js +167 -0
  116. package/dist/executors/bounded-exec/schema.d.ts +18 -1
  117. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  118. package/dist/executors/bounded-exec/verdict.d.ts +40 -11
  119. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -1
  120. package/dist/executors/bounded-exec/verdict.js +88 -19
  121. package/dist/executors/cargo-zigbuild/executor.d.ts +21 -0
  122. package/dist/executors/cargo-zigbuild/executor.d.ts.map +1 -1
  123. package/dist/executors/cargo-zigbuild/executor.js +67 -12
  124. package/dist/executors/clean-outputs/executor.js +1 -0
  125. package/dist/executors/scriptc-native/executor.d.ts +79 -0
  126. package/dist/executors/scriptc-native/executor.d.ts.map +1 -0
  127. package/dist/executors/scriptc-native/executor.js +367 -0
  128. package/dist/executors/scriptc-native/ffi-paths.d.ts +9 -0
  129. package/dist/executors/scriptc-native/ffi-paths.d.ts.map +1 -0
  130. package/dist/executors/scriptc-native/ffi-paths.js +25 -0
  131. package/dist/executors/scriptc-native/schema.d.ts +34 -0
  132. package/dist/executors/scriptc-native/schema.d.ts.map +1 -0
  133. package/dist/executors/scriptc-native/schema.js +1 -0
  134. package/dist/executors/typescript-emit/executor.d.ts +3 -1
  135. package/dist/executors/typescript-emit/executor.d.ts.map +1 -1
  136. package/dist/executors/typescript-emit/executor.js +164 -33
  137. package/dist/forbidden-spelling-policy.d.ts +56 -0
  138. package/dist/forbidden-spelling-policy.d.ts.map +1 -0
  139. package/dist/forbidden-spelling-policy.js +176 -0
  140. package/dist/generators/create-package/generator.d.ts.map +1 -1
  141. package/dist/generators/create-package/generator.js +3 -4
  142. package/dist/graph-input-contract.d.ts +14 -0
  143. package/dist/graph-input-contract.d.ts.map +1 -1
  144. package/dist/graph-input-contract.js +67 -2
  145. package/dist/index.d.ts +23 -6
  146. package/dist/index.d.ts.map +1 -1
  147. package/dist/index.js +676 -215
  148. package/dist/managed-assets.d.ts +2 -0
  149. package/dist/managed-assets.d.ts.map +1 -1
  150. package/dist/managed-files/files.d.ts +3 -3
  151. package/dist/managed-files/files.d.ts.map +1 -1
  152. package/dist/managed-files/files.js +28 -3
  153. package/dist/managed-files/managed-format.d.ts.map +1 -1
  154. package/dist/managed-files/managed-format.js +1 -0
  155. package/dist/nextest-code-bound.js +1 -0
  156. package/dist/nextest-timings.d.ts +35 -0
  157. package/dist/nextest-timings.d.ts.map +1 -0
  158. package/dist/nextest-timings.js +168 -0
  159. package/dist/owned-installation.d.ts +6 -5
  160. package/dist/owned-installation.d.ts.map +1 -1
  161. package/dist/owned-installation.js +150 -26
  162. package/dist/package-target-policy.d.ts.map +1 -1
  163. package/dist/package-target-policy.js +2 -3
  164. package/dist/process-children.d.ts +7 -0
  165. package/dist/process-children.d.ts.map +1 -0
  166. package/dist/process-children.darwin.d.ts +7 -0
  167. package/dist/process-children.darwin.d.ts.map +1 -0
  168. package/dist/process-children.darwin.js +13 -0
  169. package/dist/process-children.js +14 -0
  170. package/dist/process-children.linux.d.ts +8 -0
  171. package/dist/process-children.linux.d.ts.map +1 -0
  172. package/dist/process-children.linux.js +25 -0
  173. package/dist/process-group.d.ts +108 -0
  174. package/dist/process-group.d.ts.map +1 -0
  175. package/dist/process-group.js +171 -0
  176. package/dist/process-listing.d.ts +7 -0
  177. package/dist/process-listing.d.ts.map +1 -0
  178. package/dist/process-listing.js +51 -0
  179. package/dist/producer-receipts.d.ts +8 -2
  180. package/dist/producer-receipts.d.ts.map +1 -1
  181. package/dist/producer-receipts.js +75 -48
  182. package/dist/task-graph-policy.d.ts +21 -0
  183. package/dist/task-graph-policy.d.ts.map +1 -0
  184. package/dist/task-graph-policy.js +91 -0
  185. package/dist/test-timings.js +4 -4
  186. package/dist/test-walk-policy.d.ts +14 -5
  187. package/dist/test-walk-policy.d.ts.map +1 -1
  188. package/dist/test-walk-policy.js +8 -2
  189. package/dist/testing.d.ts +73 -28
  190. package/dist/testing.d.ts.map +1 -1
  191. package/dist/testing.js +217 -223
  192. package/dist/tool-bins.d.ts +33 -0
  193. package/dist/tool-bins.d.ts.map +1 -0
  194. package/dist/tool-bins.js +72 -0
  195. package/dist/typecheck-test-policy.d.ts.map +1 -1
  196. package/dist/typecheck-test-policy.js +3 -4
  197. package/dist/wait-why-policy.d.ts +28 -0
  198. package/dist/wait-why-policy.d.ts.map +1 -0
  199. package/dist/wait-why-policy.js +223 -0
  200. package/dist/workspace-config-policy.d.ts +14 -8
  201. package/dist/workspace-config-policy.d.ts.map +1 -1
  202. package/dist/workspace-config-policy.js +60 -16
  203. package/dist/workspace-manifest.d.ts +41 -6
  204. package/dist/workspace-manifest.d.ts.map +1 -1
  205. package/dist/workspace-manifest.js +57 -0
  206. package/executors.json +21 -1
  207. package/loader.js +2 -0
  208. package/managed/raw/envrc +11 -0
  209. package/managed/raw/patches/nx@23.2.1.patch +2840 -199
  210. package/managed/raw/patches/ttsc@0.34.1.patch +119 -0
  211. package/managed/raw/tooling/direnv/cargo-fetch-bound.ts +245 -0
  212. package/managed/raw/tooling/direnv/cargo-fetch-run.ts +299 -0
  213. package/managed/raw/tooling/direnv/compiler-variables.sh +42 -0
  214. package/managed/raw/tooling/direnv/developer-links.ts +464 -25
  215. package/managed/raw/tooling/direnv/devenv.smoo.nix +78 -38
  216. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +14 -12
  217. package/managed/raw/tooling/direnv/installed-bun-links.ts +308 -0
  218. package/managed/raw/tooling/direnv/linked-snapshots.ts +62 -3
  219. package/managed/raw/tooling/direnv/nx-socket-dir.sh +56 -17
  220. package/managed/raw/tooling/direnv/repo-path +68 -6
  221. package/managed/raw/tooling/direnv/secret-references.ts +13 -4
  222. package/managed/raw/tooling/direnv/setup-environment.ts +128 -537
  223. package/managed/raw/tooling/direnv/toolchain-stamp.ts +4 -2
  224. package/managed/raw/tooling/direnv/ttsc-env.sh +9 -0
  225. package/managed/raw/tooling/direnv/uv-relocation.ts +227 -0
  226. package/managed/raw/tooling/git-hooks/commit-msg.sh +2 -1
  227. package/managed/raw/tooling/git-hooks/pre-commit.sh +2 -1
  228. package/managed/raw/tooling/git-hooks/pre-push.sh +2 -1
  229. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +85 -7
  230. package/managed/templates/github/actions/save-nix-devenv/action.yml +12 -2
  231. package/managed/templates/github/actions/setup-devenv/action.yml +2 -0
  232. package/package.json +77 -13
  233. package/src/bin/smoo-nx-cargo-toolchain.ts +11 -0
  234. package/src/bin/smoo-nx-forbidden-spellings.ts +33 -0
  235. package/src/bin/smoo-nx-nextest-timings.ts +31 -0
  236. package/src/bounded-test-policy.ts +12 -14
  237. package/src/build-state-output-policy.ts +458 -34
  238. package/src/bun-lock-scope.ts +108 -0
  239. package/src/cargo-build-script-env.ts +265 -0
  240. package/src/cargo-closure-input.ts +74 -7
  241. package/src/cargo-retention-hook.ts +94 -0
  242. package/src/cargo-source-hash.ts +138 -41
  243. package/src/cargo-toolchain-paths.ts +95 -0
  244. package/src/cargo-toolchain-policy.ts +49 -5
  245. package/src/cargo-workspace.ts +72 -123
  246. package/src/cross-check-policy.ts +12 -10
  247. package/src/disk-command-policy.ts +1 -0
  248. package/src/ensure-built-receipt.ts +132 -39
  249. package/src/ensure-built-witness.ts +62 -10
  250. package/src/ensure-built.ts +11 -1
  251. package/src/eslint-config-closure.ts +357 -0
  252. package/src/executors/all-verdicts/executor.ts +164 -0
  253. package/src/executors/all-verdicts/schema.json +22 -0
  254. package/src/executors/all-verdicts/schema.ts +10 -0
  255. package/src/executors/bounded-exec/bounds.ts +76 -0
  256. package/src/executors/bounded-exec/cpu-pool.ts +51 -117
  257. package/src/executors/bounded-exec/executor.ts +423 -259
  258. package/src/executors/bounded-exec/gateway-lease.ts +82 -33
  259. package/src/executors/bounded-exec/hang-diagnostics.ts +173 -31
  260. package/src/executors/bounded-exec/lease-wait.ts +89 -0
  261. package/src/executors/bounded-exec/lock-wait.ts +141 -0
  262. package/src/executors/bounded-exec/owned-subtree.ts +235 -0
  263. package/src/executors/bounded-exec/progress.ts +9 -3
  264. package/src/executors/bounded-exec/ram-attach.ts +238 -0
  265. package/src/executors/bounded-exec/ram-detach.ts +226 -0
  266. package/src/executors/bounded-exec/ram-temp-fixtures.ts +358 -0
  267. package/src/executors/bounded-exec/ram-temp-registry.txt +440 -0
  268. package/src/executors/bounded-exec/ram-temp.ts +1497 -460
  269. package/src/executors/bounded-exec/run-cpu-pool.ts +22 -30
  270. package/src/executors/bounded-exec/runner-hook.ts +14 -6
  271. package/src/executors/bounded-exec/runner-lifecycle.ts +31 -8
  272. package/src/executors/bounded-exec/{cpu-tokens.ts → runner-sizing.ts} +13 -59
  273. package/src/executors/bounded-exec/runtime-pin.ts +232 -0
  274. package/src/executors/bounded-exec/schema.json +11 -2
  275. package/src/executors/bounded-exec/schema.ts +19 -1
  276. package/src/executors/bounded-exec/verdict.ts +137 -34
  277. package/src/executors/cargo-zigbuild/executor.ts +82 -8
  278. package/src/executors/clean-outputs/executor.ts +1 -0
  279. package/src/executors/scriptc-native/executor.ts +394 -0
  280. package/src/executors/scriptc-native/ffi-paths.ts +29 -0
  281. package/src/executors/scriptc-native/schema.json +60 -0
  282. package/src/executors/scriptc-native/schema.ts +34 -0
  283. package/src/executors/typescript-emit/executor.ts +205 -38
  284. package/src/forbidden-spelling-policy.ts +226 -0
  285. package/src/generators/create-package/generator.ts +7 -7
  286. package/src/graph-input-contract.ts +61 -2
  287. package/src/index.ts +792 -225
  288. package/src/managed-assets.ts +3 -0
  289. package/src/managed-files/files.ts +28 -3
  290. package/src/managed-files/managed-format.ts +1 -0
  291. package/src/nextest-code-bound.ts +1 -0
  292. package/src/nextest-timings.ts +106 -0
  293. package/src/owned-installation.ts +150 -23
  294. package/src/package-target-policy.ts +2 -3
  295. package/src/process-children.darwin.ts +14 -0
  296. package/src/process-children.linux.ts +33 -0
  297. package/src/process-children.ts +22 -0
  298. package/src/process-group.ts +209 -0
  299. package/src/process-listing.ts +54 -0
  300. package/src/producer-receipts.ts +68 -45
  301. package/src/task-graph-policy.ts +98 -0
  302. package/src/test-walk-policy.ts +23 -8
  303. package/src/testing.ts +240 -232
  304. package/src/tool-bins.ts +108 -0
  305. package/src/typecheck-test-policy.ts +2 -3
  306. package/src/wait-why-policy.ts +226 -0
  307. package/src/workspace-config-policy.ts +63 -15
  308. package/src/workspace-manifest.ts +89 -6
  309. package/test-timings.json +123 -98
  310. package/dist/bin/smoo-nx-failures.d.ts +0 -3
  311. package/dist/bin/smoo-nx-failures.d.ts.map +0 -1
  312. package/dist/bin/smoo-nx-failures.js +0 -3
  313. package/dist/bin/smoo-nx-nextest-extract.d.ts +0 -3
  314. package/dist/bin/smoo-nx-nextest-extract.d.ts.map +0 -1
  315. package/dist/bin/smoo-nx-nextest-extract.js +0 -42
  316. package/dist/executors/bounded-exec/cpu-tokens.d.ts.map +0 -1
  317. package/dist/failure-summary.d.ts +0 -5
  318. package/dist/failure-summary.d.ts.map +0 -1
  319. package/dist/failure-summary.js +0 -118
  320. package/dist/nextest-extraction.d.ts +0 -117
  321. package/dist/nextest-extraction.d.ts.map +0 -1
  322. package/dist/nextest-extraction.js +0 -303
  323. package/managed/raw/patches/ttsc@0.30.4.patch +0 -2255
  324. package/src/__tests__/cargo-closure-filesets.ts +0 -94
  325. package/src/__tests__/cargo-closure-fixture.ts +0 -113
  326. package/src/__tests__/counted-cargo-process.ts +0 -286
  327. package/src/__tests__/counted-cargo.ts +0 -713
  328. package/src/__tests__/directory-change.ts +0 -27
  329. package/src/__tests__/fixture-cargo-home.ts +0 -36
  330. package/src/__tests__/fixture-nx-env.ts +0 -193
  331. package/src/__tests__/owned-installation.ts +0 -13
  332. package/src/__tests__/past-tick.ts +0 -12
  333. package/src/__tests__/progress-clock.ts +0 -43
  334. package/src/__tests__/runtime-input.ts +0 -23
  335. package/src/bin/smoo-nx-bound-failures.test.ts +0 -127
  336. package/src/bin/smoo-nx-failures.ts +0 -4
  337. package/src/bin/smoo-nx-nextest-extract.ts +0 -44
  338. package/src/bounded-test-policy.test.ts +0 -1029
  339. package/src/build-state-output-policy.test.ts +0 -115
  340. package/src/bun-bootstrap.test.ts +0 -102
  341. package/src/bun-file-packages.test.ts +0 -47
  342. package/src/cargo-closure-filesets.test.ts +0 -63
  343. package/src/cargo-closure-input.property.test.ts +0 -50
  344. package/src/cargo-closure-input.test.ts +0 -506
  345. package/src/cargo-closure-key.test.ts +0 -240
  346. package/src/cargo-resolve-cache.test.ts +0 -1181
  347. package/src/cargo-source-hash.test.ts +0 -707
  348. package/src/cargo-workspace.test.ts +0 -615
  349. package/src/cross-check-policy.test.ts +0 -316
  350. package/src/disk-command-policy.test.ts +0 -61
  351. package/src/ensure-built-receipt.test.ts +0 -279
  352. package/src/ensure-built-witness.test.ts +0 -688
  353. package/src/ensure-built.test.ts +0 -1462
  354. package/src/executors/bounded-exec/cargo-progress-host.test.ts +0 -332
  355. package/src/executors/bounded-exec/cpu-pool.test.ts +0 -684
  356. package/src/executors/bounded-exec/cpu-tokens.test.ts +0 -519
  357. package/src/executors/bounded-exec/disk-lease.test.ts +0 -219
  358. package/src/executors/bounded-exec/executor-host.test.ts +0 -800
  359. package/src/executors/bounded-exec/executor.test.ts +0 -1819
  360. package/src/executors/bounded-exec/go-progress-host.test.ts +0 -171
  361. package/src/executors/bounded-exec/hang-diagnostics.test.ts +0 -291
  362. package/src/executors/bounded-exec/progress.test.ts +0 -139
  363. package/src/executors/bounded-exec/ram-temp-held.test.ts +0 -264
  364. package/src/executors/bounded-exec/ram-temp-host.test.ts +0 -635
  365. package/src/executors/bounded-exec/ram-temp.test.ts +0 -750
  366. package/src/executors/bounded-exec/run-cpu-pool.test.ts +0 -79
  367. package/src/executors/bounded-exec/runner-hook.test.ts +0 -193
  368. package/src/executors/bounded-exec/runner-lifecycle.test.ts +0 -82
  369. package/src/executors/bounded-exec/verdict.test.ts +0 -545
  370. package/src/executors/cargo-zigbuild/executor.test.ts +0 -129
  371. package/src/executors/clean-outputs/executor.test.ts +0 -20
  372. package/src/executors/typescript-emit/executor.test.ts +0 -83
  373. package/src/failure-summary.ts +0 -119
  374. package/src/generators/bounded-test-targets/generator.test.ts +0 -138
  375. package/src/generators/bun-test-tracing/generator.test.ts +0 -250
  376. package/src/generators/create-package/generator.test.ts +0 -190
  377. package/src/generators/make-public/generator.test.ts +0 -137
  378. package/src/graph-input-contract.test.ts +0 -379
  379. package/src/host-controller-wiring.test.ts +0 -31
  380. package/src/index.test.ts +0 -3319
  381. package/src/linked-snapshots.nx.test.ts +0 -254
  382. package/src/managed-files/forgejo-artifact.test.ts +0 -395
  383. package/src/managed-files/generator.test.ts +0 -243
  384. package/src/managed-files/github-host-cache-isolation.test.ts +0 -86
  385. package/src/managed-files/json-edit.test.ts +0 -216
  386. package/src/managed-files/managed-content.test.ts +0 -166
  387. package/src/managed-files/managed-format-json.test.ts +0 -308
  388. package/src/managed-files/repo-path.test.ts +0 -172
  389. package/src/managed-files/setup-devenv-free-disk.test.ts +0 -95
  390. package/src/managed-files/trace-db-artifact.test.ts +0 -7
  391. package/src/managed-files/tree-permissions.test.ts +0 -109
  392. package/src/managed-files/tree.test.ts +0 -123
  393. package/src/manifest-hash.test.ts +0 -219
  394. package/src/nextest-code-bound.test.ts +0 -161
  395. package/src/nextest-extraction.test.ts +0 -216
  396. package/src/nextest-extraction.ts +0 -371
  397. package/src/nextest-partitions.test.ts +0 -501
  398. package/src/nx-cache-bound.test.ts +0 -109
  399. package/src/nx-cache-restore-mtime.test.ts +0 -170
  400. package/src/nx-daemon-claim.test.ts +0 -279
  401. package/src/nx-daemon-idle-cpu.test.ts +0 -80
  402. package/src/nx-daemon-idle-policy.test.ts +0 -111
  403. package/src/nx-daemon-ignore-files.test.ts +0 -210
  404. package/src/nx-daemon-root-normalization.test.ts +0 -105
  405. package/src/nx-daemon-start-never.test.ts +0 -292
  406. package/src/nx-daemon-validity.test.ts +0 -1055
  407. package/src/nx-dot-input-policy.test.ts +0 -353
  408. package/src/nx-failure-life-cycles.test.ts +0 -207
  409. package/src/nx-files-archive-racy.test.ts +0 -97
  410. package/src/nx-foreign-workspace-env.test.ts +0 -329
  411. package/src/nx-incomplete-run-summary.test.ts +0 -70
  412. package/src/nx-plugin-load-errors.test.ts +0 -120
  413. package/src/nx-project-graph-errors.test.ts +0 -70
  414. package/src/nx-project-resolution-cache.test.ts +0 -176
  415. package/src/nx-raw-inputs.test.ts +0 -166
  416. package/src/nx-resident-graph-workers.test.ts +0 -112
  417. package/src/nx-run-information.test.ts +0 -118
  418. package/src/nx-skipped-task-exit.test.ts +0 -180
  419. package/src/nx-state-location.test.ts +0 -63
  420. package/src/nx-store-resolution.test.ts +0 -81
  421. package/src/nx-task-graph-cycles.test.ts +0 -148
  422. package/src/nx-task-output-lease.test.ts +0 -550
  423. package/src/nx-use-local.test.ts +0 -105
  424. package/src/owned-installation.test.ts +0 -105
  425. package/src/package-target-policy.test.ts +0 -1014
  426. package/src/producer-receipts.test.ts +0 -285
  427. package/src/release-config-policy.test.ts +0 -311
  428. package/src/runtime-input.test.ts +0 -393
  429. package/src/serial-group-wiring.test.ts +0 -326
  430. package/src/task-history-namespace.test.ts +0 -181
  431. package/src/task-results.test.ts +0 -228
  432. package/src/test-clock-policy.test.ts +0 -338
  433. package/src/test-program.test.ts +0 -303
  434. package/src/test-timings.test.ts +0 -240
  435. package/src/test-walk-policy.test.ts +0 -620
  436. package/src/testing.test.ts +0 -509
  437. package/src/typecheck-test-policy.test.ts +0 -1468
  438. package/src/typescript-resolution.test.ts +0 -76
  439. package/src/version-actions.test.ts +0 -80
  440. package/src/workspace-config-policy.test.ts +0 -737
@@ -1,1462 +0,0 @@
1
- import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
2
- import { spawn, spawnSync } from 'node:child_process';
3
- import { chmod, cp, mkdir, mkdtemp, readdir, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises';
4
- import { tmpdir } from 'node:os';
5
- import { dirname, isAbsolute, join } from 'node:path';
6
- import { fileURLToPath } from 'node:url';
7
- import type { ProjectGraph } from 'nx/src/config/project-graph';
8
- import type { Task } from 'nx/src/config/task-graph';
9
- import type { DaemonProcessJson } from 'nx/src/daemon/cache';
10
- import { expandOutputs } from 'nx/src/native';
11
- import { getExecutorNameForTask } from 'nx/src/tasks-runner/utils';
12
- import { signalToCode } from 'nx/src/utils/exit-codes';
13
- import typia from 'typia';
14
- import { nxFixtureRoot, withNxFixture } from './__tests__/fixture-nx-env.js';
15
- import { testFileInstallation } from './__tests__/owned-installation.js';
16
- import { pastTick } from './__tests__/past-tick.js';
17
- import type { EnsureBuiltProbeResult } from './ensure-built.js';
18
- import {
19
- assignEnvironment,
20
- callerOwnsWorkspace,
21
- cliExitOutcome,
22
- compareWithArtifacts,
23
- describeError,
24
- describeMiss,
25
- ensureBuilt,
26
- firstCacheMiss,
27
- firstMovedClaim,
28
- missBeforeProbe,
29
- outputClaims,
30
- parseExecArguments,
31
- parseTargetSelector,
32
- recordedTasks,
33
- selectorTaskId,
34
- unvouched,
35
- withoutOuterTaskCacheBypass,
36
- workspaceEnvironment,
37
- workspaceFileChanges,
38
- } from './ensure-built.js';
39
- import { managedAssetsRoot } from './managed-assets.js';
40
- import { NX_LONGEST_SOCKET_NAME, ownedSocketDirectory, pidsWorkingIn } from './testing.js';
41
-
42
- function task(overrides: Partial<Task> & Pick<Task, 'id'>): Task {
43
- const [project, target] = overrides.id.split(':');
44
- return {
45
- target: { project, target },
46
- overrides: {},
47
- outputs: [],
48
- cache: true,
49
- hash: `hash-of-${overrides.id}`,
50
- ...overrides,
51
- };
52
- }
53
-
54
- describe('parseTargetSelector', () => {
55
- it('accepts project:target and project:target:configuration', () => {
56
- expect(parseTargetSelector('app:build')).toEqual({
57
- project: 'app',
58
- target: 'build',
59
- configuration: undefined,
60
- });
61
- expect(parseTargetSelector('app:build:production')).toEqual({
62
- project: 'app',
63
- target: 'build',
64
- configuration: 'production',
65
- });
66
- });
67
-
68
- it('rejects anything that is not a two or three part selector', () => {
69
- expect(parseTargetSelector('build')).toBeNull();
70
- expect(parseTargetSelector('app:')).toBeNull();
71
- expect(parseTargetSelector(':build')).toBeNull();
72
- expect(parseTargetSelector('app:build:production:extra')).toBeNull();
73
- });
74
- });
75
-
76
- describe('selectorTaskId', () => {
77
- it('is the id Nx gives the task a selector names, configuration included', () => {
78
- expect(selectorTaskId({ project: 'app', target: 'build', configuration: undefined })).toBe('app:build');
79
- expect(selectorTaskId({ project: 'app', target: 'build', configuration: 'production' })).toBe(
80
- 'app:build:production',
81
- );
82
- });
83
- });
84
-
85
- describe('parseExecArguments', () => {
86
- function usageOf(args: readonly string[]): string {
87
- const parsed = parseExecArguments(args);
88
- if (parsed.ok) {
89
- throw new Error(`${args.join(' ')} parsed as ${JSON.stringify(parsed.invocation)}`);
90
- }
91
- return parsed.usage;
92
- }
93
-
94
- it('reads the target, a workspace root in either spelling, and the binary with its arguments', () => {
95
- expect(parseExecArguments(['app:build', '--workspace-root', '/w', '--', './cli', '--flag'])).toEqual({
96
- ok: true,
97
- invocation: { target: 'app:build', workspaceRoot: '/w', command: ['./cli', '--flag'] },
98
- });
99
- expect(parseExecArguments(['--workspace-root=/w', 'app:build:production'])).toEqual({
100
- ok: true,
101
- invocation: { target: 'app:build:production', workspaceRoot: '/w', command: [] },
102
- });
103
- });
104
-
105
- it('rejects a malformed invocation, naming the mistake', () => {
106
- expect(usageOf(['app:build', '--'])).toContain('no binary given');
107
- expect(usageOf(['build', '--', './report'])).toContain('not a project:target');
108
- expect(usageOf(['app:build', '--', 'report'])).toContain('not a name to look up on PATH');
109
- expect(usageOf(['app:build', 'lib:build'])).toContain('more than one target');
110
- expect(usageOf(['app:build', '--workspace-root'])).toContain('--workspace-root needs a directory');
111
- expect(usageOf(['app:build', '--watch'])).toContain('unknown flag --watch');
112
- expect(usageOf([])).toContain('no project:target given');
113
- });
114
- });
115
-
116
- describe('describeError', () => {
117
- it('prints the message of a plain-object Nx rejection, never [object Object]', () => {
118
- expect(describeError({ stack: 'synthetic stack', message: 'daemon belongs to a different workspace' })).toBe(
119
- 'daemon belongs to a different workspace',
120
- );
121
- });
122
-
123
- it('prints an Error by its message, a string as itself, and anything else inspected on one line', () => {
124
- expect(describeError(new Error('boom'))).toBe('boom');
125
- expect(describeError('plain')).toBe('plain');
126
- expect(describeError({ code: 7, nested: { deep: true } })).toBe('{ code: 7, nested: { deep: true } }');
127
- });
128
- });
129
-
130
- describe('firstCacheMiss', () => {
131
- const cached = new Map([
132
- ['hash-of-app:build', 0],
133
- ['hash-of-lib:build', 0],
134
- ]);
135
-
136
- it('clears a graph whose every task is a recorded success', () => {
137
- expect(firstCacheMiss([task({ id: 'lib:build' }), task({ id: 'app:build' })], cached)).toBeNull();
138
- });
139
-
140
- it('reports the uncacheable task rather than looking it up', () => {
141
- expect(firstCacheMiss([task({ id: 'app:build', cache: false })], cached)).toEqual({
142
- kind: 'uncacheable',
143
- taskId: 'app:build',
144
- });
145
- });
146
-
147
- it('reports a task that could not be hashed', () => {
148
- expect(firstCacheMiss([task({ id: 'app:build', hash: undefined })], cached)).toEqual({
149
- kind: 'unhashable',
150
- taskId: 'app:build',
151
- });
152
- });
153
-
154
- it('reports a task whose current inputs are not in the cache', () => {
155
- expect(firstCacheMiss([task({ id: 'other:build' })], cached)).toEqual({
156
- kind: 'not-cached',
157
- taskId: 'other:build',
158
- });
159
- });
160
-
161
- it('refuses to replay a cached failure', () => {
162
- const failures = new Map([['hash-of-app:build', 3]]);
163
- expect(firstCacheMiss([task({ id: 'app:build' })], failures)).toEqual({
164
- kind: 'cached-failure',
165
- taskId: 'app:build',
166
- code: 3,
167
- });
168
- });
169
-
170
- it('names the first failing task in graph order', () => {
171
- const tasks = [task({ id: 'lib:build' }), task({ id: 'app:build', cache: false }), task({ id: 'other:build' })];
172
- expect(firstCacheMiss(tasks, cached)).toEqual({ kind: 'uncacheable', taskId: 'app:build' });
173
- });
174
- });
175
-
176
- describe('recordedTasks', () => {
177
- // The project graph Nx hands the probe, reduced to the executors it is asked for.
178
- const graph: ProjectGraph = {
179
- nodes: {
180
- app: {
181
- name: 'app',
182
- type: 'app',
183
- data: {
184
- root: 'packages/app',
185
- targets: {
186
- build: { executor: 'nx:run-commands' },
187
- // A command-less target that only names dependencies, as Nx normalizes it.
188
- stage: { executor: 'nx:noop' },
189
- ship: { executor: 'nx:run-commands' },
190
- deploy: { executor: 'nx:run-commands' },
191
- },
192
- },
193
- },
194
- },
195
- dependencies: {},
196
- };
197
- const executorOf = (entry: Task) => getExecutorNameForTask(entry, graph);
198
- const records = new Map([
199
- ['hash-of-app:build', 0],
200
- ['hash-of-app:ship', 0],
201
- ]);
202
-
203
- it('needs no cache record for an uncacheable nx:noop aggregate, whose dependencies answer for it', () => {
204
- const tasks = [task({ id: 'app:build' }), task({ id: 'app:stage', cache: false }), task({ id: 'app:ship' })];
205
- const recorded = recordedTasks(tasks, executorOf);
206
- expect(recorded.map(({ id }) => id)).toEqual(['app:build', 'app:ship']);
207
- expect(firstCacheMiss(recorded, records)).toBeNull();
208
- });
209
-
210
- it('still holds an uncacheable task with a command to account', () => {
211
- const tasks = [task({ id: 'app:build' }), task({ id: 'app:deploy', cache: false })];
212
- expect(firstCacheMiss(recordedTasks(tasks, executorOf), records)).toEqual({
213
- kind: 'uncacheable',
214
- taskId: 'app:deploy',
215
- });
216
- });
217
- });
218
-
219
- describe('outputClaims', () => {
220
- it('claims the declared outputs of every hashed task that declares any, under its hash', () => {
221
- const tasks = [
222
- task({ id: 'lib:build', outputs: ['packages/lib/dist'] }),
223
- task({ id: 'app:stage' }),
224
- task({ id: 'app:build', outputs: ['packages/app/dist'], hash: undefined }),
225
- ];
226
- expect(outputClaims(tasks)).toEqual([
227
- { taskId: 'lib:build', outputs: ['packages/lib/dist'], hash: 'hash-of-lib:build' },
228
- ]);
229
- });
230
- });
231
-
232
- describe('unvouched', () => {
233
- const tasks = [task({ id: 'lib:build', outputs: ['lib/dist'] }), task({ id: 'app:build', outputs: ['app/dist'] })];
234
-
235
- it('clears outputs the daemon vouches for', () => {
236
- expect(unvouched(tasks, [true, true])).toEqual([]);
237
- });
238
-
239
- it('keeps the tasks whose outputs the daemon does not vouch for', () => {
240
- expect(unvouched(tasks, [true, false]).map(({ id }) => id)).toEqual(['app:build']);
241
- });
242
-
243
- it('treats a missing verdict as unvouched rather than as a hit', () => {
244
- expect(unvouched(tasks, [true]).map(({ id }) => id)).toEqual(['app:build']);
245
- expect(unvouched(tasks, []).map(({ id }) => id)).toEqual(['lib:build', 'app:build']);
246
- });
247
- });
248
-
249
- describe('compareWithArtifacts', () => {
250
- it('reuses a verified two-tree inventory without expanding or rereading artifact bytes', async () => {
251
- // An inventory recorded in the tick its fixture was written in is unproven, and the next comparison is a full one.
252
- await pastTick();
253
- const path = join(root, 'verified.json');
254
- let walks = 0;
255
- const expand: typeof expandOutputs = (...args) => {
256
- walks += 1;
257
- return expandOutputs(...args);
258
- };
259
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expand, path).kind).toBe('restorable');
260
- expect(walks).toBeGreaterThan(0);
261
- walks = 0;
262
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expand, path).kind).toBe('restorable');
263
- expect(walks).toBe(0);
264
- });
265
-
266
- it('invalidates verified equality for output or cache mutations even with restored mtime', async () => {
267
- const path = join(root, 'verified.json');
268
- const artifact = artifacts().get(claim.hash);
269
- if (artifact === undefined) throw new Error('Missing cache artifact in output-mutation fixture');
270
- const expected = join(artifact.outputsPath, 'packages/app/dist/marker.txt');
271
- for (const file of [marker(), expected]) {
272
- await writeFile(marker(), 'built\nlib\n');
273
- await writeFile(expected, 'built\nlib\n');
274
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
275
- const { stat, utimes } = await import('node:fs/promises');
276
- const original = await stat(file);
277
- await writeFile(file, 'BUILT\nLIB\n');
278
- await utimes(file, original.atime, original.mtime);
279
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path)).toEqual({
280
- kind: 'stale-outputs',
281
- taskId: 'app:build',
282
- });
283
- }
284
- });
285
-
286
- it('invalidates inventories for deletion, permission changes, parent symlinks and added directory members', async () => {
287
- const path = join(root, 'verified.json');
288
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
289
- await chmod(marker(), 0o700);
290
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('stale-outputs');
291
- await chmod(marker(), 0o644);
292
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
293
- await writeFile(join(workspace(), 'packages/app/dist/added'), 'added');
294
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('stale-outputs');
295
- await rm(join(workspace(), 'packages/app/dist/added'));
296
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
297
- await rm(marker());
298
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('stale-outputs');
299
- await writeFile(marker(), 'built\nlib\n');
300
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
301
- const { rename } = await import('node:fs/promises');
302
- await rename(join(workspace(), 'packages/app'), join(workspace(), 'packages/real-app'));
303
- await symlink('real-app', join(workspace(), 'packages/app'));
304
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('stale-outputs');
305
- });
306
-
307
- it('falls back to real comparison for missing/unreadable witness and a changed cache binding', async () => {
308
- const path = join(root, 'verified.json');
309
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
310
- await chmod(path, 0);
311
- try {
312
- expect(compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs, path).kind).toBe('restorable');
313
- } finally {
314
- await chmod(path, 0o600);
315
- }
316
- const renamed = join(root, 'cache', 'other', 'outputs');
317
- await mkdir(join(renamed, 'packages/app/dist'), { recursive: true });
318
- await writeFile(join(renamed, 'packages/app/dist/marker.txt'), 'other');
319
- expect(
320
- compareWithArtifacts(workspace(), [claim], new Map([[claim.hash, { outputsPath: renamed }]]), expandOutputs, path)
321
- .kind,
322
- ).toBe('stale-outputs');
323
- });
324
- // A working tree and the artifact Nx's local cache holds for the claim's
325
- // hash, laid out as Nx stores one: the outputs under their workspace paths.
326
- let root = '';
327
- const claim = { taskId: 'app:build', outputs: ['packages/app/dist'], hash: 'app-hash' };
328
- const workspace = () => join(root, 'workspace');
329
- const marker = () => join(workspace(), 'packages', 'app', 'dist', 'marker.txt');
330
- const artifacts = () => new Map([[claim.hash, { outputsPath: join(root, 'cache', claim.hash, 'outputs') }]]);
331
- const compare = () => compareWithArtifacts(workspace(), [claim], artifacts(), expandOutputs);
332
-
333
- beforeEach(async () => {
334
- root = await realpath(await mkdtemp(join(tmpdir(), 'ensure-built-artifact-')));
335
- for (const base of [workspace(), join(root, 'cache', claim.hash, 'outputs')]) {
336
- await mkdir(join(base, 'packages', 'app', 'dist'), { recursive: true });
337
- await writeFile(join(base, 'packages', 'app', 'dist', 'marker.txt'), 'built\nlib\n');
338
- }
339
- });
340
-
341
- afterEach(async () => {
342
- await rm(root, { recursive: true, force: true });
343
- });
344
-
345
- it('vouches for a working tree that restoring the artifact would leave unchanged', () => {
346
- expect(compare().kind).toBe('restorable');
347
- });
348
-
349
- it('never vouches for rewritten output bytes', async () => {
350
- // Same length, different bytes: only a content comparison can tell.
351
- await writeFile(marker(), 'BUILT\nLIB\n');
352
- expect(compare()).toEqual({ kind: 'stale-outputs', taskId: 'app:build' });
353
- });
354
-
355
- it('runs again once a recorded output is gone from the working tree', async () => {
356
- await rm(marker());
357
- expect(compare()).toEqual({ kind: 'stale-outputs', taskId: 'app:build' });
358
- });
359
-
360
- it('runs again when the cache holds no artifact for the hash', () => {
361
- expect(compareWithArtifacts(workspace(), [claim], new Map(), expandOutputs)).toEqual({
362
- kind: 'stale-outputs',
363
- taskId: 'app:build',
364
- });
365
- });
366
-
367
- it('notices an output written after it was compared', async () => {
368
- const verdict = compare();
369
- if (verdict.kind !== 'restorable') {
370
- throw new Error(`expected a restorable tree, got ${JSON.stringify(verdict)}`);
371
- }
372
- expect(firstMovedClaim(verdict.observed)).toBeNull();
373
- await writeFile(marker(), 'built\nlib\nlater\n');
374
- expect(firstMovedClaim(verdict.observed)).toBe('app:build');
375
- });
376
- });
377
-
378
- describe('workspaceFileChanges', () => {
379
- it("splits the disk's file table from the daemon's into created, updated and deleted files", () => {
380
- const daemon = [
381
- { file: 'packages/lib/source.txt', hash: 'lib' },
382
- { file: 'packages/lib/added.txt', hash: 'added' },
383
- { file: 'packages/app/source.txt', hash: 'app' },
384
- ];
385
- const disk = [
386
- { file: 'packages/lib/source.txt', hash: 'lib changed' },
387
- { file: 'packages/app/source.txt', hash: 'app' },
388
- { file: 'packages/lib/new.txt', hash: 'new' },
389
- ];
390
- expect(workspaceFileChanges(daemon, disk)).toEqual({
391
- created: ['packages/lib/new.txt'],
392
- updated: ['packages/lib/source.txt'],
393
- deleted: ['packages/lib/added.txt'],
394
- });
395
- });
396
- });
397
-
398
- describe('missBeforeProbe', () => {
399
- it("drops an outer Nx task's cache bypass, which describes that task rather than the nested target", () => {
400
- const outer = {
401
- NX_TASK_TARGET_PROJECT: 'nx-plugin',
402
- NX_TASK_TARGET_TARGET: 'test',
403
- NX_SKIP_NX_CACHE: 'true',
404
- NX_DISABLE_NX_CACHE: 'true',
405
- };
406
- const nested = withoutOuterTaskCacheBypass(outer);
407
- expect(nested).toEqual({ NX_TASK_TARGET_PROJECT: 'nx-plugin', NX_TASK_TARGET_TARGET: 'test' });
408
- expect(missBeforeProbe(nested, 'app:build')).toBeNull();
409
- });
410
-
411
- it('honors a cache bypass the caller asked for outside an Nx task child', () => {
412
- for (const env of [{ NX_SKIP_NX_CACHE: 'true' }, { NX_DISABLE_NX_CACHE: 'true' }]) {
413
- const caller = withoutOuterTaskCacheBypass(env);
414
- expect(caller).toEqual(env);
415
- expect(missBeforeProbe(caller, 'app:build')).toEqual({ kind: 'cache-disabled', taskId: 'app:build' });
416
- }
417
- });
418
-
419
- it('leaves current input and artifact evaluation to the probe', () => {
420
- expect(missBeforeProbe({}, 'app:build')).toBeNull();
421
- });
422
- });
423
-
424
- describe('describeMiss', () => {
425
- it('names the task in every reason', () => {
426
- const reasons = [
427
- describeMiss({ kind: 'uncacheable', taskId: 'app:build' }),
428
- describeMiss({ kind: 'unhashable', taskId: 'app:build' }),
429
- describeMiss({ kind: 'not-cached', taskId: 'app:build' }),
430
- describeMiss({ kind: 'cached-failure', taskId: 'app:build', code: 7 }),
431
- describeMiss({ kind: 'stale-outputs', taskId: 'app:build' }),
432
- describeMiss({ kind: 'cache-disabled', taskId: 'app:build' }),
433
- describeMiss({ kind: 'no-daemon', taskId: 'app:build' }),
434
- ];
435
- for (const reason of reasons) {
436
- expect(reason).toContain('app:build');
437
- }
438
- expect(reasons[3]).toContain('7');
439
- });
440
- });
441
-
442
- describe('cliExitOutcome', () => {
443
- const reason = { kind: 'no-daemon', taskId: 'app:build' } as const;
444
-
445
- it('treats a clean exit as a completed build', () => {
446
- expect(cliExitOutcome(reason, { code: 0, signal: null }, signalToCode)).toEqual({
447
- disposition: 'built',
448
- reason,
449
- });
450
- });
451
-
452
- it('forwards a nonzero exit code verbatim', () => {
453
- expect(cliExitOutcome(reason, { code: 3, signal: null }, signalToCode)).toEqual({
454
- disposition: 'failed',
455
- reason,
456
- exitCode: 3,
457
- signal: null,
458
- });
459
- });
460
-
461
- it('reports a signal as a signal, not as a plain failure', () => {
462
- expect(cliExitOutcome(reason, { code: null, signal: 'SIGTERM' }, signalToCode)).toEqual({
463
- disposition: 'failed',
464
- reason,
465
- exitCode: signalToCode('SIGTERM'),
466
- signal: 'SIGTERM',
467
- });
468
- expect(cliExitOutcome(reason, { code: null, signal: 'SIGINT' }, signalToCode).disposition).toBe('failed');
469
- });
470
- });
471
-
472
- describe('the environment Nx runs under', () => {
473
- const caller = {
474
- PATH: '/usr/bin',
475
- NX_SOCKET_DIR: '/tmp/other-sock',
476
- NX_DAEMON_SOCKET_DIR: '/tmp/other-daemon-sock',
477
- NX_WORKSPACE_DATA_DIRECTORY: '/shared/workspace-data',
478
- NX_CACHE_DIRECTORY: '/shared/cache',
479
- };
480
- let root = '';
481
- const workspace = () => join(root, 'workspace');
482
- const elsewhere = () => join(root, 'elsewhere');
483
-
484
- beforeEach(async () => {
485
- root = await realpath(await mkdtemp(join(tmpdir(), 'ensure-built-caller-')));
486
- await mkdir(join(workspace(), 'packages'), { recursive: true });
487
- await mkdir(elsewhere());
488
- await writeFile(join(workspace(), 'nx.json'), '{}');
489
- });
490
-
491
- afterEach(async () => {
492
- await rm(root, { recursive: true, force: true });
493
- });
494
-
495
- it("passes none of another workspace's socket, database or cache to the root's Nx", () => {
496
- // A devenv shell set up for another workspace, entering this root from outside it.
497
- const owns = callerOwnsWorkspace(caller, elsewhere(), workspace());
498
- expect(owns).toBe(false);
499
- expect(workspaceEnvironment(caller, workspace(), owns)).toEqual({
500
- PATH: '/usr/bin',
501
- NX_WORKSPACE_ROOT_PATH: workspace(),
502
- NX_USE_LOCAL: 'true',
503
- });
504
- });
505
-
506
- it('keeps the socket, database and cache of a caller standing in the root it was set up for', () => {
507
- const owns = callerOwnsWorkspace(caller, join(workspace(), 'packages'), workspace());
508
- expect(owns).toBe(true);
509
- expect(workspaceEnvironment({ ...caller, NX_USE_LOCAL: 'false' }, workspace(), owns)).toEqual({
510
- ...caller,
511
- NX_WORKSPACE_ROOT_PATH: workspace(),
512
- NX_USE_LOCAL: 'true',
513
- });
514
- });
515
-
516
- it("takes the caller's workspace from NX_WORKSPACE_ROOT_PATH, relative to where it stands, over its nx.json", () => {
517
- expect(callerOwnsWorkspace({ NX_WORKSPACE_ROOT_PATH: '../workspace' }, elsewhere(), workspace())).toBe(true);
518
- expect(callerOwnsWorkspace({ NX_WORKSPACE_ROOT_PATH: elsewhere() }, workspace(), workspace())).toBe(false);
519
- });
520
-
521
- it("leaves the caller's environment exactly as it was, whatever Nx set, changed or removed", () => {
522
- const callerEnv = { PATH: '/usr/bin', NX_SKIP_NX_CACHE: 'caller-skip', NX_DISABLE_NX_CACHE: 'caller-disable' };
523
- const env: NodeJS.ProcessEnv = {
524
- PATH: '/usr/bin',
525
- NX_WORKSPACE_ROOT_PATH: workspace(),
526
- NX_STREAM_OUTPUT: 'true',
527
- NX_SKIP_NX_CACHE: 'false',
528
- };
529
- assignEnvironment(env, callerEnv);
530
- expect(env).toEqual(callerEnv);
531
- });
532
-
533
- it('retains a real socket-owner mkdir refusal before any target can run', async () => {
534
- const blocker = join(root, 'ordinary-file');
535
- const marker = join(workspace(), 'target-ran');
536
- await writeFile(blocker, 'not a directory');
537
- await writeFile(
538
- join(workspace(), 'project.json'),
539
- JSON.stringify({
540
- name: 'app',
541
- targets: { build: { executor: 'nx:run-commands', options: { command: 'touch target-ran' } } },
542
- }),
543
- );
544
- const saved = { ...process.env };
545
- try {
546
- process.env.DEVENV_RUNTIME = join(blocker, 'runtime');
547
- process.env.NX_WORKSPACE_ROOT_PATH = elsewhere();
548
- process.env.NX_SOCKET_DIR = elsewhere();
549
- const result = await ensureBuilt({ target: 'app:build', cwd: workspace() });
550
- expect(result.disposition).toBe('failed');
551
- if (result.disposition !== 'failed') throw new Error('the socket owner must refuse before the target runs');
552
- expect(result.reason.kind).toBe('workspace-socket');
553
- if (result.reason.kind !== 'workspace-socket') throw new Error('the refusal must retain its socket owner');
554
- expect(result.reason.taskId).toBe('app:build');
555
- expect(result.reason.workspaceRoot).toBe(workspace());
556
- expect(result.reason.detail).toContain('socket owner ended with exit');
557
- expect(result.reason.detail).toContain('mkdir:');
558
- expect(result.reason.detail).toContain(blocker);
559
- expect(result.exitCode).not.toBe(0);
560
- expect(result.signal).toBeNull();
561
- expect(await readFile(blocker, 'utf8')).toBe('not a directory');
562
- await expect(readFile(marker)).rejects.toMatchObject({ code: 'ENOENT' });
563
- } finally {
564
- assignEnvironment(process.env, saved);
565
- }
566
- });
567
- });
568
-
569
- const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
570
- const binEntry = join(packageRoot, 'src', 'bin', 'smoo-nx-exec.ts');
571
- const builtBinEntry = join(packageRoot, 'dist', 'bin', 'smoo-nx-exec.js');
572
- /** The Nx CLI of a fixture workspace's own installation. */
573
- const nxEntry = (workspace: string) => join(workspace, 'node_modules', '.bin', 'nx');
574
- const MARKER = 'EXEC_OK';
575
- /**
576
- * Reports what the exec'd process inherited: the marker proves execve
577
- * happened, the cwd that it kept the caller's directory, and the root path
578
- * that the wrapper took its Nx configuration back out of the environment.
579
- */
580
- const REPORT = `#!/bin/sh\necho ${MARKER} "$@"\necho "cwd=$PWD"\necho "NX_WORKSPACE_ROOT_PATH=\${NX_WORKSPACE_ROOT_PATH:-unset}"\n`;
581
-
582
- interface BinRun {
583
- readonly code: number | null;
584
- readonly signal: NodeJS.Signals | null;
585
- readonly stdout: string;
586
- readonly stderr: string;
587
- }
588
-
589
- /**
590
- * This process's environment without the `NX_*` an outer
591
- * `nx run nx-plugin:test` exported to it (its cache bypass and task identity
592
- * would reconfigure the fixture's Nx), and without NO_COLOR, which beside that
593
- * outer Nx's FORCE_COLOR makes Bun warn on stderr, where a hit must be silent.
594
- */
595
- function childEnvironment(env: Readonly<Record<string, string>>): Record<string, string> {
596
- const childEnv: Record<string, string> = {};
597
- for (const [key, value] of Object.entries(process.env)) {
598
- if (value !== undefined && !key.startsWith('NX_') && key !== 'NO_COLOR') {
599
- childEnv[key] = value;
600
- }
601
- }
602
- return { ...childEnv, CI: '', ...env };
603
- }
604
-
605
- /**
606
- * The wrapper runs in a child process because `execve` replaces the process,
607
- * which is the behaviour under test.
608
- */
609
- function run(
610
- runtime: 'bun' | 'node',
611
- entry: string,
612
- cwd: string,
613
- args: readonly string[],
614
- env: Readonly<Record<string, string>>,
615
- ): Promise<BinRun> {
616
- const child = spawn(runtime, [entry, ...args], {
617
- cwd,
618
- env: childEnvironment(env),
619
- stdio: ['ignore', 'pipe', 'pipe'],
620
- });
621
- let stdout = '';
622
- let stderr = '';
623
- child.stdout.setEncoding('utf8').on('data', (text: string) => {
624
- stdout += text;
625
- });
626
- child.stderr.setEncoding('utf8').on('data', (text: string) => {
627
- stderr += text;
628
- });
629
- const { promise, resolve, reject } = Promise.withResolvers<BinRun>();
630
- child.once('error', reject);
631
- child.once('close', (code, signal) => resolve({ code, signal, stdout, stderr }));
632
- return promise;
633
- }
634
-
635
- async function writeExecutable(path: string, content: string): Promise<void> {
636
- await writeFile(path, content);
637
- await chmod(path, 0o755);
638
- }
639
-
640
- describe('smoo-nx-exec without a daemon', () => {
641
- // A workspace whose `nx` is a script standing in for the CLI. With the
642
- // daemon off, the wrapper loads no Nx at all and hands the target straight
643
- // to that CLI, so what runs here is the wrapper's own process handling —
644
- // stdio, exit status, signals, cwd, environment, execve — and no Nx.
645
- let workspace = '';
646
- const daemonless = { NX_DAEMON: 'false' };
647
- const wrapper = (cwd: string, args: readonly string[], env: Readonly<Record<string, string>> = {}) =>
648
- run('bun', binEntry, cwd, args, { ...daemonless, ...env });
649
-
650
- beforeAll(async () => {
651
- workspace = await nxFixtureRoot('ensure-built-cli-');
652
- await mkdir(join(workspace, 'node_modules', '.bin'), { recursive: true });
653
- await mkdir(join(workspace, 'packages', 'app'), { recursive: true });
654
- await writeFile(join(workspace, 'nx.json'), '{}');
655
- // `nx run <task> --outputStyle=stream`, as the wrapper starts it on a miss.
656
- await writeExecutable(
657
- join(workspace, 'node_modules', '.bin', 'nx'),
658
- '#!/bin/sh\necho "nx run $2"\ncase "$2" in\n app:broken) exit 3 ;;\n app:killed) kill -TERM $$ ;;\nesac\n',
659
- );
660
- await writeExecutable(join(workspace, 'report'), REPORT);
661
- });
662
-
663
- afterAll(async () => {
664
- if (workspace) {
665
- await rm(workspace, { recursive: true, force: true });
666
- }
667
- });
668
-
669
- it('shows the run on stderr, then execs the binary with stdout its own', async () => {
670
- const result = await wrapper(workspace, ['app:build', '--', './report', 'one']);
671
- expect(result.code, result.stderr).toBe(0);
672
- // Stdout is the exec'd binary's and holds nothing else, or `wrapper | jq` reads Nx's log as data.
673
- expect(result.stderr).toContain('nx run app:build');
674
- expect(result.stdout).toBe(`${MARKER} one\ncwd=${workspace}\nNX_WORKSPACE_ROOT_PATH=unset\n`);
675
- });
676
-
677
- it('without a binary, shows the run on stderr, says why it ran, and exits 0', async () => {
678
- const result = await wrapper(workspace, ['app:build'], { NX_VERBOSE_LOGGING: 'true' });
679
- expect(result.code, result.stderr).toBe(0);
680
- expect(result.stdout).toBe('');
681
- expect(result.stderr).toContain('nx run app:build');
682
- expect(result.stderr).toContain(
683
- `smoo-nx-exec: ran app:build because ${describeMiss({ kind: 'no-daemon', taskId: 'app:build' })}`,
684
- );
685
- });
686
-
687
- it("forwards a failing target's exit code and never execs", async () => {
688
- const result = await wrapper(workspace, ['app:broken', '--', './report']);
689
- expect(result.code).toBe(3);
690
- expect(result.stderr).toContain('nx run app:broken');
691
- expect(result.stdout).toBe('');
692
- });
693
-
694
- it('re-raises the signal that killed nx instead of flattening it to a code', async () => {
695
- const result = await wrapper(workspace, ['app:killed', '--', './report']);
696
- expect(result.signal).toBe('SIGTERM');
697
- expect(result.stdout).toBe('');
698
- });
699
-
700
- it("leaves the exec'd binary the caller's cwd, with the binary named relative to it", async () => {
701
- const app = join(workspace, 'packages', 'app');
702
- const result = await wrapper(app, ['app:build', '--workspace-root', workspace, '--', '../../report']);
703
- expect(result.code, result.stderr).toBe(0);
704
- expect(result.stdout).toBe(`${MARKER}\ncwd=${app}\nNX_WORKSPACE_ROOT_PATH=unset\n`);
705
- });
706
-
707
- it("hands the exec'd binary blocking stdio, so a pipe its output fills is never cut", async () => {
708
- // Node leaves a pipe O_NONBLOCK on macOS, and the flag belongs to the open file description, so
709
- // it survives execve: the binary's writes then fail with EAGAIN once the pipe holds 64 KiB and
710
- // nobody is reading. A reader that starts late is what makes the pipe fill.
711
- const flood = join(workspace, 'flood');
712
- await writeExecutable(flood, '#!/bin/sh\nhead -c 300000 /dev/zero\n');
713
- const piped = Bun.spawn(
714
- ['sh', '-c', `"$0" "$1" app:build -- ./flood | { sleep 1; tr -cd '\\000' | wc -c; }`, 'node', builtBinEntry],
715
- { cwd: workspace, env: childEnvironment(daemonless), stdout: 'pipe', stderr: 'pipe' },
716
- );
717
- const received = (await new Response(piped.stdout).text()).trim();
718
- expect(await piped.exited).toBe(0);
719
- expect(received).toBe('300000');
720
- });
721
- });
722
-
723
- /** Fixture Nx configuration: its cache and database stay under its removable root. */
724
- const FIXTURE_NX_JSON = {
725
- useDaemonProcess: true,
726
- cacheDirectory: '.nx/cache',
727
- plugins: ['@smoothbricks/nx-plugin'],
728
- };
729
-
730
- /** The Nx installation this file's fixtures share: one copy kept for this file, not one per fixture. */
731
- const installation = testFileInstallation('ensure-built-installation');
732
-
733
- /**
734
- * Two projects, `app:build` reading `lib:build`'s outputs through
735
- * `dependentTasksOutputFiles`: Nx's runner-warmup hasher leaves such a task
736
- * unhashed, so a probe that used it instead of hashing every task would call
737
- * this graph 'unhashable' and never hit. Each lib build appends to `builds`,
738
- * outside the workspace: a log inside it would be an undeclared output the
739
- * snapshot diff rightly reports as a changed input.
740
- */
741
- async function writeTwoProjectWorkspace(workspace: string, builds: string, publishReceipts = false): Promise<void> {
742
- // Cowshed's scratch is ignored by its enclosing Git checkout. This is an
743
- // independent Nx workspace: its own Git boundary keeps the daemon's
744
- // ignore-aware watcher from dropping all of its source changes.
745
- expect(Bun.spawnSync(['git', 'init', '--quiet', workspace]).exitCode).toBe(0);
746
- await writeFile(join(workspace, '.gitignore'), '.nx\nnode_modules\npackages/*/dist\n');
747
- await mkdir(join(workspace, 'packages', 'app'), { recursive: true });
748
- await mkdir(join(workspace, 'packages', 'lib'), { recursive: true });
749
- await symlink(await installation.nodeModules(), join(workspace, 'node_modules'), 'dir');
750
- const nxJson = publishReceipts
751
- ? {
752
- ...FIXTURE_NX_JSON,
753
- plugins: [{ plugin: '@smoothbricks/nx-plugin', options: { producerReceipts: { targets: ['app:build'] } } }],
754
- }
755
- : FIXTURE_NX_JSON;
756
- await writeFile(join(workspace, 'nx.json'), JSON.stringify(nxJson));
757
- await writeFile(
758
- join(workspace, 'packages', 'lib', 'project.json'),
759
- JSON.stringify({
760
- name: 'lib',
761
- targets: {
762
- build: {
763
- executor: 'nx:run-commands',
764
- cache: true,
765
- inputs: ['{projectRoot}/source.txt'],
766
- outputs: ['{projectRoot}/dist'],
767
- options: {
768
- command: `mkdir -p dist && cp source.txt dist/lib.txt && cat dist/lib.txt >> ${builds}`,
769
- cwd: '{projectRoot}',
770
- },
771
- },
772
- },
773
- }),
774
- );
775
- await writeFile(join(workspace, 'packages', 'lib', 'source.txt'), 'lib\n');
776
- await writeFile(
777
- join(workspace, 'packages', 'app', 'project.json'),
778
- JSON.stringify({
779
- name: 'app',
780
- targets: {
781
- build: {
782
- executor: 'nx:run-commands',
783
- cache: true,
784
- inputs: ['{projectRoot}/source.txt', { dependentTasksOutputFiles: '**/*' }],
785
- outputs: ['{projectRoot}/dist'],
786
- dependsOn: ['^build'],
787
- options: {
788
- command: 'mkdir -p dist && cat source.txt ../lib/dist/lib.txt > dist/marker.txt',
789
- cwd: '{projectRoot}',
790
- },
791
- },
792
- },
793
- implicitDependencies: ['lib'],
794
- }),
795
- );
796
- await writeFile(join(workspace, 'packages', 'app', 'source.txt'), 'built\n');
797
- await writeExecutable(join(workspace, 'report'), REPORT);
798
- }
799
-
800
- describe('smoo-nx-exec with a fresh daemon', () => {
801
- // The fixtures share one installation because none writes into it; otherwise one fixture's write would be
802
- // another's input. Its identity when retired must be the one it was made with.
803
- afterAll(() => installation.retire());
804
-
805
- /**
806
- * The socket directory a call entered from another workspace's shell is given for `workspace`, or null where the
807
- * packaged socket owner has no managed shell runtime to bind in (`DEVENV_RUNTIME` unset), and Nx keeps its own
808
- * defaults. Found by running that same packaged script in the workspace, as the call does, with none of the
809
- * caller's Nx state: neither the directory nor how it is named is restated here.
810
- */
811
- const providerSocketDirectory = (workspace: string): string | null => {
812
- const runtime = process.env.DEVENV_RUNTIME;
813
- if (runtime === undefined || runtime === '') return null;
814
- expect(isAbsolute(runtime), `DEVENV_RUNTIME=${runtime} must name the managed shell runtime directory`).toBe(true);
815
- const script = join(managedAssetsRoot, 'raw/tooling/direnv/nx-socket-dir.sh');
816
- const owner = spawnSync('/bin/sh', ['-c', '. "$1" && printf %s "$NX_SOCKET_DIR"', 'sh', script], {
817
- cwd: workspace,
818
- env: { ...childEnvironment({}), PWD: workspace },
819
- encoding: 'utf8',
820
- });
821
- expect(owner.status, `${script} in ${workspace}\n${owner.error?.message ?? ''}${owner.stderr}`).toBe(0);
822
- expect(isAbsolute(owner.stdout), `${script} named ${JSON.stringify(owner.stdout)}`).toBe(true);
823
- return owner.stdout;
824
- };
825
-
826
- // These integration controls run real Nx because their subject is the daemon:
827
- // the daemon a probe starts holds no output records, so every output must be
828
- // vouched for by comparing the working tree with Nx's cache artifact. The
829
- // daemon it starts is also the one whose socket is in question, so the same
830
- // lifetime answers where a root entered from another workspace's shell binds.
831
- it('reuses authoritative graphs without assuming an unstable generation republishes its witness', async () => {
832
- await withNxFixture(
833
- 'ensure-built-graph-witness-',
834
- async ({ root, workspace, socketDirectory }) => {
835
- const builds = join(root, 'lib-builds.log');
836
- await writeTwoProjectWorkspace(workspace, builds);
837
- // The workspace takes its own copy of TypeScript, which the census resolves from the workspace root, so the
838
- // installation the script below writes into is the fixture's, not the copy this file's fixtures share.
839
- const shared = await realpath(join(workspace, 'node_modules'));
840
- await rm(join(workspace, 'node_modules'));
841
- await mkdir(join(workspace, 'node_modules'));
842
- for (const entry of await readdir(shared)) {
843
- if (entry !== 'typescript') await symlink(join(shared, entry), join(workspace, 'node_modules', entry));
844
- }
845
- await cp(await realpath(join(shared, 'typescript')), join(workspace, 'node_modules', 'typescript'), {
846
- recursive: true,
847
- });
848
- const built = await run(
849
- 'node',
850
- nxEntry(workspace),
851
- workspace,
852
- ['run-many', '-t', 'build', '-p', 'app', '--outputStyle=static-failures-only'],
853
- { NX_DAEMON: 'false', NX_WORKSPACE_ROOT_PATH: workspace },
854
- );
855
- expect(built.code, built.stdout + built.stderr).toBe(0);
856
- const reuseEntry = join(root, 'graph-reuse.ts');
857
- const resultsPath = join(root, 'graph-checks.json');
858
- await writeFile(
859
- reuseEntry,
860
- `
861
- import assert from 'node:assert/strict';
862
- import { existsSync } from 'node:fs';
863
- import { createRequire } from 'node:module';
864
- import { chmod, readFile, rename, rm, stat, utimes, writeFile } from 'node:fs/promises';
865
- import { join } from 'node:path';
866
- import { ensureBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
867
- const requireNx = createRequire(process.cwd() + '/package.json');
868
- const { daemonClient } = requireNx('nx/src/daemon/client/client');
869
- const { workspaceDataDirectoryForWorkspace } = requireNx('nx/src/utils/cache-directory');
870
- const witness = join(workspaceDataDirectoryForWorkspace(process.cwd()), 'ensure-built-graph.json');
871
- const savedWitness = ${JSON.stringify(join(root, 'authoritative-graph.json'))};
872
- const source = join(process.cwd(), 'packages/lib/source.txt');
873
- const text = await readFile(source, 'utf8');
874
- const request = daemonClient.getProjectGraphAndSourceMaps.bind(daemonClient);
875
- let requests = 0;
876
- let invalidateGeneration = false;
877
- daemonClient.getProjectGraphAndSourceMaps = async () => {
878
- requests += 1;
879
- const response = await request();
880
- if (invalidateGeneration) {
881
- invalidateGeneration = false;
882
- await writeFile(source, 'transient graph input');
883
- await writeFile(source, text);
884
- }
885
- return response;
886
- };
887
- const results = [];
888
- async function check(label) {
889
- const before = requests;
890
- const result = await ensureBuilt({ target: 'app:build', cwd: process.cwd() });
891
- results.push({ label, requests: requests - before, disposition: result.disposition, witnessExists: existsSync(witness) });
892
- }
893
- await check('establish');
894
- await check('reuse');
895
- const added = join(process.cwd(), 'new-graph-input.txt');
896
- await writeFile(added, 'new');
897
- await check('created');
898
- await rm(added);
899
- await check('deleted');
900
- const project = join(process.cwd(), 'packages/app/project.json');
901
- const original = await readFile(project, 'utf8');
902
- const config = JSON.parse(original);
903
- config.implicitDependencies = [];
904
- await writeFile(project, JSON.stringify(config));
905
- await check('dependency');
906
- await writeFile(project, original);
907
- await check('dependency-restored');
908
- // Every call censuses the installation again, taking the hashes of files whose stamps have not moved from the
909
- // witness. A same-size rewrite that keeps its file's mtime moves its ctime: the next call reads it and sees the
910
- // changed installation, and the call after that reuses the graph the changed installation was proved with.
911
- const installed = join(process.cwd(), 'node_modules/typescript/README.md');
912
- const readme = await readFile(installed);
913
- const { atime, mtime } = await stat(installed);
914
- readme[0] ^= 1;
915
- await writeFile(installed, readme);
916
- await utimes(installed, atime, mtime);
917
- await check('installation');
918
- await check('installation-reuse');
919
- // Save only evidence the real daemon generation actually authorized, outside
920
- // the workspace: the later missing-witness RPC is not obliged to replace it.
921
- const authoritativeWitness = await readFile(witness, 'utf8');
922
- const witnessMode = (await stat(witness)).mode & 0o7777;
923
- await rename(witness, savedWitness);
924
- // Equal pre/post bytes do not authorize publication after a write/revert.
925
- // Count and return the actual RPC response, including the required successor.
926
- invalidateGeneration = true;
927
- await check('missing-witness');
928
- assert.equal(invalidateGeneration, false);
929
- assert.equal(existsSync(witness), false);
930
- // Restore that same genuine witness, not synthesized evidence or a retry of
931
- // the unstable generation, so the unreadable control always runs.
932
- await rename(savedWitness, witness);
933
- assert.equal(await readFile(witness, 'utf8'), authoritativeWitness);
934
- await chmod(witness, 0);
935
- try {
936
- await assert.rejects(readFile(witness), { code: 'EACCES' });
937
- await check('unreadable-witness');
938
- } finally {
939
- await chmod(witness, witnessMode);
940
- }
941
- await writeFile(${JSON.stringify(resultsPath)}, JSON.stringify(results));
942
- `,
943
- );
944
- const reused = await run('bun', reuseEntry, workspace, [], {
945
- NX_DAEMON: 'true',
946
- NX_USE_LOCAL: 'true',
947
- NX_WORKSPACE_ROOT_PATH: workspace,
948
- NX_SOCKET_DIR: socketDirectory,
949
- });
950
- expect(reused.code, reused.stdout + reused.stderr).toBe(0);
951
- // A changed dependency configuration may legitimately run app:build;
952
- // its streamed logs are not the graph-observation protocol.
953
- const graphChecks = typia.json.assertParse<
954
- { label: string; requests: number; disposition: string; witnessExists: boolean }[]
955
- >(await readFile(resultsPath, 'utf8'));
956
- expect(graphChecks.find(({ label }) => label === 'reuse')).toEqual({
957
- label: 'reuse',
958
- requests: 0,
959
- disposition: 'hit',
960
- witnessExists: true,
961
- });
962
- for (const label of [
963
- 'created',
964
- 'deleted',
965
- 'dependency',
966
- 'dependency-restored',
967
- 'installation',
968
- 'unreadable-witness',
969
- ]) {
970
- expect(graphChecks.find((check) => check.label === label)?.requests, label).toBeGreaterThan(0);
971
- }
972
- expect(graphChecks.find(({ label }) => label === 'missing-witness')).toEqual({
973
- label: 'missing-witness',
974
- requests: 2,
975
- disposition: 'hit',
976
- witnessExists: false,
977
- });
978
- expect(graphChecks.find(({ label }) => label === 'installation-reuse')).toEqual({
979
- label: 'installation-reuse',
980
- requests: 0,
981
- disposition: 'hit',
982
- witnessExists: true,
983
- });
984
- expect(graphChecks.find(({ label }) => label === 'unreadable-witness')?.disposition).toBe('hit');
985
- expect(await readFile(builds, 'utf8')).toBe('lib\n');
986
- expect(await readFile(join(workspace, 'packages/app/dist/marker.txt'), 'utf8')).toBe('built\nlib\n');
987
- },
988
- 'workspace',
989
- );
990
- });
991
-
992
- // Publication is opt-in only for the receipt case. Graph/exec probes below
993
- // keep ordinary plugin hooks but have no producer source/tool prepass.
994
- it('publishes real completion receipts and reuses their original basis for the same tree', async () => {
995
- let providerSockets: string | null = null;
996
- try {
997
- await withNxFixture(
998
- 'ensure-built-producer-',
999
- async ({ root, workspace }) => {
1000
- const builds = join(root, 'lib-builds.log');
1001
- await writeTwoProjectWorkspace(workspace, builds, true);
1002
- providerSockets = providerSocketDirectory(workspace);
1003
- const ownEnv: Record<string, string> = providerSockets === null ? {} : { NX_SOCKET_DIR: providerSockets };
1004
- const built = await run(
1005
- 'node',
1006
- nxEntry(workspace),
1007
- workspace,
1008
- ['run-many', '-t', 'build', '-p', 'app', '--outputStyle=static-failures-only'],
1009
- { NX_DAEMON: 'false', NX_WORKSPACE_ROOT_PATH: workspace },
1010
- );
1011
- expect(built.code, built.stdout + built.stderr).toBe(0);
1012
- expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1013
- // Probe-only receipts use the real Nx keys/cache and independently
1014
- // census public output bytes without starting a task runner.
1015
- const committed = spawnSync(
1016
- 'git',
1017
- [
1018
- '-C',
1019
- workspace,
1020
- 'add',
1021
- '.gitignore',
1022
- 'report',
1023
- 'nx.json',
1024
- 'packages/app/project.json',
1025
- 'packages/app/source.txt',
1026
- 'packages/lib/project.json',
1027
- 'packages/lib/source.txt',
1028
- ],
1029
- { encoding: 'utf8' },
1030
- );
1031
- expect(committed.status, committed.stdout + committed.stderr).toBe(0);
1032
- const sourceCommit = spawnSync(
1033
- 'git',
1034
- [
1035
- '-C',
1036
- workspace,
1037
- '-c',
1038
- 'user.name=EnsureBuilt fixture',
1039
- '-c',
1040
- 'user.email=fixture@example.invalid',
1041
- 'commit',
1042
- '-qm',
1043
- 'source fixture',
1044
- ],
1045
- { encoding: 'utf8' },
1046
- );
1047
- expect(sourceCommit.status, sourceCommit.stdout + sourceCommit.stderr).toBe(0);
1048
- // The receipt binds the producer's executables. A `git` this fixture owns lets the consumer case below move
1049
- // one tool node's ctime alone, as a same-mode chmod by another checkout's install moves a shared store file.
1050
- const realGit = Bun.which('git');
1051
- if (realGit === null) throw new Error('git is not on PATH');
1052
- const fixtureBin = join(root, 'bin');
1053
- await mkdir(fixtureBin);
1054
- const fixtureGit = join(fixtureBin, 'git');
1055
- await writeExecutable(fixtureGit, `#!/bin/sh\nexec ${JSON.stringify(realGit)} "$@"\n`);
1056
- const published = await run(
1057
- 'node',
1058
- nxEntry(workspace),
1059
- workspace,
1060
- ['run', 'app:build', '--outputStyle=static-failures-only'],
1061
- {
1062
- NX_DAEMON: 'true',
1063
- NX_WORKSPACE_ROOT_PATH: workspace,
1064
- ...ownEnv,
1065
- PATH: `${fixtureBin}:${process.env.PATH ?? ''}`,
1066
- },
1067
- );
1068
- expect(published.code, published.stdout + published.stderr).toBe(0);
1069
- expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1070
- const probeEntry = join(root, 'probe-receipt.ts');
1071
- await writeFile(
1072
- probeEntry,
1073
- `
1074
- import { readFile, stat, writeFile } from 'node:fs/promises';
1075
- import { join } from 'node:path';
1076
- import { probeBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
1077
- const output = join(process.cwd(), 'packages/app/dist/marker.txt');
1078
- const source = join(process.cwd(), 'packages/lib/source.txt');
1079
- const originalOutput = await readFile(output, 'utf8');
1080
- const originalSource = await readFile(source, 'utf8');
1081
- const before = await stat(output, { bigint: true });
1082
- const hit = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1083
- const after = await stat(output, { bigint: true });
1084
- process.env.NX_DAEMON = 'false';
1085
- const daemonless = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1086
- process.env.NX_DAEMON = 'true';
1087
- await writeFile(output, 'tampered');
1088
- const stale = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1089
- await writeFile(output, originalOutput);
1090
- await writeFile(source, 'new uncached source');
1091
- const uncached = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1092
- const outputAfterMiss = await readFile(output, 'utf8');
1093
- await writeFile(source, originalSource);
1094
- await new Promise<void>((resolve, reject) => process.stdout.write(JSON.stringify({ hit, daemonless, stale, uncached, outputUnwritten: before.ino === after.ino && before.mtimeNs === after.mtimeNs && before.ctimeNs === after.ctimeNs, outputAfterMiss }) + "\\n", error => error ? reject(error) : resolve()));
1095
- `,
1096
- );
1097
- const probed = await run('bun', probeEntry, workspace, [], {
1098
- NX_DAEMON: 'true',
1099
- NX_USE_LOCAL: 'true',
1100
- NX_WORKSPACE_ROOT_PATH: workspace,
1101
- ...ownEnv,
1102
- });
1103
- expect(probed.code, probed.stdout + probed.stderr).toBe(0);
1104
- const receipts = typia.json.assertParse<{
1105
- hit: EnsureBuiltProbeResult;
1106
- daemonless: EnsureBuiltProbeResult;
1107
- stale: EnsureBuiltProbeResult;
1108
- uncached: EnsureBuiltProbeResult;
1109
- outputUnwritten: boolean;
1110
- outputAfterMiss: string;
1111
- }>(probed.stdout);
1112
- expect(receipts.hit.disposition, probed.stderr).toBe('hit');
1113
- if (receipts.hit.disposition === 'hit') {
1114
- expect(receipts.hit.receipt.tasks.map(({ id }) => id).sort()).toEqual(['app:build', 'lib:build']);
1115
- expect(
1116
- receipts.hit.receipt.tasks
1117
- .flatMap(({ outputs }) => outputs)
1118
- .find(({ path }) => path === 'packages/app/dist/marker.txt'),
1119
- ).toMatchObject({ type: 'file', sha256: expect.stringMatching(/^[a-f0-9]{64}$/) });
1120
- }
1121
- expect(receipts.daemonless.disposition).toBe('hit');
1122
- expect(receipts.stale).toMatchObject({ disposition: 'failed', reason: { kind: 'provider-proof' } });
1123
- expect(receipts.uncached.disposition).toBe('failed');
1124
- expect(receipts.outputUnwritten).toBe(true);
1125
- expect(receipts.outputAfterMiss).toBe('built\nlib\n');
1126
- expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1127
-
1128
- const producerEnvironmentEntry = join(root, 'producer-environment-independence.ts');
1129
- await writeFile(
1130
- producerEnvironmentEntry,
1131
- `
1132
- import { createRequire } from 'node:module';
1133
- import { spawnSync } from 'node:child_process';
1134
- import { probeBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
1135
- const { daemonClient } = createRequire(process.cwd() + '/package.json')('nx/src/daemon/client/client');
1136
- daemonClient.hashTasks = async () => { throw new Error('readonly consumer must not hash its own environment'); };
1137
- const packageJson = createRequire(process.cwd() + '/package.json')('nx/src/utils/package-json');
1138
- const readModulePackageJson = packageJson.readModulePackageJson;
1139
- let moduleInspections = 0;
1140
- packageJson.readModulePackageJson = (...args) => { moduleInspections += 1; return readModulePackageJson(...args); };
1141
- process.env.PRODUCER_CONSUMER_DIFFERENCE = 'consumer-only';
1142
- const first = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1143
- const empty = spawnSync('git', ['-c', 'user.name=Receipt fixture', '-c', 'user.email=receipt@example.invalid', 'commit', '--allow-empty', '-qm', 'same tree'], { encoding: 'utf8' });
1144
- if (empty.status !== 0) throw new Error(empty.stderr);
1145
- const sameTree = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1146
- await new Promise<void>((resolve, reject) => process.stdout.write(JSON.stringify({ first, sameTree, moduleInspections }) + "\\n", error => error ? reject(error) : resolve()));
1147
- `,
1148
- );
1149
- const producerEnvironment = await run('bun', producerEnvironmentEntry, workspace, [], {
1150
- NX_DAEMON: 'true',
1151
- NX_USE_LOCAL: 'true',
1152
- NX_WORKSPACE_ROOT_PATH: workspace,
1153
- ...ownEnv,
1154
- });
1155
- expect(producerEnvironment.code, producerEnvironment.stdout + producerEnvironment.stderr).toBe(0);
1156
- const environmentResults = typia.json.assertParse<{
1157
- first: EnsureBuiltProbeResult;
1158
- sameTree: EnsureBuiltProbeResult;
1159
- moduleInspections: number;
1160
- }>(producerEnvironment.stdout);
1161
- expect(environmentResults.first.disposition, producerEnvironment.stderr).toBe('hit');
1162
- expect(environmentResults.sameTree).toEqual(environmentResults.first);
1163
- expect(environmentResults.moduleInspections).toBe(0);
1164
- expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1165
-
1166
- // Between its readonly read of the receipt's tools and its last check of them, the consumer censuses the
1167
- // public outputs through Nx's expandOutputs. Moving the fixture `git` there is a tool node moving under the
1168
- // readonly validation: a same-mode chmod moves its ctime alone and keeps the hit, a byte change refuses and
1169
- // names the node.
1170
- const toolMoveEntry = join(root, 'tool-node-move.ts');
1171
- await writeFile(
1172
- toolMoveEntry,
1173
- `
1174
- import { chmodSync, statSync, writeFileSync } from 'node:fs';
1175
- import { createRequire } from 'node:module';
1176
- import { probeBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
1177
- const git = ${JSON.stringify(fixtureGit)};
1178
- const native = createRequire(process.cwd() + '/package.json')('nx/src/native');
1179
- const expand = native.expandOutputs;
1180
- let move = () => {};
1181
- let moves = 0;
1182
- native.expandOutputs = (...args) => {
1183
- move();
1184
- moves += 1;
1185
- return expand(...args);
1186
- };
1187
- const before = statSync(git, { bigint: true });
1188
- move = () => chmodSync(git, 0o755);
1189
- const chmodded = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1190
- const after = statSync(git, { bigint: true });
1191
- const ctimeAlone = before.ino === after.ino && before.mode === after.mode && before.size === after.size && before.mtimeNs === after.mtimeNs && before.ctimeNs !== after.ctimeNs;
1192
- const chmodMoves = moves;
1193
- move = () => writeFileSync(git, '#!/bin/sh\\nexit 1\\n');
1194
- const rewritten = await probeBuilt({ target: 'app:build', cwd: process.cwd() });
1195
- await new Promise<void>((resolve, reject) => process.stdout.write(JSON.stringify({ chmodded, ctimeAlone, chmodMoves, rewritten }) + "\\n", error => error ? reject(error) : resolve()));
1196
- `,
1197
- );
1198
- const toolMove = await run('bun', toolMoveEntry, workspace, [], {
1199
- NX_DAEMON: 'true',
1200
- NX_USE_LOCAL: 'true',
1201
- NX_WORKSPACE_ROOT_PATH: workspace,
1202
- ...ownEnv,
1203
- });
1204
- expect(toolMove.code, toolMove.stdout + toolMove.stderr).toBe(0);
1205
- const toolMoves = typia.json.assertParse<{
1206
- chmodded: EnsureBuiltProbeResult;
1207
- ctimeAlone: boolean;
1208
- chmodMoves: number;
1209
- rewritten: EnsureBuiltProbeResult;
1210
- }>(toolMove.stdout);
1211
- expect(toolMoves.chmodMoves).toBeGreaterThan(0);
1212
- expect(toolMoves.ctimeAlone).toBe(true);
1213
- expect(toolMoves.chmodded, toolMove.stderr).toEqual(environmentResults.first);
1214
- expect(toolMoves.rewritten).toMatchObject({
1215
- disposition: 'failed',
1216
- reason: {
1217
- kind: 'provider-proof',
1218
- detail: `Producer tool namespace changed during independent product validation: ${fixtureGit}`,
1219
- },
1220
- });
1221
- },
1222
- 'workspace',
1223
- );
1224
- } finally {
1225
- if (providerSockets !== null) await rm(providerSockets, { recursive: true, force: true });
1226
- }
1227
- });
1228
-
1229
- // A sandboxed consumer is granted its provider read-only, and starting a daemon writes the provider's workspace
1230
- // data (`.nx/workspace-data/d`): the read-only probe connects to a serving daemon or reports that none serves.
1231
- it('reports no-daemon and writes nothing when no daemon serves a provider without a receipt', async () => {
1232
- await withNxFixture(
1233
- 'ensure-built-probe-no-daemon-',
1234
- async ({ root, workspace, socketDirectory }) => {
1235
- await writeTwoProjectWorkspace(workspace, join(root, 'lib-builds.log'), true);
1236
- const listing = async () =>
1237
- (await readdir(workspace, { recursive: true })).filter((entry) => !entry.startsWith('node_modules')).sort();
1238
- const before = await listing();
1239
- const probeEntry = join(root, 'probe-no-daemon.ts');
1240
- await writeFile(
1241
- probeEntry,
1242
- `
1243
- import { probeBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
1244
- const result = await probeBuilt({ target: 'app:build', cwd: ${JSON.stringify(workspace)} });
1245
- await new Promise<void>((resolve, reject) => process.stdout.write(JSON.stringify(result) + "\\n", error => error ? reject(error) : resolve()));
1246
- `,
1247
- );
1248
- // Run from the fixture root, outside the provider workspace, as a consumer calls it.
1249
- const probed = await run('bun', probeEntry, root, [], { NX_DAEMON: 'true', NX_SOCKET_DIR: socketDirectory });
1250
- expect(probed.code, probed.stdout + probed.stderr).toBe(0);
1251
- const result = typia.json.assertParse<EnsureBuiltProbeResult>(probed.stdout);
1252
- expect(result).toMatchObject({
1253
- disposition: 'failed',
1254
- reason: { kind: 'provider-proof', taskId: 'app:build' },
1255
- });
1256
- if (result.disposition !== 'failed' || result.reason.kind !== 'provider-proof') {
1257
- throw new Error(`the probe must refuse with its provider proof, not ${probed.stdout}`);
1258
- }
1259
- expect(result.reason.detail).toEndWith(
1260
- `authoritative graph unavailable: ${describeMiss({ kind: 'no-daemon', taskId: 'app:build' })}`,
1261
- );
1262
- expect(await listing()).toEqual(before);
1263
- },
1264
- 'workspace',
1265
- );
1266
- });
1267
-
1268
- // The graph/exec case runs real Nx because its subject is the daemon:
1269
- // the daemon a probe starts holds no output records, so every output must be
1270
- // vouched for by comparing the working tree with Nx's cache artifact. The
1271
- // daemon it starts is also the one whose socket is in question, so the same
1272
- // lifetime answers where a root entered from another workspace's shell binds.
1273
- it('replays current outputs and refreshes stale snapshots without running unrelated edits', async () => {
1274
- // A socket path has a 95 character budget and macOS's temp directory spends most of it, so the
1275
- // socket directory is made in the short socket namespace the sandbox admits.
1276
- const socketDir = await ownedSocketDirectory('eb-sock-', NX_LONGEST_SOCKET_NAME);
1277
- let root = '';
1278
- let failure: { readonly error: unknown } | null = null;
1279
- const providerDirectories: string[] = [];
1280
- try {
1281
- await withNxFixture(
1282
- 'ensure-built-daemon-',
1283
- async (fixture) => {
1284
- root = fixture.root;
1285
- const { workspace } = fixture;
1286
- const builds = join(root, 'lib-builds.log');
1287
- await writeTwoProjectWorkspace(workspace, builds);
1288
- // What the provider binds for this workspace when the call is entered from another one's shell.
1289
- const providerSockets = providerSocketDirectory(workspace);
1290
- if (providerSockets !== null) providerDirectories.push(providerSockets);
1291
- const ownEnv: Record<string, string> = providerSockets === null ? {} : { NX_SOCKET_DIR: providerSockets };
1292
-
1293
- // Built by daemonless Nx, as CI or a restarted daemon leaves a tree:
1294
- // cached and on disk, recorded by no daemon.
1295
- const built = await run(
1296
- 'node',
1297
- nxEntry(workspace),
1298
- workspace,
1299
- ['run-many', '-t', 'build', '-p', 'app', '--outputStyle=static-failures-only'],
1300
- { NX_DAEMON: 'false', NX_WORKSPACE_ROOT_PATH: workspace },
1301
- );
1302
- expect(built.code, built.stdout + built.stderr).toBe(0);
1303
- expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1304
-
1305
- // Entered from outside the root by a shell set up for another
1306
- // workspace, as a managed devenv's is: its socket directory belongs to
1307
- // that workspace's daemon, and a second daemon listening there would
1308
- // take the socket from it.
1309
- const caller = join(root, 'caller');
1310
- await mkdir(caller);
1311
- const hit = await run(
1312
- 'bun',
1313
- binEntry,
1314
- caller,
1315
- ['app:build', '--workspace-root', workspace, '--', join(workspace, 'report')],
1316
- { NX_DAEMON: 'true', NX_USE_LOCAL: 'true', NX_SOCKET_DIR: socketDir },
1317
- );
1318
- expect(hit.code, hit.stdout + hit.stderr).toBe(0);
1319
- expect(hit.stderr).toBe('');
1320
- expect(hit.stdout.split('\n')[0], hit.stdout).toBe(MARKER);
1321
- expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1322
- expect(await readdir(socketDir)).toEqual([]);
1323
- const record = await readFile(join(workspace, '.nx', 'workspace-data', 'd', 'server-process.json'), 'utf-8');
1324
- expect(record).not.toContain(socketDir);
1325
- // The daemon it started binds in the directory the provider named, not the caller's nor Nx's default.
1326
- const daemon = typia.json.assertParse<DaemonProcessJson>(record);
1327
- if (providerSockets !== null) {
1328
- expect(daemon.socketPath.startsWith(`${providerSockets}/`), record).toBe(true);
1329
- }
1330
-
1331
- // That hit re-armed the daemon's records. The emitted wrapper, under
1332
- // Node and with nothing to exec, is as silent.
1333
- const again = await run('node', builtBinEntry, workspace, ['app:build'], {
1334
- NX_DAEMON: 'true',
1335
- NX_USE_LOCAL: 'true',
1336
- ...ownEnv,
1337
- });
1338
- expect(again).toEqual({ code: 0, signal: null, stdout: '', stderr: '' });
1339
- expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1340
-
1341
- // An awaited daemon graph can see B while both disk snapshots see
1342
- // A. Node stamps revoke that generation; the fresh daemon file table
1343
- // supplies the A reconciliation instead of an empty A-to-A diff.
1344
- const generationRaceEntry = join(root, 'graph-generation-race.ts');
1345
- await writeFile(
1346
- generationRaceEntry,
1347
- `
1348
- import { createRequire } from 'node:module';
1349
- import { readFile, rm, writeFile } from 'node:fs/promises';
1350
- import { join } from 'node:path';
1351
- import { ensureBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
1352
- const source = join(process.cwd(), 'packages/lib/source.txt');
1353
- const text = await readFile(source, 'utf8');
1354
- await ensureBuilt({ target: 'app:build', cwd: process.cwd() });
1355
- const requireNx = createRequire(process.cwd() + '/package.json');
1356
- const { workspaceDataDirectoryForWorkspace } = requireNx('nx/src/utils/cache-directory');
1357
- await rm(join(workspaceDataDirectoryForWorkspace(process.cwd()), 'ensure-built-graph.json'), { force: true });
1358
- const { daemonClient } = createRequire(process.cwd() + '/package.json')('nx/src/daemon/client/client');
1359
- const request = daemonClient.getProjectGraphAndSourceMaps.bind(daemonClient);
1360
- let requests = 0;
1361
- daemonClient.getProjectGraphAndSourceMaps = async () => {
1362
- requests += 1;
1363
- const result = await request();
1364
- if (requests !== 1) return result;
1365
- await writeFile(source, 'transient graph input');
1366
- await daemonClient.updateWorkspaceContext([], ['packages/lib/source.txt'], []);
1367
- const next = await request();
1368
- await writeFile(source, text);
1369
- return next;
1370
- };
1371
- const result = await ensureBuilt({ target: 'app:build', cwd: process.cwd() });
1372
- console.log(JSON.stringify({ result, requests }));
1373
- `,
1374
- );
1375
- const generationRace = await run('bun', generationRaceEntry, workspace, [], {
1376
- NX_DAEMON: 'true',
1377
- NX_USE_LOCAL: 'true',
1378
- NX_WORKSPACE_ROOT_PATH: workspace,
1379
- ...ownEnv,
1380
- });
1381
- expect(generationRace.code, generationRace.stdout + generationRace.stderr).toBe(0);
1382
- const generations = typia.json.assertParse<{
1383
- result: import('./ensure-built.js').EnsureBuiltResult;
1384
- requests: number;
1385
- }>(generationRace.stdout);
1386
- expect(generations.result).toEqual({ disposition: 'hit' });
1387
- expect(generations.requests).toBeGreaterThanOrEqual(2);
1388
- expect(generationRace.stderr).toBe('');
1389
- expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1390
- // Coordinate a real write after the real daemon returned its file
1391
- // table. The response is not substituted: this makes the
1392
- // graph→snapshot race deterministic without relying on FSEvents.
1393
- const raceEntry = join(root, 'freshness-race.ts');
1394
- await writeFile(
1395
- raceEntry,
1396
- `
1397
- import { createRequire } from 'node:module';
1398
- import { writeFile } from 'node:fs/promises';
1399
- import { ensureBuilt } from ${JSON.stringify(join(packageRoot, 'dist', 'ensure-built.js'))};
1400
- const { daemonClient } = createRequire(process.cwd() + '/package.json')('nx/src/daemon/client/client');
1401
- const readFiles = daemonClient.getWorkspaceContextFileData.bind(daemonClient);
1402
- daemonClient.getWorkspaceContextFileData = async () => {
1403
- const files = await readFiles();
1404
- await writeFile(process.argv[2], process.argv[3]);
1405
- return files;
1406
- };
1407
- console.log(JSON.stringify(await ensureBuilt({ target: 'app:build', cwd: process.cwd() })));
1408
- `,
1409
- );
1410
- const refreshed = await run(
1411
- 'bun',
1412
- raceEntry,
1413
- workspace,
1414
- [join(workspace, 'README.md'), 'an unrelated edit\n'],
1415
- { NX_DAEMON: 'true', NX_USE_LOCAL: 'true', NX_WORKSPACE_ROOT_PATH: workspace, ...ownEnv },
1416
- );
1417
- expect(refreshed.code, refreshed.stdout + refreshed.stderr).toBe(0);
1418
- expect(refreshed.stdout.trim()).toBe(JSON.stringify({ disposition: 'hit' }));
1419
- expect(refreshed.stderr).toBe('');
1420
- expect(await readFile(builds, 'utf-8')).toBe('lib\n');
1421
-
1422
- // STRICT-BY: the same boundary moving an actual declared input must
1423
- // miss, run its producer, and rebuild the dependent artifact.
1424
- const changed = await run(
1425
- 'bun',
1426
- raceEntry,
1427
- workspace,
1428
- [join(workspace, 'packages', 'lib', 'source.txt'), 'changed\n'],
1429
- { NX_DAEMON: 'true', NX_USE_LOCAL: 'true', NX_WORKSPACE_ROOT_PATH: workspace, ...ownEnv },
1430
- );
1431
- expect(changed.code, changed.stdout + changed.stderr).toBe(0);
1432
- expect(changed.stdout).toContain('"disposition":"built"');
1433
- expect(await readFile(builds, 'utf-8')).toBe('lib\nchanged\n');
1434
- expect(await readFile(join(workspace, 'packages', 'app', 'dist', 'marker.txt'), 'utf-8')).toBe(
1435
- 'built\nchanged\n',
1436
- );
1437
- },
1438
- 'workspace',
1439
- );
1440
- } catch (error) {
1441
- failure = { error };
1442
- }
1443
- // Only the directories this test made: the caller's, and the one the provider bound for this workspace.
1444
- for (const directory of [socketDir, ...providerDirectories]) {
1445
- await rm(directory, { recursive: true, force: true });
1446
- }
1447
- // The fixture retires on every exit path of its body, a throwing one
1448
- // included: once it has, nothing works in its root.
1449
- const leftovers = root === '' ? [] : await pidsWorkingIn(root);
1450
- if (failure === null) {
1451
- expect(leftovers).toEqual([]);
1452
- } else if (leftovers.length === 0) {
1453
- throw failure.error;
1454
- } else {
1455
- // A cause, not an AggregateError: the test harness prints an aggregate's
1456
- // inner errors without its message.
1457
- throw new Error(`processes ${leftovers.join(', ')} still work in ${root} after its body failed`, {
1458
- cause: failure.error,
1459
- });
1460
- }
1461
- });
1462
- });