@cnc-tools/storm 0.9.1 → 0.11.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 (731) hide show
  1. package/bin/storm.js +11 -2
  2. package/dist/application.d.ts +5 -5
  3. package/dist/application.js +11 -9
  4. package/dist/bin/storm.js +32 -20
  5. package/dist/build-info.js +1 -1
  6. package/dist/chunks/chunk-3ZZVZPMG.js +10 -0
  7. package/dist/chunks/{chunk-WV6WQFC6.js → chunk-4EU4AH7E.js} +150 -26
  8. package/dist/chunks/chunk-4PRAB24Y.js +4400 -0
  9. package/dist/chunks/chunk-AMTYHUYB.js +257 -0
  10. package/dist/chunks/chunk-ETCZ6WP7.js +431 -0
  11. package/dist/chunks/chunk-FVMQKYTT.js +10 -0
  12. package/dist/chunks/chunk-GRMD7G4J.js +1267 -0
  13. package/dist/chunks/chunk-ICB4BZJX.js +22 -0
  14. package/dist/chunks/chunk-KR7WIYLG.js +2184 -0
  15. package/dist/chunks/chunk-L4ZPMSKQ.js +808 -0
  16. package/dist/chunks/chunk-NPPJ57W7.js +569 -0
  17. package/dist/chunks/chunk-O4BUT7BE.js +3361 -0
  18. package/dist/chunks/chunk-OJOKQRM6.js +1457 -0
  19. package/dist/chunks/chunk-SLNKW4ZM.js +40 -0
  20. package/dist/chunks/chunk-TRFEAYNC.js +1952 -0
  21. package/dist/chunks/chunk-VZZTHCBW.js +93 -0
  22. package/dist/chunks/chunk-WNIQA5J6.js +19 -0
  23. package/dist/chunks/chunk-WSIF7SR6.js +10 -0
  24. package/dist/chunks/{live-app-X3PW2W42.js → live-app-LOGYUBKB.js} +73 -20
  25. package/dist/command-tree.d.ts +3 -0
  26. package/dist/command-tree.js +3 -0
  27. package/dist/commands/dashboard.d.ts +1 -1
  28. package/dist/commands/dashboard.js +1 -1
  29. package/dist/commands/exec/cleanup.d.ts +28 -44
  30. package/dist/commands/exec/cleanup.js +25 -55
  31. package/dist/commands/exec/command.d.ts +73 -545
  32. package/dist/commands/exec/command.js +65 -25
  33. package/dist/commands/exec/job-summary.d.ts +2 -2
  34. package/dist/commands/exec/job-summary.js +3 -3
  35. package/dist/commands/exec/live-view.d.ts +9 -9
  36. package/dist/commands/exec/live-view.js +49 -42
  37. package/dist/commands/exec/metadata.d.ts +0 -65
  38. package/dist/commands/exec/metadata.js +2 -61
  39. package/dist/commands/exec/mint-failed.d.ts +1 -1
  40. package/dist/commands/exec/mint-failed.js +8 -8
  41. package/dist/commands/exec/outcomes.d.ts +63 -468
  42. package/dist/commands/exec/outcomes.js +47 -75
  43. package/dist/commands/exec/plan-run.d.ts +148 -0
  44. package/dist/commands/exec/plan-run.js +121 -0
  45. package/dist/commands/exec/progress.d.ts +26 -16
  46. package/dist/commands/exec/progress.js +63 -42
  47. package/dist/commands/exec/redaction.d.ts +3 -3
  48. package/dist/commands/exec/redaction.js +4 -4
  49. package/dist/commands/exec/resource-flags.d.ts +50 -0
  50. package/dist/commands/exec/resource-flags.js +125 -0
  51. package/dist/commands/exec/resource-refusals.d.ts +64 -0
  52. package/dist/commands/exec/resource-refusals.js +58 -0
  53. package/dist/commands/exec/run-command.d.ts +87 -167
  54. package/dist/commands/exec/run-command.js +296 -418
  55. package/dist/commands/exec/run-metadata.d.ts +20 -43
  56. package/dist/commands/exec/run-metadata.js +18 -37
  57. package/dist/commands/exec/test-plan.d.ts +11 -0
  58. package/dist/commands/exec/test-plan.js +39 -0
  59. package/dist/commands/exec/tests-summary.d.ts +5 -5
  60. package/dist/commands/exec/tests-summary.js +2 -2
  61. package/dist/commands/exec/text.d.ts +8 -2
  62. package/dist/commands/exec/text.js +8 -0
  63. package/dist/commands/exec/view.d.ts +5 -7
  64. package/dist/commands/exec/view.js +22 -14
  65. package/dist/commands/exec/waterfall.d.ts +4 -9
  66. package/dist/commands/exec/waterfall.js +22 -26
  67. package/dist/commands/exec/worker-chart.d.ts +1 -1
  68. package/dist/commands/ext/metadata.d.ts +4 -0
  69. package/dist/commands/ext/metadata.js +8 -0
  70. package/dist/commands/runs/facts.d.ts +11 -6
  71. package/dist/commands/runs/facts.js +27 -15
  72. package/dist/commands/runs/list/command.d.ts +15 -8
  73. package/dist/commands/runs/list/command.js +39 -32
  74. package/dist/commands/runs/list/metadata.d.ts +16 -14
  75. package/dist/commands/runs/list/metadata.js +17 -15
  76. package/dist/commands/runs/list/outcomes.d.ts +6 -2
  77. package/dist/commands/runs/logs/command.d.ts +3 -4
  78. package/dist/commands/runs/logs/command.js +46 -41
  79. package/dist/commands/runs/logs/metadata.d.ts +17 -15
  80. package/dist/commands/runs/logs/metadata.js +20 -18
  81. package/dist/commands/runs/past-run.d.ts +3 -33
  82. package/dist/commands/runs/past-run.js +3 -52
  83. package/dist/commands/runs/show/command.d.ts +57 -42
  84. package/dist/commands/runs/show/command.js +93 -82
  85. package/dist/commands/runs/show/metadata.d.ts +20 -18
  86. package/dist/commands/runs/show/metadata.js +20 -18
  87. package/dist/commands/runs/show/outcomes.d.ts +27 -19
  88. package/dist/commands/runs/show/outcomes.js +8 -6
  89. package/dist/commands/vitest/command.d.ts +95 -560
  90. package/dist/commands/vitest/command.js +84 -100
  91. package/dist/commands/vitest/metadata.d.ts +0 -65
  92. package/dist/commands/vitest/metadata.js +2 -41
  93. package/dist/commands/vitest/outcomes.d.ts +44 -274
  94. package/dist/commands/vitest/outcomes.js +7 -14
  95. package/dist/config/credential-resolver.d.ts +134 -0
  96. package/dist/config/credential-resolver.js +70 -0
  97. package/dist/{credential/settle.d.ts → config/credential-settle.d.ts} +1 -2
  98. package/dist/config/errors.d.ts +1 -1
  99. package/dist/config/errors.js +5 -5
  100. package/dist/config/index.d.ts +7 -6
  101. package/dist/config/index.js +13 -9
  102. package/dist/config/load.d.ts +16 -13
  103. package/dist/config/load.js +55 -40
  104. package/dist/config/recipe-run.d.ts +26 -0
  105. package/dist/config/recipe-run.js +27 -0
  106. package/dist/config/resolve.d.ts +103 -15
  107. package/dist/config/resolve.js +137 -47
  108. package/dist/config/resolver.d.ts +40 -0
  109. package/dist/config/resolver.js +31 -0
  110. package/dist/config/schema.d.ts +13 -17
  111. package/dist/config/schema.js +14 -35
  112. package/dist/config/settings-file.d.ts +28 -16
  113. package/dist/config/settings-file.js +39 -24
  114. package/dist/config/typed-options.d.ts +21 -0
  115. package/dist/config/typed-options.js +28 -0
  116. package/dist/config-file/define.d.ts +33 -31
  117. package/dist/config-file/define.js +14 -4
  118. package/dist/config-file/toolchain.d.ts +1 -1
  119. package/dist/context.d.ts +60 -29
  120. package/dist/context.js +32 -13
  121. package/dist/core/before-run.d.ts +38 -0
  122. package/dist/core/before-run.js +44 -0
  123. package/dist/core/definition-lookup.d.ts +22 -0
  124. package/dist/core/definition-lookup.js +34 -0
  125. package/dist/core/events.d.ts +59 -64
  126. package/dist/core/gateways.d.ts +23 -164
  127. package/dist/core/index.d.ts +14 -15
  128. package/dist/core/index.js +13 -11
  129. package/dist/core/launcher-supplies.d.ts +11 -0
  130. package/dist/core/launcher-supplies.js +28 -0
  131. package/dist/core/live/terminal-command-gateway.d.ts +8 -0
  132. package/dist/core/live/terminal-command-gateway.js +49 -0
  133. package/dist/core/payload.d.ts +13 -14
  134. package/dist/core/payload.js +9 -8
  135. package/dist/core/presentations.d.ts +38 -37
  136. package/dist/core/presentations.js +48 -56
  137. package/dist/core/reports.d.ts +5 -0
  138. package/dist/core/reports.js +13 -0
  139. package/dist/core/resource-registry.d.ts +38 -0
  140. package/dist/core/resource-registry.js +30 -0
  141. package/dist/core/resource-reports.d.ts +69 -0
  142. package/dist/core/resource-reports.js +67 -0
  143. package/dist/core/resource.d.ts +135 -243
  144. package/dist/core/resource.js +7 -5
  145. package/dist/core/resources-of.d.ts +16 -0
  146. package/dist/core/resources-of.js +8 -0
  147. package/dist/core/resources.d.ts +97 -84
  148. package/dist/core/resources.js +166 -165
  149. package/dist/core/run-state.d.ts +30 -42
  150. package/dist/core/run-state.js +56 -60
  151. package/dist/core/run.d.ts +83 -90
  152. package/dist/core/run.js +109 -155
  153. package/dist/core/state-directory.js +4 -3
  154. package/dist/core/timeline.d.ts +42 -24
  155. package/dist/core/timeline.js +46 -27
  156. package/dist/core/timing.d.ts +3 -3
  157. package/dist/core/timing.js +1 -1
  158. package/dist/credential/events.d.ts +20 -0
  159. package/dist/credential/events.js +4 -0
  160. package/dist/credential/gateways.d.ts +1 -80
  161. package/dist/credential/index.d.ts +4 -5
  162. package/dist/credential/index.js +8 -5
  163. package/dist/credential/live/github-actions-token-response.js +1 -1
  164. package/dist/credential/live/vercel-cli-gateway.d.ts +2 -1
  165. package/dist/credential/live/vercel-cli-gateway.js +1 -1
  166. package/dist/credential/live/vercel-output.d.ts +1 -1
  167. package/dist/credential/source.d.ts +44 -75
  168. package/dist/credential/source.js +33 -28
  169. package/dist/credential/target.d.ts +1 -1
  170. package/dist/extension-commands.d.ts +20 -0
  171. package/dist/extension-commands.js +27 -0
  172. package/dist/extensions/github/definition.d.ts +26 -0
  173. package/dist/extensions/github/definition.js +29 -0
  174. package/dist/extensions/github/extension.d.ts +18 -0
  175. package/dist/extensions/github/extension.js +6 -0
  176. package/dist/{resources → extensions}/github/fixture-repo.d.ts +11 -8
  177. package/dist/{resources → extensions}/github/fixture-repo.js +8 -4
  178. package/dist/extensions/github/index.d.ts +13 -0
  179. package/dist/extensions/github/index.js +17 -0
  180. package/dist/extensions/github/lifecycle.d.ts +30 -0
  181. package/dist/extensions/github/lifecycle.js +69 -0
  182. package/dist/extensions/github/live/world.d.ts +6 -0
  183. package/dist/extensions/github/live/world.js +16 -0
  184. package/dist/extensions/github/options.d.ts +36 -0
  185. package/dist/extensions/github/options.js +36 -0
  186. package/dist/extensions/github/refusals.d.ts +32 -0
  187. package/dist/extensions/github/refusals.js +43 -0
  188. package/dist/extensions/github/release.d.ts +17 -0
  189. package/dist/extensions/github/release.js +34 -0
  190. package/dist/extensions/github/resource.d.ts +36 -0
  191. package/dist/extensions/github/resource.js +21 -0
  192. package/dist/extensions/github/run/payload.d.ts +27 -0
  193. package/dist/extensions/github/run/payload.js +42 -0
  194. package/dist/extensions/github/world.d.ts +15 -0
  195. package/dist/extensions/github/world.js +3 -0
  196. package/dist/extensions/story/command-tree.d.ts +6 -0
  197. package/dist/extensions/story/command-tree.js +21 -0
  198. package/dist/extensions/story/commands/app.d.ts +23 -0
  199. package/dist/extensions/story/commands/app.js +5 -0
  200. package/dist/extensions/story/commands/run/command.d.ts +211 -0
  201. package/dist/extensions/story/commands/run/command.js +259 -0
  202. package/dist/extensions/story/commands/run/metadata.d.ts +4 -0
  203. package/dist/extensions/story/commands/run/metadata.js +8 -0
  204. package/dist/extensions/story/commands/run/outcomes.d.ts +101 -0
  205. package/dist/extensions/story/commands/run/outcomes.js +73 -0
  206. package/dist/extensions/story/commands/tree.d.ts +2 -0
  207. package/dist/extensions/story/commands/tree.js +6 -0
  208. package/dist/extensions/story/extension.d.ts +2 -0
  209. package/dist/extensions/story/extension.js +8 -0
  210. package/dist/extensions/testserver/canceled.d.ts +7 -0
  211. package/dist/extensions/testserver/canceled.js +27 -0
  212. package/dist/extensions/testserver/command-tree.d.ts +6 -0
  213. package/dist/extensions/testserver/command-tree.js +20 -0
  214. package/dist/extensions/testserver/commands/app.d.ts +22 -0
  215. package/dist/extensions/testserver/commands/app.js +5 -0
  216. package/dist/{resources/testserver/commands → extensions/testserver/commands/pool}/create/command.d.ts +277 -237
  217. package/dist/{resources/testserver/commands → extensions/testserver/commands/pool}/create/command.js +112 -141
  218. package/dist/extensions/testserver/commands/pool/create/metadata.d.ts +33 -0
  219. package/dist/extensions/testserver/commands/pool/create/metadata.js +55 -0
  220. package/dist/{resources/testserver/commands → extensions/testserver/commands/pool}/create/outcomes.d.ts +132 -112
  221. package/dist/{resources/testserver/commands → extensions/testserver/commands/pool}/create/outcomes.js +6 -24
  222. package/dist/{resources/testserver/commands → extensions/testserver/commands/pool}/list/command.d.ts +3 -4
  223. package/dist/{resources/testserver/commands → extensions/testserver/commands/pool}/list/command.js +34 -28
  224. package/dist/extensions/testserver/commands/pool/list/metadata.d.ts +11 -0
  225. package/dist/{resources/testserver/commands → extensions/testserver/commands/pool}/list/metadata.js +7 -5
  226. package/dist/{resources/testserver/commands → extensions/testserver/commands/pool}/list/outcomes.js +1 -1
  227. package/dist/extensions/testserver/commands/pool/metadata.d.ts +3 -0
  228. package/dist/extensions/testserver/commands/pool/metadata.js +7 -0
  229. package/dist/extensions/testserver/commands/tree.d.ts +2 -0
  230. package/dist/extensions/testserver/commands/tree.js +6 -0
  231. package/dist/{resources → extensions}/testserver/credential-facts.d.ts +6 -40
  232. package/dist/{resources → extensions}/testserver/credential-facts.js +13 -35
  233. package/dist/extensions/testserver/definition.d.ts +57 -0
  234. package/dist/extensions/testserver/definition.js +71 -0
  235. package/dist/{resources → extensions}/testserver/events.d.ts +5 -4
  236. package/dist/extensions/testserver/events.js +4 -0
  237. package/dist/extensions/testserver/extension.d.ts +46 -0
  238. package/dist/extensions/testserver/extension.js +68 -0
  239. package/dist/extensions/testserver/index.d.ts +20 -0
  240. package/dist/extensions/testserver/index.js +31 -0
  241. package/dist/extensions/testserver/lifecycle.d.ts +24 -0
  242. package/dist/extensions/testserver/lifecycle.js +116 -0
  243. package/dist/{core → extensions/testserver}/limit.js +1 -0
  244. package/dist/extensions/testserver/live/world.d.ts +8 -0
  245. package/dist/extensions/testserver/live/world.js +38 -0
  246. package/dist/{resources/testserver/sandbox → extensions/testserver/options}/channels.d.ts +1 -1
  247. package/dist/extensions/testserver/options/index.d.ts +5 -0
  248. package/dist/extensions/testserver/options/index.js +11 -0
  249. package/dist/extensions/testserver/options/rules.d.ts +69 -0
  250. package/dist/extensions/testserver/options/rules.js +92 -0
  251. package/dist/extensions/testserver/options/sandboxes.d.ts +29 -0
  252. package/dist/extensions/testserver/options/sandboxes.js +33 -0
  253. package/dist/extensions/testserver/options/ttl.d.ts +23 -0
  254. package/dist/extensions/testserver/options/ttl.js +42 -0
  255. package/dist/{resources → extensions}/testserver/pool/channels.d.ts +3 -3
  256. package/dist/{resources → extensions}/testserver/pool/channels.js +2 -2
  257. package/dist/{resources → extensions}/testserver/pool/create.d.ts +1 -2
  258. package/dist/{resources → extensions}/testserver/pool/create.js +2 -1
  259. package/dist/{resources → extensions}/testserver/pool/index.d.ts +0 -1
  260. package/dist/{resources → extensions}/testserver/pool/index.js +2 -3
  261. package/dist/{resources → extensions}/testserver/pool/inspect.d.ts +1 -1
  262. package/dist/{resources → extensions}/testserver/pool/lease.d.ts +1 -1
  263. package/dist/extensions/testserver/pool/live/pool-store-gateway.d.ts +12 -0
  264. package/dist/{resources → extensions}/testserver/pool/live/pool-store-gateway.js +4 -4
  265. package/dist/{resources → extensions}/testserver/pool/pull-request.d.ts +8 -5
  266. package/dist/{resources → extensions}/testserver/pool/pull-request.js +2 -2
  267. package/dist/extensions/testserver/pr-build-facts.d.ts +156 -0
  268. package/dist/extensions/testserver/pr-build-facts.js +309 -0
  269. package/dist/extensions/testserver/presentation.d.ts +11 -0
  270. package/dist/{resources → extensions}/testserver/presentation.js +35 -56
  271. package/dist/{resources/testserver/lane.d.ts → extensions/testserver/progress.d.ts} +10 -6
  272. package/dist/{resources/testserver/lane.js → extensions/testserver/progress.js} +21 -16
  273. package/dist/extensions/testserver/provision.d.ts +160 -0
  274. package/dist/{resources/testserver/provider.js → extensions/testserver/provision.js} +80 -108
  275. package/dist/{resources → extensions}/testserver/pull-request/gateways.d.ts +1 -1
  276. package/dist/extensions/testserver/pull-request/gateways.js +5 -0
  277. package/dist/{resources → extensions}/testserver/pull-request/index.js +2 -2
  278. package/dist/{resources → extensions}/testserver/pull-request/live/github-token-gateway.d.ts +4 -4
  279. package/dist/{resources → extensions}/testserver/pull-request/live/github-token-gateway.js +4 -4
  280. package/dist/extensions/testserver/refusals.d.ts +72 -0
  281. package/dist/extensions/testserver/refusals.js +117 -0
  282. package/dist/extensions/testserver/release.d.ts +14 -0
  283. package/dist/extensions/testserver/release.js +26 -0
  284. package/dist/extensions/testserver/resource.d.ts +57 -0
  285. package/dist/extensions/testserver/resource.js +19 -0
  286. package/dist/extensions/testserver/result.d.ts +55 -0
  287. package/dist/extensions/testserver/result.js +98 -0
  288. package/dist/extensions/testserver/run/connection.d.ts +21 -0
  289. package/dist/extensions/testserver/run/connection.js +39 -0
  290. package/dist/extensions/testserver/run-sandbox.d.ts +16 -0
  291. package/dist/extensions/testserver/run-sandbox.js +11 -0
  292. package/dist/{resources → extensions}/testserver/sandbox/create.d.ts +1 -11
  293. package/dist/{resources → extensions}/testserver/sandbox/create.js +0 -15
  294. package/dist/{resources → extensions}/testserver/sandbox/gateways.d.ts +1 -1
  295. package/dist/{resources → extensions}/testserver/sandbox/index.d.ts +1 -3
  296. package/dist/extensions/testserver/sandbox/index.js +6 -0
  297. package/dist/extensions/testserver/testserver-sdk.d.ts +1 -0
  298. package/dist/extensions/testserver/testserver-sdk.js +4 -0
  299. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/arguments.js +1 -1
  300. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/context.js +1 -1
  301. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/driver.d.ts +1 -1
  302. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/gateways.js +1 -1
  303. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/index.js +4 -4
  304. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/invocation.d.ts +1 -1
  305. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/invocation.js +1 -1
  306. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/redaction.js +1 -1
  307. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/report.d.ts +1 -1
  308. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/report.js +1 -1
  309. package/dist/{vercel-cli → extensions/testserver/vercel-cli}/verbose.js +1 -1
  310. package/dist/extensions/testserver/vitest/config.d.ts +30 -0
  311. package/dist/extensions/testserver/vitest/config.js +41 -0
  312. package/dist/{vitest → extensions/testserver/vitest}/container-scope.d.ts +25 -14
  313. package/dist/{vitest → extensions/testserver/vitest}/container-scope.js +55 -17
  314. package/dist/extensions/testserver/vitest/container-start.d.ts +19 -0
  315. package/dist/extensions/testserver/vitest/container-start.js +31 -0
  316. package/dist/{vitest → extensions/testserver/vitest}/diagnostics.d.ts +66 -29
  317. package/dist/{vitest → extensions/testserver/vitest}/diagnostics.js +146 -50
  318. package/dist/{vitest → extensions/testserver/vitest}/fixtures.d.ts +7 -5
  319. package/dist/{vitest → extensions/testserver/vitest}/fixtures.js +69 -26
  320. package/dist/extensions/testserver/vitest/index.d.ts +3 -0
  321. package/dist/extensions/testserver/vitest/index.js +10 -0
  322. package/dist/extensions/testserver/vitest/sandbox.d.ts +25 -0
  323. package/dist/extensions/testserver/vitest/sandbox.js +43 -0
  324. package/dist/{vitest → extensions/testserver/vitest}/types.d.ts +1 -1
  325. package/dist/extensions/testserver/world.d.ts +25 -0
  326. package/dist/extensions/testserver/world.js +4 -0
  327. package/dist/extensions.d.ts +144 -0
  328. package/dist/extensions.js +41 -0
  329. package/dist/forward-sigterm.d.ts +8 -0
  330. package/dist/forward-sigterm.js +18 -0
  331. package/dist/help-logo.js +5 -5
  332. package/dist/launch.js +46 -0
  333. package/dist/launcher-resolvers/index.d.ts +2 -0
  334. package/dist/launcher-resolvers/index.js +8 -0
  335. package/dist/launcher-resolvers/local-services.d.ts +57 -0
  336. package/dist/launcher-resolvers/local-services.js +7 -0
  337. package/dist/live-app.js +12 -7
  338. package/dist/local-services.d.ts +19 -0
  339. package/dist/local-services.js +37 -0
  340. package/dist/presentation.js +2 -2
  341. package/dist/run-directory/gateways.d.ts +167 -0
  342. package/dist/run-directory/gateways.js +2 -0
  343. package/dist/run-directory/index.d.ts +8 -0
  344. package/dist/run-directory/index.js +13 -0
  345. package/dist/run-directory/plan.d.ts +35 -0
  346. package/dist/run-directory/plan.js +24 -0
  347. package/dist/run-directory/reader.d.ts +70 -0
  348. package/dist/run-directory/reader.js +51 -0
  349. package/dist/run-directory/recording.d.ts +92 -0
  350. package/dist/run-directory/recording.js +85 -0
  351. package/dist/run-directory/run-collector.d.ts +36 -0
  352. package/dist/{commands/exec → run-directory}/run-collector.js +10 -12
  353. package/dist/{core → run-directory}/run-directory.d.ts +13 -14
  354. package/dist/{core → run-directory}/run-directory.js +11 -11
  355. package/dist/{commands/exec → run-directory}/run-record.d.ts +92 -61
  356. package/dist/run-directory/run-record.js +209 -0
  357. package/dist/run-directory/timeline-facts.d.ts +53 -0
  358. package/dist/run-directory/timeline-facts.js +76 -0
  359. package/dist/runner/base.js +1 -1
  360. package/dist/runner/context.js +1 -1
  361. package/dist/runner/events.d.ts +6 -5
  362. package/dist/runner/events.js +1 -1
  363. package/dist/runner/gateways.d.ts +11 -11
  364. package/dist/runner/gateways.js +1 -1
  365. package/dist/runner/index.d.ts +13 -17
  366. package/dist/runner/index.js +10 -14
  367. package/dist/runner/live/sandbox-gateway.js +4 -4
  368. package/dist/runner/live/terminal.d.ts +1 -1
  369. package/dist/runner/live/terminal.js +1 -1
  370. package/dist/runner/prepare.d.ts +40 -17
  371. package/dist/runner/prepare.js +17 -11
  372. package/dist/runner/ready.js +2 -2
  373. package/dist/runner/recipe.d.ts +38 -20
  374. package/dist/runner/recipe.js +31 -17
  375. package/dist/runner/{remote-command.d.ts → sandboxed-command.d.ts} +18 -19
  376. package/dist/runner/{remote-command.js → sandboxed-command.js} +21 -22
  377. package/dist/runner/scope.d.ts +21 -14
  378. package/dist/runner/scope.js +12 -10
  379. package/dist/runner/secrets.js +1 -1
  380. package/dist/runner/session.d.ts +100 -0
  381. package/dist/runner/session.js +109 -0
  382. package/dist/runner/snapshot-key.d.ts +1 -1
  383. package/dist/runner/snapshot-key.js +4 -4
  384. package/dist/runner/snapshot-save.d.ts +3 -2
  385. package/dist/runner/snapshot-save.js +8 -7
  386. package/dist/sdk/extension/ci.d.ts +2 -0
  387. package/dist/sdk/extension/ci.js +6 -0
  388. package/dist/sdk/extension/commands.d.ts +69 -0
  389. package/dist/sdk/extension/commands.js +31 -0
  390. package/dist/{credential/diagnosis.d.ts → sdk/extension/credential-diagnosis.d.ts} +1 -7
  391. package/dist/{credential/diagnosis.js → sdk/extension/credential-diagnosis.js} +2 -11
  392. package/dist/sdk/extension/credential-source.d.ts +132 -0
  393. package/dist/sdk/extension/credential-source.js +5 -0
  394. package/dist/{credential → sdk/extension}/credential.d.ts +8 -7
  395. package/dist/{credential → sdk/extension}/credential.js +9 -6
  396. package/dist/sdk/extension/index.d.ts +16 -0
  397. package/dist/sdk/extension/index.js +40 -0
  398. package/dist/sdk/extension/launcher-supplies.d.ts +24 -0
  399. package/dist/sdk/extension/launcher-supplies.js +3 -0
  400. package/dist/sdk/extension/lifecycle.d.ts +212 -0
  401. package/dist/sdk/extension/lifecycle.js +9 -0
  402. package/dist/sdk/extension/presentation.d.ts +31 -0
  403. package/dist/sdk/extension/presentation.js +7 -0
  404. package/dist/sdk/extension/progress.d.ts +75 -0
  405. package/dist/sdk/extension/progress.js +8 -0
  406. package/dist/sdk/extension/reports.d.ts +15 -0
  407. package/dist/sdk/extension/reports.js +5 -0
  408. package/dist/sdk/extension/resource-definition.d.ts +204 -0
  409. package/dist/sdk/extension/resource-definition.js +24 -0
  410. package/dist/sdk/extension/resource-factory.d.ts +10 -0
  411. package/dist/sdk/extension/resource-factory.js +15 -0
  412. package/dist/sdk/extension/resource.d.ts +60 -0
  413. package/dist/sdk/extension/resource.js +42 -0
  414. package/dist/sdk/extension/rules.d.ts +16 -0
  415. package/dist/sdk/extension/rules.js +30 -0
  416. package/dist/sdk/extension/span.d.ts +8 -0
  417. package/dist/sdk/extension/span.js +4 -0
  418. package/dist/sdk/extension/time.d.ts +11 -0
  419. package/dist/sdk/extension/time.js +4 -0
  420. package/dist/sdk/extension/token-request-facts.d.ts +39 -0
  421. package/dist/sdk/extension/token-request-facts.js +35 -0
  422. package/dist/sdk/index.d.ts +4 -7
  423. package/dist/sdk/index.js +7 -15
  424. package/dist/sdk/run/contract.d.ts +32 -0
  425. package/dist/sdk/run/contract.js +12 -0
  426. package/dist/sdk/run/launcher.d.ts +5 -0
  427. package/dist/sdk/run/launcher.js +6 -0
  428. package/dist/sdk/run/payload.d.ts +58 -0
  429. package/dist/sdk/run/payload.js +73 -0
  430. package/dist/sdk/run/present.d.ts +11 -0
  431. package/dist/sdk/run/present.js +4 -0
  432. package/dist/sdk/run/redact.d.ts +5 -0
  433. package/dist/sdk/run/redact.js +12 -0
  434. package/dist/story/align.d.ts +1 -1
  435. package/dist/story/align.js +1 -1
  436. package/dist/story/command-line.d.ts +6 -16
  437. package/dist/story/command-line.js +11 -23
  438. package/dist/story/errors.d.ts +1 -1
  439. package/dist/story/errors.js +1 -1
  440. package/dist/story/host.d.ts +1 -1
  441. package/dist/story/host.js +2 -2
  442. package/dist/story/index.d.ts +2 -2
  443. package/dist/story/index.js +4 -3
  444. package/dist/story/launch.d.ts +70 -0
  445. package/dist/story/launch.js +77 -0
  446. package/dist/story/report.d.ts +2 -2
  447. package/dist/story/report.js +3 -4
  448. package/dist/story/settle.d.ts +7 -7
  449. package/dist/story/settle.js +5 -5
  450. package/dist/story/start.d.ts +2 -2
  451. package/dist/time/duration.js +2 -2
  452. package/dist/time/index.js +2 -1
  453. package/dist/time/time.d.ts +2 -11
  454. package/dist/time/time.js +2 -2
  455. package/dist/{sdk → vendor/testserver-sdk}/container/api-request.d.ts +14 -2
  456. package/dist/vendor/testserver-sdk/container/api-request.js +68 -0
  457. package/dist/vendor/testserver-sdk/container/container.d.ts +199 -0
  458. package/dist/vendor/testserver-sdk/container/container.js +458 -0
  459. package/dist/vendor/testserver-sdk/container/external.d.ts +111 -0
  460. package/dist/vendor/testserver-sdk/container/external.js +76 -0
  461. package/dist/vendor/testserver-sdk/container/gateways.d.ts +156 -0
  462. package/dist/{sdk → vendor/testserver-sdk}/container/index.d.ts +2 -1
  463. package/dist/{sdk → vendor/testserver-sdk}/container/index.js +2 -1
  464. package/dist/vendor/testserver-sdk/container/live/container-gateway.d.ts +22 -0
  465. package/dist/vendor/testserver-sdk/container/live/container-gateway.js +165 -0
  466. package/dist/vendor/testserver-sdk/container/recorder.d.ts +69 -0
  467. package/dist/vendor/testserver-sdk/container/recorder.js +121 -0
  468. package/dist/{sdk → vendor/testserver-sdk}/factories/build.d.ts +33 -12
  469. package/dist/{sdk → vendor/testserver-sdk}/factories/build.js +36 -14
  470. package/dist/vendor/testserver-sdk/factories/definition.d.ts +39 -0
  471. package/dist/{sdk → vendor/testserver-sdk}/factories/definition.js +1 -1
  472. package/dist/{sdk → vendor/testserver-sdk}/factories/definitions.d.ts +7 -4
  473. package/dist/{sdk → vendor/testserver-sdk}/factories/definitions.js +10 -0
  474. package/dist/vendor/testserver-sdk/factories/gateways.d.ts +31 -0
  475. package/dist/vendor/testserver-sdk/factories/index.d.ts +4 -0
  476. package/dist/{sdk → vendor/testserver-sdk}/factories/index.js +3 -3
  477. package/dist/vendor/testserver-sdk/index.d.ts +6 -0
  478. package/dist/vendor/testserver-sdk/index.js +11 -0
  479. package/dist/{sdk → vendor/testserver-sdk}/proxy/exchange.d.ts +2 -1
  480. package/dist/{sdk → vendor/testserver-sdk}/proxy/exchange.js +8 -4
  481. package/dist/{sdk → vendor/testserver-sdk}/proxy/faulted-exchange.js +7 -2
  482. package/dist/{sdk → vendor/testserver-sdk}/proxy/faults.d.ts +2 -1
  483. package/dist/{sdk → vendor/testserver-sdk}/proxy/records.d.ts +10 -1
  484. package/dist/{sdk → vendor/testserver-sdk}/proxy/records.js +13 -0
  485. package/dist/{sdk → vendor/testserver-sdk}/records/index.d.ts +1 -1
  486. package/dist/{sdk → vendor/testserver-sdk}/records/records.d.ts +17 -1
  487. package/dist/vendor/testserver-sdk/testserver/external-ids.d.ts +38 -0
  488. package/dist/vendor/testserver-sdk/testserver/external-ids.js +46 -0
  489. package/dist/vendor/testserver-sdk/testserver/failure.d.ts +102 -0
  490. package/dist/vendor/testserver-sdk/testserver/failure.js +109 -0
  491. package/dist/vendor/testserver-sdk/testserver/index.d.ts +7 -0
  492. package/dist/vendor/testserver-sdk/testserver/index.js +11 -0
  493. package/dist/{sdk → vendor/testserver-sdk}/testserver/live/request.d.ts +8 -10
  494. package/dist/{sdk → vendor/testserver-sdk}/testserver/live/request.js +8 -6
  495. package/dist/vendor/testserver-sdk/testserver/routes.d.ts +60 -0
  496. package/dist/vendor/testserver-sdk/testserver/routes.js +84 -0
  497. package/dist/vendor/testserver-sdk/testserver/service-ids.d.ts +31 -0
  498. package/dist/{sdk → vendor/testserver-sdk}/testserver/service-ids.js +27 -4
  499. package/dist/vitest/config.d.ts +2 -28
  500. package/dist/vitest/config.js +6 -36
  501. package/dist/vitest/gateways.js +1 -1
  502. package/dist/vitest/index.d.ts +2 -3
  503. package/dist/vitest/index.js +5 -9
  504. package/dist/vitest/plan.d.ts +1 -16
  505. package/dist/vitest/plan.js +4 -36
  506. package/dist/vitest/test-events.d.ts +1 -18
  507. package/dist/vitest/test-events.js +2 -31
  508. package/package.json +52 -23
  509. package/skills/overview.md +12 -9
  510. package/skills/read-run-output.md +26 -3
  511. package/skills/testserver-builds.md +8 -8
  512. package/dist/chunks/chunk-5CQCRX2L.js +0 -5768
  513. package/dist/chunks/chunk-5U5Q6VZR.js +0 -556
  514. package/dist/chunks/chunk-7O6UN63H.js +0 -63
  515. package/dist/chunks/chunk-NX55IJ5S.js +0 -1842
  516. package/dist/chunks/chunk-OCZJE5XV.js +0 -910
  517. package/dist/chunks/chunk-RRQ2ZGSE.js +0 -1512
  518. package/dist/chunks/chunk-S5NAIZYS.js +0 -13
  519. package/dist/chunks/chunk-UHO5OCEX.js +0 -360
  520. package/dist/chunks/chunk-WBIHJM7D.js +0 -188
  521. package/dist/combine-errors.d.ts +0 -11
  522. package/dist/combine-errors.js +0 -19
  523. package/dist/commands/exec/run-collector.d.ts +0 -30
  524. package/dist/commands/exec/run-record.js +0 -152
  525. package/dist/commands/exec/testserver-flags.d.ts +0 -48
  526. package/dist/commands/exec/testserver-flags.js +0 -80
  527. package/dist/config/by-name.d.ts +0 -24
  528. package/dist/config/by-name.js +0 -26
  529. package/dist/config/resource-config.d.ts +0 -132
  530. package/dist/config/resource-config.js +0 -19
  531. package/dist/config/set.d.ts +0 -27
  532. package/dist/config/set.js +0 -71
  533. package/dist/core/command-provider.d.ts +0 -126
  534. package/dist/core/command-provider.js +0 -13
  535. package/dist/core/command-slots.d.ts +0 -73
  536. package/dist/core/command-slots.js +0 -140
  537. package/dist/core/keyed.d.ts +0 -12
  538. package/dist/core/keyed.js +0 -24
  539. package/dist/core/lane.d.ts +0 -46
  540. package/dist/core/lane.js +0 -5
  541. package/dist/core/mint.d.ts +0 -10
  542. package/dist/core/mint.js +0 -14
  543. package/dist/core/presentation.d.ts +0 -87
  544. package/dist/core/presentation.js +0 -5
  545. package/dist/core/provider.d.ts +0 -79
  546. package/dist/core/provider.js +0 -5
  547. package/dist/resource-commands.d.ts +0 -13
  548. package/dist/resource-commands.js +0 -22
  549. package/dist/resources/github/cleanup.d.ts +0 -23
  550. package/dist/resources/github/cleanup.js +0 -39
  551. package/dist/resources/github/command.d.ts +0 -126
  552. package/dist/resources/github/command.js +0 -117
  553. package/dist/resources/github/config.d.ts +0 -16
  554. package/dist/resources/github/config.js +0 -37
  555. package/dist/resources/github/events.d.ts +0 -26
  556. package/dist/resources/github/events.js +0 -2
  557. package/dist/resources/github/index.d.ts +0 -12
  558. package/dist/resources/github/index.js +0 -15
  559. package/dist/resources/github/live/gateways.d.ts +0 -6
  560. package/dist/resources/github/live/gateways.js +0 -13
  561. package/dist/resources/github/presentation.d.ts +0 -13
  562. package/dist/resources/github/presentation.js +0 -43
  563. package/dist/resources/github/provider.d.ts +0 -66
  564. package/dist/resources/github/provider.js +0 -58
  565. package/dist/resources/github/resource-provider.d.ts +0 -6
  566. package/dist/resources/github/resource-provider.js +0 -20
  567. package/dist/resources/github/resource.d.ts +0 -33
  568. package/dist/resources/github/resource.js +0 -12
  569. package/dist/resources/testserver/cleanup.d.ts +0 -14
  570. package/dist/resources/testserver/cleanup.js +0 -22
  571. package/dist/resources/testserver/command-tree.d.ts +0 -4
  572. package/dist/resources/testserver/command-tree.js +0 -12
  573. package/dist/resources/testserver/command.d.ts +0 -520
  574. package/dist/resources/testserver/command.js +0 -252
  575. package/dist/resources/testserver/commands/app.d.ts +0 -18
  576. package/dist/resources/testserver/commands/app.js +0 -3
  577. package/dist/resources/testserver/commands/create/metadata.d.ts +0 -31
  578. package/dist/resources/testserver/commands/create/metadata.js +0 -53
  579. package/dist/resources/testserver/commands/list/metadata.d.ts +0 -9
  580. package/dist/resources/testserver/config.d.ts +0 -18
  581. package/dist/resources/testserver/config.js +0 -88
  582. package/dist/resources/testserver/events.js +0 -4
  583. package/dist/resources/testserver/index.d.ts +0 -16
  584. package/dist/resources/testserver/index.js +0 -25
  585. package/dist/resources/testserver/live/gateways.d.ts +0 -8
  586. package/dist/resources/testserver/live/gateways.js +0 -39
  587. package/dist/resources/testserver/options.d.ts +0 -5
  588. package/dist/resources/testserver/options.js +0 -5
  589. package/dist/resources/testserver/pool/directory.d.ts +0 -4
  590. package/dist/resources/testserver/pool/directory.js +0 -5
  591. package/dist/resources/testserver/pool/live/pool-store-gateway.d.ts +0 -12
  592. package/dist/resources/testserver/pr-build-facts.d.ts +0 -130
  593. package/dist/resources/testserver/pr-build-facts.js +0 -261
  594. package/dist/resources/testserver/presentation.d.ts +0 -9
  595. package/dist/resources/testserver/provider.d.ts +0 -187
  596. package/dist/resources/testserver/pull-request/gateways.js +0 -5
  597. package/dist/resources/testserver/ran.d.ts +0 -92
  598. package/dist/resources/testserver/ran.js +0 -156
  599. package/dist/resources/testserver/resource-provider.d.ts +0 -12
  600. package/dist/resources/testserver/resource-provider.js +0 -32
  601. package/dist/resources/testserver/resource.d.ts +0 -36
  602. package/dist/resources/testserver/resource.js +0 -10
  603. package/dist/resources/testserver/run-sandbox.d.ts +0 -13
  604. package/dist/resources/testserver/run-sandbox.js +0 -6
  605. package/dist/resources/testserver/sandbox/index.js +0 -8
  606. package/dist/resources.d.ts +0 -702
  607. package/dist/resources.js +0 -83
  608. package/dist/sdk/container/api-request.js +0 -46
  609. package/dist/sdk/container/container.d.ts +0 -144
  610. package/dist/sdk/container/container.js +0 -346
  611. package/dist/sdk/container/gateways.d.ts +0 -108
  612. package/dist/sdk/container/live/container-gateway.d.ts +0 -17
  613. package/dist/sdk/container/live/container-gateway.js +0 -114
  614. package/dist/sdk/factories/definition.d.ts +0 -28
  615. package/dist/sdk/factories/gateways.d.ts +0 -25
  616. package/dist/sdk/factories/index.d.ts +0 -5
  617. package/dist/sdk/factories/live/factory-gateway.d.ts +0 -10
  618. package/dist/sdk/factories/live/factory-gateway.js +0 -29
  619. package/dist/sdk/host.d.ts +0 -2
  620. package/dist/sdk/host.js +0 -7
  621. package/dist/sdk/payload/index.d.ts +0 -2
  622. package/dist/sdk/payload/index.js +0 -4
  623. package/dist/sdk/payload/payload.d.ts +0 -47
  624. package/dist/sdk/payload/payload.js +0 -74
  625. package/dist/sdk/testserver/failure.d.ts +0 -73
  626. package/dist/sdk/testserver/failure.js +0 -61
  627. package/dist/sdk/testserver/index.d.ts +0 -5
  628. package/dist/sdk/testserver/index.js +0 -8
  629. package/dist/sdk/testserver/service-ids.d.ts +0 -19
  630. package/dist/story/mode.d.ts +0 -17
  631. package/dist/story/mode.js +0 -21
  632. package/dist/vitest/sandbox.d.ts +0 -22
  633. package/dist/vitest/sandbox.js +0 -41
  634. /package/dist/{credential/settle.js → config/credential-settle.js} +0 -0
  635. /package/dist/{resources → extensions}/github/gateways.d.ts +0 -0
  636. /package/dist/{resources → extensions}/github/gateways.js +0 -0
  637. /package/dist/{resources → extensions}/github/live/fixture-repo-gateway.d.ts +0 -0
  638. /package/dist/{resources → extensions}/github/live/fixture-repo-gateway.js +0 -0
  639. /package/dist/{resources/testserver/commands → extensions/testserver/commands/pool}/list/outcomes.d.ts +0 -0
  640. /package/dist/{core → extensions/testserver}/limit.d.ts +0 -0
  641. /package/dist/{resources/testserver/sandbox → extensions/testserver/options}/build-reference.d.ts +0 -0
  642. /package/dist/{resources/testserver/sandbox → extensions/testserver/options}/build-reference.js +0 -0
  643. /package/dist/{resources/testserver/sandbox → extensions/testserver/options}/channels.js +0 -0
  644. /package/dist/{resources → extensions}/testserver/pool/gateways.d.ts +0 -0
  645. /package/dist/{resources → extensions}/testserver/pool/gateways.js +0 -0
  646. /package/dist/{resources → extensions}/testserver/pool/host.d.ts +0 -0
  647. /package/dist/{resources → extensions}/testserver/pool/host.js +0 -0
  648. /package/dist/{resources → extensions}/testserver/pool/inspect.js +0 -0
  649. /package/dist/{resources → extensions}/testserver/pool/lease.js +0 -0
  650. /package/dist/{resources → extensions}/testserver/pool/live/pool-records.d.ts +0 -0
  651. /package/dist/{resources → extensions}/testserver/pool/live/pool-records.js +0 -0
  652. /package/dist/{resources → extensions}/testserver/pool/staleness.d.ts +0 -0
  653. /package/dist/{resources → extensions}/testserver/pool/staleness.js +0 -0
  654. /package/dist/{resources → extensions}/testserver/pull-request/index.d.ts +0 -0
  655. /package/dist/{resources → extensions}/testserver/pull-request/live/github-rest.d.ts +0 -0
  656. /package/dist/{resources → extensions}/testserver/pull-request/live/github-rest.js +0 -0
  657. /package/dist/{resources → extensions}/testserver/pull-request/live/pull-request-gateway.d.ts +0 -0
  658. /package/dist/{resources → extensions}/testserver/pull-request/live/pull-request-gateway.js +0 -0
  659. /package/dist/{resources → extensions}/testserver/pull-request/live/testserver-workflow-gateway.d.ts +0 -0
  660. /package/dist/{resources → extensions}/testserver/pull-request/live/testserver-workflow-gateway.js +0 -0
  661. /package/dist/{resources → extensions}/testserver/sandbox/create-failure.d.ts +0 -0
  662. /package/dist/{resources → extensions}/testserver/sandbox/create-failure.js +0 -0
  663. /package/dist/{resources → extensions}/testserver/sandbox/gateways.js +0 -0
  664. /package/dist/{resources → extensions}/testserver/sandbox/live/builds-response.d.ts +0 -0
  665. /package/dist/{resources → extensions}/testserver/sandbox/live/builds-response.js +0 -0
  666. /package/dist/{resources → extensions}/testserver/sandbox/live/control-plane-gateway.d.ts +0 -0
  667. /package/dist/{resources → extensions}/testserver/sandbox/live/control-plane-gateway.js +0 -0
  668. /package/dist/{resources → extensions}/testserver/sandbox/live/create-response.d.ts +0 -0
  669. /package/dist/{resources → extensions}/testserver/sandbox/live/create-response.js +0 -0
  670. /package/dist/{resources → extensions}/testserver/sandbox/live/fetch-failure.d.ts +0 -0
  671. /package/dist/{resources → extensions}/testserver/sandbox/live/fetch-failure.js +0 -0
  672. /package/dist/{resources → extensions}/testserver/sandbox/live/health-check-gateway.d.ts +0 -0
  673. /package/dist/{resources → extensions}/testserver/sandbox/live/health-check-gateway.js +0 -0
  674. /package/dist/{resources → extensions}/testserver/sandbox/live/sse.d.ts +0 -0
  675. /package/dist/{resources → extensions}/testserver/sandbox/live/sse.js +0 -0
  676. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/ansi.d.ts +0 -0
  677. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/ansi.js +0 -0
  678. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/arguments.d.ts +0 -0
  679. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/auth-config.d.ts +0 -0
  680. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/auth-config.js +0 -0
  681. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/clock.d.ts +0 -0
  682. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/clock.js +0 -0
  683. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/config-files.d.ts +0 -0
  684. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/config-files.js +0 -0
  685. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/context.d.ts +0 -0
  686. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/driver.js +0 -0
  687. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/entry.d.ts +0 -0
  688. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/entry.js +0 -0
  689. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/environment.d.ts +0 -0
  690. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/environment.js +0 -0
  691. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/errors.d.ts +0 -0
  692. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/errors.js +0 -0
  693. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/gateways.d.ts +0 -0
  694. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/index.d.ts +0 -0
  695. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/keys.d.ts +0 -0
  696. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/keys.js +0 -0
  697. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/live/config-files.d.ts +0 -0
  698. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/live/config-files.js +0 -0
  699. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/live/process-gateway.d.ts +0 -0
  700. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/live/process-gateway.js +0 -0
  701. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/redaction.d.ts +0 -0
  702. /package/dist/{vercel-cli → extensions/testserver/vercel-cli}/verbose.d.ts +0 -0
  703. /package/dist/{vitest → extensions/testserver/vitest}/types.js +0 -0
  704. /package/dist/{core → run-directory}/live/run-directory-gateway.d.ts +0 -0
  705. /package/dist/{core → run-directory}/live/run-directory-gateway.js +0 -0
  706. /package/dist/sdk/{payload → run}/test-events.d.ts +0 -0
  707. /package/dist/sdk/{payload → run}/test-events.js +0 -0
  708. /package/dist/{sdk → vendor/testserver-sdk}/container/feature-flags.d.ts +0 -0
  709. /package/dist/{sdk → vendor/testserver-sdk}/container/feature-flags.js +0 -0
  710. /package/dist/{sdk → vendor/testserver-sdk}/container/gateways.js +0 -0
  711. /package/dist/{sdk → vendor/testserver-sdk}/factories/gateways.js +0 -0
  712. /package/dist/{sdk → vendor/testserver-sdk}/proxy/faulted-exchange.d.ts +0 -0
  713. /package/dist/{sdk → vendor/testserver-sdk}/proxy/faults.js +0 -0
  714. /package/dist/{sdk → vendor/testserver-sdk}/proxy/index.d.ts +0 -0
  715. /package/dist/{sdk → vendor/testserver-sdk}/proxy/index.js +0 -0
  716. /package/dist/{sdk → vendor/testserver-sdk}/proxy/proxy.d.ts +0 -0
  717. /package/dist/{sdk → vendor/testserver-sdk}/proxy/proxy.js +0 -0
  718. /package/dist/{sdk → vendor/testserver-sdk}/records/body.d.ts +0 -0
  719. /package/dist/{sdk → vendor/testserver-sdk}/records/body.js +0 -0
  720. /package/dist/{sdk → vendor/testserver-sdk}/records/index.js +0 -0
  721. /package/dist/{sdk → vendor/testserver-sdk}/records/records.js +0 -0
  722. /package/dist/{sdk → vendor/testserver-sdk}/seed/index.d.ts +0 -0
  723. /package/dist/{sdk → vendor/testserver-sdk}/seed/index.js +0 -0
  724. /package/dist/{sdk → vendor/testserver-sdk}/seed/seed.d.ts +0 -0
  725. /package/dist/{sdk → vendor/testserver-sdk}/seed/seed.js +0 -0
  726. /package/dist/{sdk → vendor/testserver-sdk}/testserver/clock.d.ts +0 -0
  727. /package/dist/{sdk → vendor/testserver-sdk}/testserver/clock.js +0 -0
  728. /package/dist/{sdk → vendor/testserver-sdk}/testserver/live/connect-failure.d.ts +0 -0
  729. /package/dist/{sdk → vendor/testserver-sdk}/testserver/live/connect-failure.js +0 -0
  730. /package/dist/{sdk → vendor/testserver-sdk}/testserver/test-id.d.ts +0 -0
  731. /package/dist/{sdk → vendor/testserver-sdk}/testserver/test-id.js +0 -0
@@ -0,0 +1,3361 @@
1
+ import {
2
+ Credential,
3
+ NOT_COUNTED,
4
+ defaultResourceKey,
5
+ describeMintFailure,
6
+ describeValue,
7
+ nonEmptyString,
8
+ optionKeyPath,
9
+ resourceCall,
10
+ tokenRequestFailureFacts,
11
+ tokenRequestFailureShape
12
+ } from "./chunk-AMTYHUYB.js";
13
+ import {
14
+ defineErrors,
15
+ refused
16
+ } from "./chunk-4PRAB24Y.js";
17
+
18
+ // src/runner/live/user.ts
19
+ import { userInfo } from "node:os";
20
+ function localUserName() {
21
+ try {
22
+ return userInfo().username;
23
+ } catch {
24
+ return "unknown";
25
+ }
26
+ }
27
+
28
+ // src/runner/events.ts
29
+ function progressQueue(progress) {
30
+ let pending = Promise.resolve();
31
+ return {
32
+ add(event) {
33
+ pending = pending.then(() => progress.emit(event));
34
+ },
35
+ flush: () => pending
36
+ };
37
+ }
38
+
39
+ // src/runner/live/checkout-gateway.ts
40
+ import { execFile, spawn } from "node:child_process";
41
+
42
+ // src/runner/live/git-output.ts
43
+ function splitNul(output) {
44
+ const text = typeof output === "string" ? output : Buffer.from(output).toString("utf8");
45
+ return text.split("\0").filter((entry) => entry.length > 0);
46
+ }
47
+ function submodulePaths(entries) {
48
+ return entries.filter((entry) => entry.startsWith("160000 ")).map((entry) => entry.slice(entry.indexOf(" ") + 1));
49
+ }
50
+ function partitionUntracked(entries) {
51
+ const files = [];
52
+ const nestedRepositories = [];
53
+ for (const entry of entries) {
54
+ if (entry.endsWith("/")) nestedRepositories.push(entry.slice(0, -1));
55
+ else files.push(entry);
56
+ }
57
+ return { files, nestedRepositories };
58
+ }
59
+ function displayCommand(command, args) {
60
+ return [command, ...args].map(shellQuote).join(" ");
61
+ }
62
+ function shellQuote(argument) {
63
+ return /^[\w@%+=:,./^{}-]+$/.test(argument) ? argument : `'${argument.replaceAll("'", `'\\''`)}'`;
64
+ }
65
+
66
+ // src/runner/live/checkout-gateway.ts
67
+ var GIT_MAX_BUFFER = 1024 * 1024 * 1024;
68
+ var DIFF_OPTIONS = [
69
+ "--no-color",
70
+ "--no-ext-diff",
71
+ "--no-textconv",
72
+ "--no-renames",
73
+ "--no-relative",
74
+ "--ignore-submodules"
75
+ ];
76
+ function liveCheckoutGateway() {
77
+ return {
78
+ repositoryRoot: ({ cwd }) => repositoryRoot(cwd),
79
+ head: ({ repoRoot }) => head(repoRoot),
80
+ baseCandidate: ({ repoRoot, ref }) => baseCandidate(repoRoot, ref),
81
+ contains: ({ repoRoot, ancestor, descendant }) => contains(repoRoot, ancestor, descendant),
82
+ commitTime: ({ repoRoot, commit }) => commitTime(repoRoot, commit),
83
+ readFileAt: ({ repoRoot, commit, path }) => readFileAt(repoRoot, commit, path),
84
+ submodules: ({ repoRoot }) => submodules(repoRoot),
85
+ assembleUpload: ({ repoRoot, base }) => assembleUpload(repoRoot, base),
86
+ baseArchive: ({ repoRoot, base }) => baseArchive(repoRoot, base)
87
+ };
88
+ }
89
+ async function repositoryRoot(cwd) {
90
+ const run = await git(cwd, ["rev-parse", "--show-toplevel"]);
91
+ return run.ok ? { ok: true, value: run.stdout.toString("utf8").trim() } : run;
92
+ }
93
+ async function head(repoRoot) {
94
+ const [commit, branch, status] = await Promise.all([
95
+ git(repoRoot, ["rev-parse", "--verify", "HEAD"]),
96
+ git(repoRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]),
97
+ git(repoRoot, ["status", "--porcelain", "-z", "--untracked-files=normal"])
98
+ ]);
99
+ if (!commit.ok) return commit;
100
+ if (!branch.ok && branch.exitCode !== 1) return branch;
101
+ if (!status.ok) return status;
102
+ return {
103
+ ok: true,
104
+ value: {
105
+ branch: branch.ok ? branch.stdout.toString("utf8").trim() : null,
106
+ commit: commit.stdout.toString("utf8").trim(),
107
+ dirty: status.stdout.length > 0
108
+ }
109
+ };
110
+ }
111
+ async function baseCandidate(repoRoot, ref) {
112
+ const exists = await git(repoRoot, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
113
+ if (!exists.ok) return exists.exitCode === 1 ? { kind: "missing-ref" } : { kind: "failed", failure: exists.failure };
114
+ const mergeBase = await git(repoRoot, ["merge-base", "HEAD", ref]);
115
+ if (!mergeBase.ok)
116
+ return mergeBase.exitCode === 1 ? { kind: "unrelated" } : { kind: "failed", failure: mergeBase.failure };
117
+ return { kind: "merge-base", base: mergeBase.stdout.toString("utf8").trim() };
118
+ }
119
+ async function contains(repoRoot, ancestor, descendant) {
120
+ const present = await git(repoRoot, ["cat-file", "-e", `${ancestor}^{commit}`]);
121
+ if (!present.ok) return { ok: true, value: false };
122
+ const run = await git(repoRoot, ["merge-base", "--is-ancestor", ancestor, descendant]);
123
+ if (run.ok) return { ok: true, value: true };
124
+ return run.exitCode === 1 ? { ok: true, value: false } : run;
125
+ }
126
+ async function commitTime(repoRoot, commit) {
127
+ const run = await git(repoRoot, ["show", "-s", "--format=%ct", `${commit}^{commit}`]);
128
+ if (!run.ok) return run;
129
+ const seconds = Number(run.stdout.toString("utf8").trim());
130
+ return Number.isSafeInteger(seconds) ? { ok: true, value: seconds * 1e3 } : { ok: false, failure: { message: `git show printed no commit time for ${commit}` } };
131
+ }
132
+ async function readFileAt(repoRoot, commit, path) {
133
+ const object = `${commit}:${path}`;
134
+ const type = await git(repoRoot, ["cat-file", "-t", object]);
135
+ if (!type.ok || type.stdout.toString("utf8").trim() !== "blob") return { kind: "missing" };
136
+ const run = await git(repoRoot, ["cat-file", "blob", object]);
137
+ return run.ok ? { kind: "found", text: run.stdout.toString("utf8") } : { kind: "failed", failure: run.failure };
138
+ }
139
+ async function submodules(repoRoot) {
140
+ const run = await git(repoRoot, ["ls-files", "--stage", "-z"]);
141
+ return run.ok ? { ok: true, value: submodulePaths(splitNul(run.stdout)) } : run;
142
+ }
143
+ async function assembleUpload(repoRoot, base) {
144
+ const [patch, others] = await Promise.all([
145
+ git(repoRoot, [
146
+ "diff",
147
+ "--binary",
148
+ // A user's `diff.context=0` makes patches that need special flags to apply.
149
+ "--unified=3",
150
+ ...DIFF_OPTIONS,
151
+ "--src-prefix=a/",
152
+ "--dst-prefix=b/",
153
+ base
154
+ ]),
155
+ git(repoRoot, ["ls-files", "--others", "--exclude-standard", "-z"])
156
+ ]);
157
+ if (!patch.ok) return patch;
158
+ if (!others.ok) return others;
159
+ const { files, nestedRepositories } = partitionUntracked(splitNul(others.stdout));
160
+ let untrackedTarball;
161
+ if (files.length > 0) {
162
+ const tarball = await createTarball(repoRoot, files);
163
+ if (!tarball.ok) return tarball;
164
+ untrackedTarball = tarball.value;
165
+ }
166
+ return { ok: true, value: { patch: patch.stdout, untracked: files, untrackedTarball, nestedRepositories } };
167
+ }
168
+ async function baseArchive(repoRoot, base) {
169
+ const [tarball, fileList] = await Promise.all([
170
+ // LF line endings, as the patch has them: with `core.autocrlf=true`, the Git for Windows default, `git archive`
171
+ // writes CRLF files the patch doesn't apply to.
172
+ git(repoRoot, ["-c", "core.autocrlf=false", "-c", "core.eol=lf", "archive", "--format=tar.gz", base]),
173
+ git(repoRoot, ["ls-tree", "-r", "--name-only", "-z", "--full-tree", base])
174
+ ]);
175
+ if (!tarball.ok) return tarball;
176
+ if (!fileList.ok) return fileList;
177
+ return {
178
+ ok: true,
179
+ value: { tarball: tarball.stdout, fileList: fileList.stdout, files: splitNul(fileList.stdout).length }
180
+ };
181
+ }
182
+ function git(repoRoot, args) {
183
+ const argv = ["-C", repoRoot, ...args];
184
+ return new Promise((resolve) => {
185
+ execFile(
186
+ "git",
187
+ argv,
188
+ { encoding: "buffer", maxBuffer: GIT_MAX_BUFFER, env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" } },
189
+ (error, stdout, stderr) => {
190
+ if (error === null) {
191
+ resolve({ ok: true, stdout });
192
+ return;
193
+ }
194
+ const subcommand = args.find((arg, index) => arg !== "-c" && args[index - 1] !== "-c") ?? "";
195
+ const detail = stderr.toString("utf8").trim() || error.message;
196
+ resolve({
197
+ ok: false,
198
+ exitCode: typeof error.code === "number" ? error.code : void 0,
199
+ failure: { message: `git ${subcommand} failed: ${detail}`, displayCommand: displayCommand("git", argv) }
200
+ });
201
+ }
202
+ );
203
+ });
204
+ }
205
+ function createTarball(repoRoot, paths) {
206
+ const args = ["--null", "-czf", "-", "-C", repoRoot, "-T", "-"];
207
+ const command = displayCommand("tar", args);
208
+ return new Promise((resolve) => {
209
+ const child = spawn("tar", args, {
210
+ stdio: ["pipe", "pipe", "pipe"],
211
+ env: { ...process.env, COPYFILE_DISABLE: "1" }
212
+ });
213
+ const chunks = [];
214
+ const errors = [];
215
+ let stdinError;
216
+ let spawnError;
217
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
218
+ child.stderr.on("data", (chunk) => errors.push(chunk));
219
+ child.stdin.on("error", (error) => {
220
+ stdinError = error;
221
+ });
222
+ child.once("error", (error) => {
223
+ spawnError = error;
224
+ });
225
+ child.once("close", (code) => {
226
+ const stderr = Buffer.concat(errors).toString("utf8").trim();
227
+ if (spawnError !== void 0)
228
+ resolve({ ok: false, failure: { message: `tar failed: ${spawnError.message}`, displayCommand: command } });
229
+ else if (code !== 0)
230
+ resolve({
231
+ ok: false,
232
+ failure: { message: `tar failed (exit ${code ?? "none"}): ${stderr}`, displayCommand: command }
233
+ });
234
+ else if (stdinError !== void 0)
235
+ resolve({
236
+ ok: false,
237
+ failure: { message: `tar didn't read the whole path list: ${stdinError.message}`, displayCommand: command }
238
+ });
239
+ else resolve({ ok: true, value: Buffer.concat(chunks) });
240
+ });
241
+ child.stdin.end(paths.map((path) => `${path}\0`).join(""));
242
+ });
243
+ }
244
+
245
+ // src/runner/snapshot-key.ts
246
+ import { createHash } from "node:crypto";
247
+
248
+ // src/runner/base.ts
249
+ async function resolveBase(checkout, request2) {
250
+ const { repoRoot } = request2;
251
+ const refused2 = [];
252
+ let best;
253
+ for (const ref of request2.baseRefs) {
254
+ const candidate = await checkout.baseCandidate({ repoRoot, ref });
255
+ if (candidate.kind === "failed") return candidate;
256
+ if (candidate.kind === "missing-ref") {
257
+ refused2.push({ ref, reason: "missing" });
258
+ continue;
259
+ }
260
+ if (candidate.kind === "unrelated") {
261
+ refused2.push({ ref, reason: "unrelated" });
262
+ continue;
263
+ }
264
+ if (best === void 0) {
265
+ best = { base: candidate.base, ref };
266
+ continue;
267
+ }
268
+ if (candidate.base === best.base) continue;
269
+ const newer = await checkout.contains({ repoRoot, ancestor: best.base, descendant: candidate.base });
270
+ if (!newer.ok) return { kind: "failed", failure: newer.failure };
271
+ if (newer.value) best = { base: candidate.base, ref };
272
+ }
273
+ return best === void 0 ? { kind: "no-base-ref", refs: refused2 } : { kind: "resolved", ...best };
274
+ }
275
+ function baseStepContext(checkout, request2) {
276
+ const { repoRoot, base } = request2;
277
+ return {
278
+ base,
279
+ readBaseFile: async (path) => {
280
+ const file = await checkout.readFileAt({ repoRoot, commit: base, path });
281
+ if (file.kind === "found") return file.text;
282
+ if (file.kind === "missing") throw new Error(`${path} doesn't exist at ${base.slice(0, 12)}`);
283
+ throw new Error(`can't read ${path} at ${base.slice(0, 12)}: ${file.failure.message}`);
284
+ }
285
+ };
286
+ }
287
+
288
+ // src/time/duration.ts
289
+ var MIN_TTL_MINUTES = 10;
290
+ var MAX_TTL_MINUTES = 300;
291
+ function parseDuration(text) {
292
+ const match = /^(\d+)([mh])$/.exec(text);
293
+ if (match === null) return void 0;
294
+ const amount = Number(match[1]);
295
+ if (!Number.isSafeInteger(amount)) return void 0;
296
+ return match[2] === "h" ? amount * 60 : amount;
297
+ }
298
+ function parseTtl(text) {
299
+ const minutes = parseDuration(text);
300
+ return minutes !== void 0 && minutes >= MIN_TTL_MINUTES && minutes <= MAX_TTL_MINUTES ? minutes : void 0;
301
+ }
302
+ function parseKeepTime(text) {
303
+ if (text === "0") return 0;
304
+ const minutes = parseDuration(text);
305
+ return minutes !== void 0 && minutes <= MAX_TTL_MINUTES ? minutes : void 0;
306
+ }
307
+
308
+ // src/time/time.ts
309
+ var systemTimer = {
310
+ sleep: (ms, signal) => new Promise((resolve) => {
311
+ if (signal?.aborted === true) {
312
+ resolve();
313
+ return;
314
+ }
315
+ const done = () => {
316
+ clearTimeout(timeout);
317
+ signal?.removeEventListener("abort", done);
318
+ resolve();
319
+ };
320
+ const timeout = setTimeout(done, ms);
321
+ signal?.addEventListener("abort", done, { once: true });
322
+ })
323
+ };
324
+ var systemClock = {
325
+ now: () => /* @__PURE__ */ new Date()
326
+ };
327
+
328
+ // src/sdk/run/payload.ts
329
+ import { z } from "zod";
330
+ var RUN_PAYLOAD_VARIABLE = "STORM_RUN";
331
+ var RUN_PAYLOAD_VERSION = 3;
332
+ var runPayloadSchema = z.object({
333
+ version: z.literal(RUN_PAYLOAD_VERSION),
334
+ resources: z.record(z.string(), z.object({ definition: z.string().min(1), payload: z.unknown() })),
335
+ testEvents: z.string().min(1).optional(),
336
+ verbose: z.literal(true).optional()
337
+ });
338
+
339
+ // src/sdk/run/test-events.ts
340
+ import { z as z2 } from "zod";
341
+ var where = { file: z2.string(), worker: z2.number().int().positive(), at: z2.number() };
342
+ var state = z2.enum(["pass", "fail", "skip"]);
343
+ var testEventSchema = z2.discriminatedUnion("kind", [
344
+ z2.object({ kind: z2.literal("file-started"), ...where }),
345
+ z2.object({ kind: z2.literal("file-finished"), ...where }),
346
+ z2.object({ kind: z2.literal("test-started"), ...where, test: z2.string(), fileTests: z2.number().int().nonnegative() }),
347
+ z2.object({
348
+ kind: z2.literal("test-attempt-finished"),
349
+ ...where,
350
+ test: z2.string(),
351
+ state,
352
+ ms: z2.number().nonnegative()
353
+ }),
354
+ z2.object({ kind: z2.literal("container-starting"), ...where }),
355
+ z2.object({
356
+ kind: z2.literal("container-started"),
357
+ ...where,
358
+ ms: z2.number().nonnegative(),
359
+ ok: z2.boolean(),
360
+ warmupMs: z2.number().nonnegative().exactOptional(),
361
+ warmupFailed: z2.number().int().nonnegative().exactOptional()
362
+ }),
363
+ z2.object({
364
+ kind: z2.literal("test-result"),
365
+ id: z2.string().min(1),
366
+ file: z2.string(),
367
+ test: z2.string(),
368
+ state,
369
+ retryCount: z2.number().int().nonnegative(),
370
+ flaky: z2.boolean(),
371
+ at: z2.number(),
372
+ errors: z2.array(
373
+ z2.object({
374
+ name: z2.string(),
375
+ message: z2.string(),
376
+ stack: z2.string().exactOptional(),
377
+ diff: z2.string().exactOptional()
378
+ })
379
+ ).exactOptional(),
380
+ output: z2.object({ text: z2.string(), droppedChars: z2.number().int().nonnegative() }).exactOptional()
381
+ })
382
+ ]);
383
+ function testEventLine(event) {
384
+ return JSON.stringify(event);
385
+ }
386
+ function parseTestEvent(line) {
387
+ let json;
388
+ try {
389
+ json = JSON.parse(line);
390
+ } catch {
391
+ return void 0;
392
+ }
393
+ const parsed = testEventSchema.safeParse(json);
394
+ return parsed.success ? parsed.data : void 0;
395
+ }
396
+
397
+ // src/sdk/run/redact.ts
398
+ var REDACTED = "<token>";
399
+ function redactSecrets(text, secrets) {
400
+ const ordered = [...secrets].filter((secret) => secret !== "").toSorted((a, b) => b.length - a.length);
401
+ return ordered.reduce((redacted, secret) => redacted.split(secret).join(REDACTED), text);
402
+ }
403
+
404
+ // src/runner/output.ts
405
+ var OUTPUT_TAIL_LINES = 40;
406
+ function lineSplitter() {
407
+ let buffer = "";
408
+ return {
409
+ push(chunk) {
410
+ const end = chunk.lastIndexOf("\n");
411
+ if (end === -1) {
412
+ buffer += chunk;
413
+ return "";
414
+ }
415
+ const lines = buffer + chunk.slice(0, end + 1);
416
+ buffer = chunk.slice(end + 1);
417
+ return lines;
418
+ },
419
+ flush() {
420
+ const rest = buffer;
421
+ buffer = "";
422
+ return rest;
423
+ }
424
+ };
425
+ }
426
+ function rewritePaths(text, fromRoot, toRoot) {
427
+ const from = `${fromRoot.replace(/\/+$/, "")}/`;
428
+ const to = `${toRoot.replace(/\/+$/, "")}/`;
429
+ return text.split(from).join(to);
430
+ }
431
+ function outputTail(limit = OUTPUT_TAIL_LINES) {
432
+ const kept = [];
433
+ return {
434
+ add(line) {
435
+ kept.push(line);
436
+ if (kept.length > limit) kept.shift();
437
+ },
438
+ lines: () => [...kept]
439
+ };
440
+ }
441
+ function splitLines(text) {
442
+ if (text === "") return [];
443
+ const lines = text.split("\n");
444
+ if (lines.at(-1) === "") lines.pop();
445
+ return lines;
446
+ }
447
+
448
+ // src/runner/steps.ts
449
+ var STEP_ENV = {
450
+ HUSKY: "0",
451
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: "0",
452
+ COREPACK_ENABLE_STRICT: "0",
453
+ npm_config_update_notifier: "false"
454
+ };
455
+ async function runStep(context, request2, progress, signal) {
456
+ const { phase, label } = request2;
457
+ const startedAt = context.clock.now().getTime();
458
+ await progress.emit({ kind: "step-started", phase, label });
459
+ const queue = progressQueue(progress);
460
+ const tail = outputTail();
461
+ const splitters = { stdout: lineSplitter(), stderr: lineSplitter() };
462
+ const emit = (stream, text) => {
463
+ for (const line of splitLines(text)) {
464
+ tail.add(line);
465
+ queue.add({ kind: "step-output", phase, stream, line });
466
+ }
467
+ };
468
+ const ran = await context.runnerSandboxes.runScript(
469
+ request2.sandbox,
470
+ { script: request2.script, env: { ...STEP_ENV, ...request2.secrets } },
471
+ ({ stream, data }) => emit(stream, splitters[stream].push(data)),
472
+ signal
473
+ );
474
+ emit("stdout", splitters.stdout.flush());
475
+ emit("stderr", splitters.stderr.flush());
476
+ await queue.flush();
477
+ if (!ran.ok) return { kind: "sandbox-failed", failure: ran.failure };
478
+ if (ran.value.exitCode !== 0) return { kind: "exited", exitCode: ran.value.exitCode, tail: tail.lines() };
479
+ const ms = context.clock.now().getTime() - startedAt;
480
+ await progress.emit({ kind: "step-finished", phase, label, ms });
481
+ return { kind: "succeeded", ms };
482
+ }
483
+ function sandboxApiFailure(operation, failure) {
484
+ if (failure.kind === "snapshot-gone")
485
+ return { kind: "sandbox-api-failed", operation, status: 410, message: failure.message };
486
+ return { kind: "sandbox-api-failed", operation, status: failure.status ?? null, message: failure.message };
487
+ }
488
+ function sandboxStop(operation, failure) {
489
+ return failure.kind === "aborted" ? { kind: "aborted" } : { kind: "failed", failure: sandboxApiFailure(operation, failure) };
490
+ }
491
+
492
+ // src/runner/recipe.ts
493
+ function runStepTakesSecret(recipe) {
494
+ return recipe.run.install.secrets.length > 0 || recipe.run.build.secrets.length > 0;
495
+ }
496
+ var RECIPE_DEFAULTS = {
497
+ cwd: ".",
498
+ timeout: "60m",
499
+ baseRefs: ["main", "origin/main"],
500
+ region: "iad1",
501
+ runtime: "node22"
502
+ };
503
+ var RECIPE_KEYS = /* @__PURE__ */ new Set([
504
+ "name",
505
+ "snapshot",
506
+ "run",
507
+ "cwd",
508
+ "vcpus",
509
+ "env",
510
+ "secrets",
511
+ "timeout",
512
+ "keepSandbox",
513
+ "saveSnapshot",
514
+ "baseRefs",
515
+ "region",
516
+ "runtime"
517
+ ]);
518
+ var SNAPSHOT_KEYS = /* @__PURE__ */ new Set(["vcpus", "summary", "toolchains", "prebuild"]);
519
+ var RUN_KEYS = /* @__PURE__ */ new Set(["install", "build"]);
520
+ var STEP_KEYS = /* @__PURE__ */ new Set(["label", "script", "secrets"]);
521
+ var NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
522
+ var VARIABLE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
523
+ var RESERVED_SECRET_NAMES = /* @__PURE__ */ new Set([
524
+ "PATH",
525
+ "HOME",
526
+ "USER",
527
+ "LOGNAME",
528
+ "SHELL",
529
+ "PWD",
530
+ "TMPDIR",
531
+ "BASH_ENV",
532
+ "ENV",
533
+ "IFS",
534
+ "NODE_OPTIONS"
535
+ ]);
536
+ var RESERVED_SECRET_PREFIXES = ["LD_", "DYLD_"];
537
+ function checkRecipe(value) {
538
+ const problems = [];
539
+ const report = (path, problem) => problems.push({ path, problem });
540
+ if (!isRecord(value)) {
541
+ report([], `must be an object, not ${describeRecipeValue(value)}`);
542
+ return { ok: false, problems };
543
+ }
544
+ reportUnknownKeys(value, RECIPE_KEYS, [], "a runner recipe key", report);
545
+ const name = value["name"];
546
+ if (typeof name !== "string" || !NAME_PATTERN.test(name))
547
+ report(
548
+ ["name"],
549
+ `must be lowercase letters, digits and dashes, starting with a letter or digit, not ${describeRecipeValue(name)}`
550
+ );
551
+ const declared = declaredSecrets(value["secrets"]);
552
+ const snapshot = checkSnapshot(value["snapshot"], declared, report);
553
+ const run = checkRun(value["run"], declared, report);
554
+ const cwd = orDefault(value["cwd"], RECIPE_DEFAULTS.cwd);
555
+ if (!isRelativePath(cwd))
556
+ report(["cwd"], `must be a path relative to the repository's root, without "..", not ${describeRecipeValue(cwd)}`);
557
+ const vcpus = value["vcpus"];
558
+ if (typeof vcpus !== "function" && !isPositiveInteger(vcpus))
559
+ report(["vcpus"], `must be a positive whole number, or a function of the run, not ${describeRecipeValue(vcpus)}`);
560
+ const env = checkEnv(value["env"], report);
561
+ const secrets = checkSecrets(value["secrets"], report);
562
+ const timeout = orDefault(value["timeout"], RECIPE_DEFAULTS.timeout);
563
+ const timeoutMinutes = typeof timeout === "string" ? parseTtl(timeout) : void 0;
564
+ if (timeoutMinutes === void 0)
565
+ report(
566
+ ["timeout"],
567
+ `must be a whole number of minutes or hours from 10m to 5h, not ${describeRecipeValue(timeout)}`
568
+ );
569
+ const keepSandbox = value["keepSandbox"];
570
+ const keepSandboxMinutes = typeof keepSandbox === "string" ? parseKeepTime(keepSandbox) : void 0;
571
+ if (keepSandbox !== void 0 && keepSandboxMinutes === void 0)
572
+ report(
573
+ ["keepSandbox"],
574
+ `must be 0, or a whole number of minutes or hours up to 5h, not ${describeRecipeValue(keepSandbox)}`
575
+ );
576
+ const saveSnapshot = value["saveSnapshot"];
577
+ if (saveSnapshot !== void 0 && typeof saveSnapshot !== "boolean")
578
+ report(["saveSnapshot"], `must be true or false, not ${describeRecipeValue(saveSnapshot)}`);
579
+ const baseRefs = checkBaseRefs(value["baseRefs"], report);
580
+ const region = orDefault(value["region"], RECIPE_DEFAULTS.region);
581
+ if (!isNonEmptyString(region)) report(["region"], `must be a non-empty string, not ${describeRecipeValue(region)}`);
582
+ const runtime = orDefault(value["runtime"], RECIPE_DEFAULTS.runtime);
583
+ if (!isNonEmptyString(runtime))
584
+ report(["runtime"], `must be a non-empty string, not ${describeRecipeValue(runtime)}`);
585
+ if (problems.length > 0 || snapshot === void 0 || run === void 0 || env === void 0 || secrets === void 0 || baseRefs === void 0 || timeoutMinutes === void 0)
586
+ return { ok: false, problems };
587
+ return {
588
+ ok: true,
589
+ value: {
590
+ name,
591
+ snapshot,
592
+ run,
593
+ cwd,
594
+ vcpus,
595
+ env,
596
+ secrets,
597
+ timeout,
598
+ timeoutMinutes,
599
+ keepSandboxMinutes,
600
+ ...typeof saveSnapshot === "boolean" ? { saveSnapshot } : {},
601
+ baseRefs,
602
+ region,
603
+ runtime
604
+ }
605
+ };
606
+ }
607
+ function declaredSecrets(value) {
608
+ if (value === void 0) return /* @__PURE__ */ new Set();
609
+ if (!Array.isArray(value)) return void 0;
610
+ return new Set(value.filter((name) => typeof name === "string"));
611
+ }
612
+ function checkSnapshot(value, declared, report) {
613
+ if (!isRecord(value)) {
614
+ report(
615
+ ["snapshot"],
616
+ `must be an object of vcpus, toolchains, prebuild and an optional summary, not ${describeRecipeValue(value)}`
617
+ );
618
+ return void 0;
619
+ }
620
+ let ok = reportUnknownKeys(value, SNAPSHOT_KEYS, ["snapshot"], "a runner recipe snapshot key", report);
621
+ const vcpus = value["vcpus"];
622
+ if (!isPositiveInteger(vcpus)) {
623
+ report(["snapshot", "vcpus"], `must be a positive whole number, not ${describeRecipeValue(vcpus)}`);
624
+ ok = false;
625
+ }
626
+ const summary = value["summary"];
627
+ if (summary !== void 0 && !isNonEmptyString(summary)) {
628
+ report(["snapshot", "summary"], `must be a non-empty string, not ${describeRecipeValue(summary)}`);
629
+ ok = false;
630
+ }
631
+ const toolchains = checkSteps(value["toolchains"], ["snapshot", "toolchains"], declared, report);
632
+ const prebuild = checkSteps(value["prebuild"], ["snapshot", "prebuild"], declared, report);
633
+ if (!ok || toolchains === void 0 || prebuild === void 0) return void 0;
634
+ return {
635
+ vcpus,
636
+ ...summary === void 0 ? {} : { summary },
637
+ toolchains,
638
+ prebuild
639
+ };
640
+ }
641
+ function checkRun(value, declared, report) {
642
+ if (!isRecord(value)) {
643
+ report(["run"], `must be an object of install and build steps, not ${describeRecipeValue(value)}`);
644
+ return void 0;
645
+ }
646
+ const ok = reportUnknownKeys(value, RUN_KEYS, ["run"], "a runner recipe run key", report);
647
+ const install = checkStep(value["install"], ["run", "install"], declared, report);
648
+ const build = checkStep(value["build"], ["run", "build"], declared, report);
649
+ return ok && install !== void 0 && build !== void 0 ? { install, build } : void 0;
650
+ }
651
+ function checkSteps(value, path, declared, report) {
652
+ if (typeof value === "function") return value;
653
+ if (!Array.isArray(value)) {
654
+ report(path, `must be a list of steps, or a function that returns one, not ${describeRecipeValue(value)}`);
655
+ return void 0;
656
+ }
657
+ const steps = value.map((step, index) => checkStep(step, [...path, String(index)], declared, report));
658
+ return steps.every((step) => step !== void 0) ? steps : void 0;
659
+ }
660
+ function checkStep(value, path, declared, report) {
661
+ if (!isRecord(value)) {
662
+ report(path, `must be a step, { label, script }, not ${describeRecipeValue(value)}`);
663
+ return void 0;
664
+ }
665
+ let ok = reportUnknownKeys(value, STEP_KEYS, path, "a step key", report);
666
+ const label = value["label"];
667
+ const script = value["script"];
668
+ if (!isNonEmptyString(label)) {
669
+ report([...path, "label"], `must be a non-empty string, not ${describeRecipeValue(label)}`);
670
+ ok = false;
671
+ }
672
+ if (!isNonEmptyString(script)) {
673
+ report([...path, "script"], `must be a non-empty string, not ${describeRecipeValue(script)}`);
674
+ ok = false;
675
+ }
676
+ const secrets = checkStepSecrets(value["secrets"], [...path, "secrets"], declared, report);
677
+ if (secrets === void 0) ok = false;
678
+ return ok && secrets !== void 0 ? { label, script, secrets } : void 0;
679
+ }
680
+ function checkStepSecrets(value, path, declared, report) {
681
+ if (value === void 0) return [];
682
+ if (!Array.isArray(value)) {
683
+ report(path, `must be a list of names runner.secrets declares, not ${describeRecipeValue(value)}`);
684
+ return void 0;
685
+ }
686
+ let ok = true;
687
+ const seen = /* @__PURE__ */ new Set();
688
+ value.forEach((name, index) => {
689
+ const at = [...path, String(index)];
690
+ if (typeof name !== "string") {
691
+ report(at, `must be a name runner.secrets declares, not ${describeRecipeValue(name)}`);
692
+ ok = false;
693
+ } else if (declared !== void 0 && !declared.has(name)) {
694
+ report(at, `names ${name}, which runner.secrets doesn't declare`);
695
+ ok = false;
696
+ } else if (seen.has(name)) {
697
+ report(at, `names ${name} again`);
698
+ ok = false;
699
+ }
700
+ if (typeof name === "string") seen.add(name);
701
+ });
702
+ return ok ? [...value] : void 0;
703
+ }
704
+ function checkEnv(value, report) {
705
+ if (value === void 0) return {};
706
+ if (!isRecord(value)) {
707
+ report(["env"], `must be an object of strings, not ${describeRecipeValue(value)}`);
708
+ return void 0;
709
+ }
710
+ let ok = true;
711
+ const env = {};
712
+ for (const [key, variable] of Object.entries(value)) {
713
+ if (key === RUN_PAYLOAD_VARIABLE) {
714
+ report(["env", key], "can't be set: storm sets it for the command");
715
+ ok = false;
716
+ } else if (typeof variable !== "string") {
717
+ report(["env", key], `must be a string, not ${describeRecipeValue(variable)}`);
718
+ ok = false;
719
+ } else env[key] = variable;
720
+ }
721
+ return ok ? env : void 0;
722
+ }
723
+ function checkSecrets(value, report) {
724
+ if (value === void 0) return [];
725
+ if (!Array.isArray(value)) {
726
+ report(["secrets"], `must be a list of environment variable names, not ${describeRecipeValue(value)}`);
727
+ return void 0;
728
+ }
729
+ let ok = true;
730
+ const seen = /* @__PURE__ */ new Set();
731
+ value.forEach((name, index) => {
732
+ const path = ["secrets", String(index)];
733
+ if (typeof name !== "string" || !VARIABLE_PATTERN.test(name)) {
734
+ report(
735
+ path,
736
+ `must be an environment variable name, letters, digits and underscores, not starting with a digit, not ${describeRecipeValue(name)}`
737
+ );
738
+ ok = false;
739
+ } else if (name === RUN_PAYLOAD_VARIABLE) {
740
+ report(path, `can't be ${name}: storm sets it for the command`);
741
+ ok = false;
742
+ } else if (Object.hasOwn(STEP_ENV, name)) {
743
+ report(path, `can't be ${name}: storm sets it for every step`);
744
+ ok = false;
745
+ } else if (RESERVED_SECRET_NAMES.has(name)) {
746
+ report(path, `can't be ${name}: it changes how a step's shell or programs run`);
747
+ ok = false;
748
+ } else if (reservedPrefix(name) !== void 0) {
749
+ report(path, `can't be ${name}: a name starting with ${reservedPrefix(name)} changes how a step's programs load`);
750
+ ok = false;
751
+ } else if (seen.has(name)) {
752
+ report(path, `names ${name} again`);
753
+ ok = false;
754
+ }
755
+ if (typeof name === "string") seen.add(name);
756
+ });
757
+ return ok ? [...value] : void 0;
758
+ }
759
+ function reservedPrefix(name) {
760
+ return RESERVED_SECRET_PREFIXES.find((prefix) => name.startsWith(prefix));
761
+ }
762
+ function checkBaseRefs(value, report) {
763
+ if (value === void 0) return [...RECIPE_DEFAULTS.baseRefs];
764
+ if (!Array.isArray(value) || value.length === 0) {
765
+ report(["baseRefs"], `must be a non-empty list of refs, not ${describeRecipeValue(value)}`);
766
+ return void 0;
767
+ }
768
+ let ok = true;
769
+ value.forEach((ref, index) => {
770
+ if (!isNonEmptyString(ref)) {
771
+ report(["baseRefs", String(index)], `must be a non-empty string, not ${describeRecipeValue(ref)}`);
772
+ ok = false;
773
+ }
774
+ });
775
+ return ok ? [...value] : void 0;
776
+ }
777
+ function reportUnknownKeys(value, known, path, what, report) {
778
+ let ok = true;
779
+ for (const key of Object.keys(value))
780
+ if (!known.has(key)) {
781
+ report([...path, key], `is not ${what}`);
782
+ ok = false;
783
+ }
784
+ return ok;
785
+ }
786
+ async function resolveSteps(steps, context, declared) {
787
+ if (typeof steps !== "function")
788
+ return {
789
+ ok: true,
790
+ steps: steps.map(({ label, script, secrets }) => ({ label, script, secrets: [...secrets ?? []] }))
791
+ };
792
+ let returned;
793
+ try {
794
+ returned = await steps(context);
795
+ } catch (error) {
796
+ return { ok: false, problem: `threw at base ${context.base.slice(0, 12)}: ${errorMessage(error)}` };
797
+ }
798
+ if (!Array.isArray(returned))
799
+ return { ok: false, problem: `must return a list of steps, not ${describeRecipeValue(returned)}` };
800
+ const problems = [];
801
+ const names = new Set(declared);
802
+ const checked = returned.map(
803
+ (step, index) => checkStep(step, [String(index)], names, (path, problem) => problems.push({ path, problem }))
804
+ );
805
+ const first = problems[0];
806
+ if (first !== void 0)
807
+ return {
808
+ ok: false,
809
+ problem: `must return a list of { label, script } steps, but item ${first.path.join(".")} ${first.problem}`
810
+ };
811
+ return { ok: true, steps: checked };
812
+ }
813
+ function resolveVcpus(recipe, { run, resourceKeys }) {
814
+ if (typeof recipe.vcpus !== "function") return { ok: true, vcpus: recipe.vcpus };
815
+ let returned;
816
+ try {
817
+ returned = recipe.vcpus(run);
818
+ } catch (error) {
819
+ return { ok: false, problem: `threw for ${describeResourceKeys(resourceKeys)}: ${errorMessage(error)}` };
820
+ }
821
+ return isPositiveInteger(returned) ? { ok: true, vcpus: returned } : {
822
+ ok: false,
823
+ problem: `must return a positive whole number, not ${describeRecipeValue(returned)} for ${describeResourceKeys(resourceKeys)}`
824
+ };
825
+ }
826
+ function describeResourceKeys(names) {
827
+ const last = names.at(-1);
828
+ if (last === void 0) return "a run with no resource";
829
+ return `a run with ${names.length === 1 ? last : `${names.slice(0, -1).join(", ")} and ${last}`}`;
830
+ }
831
+ function describeRecipeValue(value) {
832
+ if (typeof value === "string") return JSON.stringify(value);
833
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
834
+ if (value === null) return "null";
835
+ if (value === void 0) return "undefined";
836
+ if (typeof value === "function") return "a function";
837
+ if (Array.isArray(value)) return value.length === 0 ? "an empty array" : "an array";
838
+ if (typeof value === "object") return "an object";
839
+ return `a ${typeof value}`;
840
+ }
841
+ function errorMessage(error) {
842
+ return error instanceof Error ? error.message : String(error);
843
+ }
844
+ function orDefault(value, fallback) {
845
+ return value === void 0 ? fallback : value;
846
+ }
847
+ function isRecord(value) {
848
+ return typeof value === "object" && value !== null && !Array.isArray(value);
849
+ }
850
+ function isNonEmptyString(value) {
851
+ return typeof value === "string" && value.length > 0;
852
+ }
853
+ function isPositiveInteger(value) {
854
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
855
+ }
856
+ function isRelativePath(value) {
857
+ return typeof value === "string" && value.length > 0 && !value.startsWith("/") && !value.split(/[/\\]/).includes("..");
858
+ }
859
+
860
+ // src/runner/snapshot-key.ts
861
+ var SNAPSHOT_FORMAT = 2;
862
+ var SANDBOX_ROOT = "/vercel/sandbox";
863
+ var STAGED_FILES = {
864
+ baseTarball: "base.tgz",
865
+ baseFileList: "base-files",
866
+ patch: "run.patch",
867
+ untrackedTarball: "untracked.tgz",
868
+ untrackedFileList: "untracked-files"
869
+ };
870
+ var GIT_IDENTITY = "-c user.email=storm-runner@vercel.invalid -c user.name='storm runner' -c commit.gpgsign=false";
871
+ var RESET_TO_BASE = [
872
+ "root=$(git rev-list --max-parents=0 HEAD)",
873
+ 'git reset -q --hard "$root"',
874
+ "git clean -ffdq"
875
+ ];
876
+ function bashScript(lines) {
877
+ return ["set -euo pipefail", `cd ${SANDBOX_ROOT}`, ...lines].join("\n");
878
+ }
879
+ function baseIndexScript(base, staging) {
880
+ const tarball = `${staging}/${STAGED_FILES.baseTarball}`;
881
+ const fileList = `${staging}/${STAGED_FILES.baseFileList}`;
882
+ return bashScript([
883
+ `tar --warning=no-unknown-keyword -xzf ${tarball} -C ${SANDBOX_ROOT}`,
884
+ `rm -f ${tarball}`,
885
+ "git -c init.defaultBranch=main init -q",
886
+ `git --literal-pathspecs add -f --pathspec-from-file=${fileList} --pathspec-file-nul`,
887
+ `rm -f ${fileList}`,
888
+ `git ${GIT_IDENTITY} commit -q --no-verify -m 'base ${base}'`
889
+ ]);
890
+ }
891
+ function applyScript(staging) {
892
+ const patch = `${staging}/${STAGED_FILES.patch}`;
893
+ const tarball = `${staging}/${STAGED_FILES.untrackedTarball}`;
894
+ const fileList = `${staging}/${STAGED_FILES.untrackedFileList}`;
895
+ return bashScript([
896
+ ...RESET_TO_BASE,
897
+ // A build may have rewritten tracked files with the same content.
898
+ "git update-index -q --refresh || true",
899
+ `if [ -s ${patch} ]; then git apply --index --binary ${patch}; fi`,
900
+ `if [ -s ${tarball} ]; then`,
901
+ ` tar --warning=no-unknown-keyword -xzf ${tarball} -C ${SANDBOX_ROOT}`,
902
+ ` git --literal-pathspecs add -f --pathspec-from-file=${fileList} --pathspec-file-nul`,
903
+ "fi",
904
+ `git ${GIT_IDENTITY} commit -q --no-verify --allow-empty -m run`,
905
+ `rm -f ${patch} ${tarball} ${fileList}`
906
+ ]);
907
+ }
908
+ function snapshotKey(steps) {
909
+ const text = (list) => list.flatMap(({ label, script, secrets }) => [label, script, `secrets=${(secrets ?? []).toSorted().join(",")}`]);
910
+ return createHash("sha256").update(
911
+ [
912
+ `format=${SNAPSHOT_FORMAT}`,
913
+ ...text(steps.toolchains),
914
+ baseIndexScript("<base>", "<staging>"),
915
+ ...text(steps.prebuild)
916
+ ].join("\0")
917
+ ).digest("hex");
918
+ }
919
+ async function snapshotStepsAt(checkout, request2) {
920
+ const context = baseStepContext(checkout, request2);
921
+ const { snapshot, secrets } = request2.recipe;
922
+ const toolchains = await resolveSteps(snapshot.toolchains, context, secrets);
923
+ if (!toolchains.ok) return { ok: false, path: ["snapshot", "toolchains"], problem: toolchains.problem };
924
+ const prebuild = await resolveSteps(snapshot.prebuild, context, secrets);
925
+ if (!prebuild.ok) return { ok: false, path: ["snapshot", "prebuild"], problem: prebuild.problem };
926
+ return {
927
+ ok: true,
928
+ toolchains: toolchains.steps,
929
+ prebuild: prebuild.steps,
930
+ key: snapshotKey({ toolchains: toolchains.steps, prebuild: prebuild.steps })
931
+ };
932
+ }
933
+
934
+ // src/runner/live/sandbox-errors.ts
935
+ function apiStatus(error) {
936
+ if (typeof error !== "object" || error === null) return void 0;
937
+ const response = error.response;
938
+ if (typeof response !== "object" || response === null) return void 0;
939
+ const status = response.status;
940
+ return typeof status === "number" ? status : void 0;
941
+ }
942
+ function isAbortError(error) {
943
+ return typeof error === "object" && error !== null && error.name === "AbortError";
944
+ }
945
+ function sandboxFailure(error, signal) {
946
+ if (signal?.aborted === true || isAbortError(error)) return { kind: "aborted" };
947
+ return { kind: "api", status: apiStatus(error), message: error instanceof Error ? error.message : String(error) };
948
+ }
949
+
950
+ // src/runner/live/sandbox-gateway.ts
951
+ var TERMINATE_GRACE_MS = 1e4;
952
+ var KILL_GRACE_MS = 5e3;
953
+ var STDERR_MESSAGE_CHARS = 1e3;
954
+ var SNAPSHOT_GONE_STATUS = 410;
955
+ function liveRunnerSandboxGateway() {
956
+ let loading;
957
+ const sdk = () => loading ??= import("@vercel/sandbox");
958
+ const held = /* @__PURE__ */ new WeakMap();
959
+ const holding = (sandbox) => {
960
+ const found = held.get(sandbox);
961
+ if (found === void 0) throw new Error(`liveRunnerSandboxGateway: sandbox ${sandbox.name} isn't one it started`);
962
+ return found;
963
+ };
964
+ const adopt = (sandbox, role, timeoutMs) => {
965
+ const handle = Object.freeze({ name: sandbox.name, role, timeoutMs });
966
+ held.set(handle, { sandbox, staging: void 0, running: /* @__PURE__ */ new Set(), starting: /* @__PURE__ */ new Set(), keeping: false });
967
+ return handle;
968
+ };
969
+ return {
970
+ async startBuildSandbox(access, request2, signal) {
971
+ try {
972
+ const { Sandbox } = await sdk();
973
+ const sandbox = await Sandbox.create({
974
+ ...credentials(access),
975
+ // oxlint-disable-next-line typescript/no-deprecated -- the recipe names a runtime; moving to `image` changes the recipe format.
976
+ runtime: request2.runtime,
977
+ ...placement(request2),
978
+ ...signal === void 0 ? {} : { signal }
979
+ });
980
+ return { ok: true, value: adopt(sandbox, "snapshot-build", request2.timeoutMs) };
981
+ } catch (error) {
982
+ return { ok: false, failure: sandboxFailure(error, signal) };
983
+ }
984
+ },
985
+ async startRunnerSandbox(access, request2, signal) {
986
+ try {
987
+ const { Sandbox } = await sdk();
988
+ const sandbox = await Sandbox.create({
989
+ ...credentials(access),
990
+ source: { type: "snapshot", snapshotId: request2.snapshotId },
991
+ ...placement(request2),
992
+ ...signal === void 0 ? {} : { signal }
993
+ });
994
+ return { ok: true, value: adopt(sandbox, "runner", request2.timeoutMs) };
995
+ } catch (error) {
996
+ const failure = sandboxFailure(error, signal);
997
+ if (failure.kind === "api" && apiStatus(error) === SNAPSHOT_GONE_STATUS)
998
+ return { ok: false, failure: { kind: "snapshot-gone", message: failure.message } };
999
+ return { ok: false, failure };
1000
+ }
1001
+ },
1002
+ async upload(sandbox, files, signal) {
1003
+ const holder = holding(sandbox);
1004
+ try {
1005
+ const directory = await stagingDirectory(holder, signal);
1006
+ if (typeof directory !== "string") return { ok: false, failure: directory };
1007
+ await holder.sandbox.writeFiles(writes(directory, files), signal === void 0 ? void 0 : { signal });
1008
+ return { ok: true, value: { directory } };
1009
+ } catch (error) {
1010
+ return { ok: false, failure: sandboxFailure(error, signal) };
1011
+ }
1012
+ },
1013
+ async runScript(sandbox, request2, onOutput, signal) {
1014
+ const holder = holding(sandbox);
1015
+ try {
1016
+ const command = await startDetached(holder, {
1017
+ cmd: "bash",
1018
+ args: ["-lc", request2.script],
1019
+ cwd: SANDBOX_ROOT,
1020
+ env: { ...request2.env },
1021
+ ...signal === void 0 ? {} : { signal }
1022
+ });
1023
+ if (command === void 0) return { ok: false, failure: { kind: "aborted" } };
1024
+ return { ok: true, value: await follow(holder, command, onOutput, signal) };
1025
+ } catch (error) {
1026
+ return { ok: false, failure: sandboxFailure(error, signal) };
1027
+ }
1028
+ },
1029
+ async loginPath(sandbox, signal) {
1030
+ const holder = holding(sandbox);
1031
+ try {
1032
+ const finished = await holder.sandbox.runCommand({
1033
+ cmd: "bash",
1034
+ args: ["-lc", 'printf %s "$PATH"'],
1035
+ ...signal === void 0 ? {} : { signal }
1036
+ });
1037
+ if (finished.exitCode !== 0)
1038
+ return {
1039
+ ok: false,
1040
+ failure: { kind: "api", status: void 0, message: `reading the login PATH exited ${finished.exitCode}` }
1041
+ };
1042
+ return { ok: true, value: await finished.stdout(signal === void 0 ? void 0 : { signal }) };
1043
+ } catch (error) {
1044
+ return { ok: false, failure: sandboxFailure(error, signal) };
1045
+ }
1046
+ },
1047
+ async runCommand(sandbox, request2, onOutput, kill) {
1048
+ const holder = holding(sandbox);
1049
+ if (kill.aborted) return { ok: false, failure: { kind: "aborted" } };
1050
+ try {
1051
+ const cmd = await resolveExecutable(holder, request2);
1052
+ if (kill.aborted) return { ok: false, failure: { kind: "aborted" } };
1053
+ const command = await startDetached(holder, {
1054
+ cmd,
1055
+ args: [...request2.args],
1056
+ cwd: request2.cwd,
1057
+ env: { ...request2.env }
1058
+ });
1059
+ if (command === void 0) return { ok: false, failure: { kind: "aborted" } };
1060
+ const terminate = () => {
1061
+ command.kill("SIGTERM").catch(() => {
1062
+ });
1063
+ };
1064
+ if (kill.aborted) terminate();
1065
+ else kill.addEventListener("abort", terminate, { once: true });
1066
+ try {
1067
+ return { ok: true, value: await follow(holder, command, onOutput, kill) };
1068
+ } finally {
1069
+ kill.removeEventListener("abort", terminate);
1070
+ }
1071
+ } catch (error) {
1072
+ return { ok: false, failure: sandboxFailure(error, kill) };
1073
+ }
1074
+ },
1075
+ async followTestEvents(sandbox, request2, onOutput, stop) {
1076
+ const holder = holding(sandbox);
1077
+ if (stop.aborted) return { ok: true };
1078
+ try {
1079
+ const command = await startDetached(holder, { cmd: "tail", args: ["-n", "+1", "-F", request2.path] });
1080
+ if (command === void 0) return { ok: true };
1081
+ const end = () => {
1082
+ command.kill("SIGTERM").catch(() => {
1083
+ });
1084
+ };
1085
+ if (stop.aborted) end();
1086
+ else stop.addEventListener("abort", end, { once: true });
1087
+ try {
1088
+ await follow(
1089
+ holder,
1090
+ command,
1091
+ (chunk) => {
1092
+ if (chunk.stream === "stdout") onOutput(chunk);
1093
+ },
1094
+ stop
1095
+ );
1096
+ } finally {
1097
+ stop.removeEventListener("abort", end);
1098
+ }
1099
+ return { ok: true };
1100
+ } catch (error) {
1101
+ const failure = sandboxFailure(error, stop);
1102
+ return failure.kind === "aborted" ? { ok: true } : { ok: false, failure };
1103
+ }
1104
+ },
1105
+ async readTestEvents(sandbox, request2, onOutput, signal) {
1106
+ const holder = holding(sandbox);
1107
+ if (signal?.aborted === true) return { ok: false, failure: { kind: "aborted" } };
1108
+ try {
1109
+ const command = await startDetached(holder, {
1110
+ cmd: "bash",
1111
+ args: [
1112
+ "-c",
1113
+ 'test -e "$1" || exit 0; exec tail -n +"$2" -- "$1"',
1114
+ "_",
1115
+ request2.path,
1116
+ String(request2.fromLine)
1117
+ ]
1118
+ });
1119
+ if (command === void 0) return { ok: false, failure: { kind: "aborted" } };
1120
+ const end = () => {
1121
+ command.kill("SIGTERM").catch(() => {
1122
+ });
1123
+ };
1124
+ if (isAborted(signal)) end();
1125
+ else signal?.addEventListener("abort", end, { once: true });
1126
+ let stderr = "";
1127
+ try {
1128
+ const exit = await follow(
1129
+ holder,
1130
+ command,
1131
+ (chunk) => {
1132
+ if (chunk.stream === "stdout") onOutput(chunk);
1133
+ else if (stderr.length < STDERR_MESSAGE_CHARS)
1134
+ stderr += chunk.data.slice(0, STDERR_MESSAGE_CHARS - stderr.length);
1135
+ },
1136
+ signal
1137
+ );
1138
+ if (exit.exitCode === 0) return { ok: true };
1139
+ const reason = stderr.trim();
1140
+ return {
1141
+ ok: false,
1142
+ failure: {
1143
+ kind: "api",
1144
+ status: void 0,
1145
+ message: `reading the test events file exited ${exit.exitCode ?? "without a code"}${reason === "" ? "" : `: ${reason}`}`
1146
+ }
1147
+ };
1148
+ } finally {
1149
+ signal?.removeEventListener("abort", end);
1150
+ }
1151
+ } catch (error) {
1152
+ return { ok: false, failure: sandboxFailure(error, signal) };
1153
+ }
1154
+ },
1155
+ async saveSnapshot(sandbox, request2) {
1156
+ const holder = holding(sandbox);
1157
+ try {
1158
+ const snapshot = await holder.sandbox.snapshot({ expiration: request2.expirationMs });
1159
+ if (snapshot.status !== "created")
1160
+ return {
1161
+ ok: false,
1162
+ failure: {
1163
+ kind: "api",
1164
+ status: void 0,
1165
+ message: `snapshot ${snapshot.snapshotId} is ${snapshot.status}`
1166
+ }
1167
+ };
1168
+ return {
1169
+ ok: true,
1170
+ value: {
1171
+ snapshotId: snapshot.snapshotId,
1172
+ expiresAt: snapshot.expiresAt?.toISOString(),
1173
+ sizeBytes: snapshot.sizeBytes
1174
+ }
1175
+ };
1176
+ } catch (error) {
1177
+ return { ok: false, failure: sandboxFailure(error, void 0) };
1178
+ }
1179
+ },
1180
+ async keepRunning(sandbox, request2) {
1181
+ const holder = holding(sandbox);
1182
+ holder.keeping = true;
1183
+ await Promise.allSettled(holder.starting);
1184
+ const stillRunning = (await Promise.all([...holder.running].map((command) => endProcess(holder, command)))).filter((ended) => !ended).length;
1185
+ if (stillRunning > 0)
1186
+ return {
1187
+ ok: false,
1188
+ failure: {
1189
+ kind: "processes-running",
1190
+ message: `${stillRunning} ${stillRunning === 1 ? "process" : "processes"} the run started didn't end after SIGKILL`
1191
+ }
1192
+ };
1193
+ try {
1194
+ const stopsAt = holder.sandbox.expiresAt;
1195
+ const short = request2.until.getTime() - (stopsAt?.getTime() ?? Date.now());
1196
+ if (short <= 0 && stopsAt !== void 0) return { ok: true, value: { stopsAt } };
1197
+ await holder.sandbox.extendTimeout(short);
1198
+ return { ok: true, value: { stopsAt: holder.sandbox.expiresAt ?? request2.until } };
1199
+ } catch (error) {
1200
+ return { ok: false, failure: sandboxFailure(error, void 0) };
1201
+ }
1202
+ },
1203
+ async stop(sandbox) {
1204
+ const holder = holding(sandbox);
1205
+ try {
1206
+ await holder.sandbox.stop();
1207
+ return { ok: true };
1208
+ } catch (error) {
1209
+ return { ok: false, failure: sandboxFailure(error, void 0) };
1210
+ }
1211
+ },
1212
+ async delete(sandbox) {
1213
+ const holder = holding(sandbox);
1214
+ try {
1215
+ await holder.sandbox.delete({ deleteOrphanSnapshots: false });
1216
+ return { ok: true };
1217
+ } catch (error) {
1218
+ return { ok: false, failure: sandboxFailure(error, void 0) };
1219
+ }
1220
+ }
1221
+ };
1222
+ }
1223
+ function credentials(access) {
1224
+ return { token: access.credential.reveal(), teamId: access.teamId, projectId: access.projectId };
1225
+ }
1226
+ function placement(request2) {
1227
+ return {
1228
+ region: request2.region,
1229
+ resources: { vcpus: request2.vcpus },
1230
+ timeout: request2.timeoutMs,
1231
+ persistent: false,
1232
+ tags: { ...request2.tags }
1233
+ };
1234
+ }
1235
+ function writes(directory, files) {
1236
+ return files.map((file) => ({ path: `${directory}/${file.name}`, content: file.content }));
1237
+ }
1238
+ async function stagingDirectory(holder, signal) {
1239
+ if (holder.staging !== void 0) return holder.staging;
1240
+ const made = await holder.sandbox.runCommand({
1241
+ cmd: "mktemp",
1242
+ args: ["-d", "-t", "storm-runner.XXXXXXXX"],
1243
+ ...signal === void 0 ? {} : { signal }
1244
+ });
1245
+ if (made.exitCode !== 0)
1246
+ return { kind: "api", status: void 0, message: `mktemp exited ${made.exitCode} making a staging directory` };
1247
+ const directory = (await made.stdout(signal === void 0 ? void 0 : { signal })).trim();
1248
+ holder.staging = directory;
1249
+ return directory;
1250
+ }
1251
+ async function resolveExecutable(holder, request2) {
1252
+ if (request2.cmd.includes("/")) return request2.cmd;
1253
+ const found = await holder.sandbox.runCommand({
1254
+ cmd: "bash",
1255
+ args: ["-c", 'command -v -- "$1"', "_", request2.cmd],
1256
+ cwd: request2.cwd,
1257
+ env: { ...request2.env }
1258
+ });
1259
+ if (found.exitCode !== 0) return request2.cmd;
1260
+ const path = (await found.stdout()).trim();
1261
+ return path.startsWith("/") ? path : request2.cmd;
1262
+ }
1263
+ async function startDetached(holder, params) {
1264
+ if (holder.keeping) return void 0;
1265
+ const starting = holder.sandbox.runCommand({ ...params, detached: true });
1266
+ holder.starting.add(starting);
1267
+ try {
1268
+ const command = await starting;
1269
+ holder.running.add(command);
1270
+ return command;
1271
+ } finally {
1272
+ holder.starting.delete(starting);
1273
+ }
1274
+ }
1275
+ async function follow(holder, command, onOutput, signal) {
1276
+ const options = signal === void 0 ? void 0 : { signal };
1277
+ for await (const log of command.logs(options)) onOutput({ stream: log.stream, data: log.data });
1278
+ const finished = await command.wait(options);
1279
+ holder.running.delete(command);
1280
+ return { exitCode: typeof finished.exitCode === "number" ? finished.exitCode : null };
1281
+ }
1282
+ async function endProcess(holder, command) {
1283
+ for (const [signal, graceMs] of [
1284
+ ["SIGTERM", TERMINATE_GRACE_MS],
1285
+ ["SIGKILL", KILL_GRACE_MS]
1286
+ ]) {
1287
+ await command.kill(signal).catch(() => void 0);
1288
+ if (await endsWithin(command, graceMs)) {
1289
+ holder.running.delete(command);
1290
+ return true;
1291
+ }
1292
+ }
1293
+ return false;
1294
+ }
1295
+ async function endsWithin(command, ms) {
1296
+ const timeout = new AbortController();
1297
+ const timer = setTimeout(() => timeout.abort(), ms);
1298
+ try {
1299
+ await command.wait({ signal: timeout.signal });
1300
+ return true;
1301
+ } catch {
1302
+ return false;
1303
+ } finally {
1304
+ clearTimeout(timer);
1305
+ }
1306
+ }
1307
+ function isAborted(signal) {
1308
+ return signal?.aborted === true;
1309
+ }
1310
+
1311
+ // src/runner/live/terminal.ts
1312
+ function liveRunnerTerminal(options) {
1313
+ const stdout = options.stdout ?? process.stdout;
1314
+ const stderr = options.stderr ?? process.stderr;
1315
+ let failed = false;
1316
+ let listening = false;
1317
+ const fail = () => {
1318
+ failed = true;
1319
+ };
1320
+ const write = (stream, text) => {
1321
+ if (failed) return;
1322
+ if (!listening) {
1323
+ stdout.on("error", fail);
1324
+ stderr.on("error", fail);
1325
+ listening = true;
1326
+ }
1327
+ try {
1328
+ stream.write(text);
1329
+ } catch {
1330
+ fail();
1331
+ }
1332
+ };
1333
+ return {
1334
+ color: stdout.isTTY === true && options.env["NO_COLOR"] === void 0,
1335
+ writeStdout: (text) => write(stdout, text),
1336
+ writeStderr: (text) => write(stderr, text)
1337
+ };
1338
+ }
1339
+
1340
+ // src/runner/live/snapshot-cache-gateway.ts
1341
+ import { randomBytes } from "node:crypto";
1342
+ import { mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
1343
+ import { join } from "node:path";
1344
+
1345
+ // src/runner/snapshot-cache.ts
1346
+ import { createHash as createHash2 } from "node:crypto";
1347
+ var RUNNER_SNAPSHOTS_SUBPATH = ["runner", "snapshots"];
1348
+ var SNAPSHOT_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1e3;
1349
+ var SNAPSHOT_MIN_REMAINING_MS = 60 * 60 * 1e3;
1350
+ function snapshotEntryIdentity(entry) {
1351
+ return createHash2("sha256").update(
1352
+ [
1353
+ entry.teamId,
1354
+ entry.projectId,
1355
+ entry.region,
1356
+ entry.runtime,
1357
+ entry.recipeName,
1358
+ entry.snapshotKey,
1359
+ entry.base,
1360
+ ...isBranchEntry(entry) ? [entry.branch, entry.repoRoot] : []
1361
+ ].join("\0")
1362
+ ).digest("hex").slice(0, 32);
1363
+ }
1364
+ function isBranchEntry(entry) {
1365
+ return entry.branch !== void 0 && entry.head !== void 0 && entry.repoRoot !== void 0;
1366
+ }
1367
+ function snapshotEntryFileName(entry) {
1368
+ return `${snapshotEntryIdentity(entry)}.json`;
1369
+ }
1370
+ function isExpiredEntry(entry, now) {
1371
+ return Date.parse(entry.expiresAt) <= now.getTime();
1372
+ }
1373
+ function hasTimeLeft(entry, now) {
1374
+ return Date.parse(entry.expiresAt) - now.getTime() > SNAPSHOT_MIN_REMAINING_MS;
1375
+ }
1376
+ async function findSnapshotCandidates(context, request2) {
1377
+ const { checkout, runnerSnapshots } = context;
1378
+ const { repoRoot, recipe, branch } = request2;
1379
+ const notes = [];
1380
+ const listed = await runnerSnapshots.listEntries();
1381
+ if (!listed.ok) return { candidates: [], notes: [{ kind: "cache-unreadable", failure: listed.failure }] };
1382
+ const now = context.clock.now();
1383
+ const live = [];
1384
+ for (const entry of listed.value.entries) {
1385
+ if (isExpiredEntry(entry, now)) {
1386
+ const removed = await runnerSnapshots.removeEntry(entry);
1387
+ if (!removed.ok) notes.push({ kind: "expired-entry-not-removed", entry, failure: removed.failure });
1388
+ continue;
1389
+ }
1390
+ if (entry.region === recipe.region && entry.runtime === recipe.runtime && entry.recipeName === recipe.name && (isBranchEntry(entry) ? entry.branch === branch && entry.repoRoot === repoRoot : entry.branch === void 0) && hasTimeLeft(entry, now))
1391
+ live.push(entry);
1392
+ }
1393
+ const keysByBase = /* @__PURE__ */ new Map();
1394
+ for (const base of new Set(live.map((entry) => entry.base))) {
1395
+ const contained = await checkout.contains({ repoRoot, ancestor: base, descendant: "HEAD" });
1396
+ if (!contained.ok) {
1397
+ notes.push({ kind: "candidate-check-failed", base, failure: contained.failure });
1398
+ continue;
1399
+ }
1400
+ if (!contained.value) continue;
1401
+ const steps = await snapshotStepsAt(checkout, { repoRoot, base, recipe });
1402
+ if (!steps.ok) {
1403
+ notes.push({ kind: "candidate-steps-failed", base, path: steps.path, problem: steps.problem });
1404
+ continue;
1405
+ }
1406
+ keysByBase.set(base, steps.key);
1407
+ }
1408
+ const matching = live.filter((entry) => keysByBase.get(entry.base) === entry.snapshotKey);
1409
+ const commitTimes = /* @__PURE__ */ new Map();
1410
+ for (const base of new Set(matching.map((entry) => entry.base))) {
1411
+ const time = await checkout.commitTime({ repoRoot, commit: base });
1412
+ if (time.ok) commitTimes.set(base, time.value);
1413
+ else notes.push({ kind: "candidate-check-failed", base, failure: time.failure });
1414
+ }
1415
+ const bases = [...commitTimes.keys()];
1416
+ const ancestors = new Map(bases.map((base) => [base, []]));
1417
+ for (const ancestor of bases)
1418
+ for (const descendant of bases) {
1419
+ if (ancestor === descendant) continue;
1420
+ const contained = await checkout.contains({ repoRoot, ancestor, descendant });
1421
+ if (!contained.ok) notes.push({ kind: "candidate-check-failed", base: ancestor, failure: contained.failure });
1422
+ else if (contained.value) ancestors.get(descendant)?.push(ancestor);
1423
+ }
1424
+ const candidates = matching.flatMap((entry) => {
1425
+ const commitTime2 = commitTimes.get(entry.base);
1426
+ return commitTime2 === void 0 ? [] : [{ entry, commitTime: commitTime2, ancestorBases: [...ancestors.get(entry.base) ?? []] }];
1427
+ });
1428
+ return { candidates, notes };
1429
+ }
1430
+ function pickSnapshot(candidates, owner) {
1431
+ const owned = candidates.filter(({ entry }) => entry.teamId === owner.teamId && entry.projectId === owner.projectId).toSorted((a, b) => b.commitTime - a.commitTime || Date.parse(b.entry.expiresAt) - Date.parse(a.entry.expiresAt));
1432
+ const nearest = owned.find(
1433
+ (candidate) => owned.every(
1434
+ (other) => other.entry.base === candidate.entry.base || candidate.ancestorBases.includes(other.entry.base)
1435
+ )
1436
+ ) ?? owned[0];
1437
+ if (nearest === void 0) return void 0;
1438
+ return owned.filter(({ entry }) => entry.base === nearest.entry.base).toSorted(
1439
+ (a, b) => Number(isBranchEntry(b.entry)) - Number(isBranchEntry(a.entry)) || Date.parse(b.entry.expiresAt) - Date.parse(a.entry.expiresAt)
1440
+ )[0];
1441
+ }
1442
+ async function dropBranchSnapshots(runnerSnapshots, request2) {
1443
+ const { branch, repoRoot, owner, recipe } = request2;
1444
+ const listed = await runnerSnapshots.listEntries();
1445
+ if (!listed.ok) return { snapshotIds: [], failures: [listed.failure] };
1446
+ const snapshotIds = [];
1447
+ const failures = [];
1448
+ for (const entry of listed.value.entries) {
1449
+ if (!isBranchEntry(entry) || entry.branch !== branch || entry.repoRoot !== repoRoot || entry.teamId !== owner.teamId || entry.projectId !== owner.projectId || entry.region !== recipe.region || entry.runtime !== recipe.runtime || entry.recipeName !== recipe.name)
1450
+ continue;
1451
+ const removed = await runnerSnapshots.removeEntry(entry);
1452
+ if (removed.ok) snapshotIds.push(entry.snapshotId);
1453
+ else failures.push(removed.failure);
1454
+ }
1455
+ return { snapshotIds, failures };
1456
+ }
1457
+
1458
+ // src/runner/live/snapshot-records.ts
1459
+ import { z as z3 } from "zod";
1460
+ var isoTime = z3.string().refine((value) => !Number.isNaN(Date.parse(value)), { message: "not a time" });
1461
+ var nonEmpty = z3.string().min(1);
1462
+ var entrySchema = z3.object({
1463
+ version: z3.literal(1),
1464
+ teamId: nonEmpty,
1465
+ projectId: nonEmpty,
1466
+ region: nonEmpty,
1467
+ runtime: nonEmpty,
1468
+ recipeName: nonEmpty,
1469
+ snapshotKey: nonEmpty,
1470
+ base: nonEmpty,
1471
+ branch: nonEmpty.exactOptional(),
1472
+ head: nonEmpty.exactOptional(),
1473
+ repoRoot: nonEmpty.exactOptional(),
1474
+ snapshotId: nonEmpty,
1475
+ createdAt: isoTime,
1476
+ expiresAt: isoTime
1477
+ }).refine(
1478
+ (entry) => {
1479
+ const present = [entry.branch, entry.head, entry.repoRoot].filter((value) => value !== void 0).length;
1480
+ return present === 0 || present === 3;
1481
+ },
1482
+ { message: "has some of branch, head and repoRoot without the others" }
1483
+ );
1484
+ function parseSnapshotEntry(text) {
1485
+ let json;
1486
+ try {
1487
+ json = JSON.parse(text);
1488
+ } catch {
1489
+ return { ok: false, reason: "not JSON" };
1490
+ }
1491
+ const version = typeof json === "object" && json !== null ? json.version : void 0;
1492
+ if (version !== 1) return { ok: false, reason: `unknown version ${JSON.stringify(version) ?? "(none)"}` };
1493
+ const parsed = entrySchema.safeParse(json);
1494
+ if (!parsed.success) {
1495
+ const issue = parsed.error.issues[0];
1496
+ const where2 = issue === void 0 || issue.path.length === 0 ? "the record" : issue.path.join(".");
1497
+ return { ok: false, reason: `${where2}: ${issue?.message ?? "invalid"}` };
1498
+ }
1499
+ const { version: _version, ...entry } = parsed.data;
1500
+ return { ok: true, value: entry };
1501
+ }
1502
+ function snapshotEntryText(entry) {
1503
+ const { teamId, projectId, region, runtime, recipeName, snapshotKey: snapshotKey2, base, branch, head: head2, repoRoot } = entry;
1504
+ const { snapshotId, createdAt, expiresAt } = entry;
1505
+ const record = {
1506
+ version: 1,
1507
+ teamId,
1508
+ projectId,
1509
+ region,
1510
+ runtime,
1511
+ recipeName,
1512
+ snapshotKey: snapshotKey2,
1513
+ base,
1514
+ ...branch === void 0 ? {} : { branch },
1515
+ ...head2 === void 0 ? {} : { head: head2 },
1516
+ ...repoRoot === void 0 ? {} : { repoRoot },
1517
+ snapshotId,
1518
+ createdAt,
1519
+ expiresAt
1520
+ };
1521
+ return `${JSON.stringify(record, null, 2)}
1522
+ `;
1523
+ }
1524
+
1525
+ // src/runner/live/snapshot-cache-gateway.ts
1526
+ var DIRECTORY_MODE = 448;
1527
+ var FILE_MODE = 384;
1528
+ var ENTRY_FILE_NAME = /^[0-9a-f]{32}\.json$/;
1529
+ function liveRunnerSnapshotCacheGateway(options) {
1530
+ const { directory } = options;
1531
+ return {
1532
+ listEntries: () => listEntries(directory),
1533
+ writeEntry: (entry) => writeEntry(directory, entry),
1534
+ removeEntry: (entry) => removeEntry(directory, entry)
1535
+ };
1536
+ }
1537
+ function unavailableRunnerSnapshotCacheGateway(location, reason) {
1538
+ const failure = { path: location, message: reason };
1539
+ const fail = async () => ({ ok: false, failure });
1540
+ return { listEntries: fail, writeEntry: fail, removeEntry: fail };
1541
+ }
1542
+ async function listEntries(directory) {
1543
+ let names;
1544
+ try {
1545
+ names = await readdir(directory);
1546
+ } catch (error) {
1547
+ if (errorCode(error) === "ENOENT") return { ok: true, value: { directory, entries: [], unreadable: [] } };
1548
+ return { ok: false, failure: failureAt(directory, error) };
1549
+ }
1550
+ const entries = [];
1551
+ const unreadable = [];
1552
+ for (const name of names.filter((name2) => ENTRY_FILE_NAME.test(name2)).toSorted()) {
1553
+ const file = join(directory, name);
1554
+ let text;
1555
+ try {
1556
+ text = await readFile(file, "utf8");
1557
+ } catch (error) {
1558
+ if (errorCode(error) === "ENOENT") continue;
1559
+ unreadable.push({ file, reason: error instanceof Error ? error.message : String(error) });
1560
+ continue;
1561
+ }
1562
+ const parsed = parseSnapshotEntry(text);
1563
+ if (!parsed.ok) unreadable.push({ file, reason: parsed.reason });
1564
+ else if (snapshotEntryFileName(parsed.value) !== name)
1565
+ unreadable.push({ file, reason: "its name isn't its entry's identity" });
1566
+ else entries.push(parsed.value);
1567
+ }
1568
+ return { ok: true, value: { directory, entries, unreadable } };
1569
+ }
1570
+ async function writeEntry(directory, entry) {
1571
+ try {
1572
+ await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
1573
+ } catch (error) {
1574
+ return { ok: false, failure: failureAt(directory, error) };
1575
+ }
1576
+ const name = snapshotEntryFileName(entry);
1577
+ const path = join(directory, name);
1578
+ const temp = join(directory, `.${name}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
1579
+ try {
1580
+ await writeFile(temp, snapshotEntryText(entry), { mode: FILE_MODE, flag: "wx" });
1581
+ await rename(temp, path);
1582
+ return { ok: true };
1583
+ } catch (error) {
1584
+ await unlink(temp).catch(() => {
1585
+ });
1586
+ return { ok: false, failure: failureAt(path, error) };
1587
+ }
1588
+ }
1589
+ async function removeEntry(directory, entry) {
1590
+ const path = join(directory, snapshotEntryFileName(entry));
1591
+ try {
1592
+ await unlink(path);
1593
+ return { ok: true };
1594
+ } catch (error) {
1595
+ if (errorCode(error) === "ENOENT") return { ok: true };
1596
+ return { ok: false, failure: failureAt(path, error) };
1597
+ }
1598
+ }
1599
+ function errorCode(error) {
1600
+ const code = typeof error === "object" && error !== null ? error.code : void 0;
1601
+ return typeof code === "string" ? code : void 0;
1602
+ }
1603
+ function failureAt(path, error) {
1604
+ return { path, message: error instanceof Error ? error.message : String(error) };
1605
+ }
1606
+
1607
+ // src/runner/prepare.ts
1608
+ async function prepareRunner(context, request2) {
1609
+ const { checkout } = context;
1610
+ const { recipe } = request2;
1611
+ const root = await checkout.repositoryRoot({ cwd: request2.cwd });
1612
+ if (!root.ok) return { kind: "checkout-failed", failure: root.failure };
1613
+ const repoRoot = root.value;
1614
+ const head2 = await checkout.head({ repoRoot });
1615
+ if (!head2.ok) return { kind: "checkout-failed", failure: head2.failure };
1616
+ const resolved = await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
1617
+ if (resolved.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
1618
+ if (resolved.kind === "no-base-ref") return resolved;
1619
+ const { base } = resolved;
1620
+ const submodules2 = await checkout.submodules({ repoRoot });
1621
+ if (!submodules2.ok) return { kind: "checkout-failed", failure: submodules2.failure };
1622
+ if (submodules2.value.length > 0) return { kind: "submodules", paths: [...submodules2.value] };
1623
+ const steps = await snapshotStepsAt(checkout, { repoRoot, base, recipe });
1624
+ if (!steps.ok) return { kind: "invalid-recipe", path: steps.path, problem: steps.problem };
1625
+ const vcpus = resolveVcpus(recipe, request2.vcpusRun);
1626
+ if (!vcpus.ok) return { kind: "invalid-recipe", path: ["vcpus"], problem: vcpus.problem };
1627
+ const upload = await checkout.assembleUpload({ repoRoot, base });
1628
+ if (!upload.ok) return { kind: "checkout-failed", failure: upload.failure };
1629
+ const reuseBranch = request2.trustBranchSnapshots || !runStepTakesSecret(recipe);
1630
+ const cache = request2.rebuild ? { candidates: [], notes: [] } : await findSnapshotCandidates(context, { repoRoot, recipe, branch: reuseBranch ? head2.value.branch : null });
1631
+ return {
1632
+ kind: "ok",
1633
+ prepared: {
1634
+ recipe,
1635
+ repoRoot,
1636
+ head: head2.value,
1637
+ base,
1638
+ baseRef: resolved.ref,
1639
+ toolchains: steps.toolchains,
1640
+ prebuild: steps.prebuild,
1641
+ snapshotKey: steps.key,
1642
+ vcpus: vcpus.vcpus,
1643
+ upload: upload.value,
1644
+ candidates: cache.candidates,
1645
+ rebuild: request2.rebuild,
1646
+ notes: cache.notes,
1647
+ save: plannedSave(request2.save, head2.value.branch)
1648
+ }
1649
+ };
1650
+ }
1651
+ function plannedSave(mode, branch) {
1652
+ if (mode === "never") return null;
1653
+ if (branch !== null) return { kind: "branch", branch, always: mode === "always" };
1654
+ return mode === "always" ? { kind: "skipped", reason: "detached-head" } : null;
1655
+ }
1656
+
1657
+ // src/runner/sandboxed-command.ts
1658
+ import { posix } from "node:path";
1659
+ function sandboxedCommand(request2) {
1660
+ const [first = "", ...rest] = request2.argv.map((argument) => rewritePaths(argument, request2.repoRoot, SANDBOX_ROOT));
1661
+ const cmd = first.includes("/") && !first.startsWith("/") ? posix.join(request2.cwd, first) : first;
1662
+ return { cmd, args: rest };
1663
+ }
1664
+ function sandboxEnvironment(request2) {
1665
+ const bins = [
1666
+ .../* @__PURE__ */ new Set([posix.join(request2.cwd, "node_modules/.bin"), posix.join(SANDBOX_ROOT, "node_modules/.bin")])
1667
+ ];
1668
+ return {
1669
+ PATH: [...bins, request2.loginPath].filter((part) => part !== "").join(":"),
1670
+ NO_UPDATE_NOTIFIER: "1",
1671
+ ...request2.color ? { FORCE_COLOR: "1" } : { NO_COLOR: "1" },
1672
+ ...request2.env,
1673
+ [RUN_PAYLOAD_VARIABLE]: request2.runPayload
1674
+ };
1675
+ }
1676
+ var SANDBOX_TEST_EVENTS_PATH = "/tmp/storm-test-events.jsonl";
1677
+ async function runCommandInSandbox(context, request2, control, progress) {
1678
+ const { runner } = request2;
1679
+ const terminal = context.runnerTerminal;
1680
+ const command = sandboxedCommand({ argv: request2.argv, repoRoot: runner.repoRoot, cwd: runner.cwd });
1681
+ const env = sandboxEnvironment({
1682
+ cwd: runner.cwd,
1683
+ loginPath: runner.loginPath,
1684
+ color: terminal.color,
1685
+ env: runner.env,
1686
+ runPayload: request2.runPayload
1687
+ });
1688
+ await progress.emit({ kind: "command-output-started", sandbox: runner.sandbox.name, region: runner.region });
1689
+ const startedAt = context.clock.now().getTime();
1690
+ const splitters = { stdout: lineSplitter(), stderr: lineSplitter() };
1691
+ const write = (stream, text) => {
1692
+ if (text === "") return;
1693
+ const local = rewritePaths(text, SANDBOX_ROOT, runner.repoRoot);
1694
+ if (stream === "stdout") terminal.writeStdout(local);
1695
+ else terminal.writeStderr(local);
1696
+ };
1697
+ const following = followTestEvents(context, runner, request2.testEvents, control.kill);
1698
+ const ran = await context.runnerSandboxes.runCommand(
1699
+ runner.sandbox,
1700
+ { cmd: command.cmd, args: command.args, cwd: runner.cwd, env },
1701
+ ({ stream, data }) => write(stream, splitters[stream].push(data)),
1702
+ control.kill
1703
+ );
1704
+ const ms = context.clock.now().getTime() - startedAt;
1705
+ write("stdout", splitters.stdout.flush());
1706
+ write("stderr", splitters.stderr.flush());
1707
+ await following?.end(ran.ok && !control.kill.aborted);
1708
+ if (!ran.ok) {
1709
+ if (ran.failure.kind !== "aborted")
1710
+ return { kind: "failed", failure: sandboxApiFailure("run-command", ran.failure) };
1711
+ await progress.emit({ kind: "command-stopped", command: posix.basename(command.cmd) });
1712
+ return { kind: "killed" };
1713
+ }
1714
+ return { kind: "exited", exitCode: ran.value.exitCode, ms };
1715
+ }
1716
+ function followTestEvents(context, runner, testEvents, kill) {
1717
+ if (testEvents === void 0) return void 0;
1718
+ const stop = new AbortController();
1719
+ const splitter = lineSplitter();
1720
+ let handed = 0;
1721
+ const hand = (lines) => {
1722
+ for (const line of lines) {
1723
+ handed += 1;
1724
+ testEvents.onLine(line);
1725
+ }
1726
+ };
1727
+ const followed = context.runnerSandboxes.followTestEvents(
1728
+ runner.sandbox,
1729
+ { path: SANDBOX_TEST_EVENTS_PATH },
1730
+ ({ data }) => hand(splitLines(splitter.push(data))),
1731
+ stop.signal
1732
+ );
1733
+ return {
1734
+ async end(complete) {
1735
+ stop.abort();
1736
+ await followed;
1737
+ if (!complete) {
1738
+ hand(splitLines(splitter.flush()));
1739
+ return;
1740
+ }
1741
+ const reader = lineSplitter();
1742
+ let read = false;
1743
+ const result = await context.runnerSandboxes.readTestEvents(
1744
+ runner.sandbox,
1745
+ { path: SANDBOX_TEST_EVENTS_PATH, fromLine: handed + 1 },
1746
+ ({ data }) => {
1747
+ if (!read) {
1748
+ splitter.flush();
1749
+ read = true;
1750
+ }
1751
+ hand(splitLines(reader.push(data)));
1752
+ },
1753
+ kill
1754
+ );
1755
+ hand(splitLines(read ? reader.flush() : splitter.flush()));
1756
+ if (!result.ok && result.failure.kind === "api") testEvents.onIncomplete(result.failure.message);
1757
+ }
1758
+ };
1759
+ }
1760
+
1761
+ // src/runner/secrets.ts
1762
+ var RUNNER_SECRET_MIN_LENGTH = 8;
1763
+ function stepSecrets(values, names) {
1764
+ return Object.fromEntries(
1765
+ names.map((name) => {
1766
+ const value = ownValue(values, name);
1767
+ if (value === void 0) throw new Error(`stepSecrets: no value for runner secret ${name}`);
1768
+ return [name, value];
1769
+ })
1770
+ );
1771
+ }
1772
+ function readRunnerSecrets(recipe, env) {
1773
+ const values = [];
1774
+ const variables = [];
1775
+ for (const name of recipe.secrets) {
1776
+ const value = ownValue(env, name);
1777
+ if (value === void 0 || value === "") variables.push({ name, problem: "missing" });
1778
+ else if (/[\r\n]/.test(value)) variables.push({ name, problem: "multiline" });
1779
+ else if (value.length < RUNNER_SECRET_MIN_LENGTH) variables.push({ name, problem: "short" });
1780
+ else values.push([name, value]);
1781
+ }
1782
+ return variables.length === 0 ? { ok: true, values: Object.fromEntries(values) } : { ok: false, variables };
1783
+ }
1784
+ function ownValue(map, name) {
1785
+ return Object.hasOwn(map, name) ? map[name] : void 0;
1786
+ }
1787
+
1788
+ // src/runner/ready.ts
1789
+ import { posix as posix2 } from "node:path";
1790
+
1791
+ // src/runner/context.ts
1792
+ function runnerPurpose(recipeName) {
1793
+ return `storm-runner-${recipeName}`;
1794
+ }
1795
+ function runnerTags(recipeName, role, user) {
1796
+ return { purpose: runnerPurpose(recipeName), user, role };
1797
+ }
1798
+
1799
+ // src/runner/snapshot-build.ts
1800
+ var BUILD_SANDBOX_TIMEOUT_MS = 30 * 6e4;
1801
+ var BASE_INDEX_LABEL = "Committing the base's files";
1802
+ async function buildSnapshot(context, request2, control, progress) {
1803
+ const { prepared, access } = request2;
1804
+ const { recipe, repoRoot, base } = prepared;
1805
+ const { scope, signal } = control;
1806
+ const now = () => context.clock.now().getTime();
1807
+ const startedAt = now();
1808
+ await progress.emit({
1809
+ kind: "snapshot-build-started",
1810
+ base,
1811
+ reason: request2.reason,
1812
+ summary: recipe.snapshot.summary ?? [...prepared.toolchains, ...prepared.prebuild].map(({ label }) => label).join(", ")
1813
+ });
1814
+ const [started, archive] = await Promise.all([
1815
+ scope.startBuildSandbox(access, {
1816
+ region: recipe.region,
1817
+ runtime: recipe.runtime,
1818
+ vcpus: recipe.snapshot.vcpus,
1819
+ timeoutMs: BUILD_SANDBOX_TIMEOUT_MS,
1820
+ tags: runnerTags(recipe.name, "snapshot-build", request2.user)
1821
+ }),
1822
+ context.checkout.baseArchive({ repoRoot, base })
1823
+ ]);
1824
+ if (!started.ok) return sandboxStop("start-build-sandbox", started.failure);
1825
+ const sandbox = started.value;
1826
+ await progress.emit({
1827
+ kind: "sandbox-started",
1828
+ role: "snapshot-build",
1829
+ name: sandbox.name,
1830
+ region: recipe.region,
1831
+ vcpus: recipe.snapshot.vcpus,
1832
+ ms: now() - startedAt
1833
+ });
1834
+ if (!archive.ok) return { kind: "failed", failure: { kind: "checkout-failed", failure: archive.failure } };
1835
+ const staged = await context.runnerSandboxes.upload(
1836
+ sandbox,
1837
+ [
1838
+ { name: STAGED_FILES.baseTarball, content: archive.value.tarball },
1839
+ { name: STAGED_FILES.baseFileList, content: archive.value.fileList }
1840
+ ],
1841
+ signal
1842
+ );
1843
+ if (!staged.ok) return sandboxStop("upload", staged.failure);
1844
+ const recipeStep = ({ label, script, secrets }) => ({
1845
+ label,
1846
+ script,
1847
+ secrets: stepSecrets(request2.secrets, secrets)
1848
+ });
1849
+ const steps = [
1850
+ ...prepared.toolchains.map(recipeStep),
1851
+ { label: BASE_INDEX_LABEL, script: baseIndexScript(base, staged.value.directory) },
1852
+ ...prepared.prebuild.map(recipeStep)
1853
+ ];
1854
+ await progress.emit({ kind: "output-started", section: "snapshot", sandbox: sandbox.name, region: recipe.region });
1855
+ for (const step of steps) {
1856
+ const ran = await runStep(context, { sandbox, phase: "snapshot", ...step }, progress, signal);
1857
+ if (ran.kind === "succeeded") continue;
1858
+ const stop = ran.kind === "exited" ? {
1859
+ kind: "failed",
1860
+ failure: { kind: "snapshot-build-step-failed", label: step.label, exitCode: ran.exitCode, tail: ran.tail }
1861
+ } : sandboxStop("run-script", ran.failure);
1862
+ await progress.emit({
1863
+ kind: "output-ended",
1864
+ section: "snapshot",
1865
+ outcome: stop.kind === "aborted" ? "stopped" : "failed"
1866
+ });
1867
+ return stop;
1868
+ }
1869
+ await progress.emit({ kind: "output-ended", section: "snapshot", outcome: "finished" });
1870
+ if (signal.aborted) return { kind: "aborted" };
1871
+ await progress.emit({ kind: "snapshot-saving" });
1872
+ const saved = await scope.saveSnapshot(sandbox, { expirationMs: SNAPSHOT_EXPIRATION_MS });
1873
+ if (!saved.ok) return sandboxStop("save-snapshot", saved.failure);
1874
+ const savedAt2 = context.clock.now();
1875
+ const entry = {
1876
+ teamId: access.teamId,
1877
+ projectId: access.projectId,
1878
+ region: recipe.region,
1879
+ runtime: recipe.runtime,
1880
+ recipeName: recipe.name,
1881
+ snapshotKey: prepared.snapshotKey,
1882
+ base,
1883
+ snapshotId: saved.value.snapshotId,
1884
+ createdAt: savedAt2.toISOString(),
1885
+ expiresAt: saved.value.expiresAt ?? new Date(savedAt2.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString()
1886
+ };
1887
+ const written = await context.runnerSnapshots.writeEntry(entry);
1888
+ if (!written.ok) await progress.emit({ kind: "snapshot-entry-not-written", failure: written.failure });
1889
+ const { branch } = prepared.head;
1890
+ if (request2.reason === "rebuild" && branch !== null) {
1891
+ const dropped = await dropBranchSnapshots(context.runnerSnapshots, { branch, repoRoot, owner: access, recipe });
1892
+ if (dropped.snapshotIds.length > 0)
1893
+ await progress.emit({ kind: "branch-snapshots-dropped", branch, snapshotIds: dropped.snapshotIds });
1894
+ for (const failure of dropped.failures)
1895
+ await progress.emit({ kind: "branch-snapshots-not-dropped", branch, failure });
1896
+ }
1897
+ const ms = now() - startedAt;
1898
+ await progress.emit({
1899
+ kind: "snapshot-built",
1900
+ snapshotId: entry.snapshotId,
1901
+ base,
1902
+ ms,
1903
+ sizeBytes: saved.value.sizeBytes
1904
+ });
1905
+ return { kind: "ok", value: { entry, ms, sizeBytes: saved.value.sizeBytes } };
1906
+ }
1907
+
1908
+ // src/runner/ready.ts
1909
+ var APPLY_LABEL = "Applying your changes";
1910
+ async function readyRunner(context, request2, control, progress) {
1911
+ const { prepared, access } = request2;
1912
+ const { recipe, repoRoot } = prepared;
1913
+ const { scope, signal } = control;
1914
+ const now = () => context.clock.now().getTime();
1915
+ if (signal.aborted) return { kind: "aborted" };
1916
+ const picked = prepared.rebuild ? void 0 : pickSnapshot(prepared.candidates, access);
1917
+ let entry;
1918
+ if (picked !== void 0) {
1919
+ entry = picked.entry;
1920
+ await progress.emit({
1921
+ kind: "snapshot-reused",
1922
+ snapshotId: entry.snapshotId,
1923
+ base: entry.base,
1924
+ branch: entry.branch ?? null,
1925
+ head: entry.head ?? null
1926
+ });
1927
+ } else {
1928
+ const built2 = await buildSnapshot(
1929
+ context,
1930
+ {
1931
+ prepared,
1932
+ access,
1933
+ user: request2.user,
1934
+ secrets: request2.secrets,
1935
+ reason: prepared.rebuild ? "rebuild" : "no-snapshot"
1936
+ },
1937
+ control,
1938
+ progress
1939
+ );
1940
+ if (built2.kind !== "ok") return built2;
1941
+ entry = built2.value.entry;
1942
+ }
1943
+ if (signal.aborted) return { kind: "aborted" };
1944
+ await progress.emit({ kind: "runner-sandbox-starting", snapshotId: entry.snapshotId });
1945
+ const startedAt = now();
1946
+ const started = await scope.startRunnerSandbox(access, {
1947
+ snapshotId: entry.snapshotId,
1948
+ region: recipe.region,
1949
+ vcpus: prepared.vcpus,
1950
+ timeoutMs: recipe.timeoutMinutes * 6e4,
1951
+ tags: runnerTags(recipe.name, "runner", request2.user)
1952
+ });
1953
+ if (!started.ok) {
1954
+ if (started.failure.kind === "snapshot-gone") {
1955
+ const removed = await context.runnerSnapshots.removeEntry(entry);
1956
+ return { kind: "snapshot-gone", entry, removal: removed.ok ? void 0 : removed.failure };
1957
+ }
1958
+ return sandboxStop("start-runner-sandbox", started.failure);
1959
+ }
1960
+ const sandbox = started.value;
1961
+ await progress.emit({
1962
+ kind: "sandbox-started",
1963
+ role: "runner",
1964
+ name: sandbox.name,
1965
+ region: recipe.region,
1966
+ vcpus: prepared.vcpus,
1967
+ ms: now() - startedAt
1968
+ });
1969
+ const changes = await uploadChanges(context, { prepared, sandbox, base: entry.base }, signal, progress);
1970
+ if (changes.kind !== "ok") return changes;
1971
+ const applied = await stage(
1972
+ context,
1973
+ {
1974
+ sandbox,
1975
+ phase: "apply",
1976
+ step: { label: APPLY_LABEL, script: applyScript(changes.value.directory) },
1977
+ region: recipe.region
1978
+ },
1979
+ signal,
1980
+ progress
1981
+ );
1982
+ if (applied.kind !== "ok") return applied;
1983
+ const loginPath = await context.runnerSandboxes.loginPath(sandbox, signal);
1984
+ if (!loginPath.ok) return sandboxStop("login-path", loginPath.failure);
1985
+ const installed = await stage(
1986
+ context,
1987
+ {
1988
+ sandbox,
1989
+ phase: "install",
1990
+ step: recipe.run.install,
1991
+ secrets: stepSecrets(request2.secrets, recipe.run.install.secrets),
1992
+ region: recipe.region
1993
+ },
1994
+ signal,
1995
+ progress
1996
+ );
1997
+ if (installed.kind !== "ok") return installed;
1998
+ const built = await stage(
1999
+ context,
2000
+ {
2001
+ sandbox,
2002
+ phase: "build",
2003
+ step: recipe.run.build,
2004
+ secrets: stepSecrets(request2.secrets, recipe.run.build.secrets),
2005
+ region: recipe.region
2006
+ },
2007
+ signal,
2008
+ progress
2009
+ );
2010
+ if (built.kind !== "ok") return built;
2011
+ return {
2012
+ kind: "ready",
2013
+ runner: {
2014
+ sandbox,
2015
+ startedFrom: entry,
2016
+ built: picked === void 0,
2017
+ buildMs: built.value,
2018
+ vcpus: prepared.vcpus,
2019
+ region: recipe.region,
2020
+ runtime: recipe.runtime,
2021
+ repoRoot,
2022
+ cwd: posix2.join(SANDBOX_ROOT, recipe.cwd),
2023
+ env: recipe.env,
2024
+ loginPath: loginPath.value
2025
+ }
2026
+ };
2027
+ }
2028
+ async function uploadChanges(context, request2, signal, progress) {
2029
+ const { prepared } = request2;
2030
+ await progress.emit({ kind: "uploading" });
2031
+ const startedAt = context.clock.now().getTime();
2032
+ let upload = prepared.upload;
2033
+ if (request2.base !== prepared.base) {
2034
+ const assembled = await context.checkout.assembleUpload({ repoRoot: prepared.repoRoot, base: request2.base });
2035
+ if (!assembled.ok) return { kind: "failed", failure: { kind: "checkout-failed", failure: assembled.failure } };
2036
+ upload = assembled.value;
2037
+ }
2038
+ const files = stagedChanges(upload);
2039
+ const staged = await context.runnerSandboxes.upload(request2.sandbox, files, signal);
2040
+ if (!staged.ok) return sandboxStop("upload", staged.failure);
2041
+ const bytes = files.reduce((sum, file) => sum + file.content.byteLength, 0);
2042
+ await progress.emit({ kind: "uploaded", bytes, ms: context.clock.now().getTime() - startedAt });
2043
+ return { kind: "ok", value: { directory: staged.value.directory } };
2044
+ }
2045
+ function stagedChanges(upload) {
2046
+ const encoder = new TextEncoder();
2047
+ return [
2048
+ { name: STAGED_FILES.patch, content: upload.patch },
2049
+ {
2050
+ name: STAGED_FILES.untrackedFileList,
2051
+ content: encoder.encode(upload.untracked.map((path) => `${path}\0`).join(""))
2052
+ },
2053
+ ...upload.untrackedTarball === void 0 ? [] : [{ name: STAGED_FILES.untrackedTarball, content: upload.untrackedTarball }]
2054
+ ];
2055
+ }
2056
+ async function stage(context, request2, signal, progress) {
2057
+ if (signal.aborted) return { kind: "aborted" };
2058
+ const { sandbox, phase, step } = request2;
2059
+ const section = phase === "apply" ? void 0 : phase;
2060
+ if (section !== void 0)
2061
+ await progress.emit({ kind: "output-started", section, sandbox: sandbox.name, region: request2.region });
2062
+ const ran = await runStep(
2063
+ context,
2064
+ {
2065
+ sandbox,
2066
+ phase,
2067
+ label: step.label,
2068
+ script: step.script,
2069
+ ...request2.secrets === void 0 ? {} : { secrets: request2.secrets }
2070
+ },
2071
+ progress,
2072
+ signal
2073
+ );
2074
+ if (ran.kind === "succeeded") {
2075
+ if (section !== void 0) await progress.emit({ kind: "output-ended", section, outcome: "finished" });
2076
+ return { kind: "ok", value: ran.ms };
2077
+ }
2078
+ const stop = ran.kind === "exited" ? {
2079
+ kind: "failed",
2080
+ failure: { kind: `${phase}-failed`, label: step.label, exitCode: ran.exitCode, tail: ran.tail }
2081
+ } : sandboxStop("run-script", ran.failure);
2082
+ if (section !== void 0)
2083
+ await progress.emit({ kind: "output-ended", section, outcome: stop.kind === "aborted" ? "stopped" : "failed" });
2084
+ return stop;
2085
+ }
2086
+
2087
+ // src/runner/scope.ts
2088
+ var CREATE_SETTLE_MS = 2e4;
2089
+ var SNAPSHOT_SETTLE_MS = 2 * 6e4;
2090
+ function unsavedKeepMs(plan) {
2091
+ return plan.kind === "keep" ? plan.ms : plan.otherwiseKeepMs;
2092
+ }
2093
+ function runnerSandboxScope(context, progress, keep) {
2094
+ const { runnerSandboxes: sandboxes, timer, clock } = context;
2095
+ const live = /* @__PURE__ */ new Set();
2096
+ const creating = /* @__PURE__ */ new Set();
2097
+ const saving = /* @__PURE__ */ new Set();
2098
+ const notStopped = [];
2099
+ const notDeleted = [];
2100
+ let kept = null;
2101
+ let notKept = null;
2102
+ let closing;
2103
+ const track = (set, task) => {
2104
+ set.add(task);
2105
+ const forget = () => set.delete(task);
2106
+ void task.then(forget, forget);
2107
+ return task;
2108
+ };
2109
+ const remove = async (sandbox) => {
2110
+ const deleted = await sandboxes.delete(sandbox);
2111
+ if (!deleted.ok)
2112
+ notDeleted.push({ name: sandbox.name, role: sandbox.role, message: failureMessage(deleted.failure) });
2113
+ };
2114
+ const stopAndRemove = async (sandbox) => {
2115
+ const stopped = await sandboxes.stop(sandbox);
2116
+ if (!stopped.ok) {
2117
+ notStopped.push({
2118
+ name: sandbox.name,
2119
+ role: sandbox.role,
2120
+ timeoutMinutes: Math.round(sandbox.timeoutMs / 6e4),
2121
+ message: failureMessage(stopped.failure)
2122
+ });
2123
+ return;
2124
+ }
2125
+ await remove(sandbox);
2126
+ };
2127
+ const keepOrRemove = async (sandbox) => {
2128
+ const keepMs = sandbox.role === "runner" ? keep.keepMs() : 0;
2129
+ if (keepMs <= 0) return await stopAndRemove(sandbox);
2130
+ const keeping = await sandboxes.keepRunning(sandbox, { until: new Date(clock.now().getTime() + keepMs) });
2131
+ if (!keeping.ok) {
2132
+ notKept = { name: sandbox.name, message: failureMessage(keeping.failure) };
2133
+ return await stopAndRemove(sandbox);
2134
+ }
2135
+ kept = { name: sandbox.name, stopsAt: keeping.value.stopsAt.toISOString() };
2136
+ await progress.emit({ kind: "sandbox-kept", ...kept });
2137
+ };
2138
+ const owned = (start) => {
2139
+ if (closing !== void 0) return Promise.resolve({ ok: false, failure: { kind: "aborted" } });
2140
+ return track(
2141
+ creating,
2142
+ (async () => {
2143
+ const started = await start();
2144
+ if (!started.ok) return started;
2145
+ if (closing !== void 0) {
2146
+ await stopAndRemove(started.value);
2147
+ return { ok: false, failure: { kind: "aborted" } };
2148
+ }
2149
+ live.add(started.value);
2150
+ return started;
2151
+ })()
2152
+ );
2153
+ };
2154
+ return {
2155
+ get closed() {
2156
+ return closing !== void 0;
2157
+ },
2158
+ startBuildSandbox: (access, request2) => owned(() => sandboxes.startBuildSandbox(access, request2)),
2159
+ startRunnerSandbox: (access, request2) => owned(() => sandboxes.startRunnerSandbox(access, request2)),
2160
+ saveSnapshot: (sandbox, request2) => track(
2161
+ saving,
2162
+ (async () => {
2163
+ const saved = await sandboxes.saveSnapshot(sandbox, request2);
2164
+ if (saved.ok && live.delete(sandbox)) await remove(sandbox);
2165
+ return saved;
2166
+ })()
2167
+ ),
2168
+ close() {
2169
+ closing ??= (async () => {
2170
+ if (saving.size > 0) await progress.emit({ kind: "waiting-for-snapshot", settleMs: SNAPSHOT_SETTLE_MS });
2171
+ await Promise.all([
2172
+ settleWithin(timer, creating, CREATE_SETTLE_MS),
2173
+ settleWithin(timer, saving, SNAPSHOT_SETTLE_MS)
2174
+ ]);
2175
+ const held = [...live];
2176
+ live.clear();
2177
+ await Promise.all(held.map(keepOrRemove));
2178
+ return { kept, notKept, notStopped: [...notStopped], notDeleted: [...notDeleted] };
2179
+ })();
2180
+ return closing;
2181
+ }
2182
+ };
2183
+ }
2184
+ async function settleWithin(timer, tasks, ms) {
2185
+ if (tasks.size === 0) return;
2186
+ const done = new AbortController();
2187
+ await Promise.race([Promise.allSettled(tasks), timer.sleep(ms, done.signal)]);
2188
+ done.abort();
2189
+ }
2190
+ function failureMessage(failure) {
2191
+ return failure.message ?? failure.kind;
2192
+ }
2193
+
2194
+ // src/runner/snapshot-save.ts
2195
+ var FAILURE_TAIL_LINES = 3;
2196
+ var TEMP_DIRECTORIES = ["/tmp", "/var/tmp", '"${TMPDIR:-}"'];
2197
+ function scrubGitScript(root = SANDBOX_ROOT) {
2198
+ return ["set -euo pipefail", `cd ${root}`, ...RESET_TO_BASE].join("\n");
2199
+ }
2200
+ function scrubTempScript(directories = TEMP_DIRECTORIES) {
2201
+ return [
2202
+ "set -euo pipefail",
2203
+ `for dir in ${directories.join(" ")}; do`,
2204
+ ' [ -n "$dir" ] && [ -d "$dir" ] || continue',
2205
+ ' find "$dir" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true',
2206
+ ' if [ -n "$(find "$dir" -mindepth 1 -maxdepth 1 -print -quit)" ]; then',
2207
+ ' sudo -n find "$dir" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true',
2208
+ " fi",
2209
+ ' left=$(find "$dir" -mindepth 1 -maxdepth 1 -print -quit)',
2210
+ ` if [ -n "$left" ]; then echo "couldn't empty $dir: $left is left" >&2; exit 1; fi`,
2211
+ "done"
2212
+ ].join("\n");
2213
+ }
2214
+ async function saveBranchSnapshot(context, request2, control, progress) {
2215
+ const save = await saveOnce(context, request2, control, progress);
2216
+ if (save.kind !== "saved") await progress.emit({ kind: "branch-snapshot-not-saved", save });
2217
+ return save;
2218
+ }
2219
+ async function saveOnce(context, request2, control, progress) {
2220
+ const { ready, branch, head: head2 } = request2;
2221
+ const { scope, signal } = control;
2222
+ const stopped = () => signal.aborted || scope.closed;
2223
+ if (stopped()) return { kind: "stopped" };
2224
+ const { sandbox, startedFrom } = ready;
2225
+ const startedAt = context.clock.now().getTime();
2226
+ await progress.emit({ kind: "branch-snapshot-saving", branch });
2227
+ for (const script of [scrubGitScript(), scrubTempScript()]) {
2228
+ if (stopped()) return { kind: "stopped" };
2229
+ const ran = await runSaveScript(context, sandbox, script, signal);
2230
+ if (ran.kind === "stopped") return ran;
2231
+ if (ran.kind === "failed") return { kind: "failed", step: "scrub", message: ran.message };
2232
+ }
2233
+ if (stopped()) return { kind: "stopped" };
2234
+ const saved = await scope.saveSnapshot(sandbox, { expirationMs: SNAPSHOT_EXPIRATION_MS });
2235
+ if (!saved.ok)
2236
+ return saved.failure.kind === "aborted" ? { kind: "stopped" } : { kind: "failed", step: "save-snapshot", message: saved.failure.message };
2237
+ if (signal.aborted) return { kind: "stopped" };
2238
+ const savedAt2 = context.clock.now();
2239
+ const entry = {
2240
+ teamId: startedFrom.teamId,
2241
+ projectId: startedFrom.projectId,
2242
+ region: startedFrom.region,
2243
+ runtime: startedFrom.runtime,
2244
+ recipeName: startedFrom.recipeName,
2245
+ snapshotKey: startedFrom.snapshotKey,
2246
+ base: startedFrom.base,
2247
+ branch,
2248
+ head: head2,
2249
+ repoRoot: ready.repoRoot,
2250
+ snapshotId: saved.value.snapshotId,
2251
+ createdAt: savedAt2.toISOString(),
2252
+ expiresAt: saved.value.expiresAt ?? new Date(savedAt2.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString()
2253
+ };
2254
+ const written = await context.runnerSnapshots.writeEntry(entry);
2255
+ if (!written.ok) await progress.emit({ kind: "snapshot-entry-not-written", failure: written.failure });
2256
+ const ms = savedAt2.getTime() - startedAt;
2257
+ await progress.emit({
2258
+ kind: "branch-snapshot-saved",
2259
+ snapshotId: entry.snapshotId,
2260
+ branch,
2261
+ head: head2,
2262
+ ms,
2263
+ sizeBytes: saved.value.sizeBytes
2264
+ });
2265
+ return {
2266
+ kind: "saved",
2267
+ snapshotId: entry.snapshotId,
2268
+ base: entry.base,
2269
+ branch,
2270
+ head: head2,
2271
+ ms,
2272
+ sizeBytes: saved.value.sizeBytes,
2273
+ entryWritten: written.ok
2274
+ };
2275
+ }
2276
+ async function runSaveScript(context, sandbox, script, signal) {
2277
+ const splitters = { stdout: lineSplitter(), stderr: lineSplitter() };
2278
+ const tail = outputTail(FAILURE_TAIL_LINES);
2279
+ const keep = (text) => {
2280
+ for (const line of splitLines(text)) tail.add(line);
2281
+ };
2282
+ const ran = await context.runnerSandboxes.runScript(
2283
+ sandbox,
2284
+ { script, env: STEP_ENV },
2285
+ ({ stream, data }) => keep(splitters[stream].push(data)),
2286
+ signal
2287
+ );
2288
+ keep(splitters.stdout.flush());
2289
+ keep(splitters.stderr.flush());
2290
+ if (!ran.ok)
2291
+ return ran.failure.kind === "aborted" ? { kind: "stopped" } : { kind: "failed", message: ran.failure.message };
2292
+ const { exitCode } = ran.value;
2293
+ if (exitCode === 0) return { kind: "ok" };
2294
+ const lines = tail.lines();
2295
+ const ended = exitCode === null ? "ended without an exit code" : `exited ${exitCode}`;
2296
+ return { kind: "failed", message: lines.length === 0 ? ended : `${ended}: ${lines.join(" / ")}` };
2297
+ }
2298
+
2299
+ // src/runner/session.ts
2300
+ function savedAt(runner, head2) {
2301
+ const { startedFrom } = runner;
2302
+ return isBranchEntry(startedFrom) && startedFrom.head === head2;
2303
+ }
2304
+ function openRunnerSession(context, request2, control, progress) {
2305
+ const { signal, cleanup } = control;
2306
+ const plan = request2.sandbox;
2307
+ const unsaved = { kind: "keep", ms: unsavedKeepMs(plan) };
2308
+ let saveStarted = false;
2309
+ const keepMs = () => saveStarted ? 0 : unsaved.ms;
2310
+ const scope = runnerSandboxScope(context, progress, { keepMs });
2311
+ const closeScope = async () => ({ ...await scope.close(), target: request2.target });
2312
+ let readying = false;
2313
+ let readied;
2314
+ let commandRunning = false;
2315
+ let ended;
2316
+ const stop = () => {
2317
+ void progress.emit({ kind: "stopping", commandRunning, keepMs: keepMs() }).catch(() => void 0);
2318
+ void scope.close().catch(() => void 0);
2319
+ };
2320
+ if (signal.aborted) stop();
2321
+ else signal.addEventListener("abort", stop, { once: true });
2322
+ return {
2323
+ async ready(access, laneSignal) {
2324
+ if (readying) throw new Error("the runner session readies its runner sandbox once");
2325
+ readying = true;
2326
+ const outcome = await readyRunner(
2327
+ context,
2328
+ { prepared: request2.prepared, access, user: request2.user, secrets: request2.secrets },
2329
+ { scope, signal: laneSignal },
2330
+ progress
2331
+ );
2332
+ if (outcome.kind === "ready") readied = outcome.runner;
2333
+ return outcome;
2334
+ },
2335
+ async runCommand(command) {
2336
+ if (readied === void 0) throw new Error("the runner session's runner sandbox isn't ready");
2337
+ commandRunning = true;
2338
+ const ran = await runCommandInSandbox(
2339
+ context,
2340
+ {
2341
+ runner: readied,
2342
+ argv: command.argv,
2343
+ runPayload: command.runPayload,
2344
+ ...command.testEvents === void 0 ? {} : { testEvents: command.testEvents }
2345
+ },
2346
+ { kill: signal },
2347
+ progress
2348
+ );
2349
+ if (ran.kind === "exited") ended = { runner: readied, exitCode: ran.exitCode };
2350
+ return ran;
2351
+ },
2352
+ async finish() {
2353
+ commandRunning = false;
2354
+ const { prepared } = request2;
2355
+ let save = prepared.save?.kind === "skipped" ? prepared.save : null;
2356
+ let action = unsaved;
2357
+ if (plan.kind === "save" && ended !== void 0 && !signal.aborted && (plan.always || ended.exitCode === 0 && !savedAt(ended.runner, prepared.head.commit))) {
2358
+ saveStarted = true;
2359
+ action = plan;
2360
+ const saving = saveBranchSnapshot(
2361
+ context,
2362
+ { ready: ended.runner, branch: plan.branch, head: prepared.head.commit },
2363
+ { scope, signal },
2364
+ progress
2365
+ );
2366
+ try {
2367
+ await cleanup.release(plan);
2368
+ } finally {
2369
+ save = await saving;
2370
+ }
2371
+ }
2372
+ await cleanup.startCleanup(action);
2373
+ const facts = await closeScope();
2374
+ signal.removeEventListener("abort", stop);
2375
+ await cleanup.release(action);
2376
+ return { save, cleanup: facts };
2377
+ },
2378
+ async close() {
2379
+ signal.removeEventListener("abort", stop);
2380
+ try {
2381
+ return await closeScope();
2382
+ } finally {
2383
+ await cleanup.release(unsaved);
2384
+ }
2385
+ }
2386
+ };
2387
+ }
2388
+
2389
+ // src/config/load.ts
2390
+ import { dirname, join as join2 } from "node:path";
2391
+
2392
+ // src/config/schema.ts
2393
+ var CONFIG_FILE_NAME = "storm.config.ts";
2394
+ function checkWith(schema, value) {
2395
+ const parsed = schema.safeParse(value);
2396
+ if (parsed.success) return { ok: true, value: parsed.data };
2397
+ return {
2398
+ ok: false,
2399
+ problems: parsed.error.issues.map(({ path, message }) => ({ path: path.map(String), problem: message }))
2400
+ };
2401
+ }
2402
+ var SETTING_CHECKS = {
2403
+ scope: (value) => checkWith(nonEmptyString, value),
2404
+ project: (value) => checkWith(nonEmptyString, value),
2405
+ runner: checkRecipe
2406
+ };
2407
+ function isConfigSettingKey(key) {
2408
+ return Object.hasOwn(SETTING_CHECKS, key);
2409
+ }
2410
+ function checkSettingValue(key, value) {
2411
+ return SETTING_CHECKS[key](value);
2412
+ }
2413
+
2414
+ // src/config/load.ts
2415
+ async function findConfigFile(gateway, startDirectory) {
2416
+ if (await gateway.hasConfigFile(startDirectory)) return join2(startDirectory, CONFIG_FILE_NAME);
2417
+ const root = await worktreeRoot(gateway, startDirectory);
2418
+ if (root === void 0) return void 0;
2419
+ for (let directory = startDirectory; directory !== root; ) {
2420
+ directory = dirname(directory);
2421
+ if (await gateway.hasConfigFile(directory)) return join2(directory, CONFIG_FILE_NAME);
2422
+ }
2423
+ return void 0;
2424
+ }
2425
+ async function worktreeRoot(gateway, directory) {
2426
+ for (let current = directory; ; current = dirname(current)) {
2427
+ if (await gateway.isWorktreeRoot(current)) return current;
2428
+ if (dirname(current) === current) return void 0;
2429
+ }
2430
+ }
2431
+ async function loadConfig(gateway, startDirectory, definitions) {
2432
+ const path = await findConfigFile(gateway, startDirectory);
2433
+ if (path === void 0) return { kind: "none" };
2434
+ const imported = await gateway.importConfig(path);
2435
+ switch (imported.kind) {
2436
+ case "import-failed":
2437
+ return {
2438
+ kind: "invalid",
2439
+ path,
2440
+ problems: [{ key: null, location: imported.location ?? null, problem: imported.message }]
2441
+ };
2442
+ case "no-default-export":
2443
+ return {
2444
+ kind: "invalid",
2445
+ path,
2446
+ problems: [fileProblem("has no default export; export default defineConfig({ \u2026 })")]
2447
+ };
2448
+ case "default-export":
2449
+ return checkFile(path, imported.value, definitions);
2450
+ }
2451
+ }
2452
+ function checkFile(path, value, definitions) {
2453
+ if (!isRecord2(value))
2454
+ return {
2455
+ kind: "invalid",
2456
+ path,
2457
+ problems: [fileProblem(`must default-export an object, not ${describeValue(value)}`)]
2458
+ };
2459
+ const settings = {};
2460
+ const problems = [];
2461
+ let resources = {};
2462
+ for (const [key, keyValue] of Object.entries(value)) {
2463
+ if (key === "resources") resources = checkResources(keyValue, definitions, problems);
2464
+ else if (isConfigSettingKey(key)) {
2465
+ if (keyValue !== void 0) checkSetting(key, keyValue, settings, problems);
2466
+ } else problems.push({ key, location: null, problem: `is not a ${CONFIG_FILE_NAME} key` });
2467
+ }
2468
+ if (problems.length > 0) return { kind: "invalid", path, problems };
2469
+ return { kind: "loaded", path, values: { settings, resources } };
2470
+ }
2471
+ function checkSetting(key, value, settings, problems) {
2472
+ const checked = checkSettingValue(key, value);
2473
+ if (checked.ok) Object.assign(settings, { [key]: checked.value });
2474
+ else
2475
+ for (const { path: inside, problem } of checked.problems)
2476
+ problems.push({ key: [key, ...inside].join("."), location: null, problem });
2477
+ }
2478
+ function checkResources(value, definitions, problems) {
2479
+ if (value === void 0) return {};
2480
+ if (!isRecord2(value)) {
2481
+ problems.push({ key: "resources", location: null, problem: `must be an object, not ${describeValue(value)}` });
2482
+ return {};
2483
+ }
2484
+ const byName = new Map(definitions.map((definition) => [definition.name, definition]));
2485
+ const holds = definitions.length === 0 ? "none" : definitions.map((each) => each.name).join(", ");
2486
+ const found = {};
2487
+ for (const [key, resource] of Object.entries(value)) {
2488
+ const named = entryName(resource);
2489
+ const definition = byName.get(named !== void 0 && byName.has(named) ? named : key);
2490
+ if (named !== void 0 && definition !== void 0 && key !== defaultResourceKey(definition)) {
2491
+ problems.push({
2492
+ key: `resources.${key}`,
2493
+ location: null,
2494
+ problem: `holds a ${named} resource; for now a resource's key must be its definition's name: name its key ${defaultResourceKey(definition)}`
2495
+ });
2496
+ continue;
2497
+ }
2498
+ if (definition === void 0) {
2499
+ problems.push({
2500
+ key: `resources.${key}`,
2501
+ location: null,
2502
+ problem: `is not a resource; resources holds ${holds}`
2503
+ });
2504
+ continue;
2505
+ }
2506
+ if (resource === void 0) continue;
2507
+ const options = checkResource(definition, key, resource, problems);
2508
+ if (options !== void 0) found[key] = { definition: definition.name, options };
2509
+ }
2510
+ return found;
2511
+ }
2512
+ function entryName(value) {
2513
+ return isRecord2(value) && typeof value["name"] === "string" ? value["name"] : void 0;
2514
+ }
2515
+ function checkResource(definition, key, value, problems) {
2516
+ const { name } = definition;
2517
+ const options = isRecord2(value) && value["name"] === name ? value["options"] : void 0;
2518
+ if (!isRecord2(options)) {
2519
+ problems.push({
2520
+ key: `resources.${key}`,
2521
+ location: null,
2522
+ problem: `must be made by ${resourceCall(name)}, not ${describeValue(value)}`
2523
+ });
2524
+ return void 0;
2525
+ }
2526
+ const checked = {};
2527
+ let valid = true;
2528
+ for (const [option, optionValue] of Object.entries(options)) {
2529
+ const path = `resources.${key}.${option}`;
2530
+ const rule = Object.hasOwn(definition.options, option) ? definition.options[option] : void 0;
2531
+ if (rule === void 0) {
2532
+ valid = false;
2533
+ problems.push({ key: path, location: null, problem: `is not a ${name} option` });
2534
+ continue;
2535
+ }
2536
+ if (optionValue === void 0) continue;
2537
+ const result = checkWith(rule.schema, optionValue);
2538
+ if (result.ok) checked[option] = result.value;
2539
+ else {
2540
+ valid = false;
2541
+ for (const { path: inside, problem } of result.problems)
2542
+ problems.push({ key: [path, ...inside].join("."), location: null, problem });
2543
+ }
2544
+ }
2545
+ return valid ? checked : void 0;
2546
+ }
2547
+ function isRecord2(value) {
2548
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2549
+ }
2550
+ function fileProblem(problem) {
2551
+ return { key: null, location: null, problem };
2552
+ }
2553
+
2554
+ // src/config/credential-resolver.ts
2555
+ import { z as z5 } from "zod";
2556
+
2557
+ // src/credential/live/github-actions-token-response.ts
2558
+ var SAID_LIMIT = 200;
2559
+ var JWT_PATTERN = /eyJ[A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]*){0,2}/g;
2560
+ function classifyTokenResponse(response, requestToken) {
2561
+ const { status, body } = response;
2562
+ if (status < 200 || status >= 300)
2563
+ return { ok: false, failure: { kind: "http-error", status, said: said(body, requestToken) } };
2564
+ let parsed;
2565
+ try {
2566
+ parsed = JSON.parse(body);
2567
+ } catch {
2568
+ return {
2569
+ ok: false,
2570
+ failure: { kind: "bad-response", said: `an answer that isn't JSON (${body.length} characters)` }
2571
+ };
2572
+ }
2573
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
2574
+ return { ok: false, failure: { kind: "bad-response", said: "a JSON answer that isn't an object" } };
2575
+ const { value } = parsed;
2576
+ if (typeof value === "string" && value !== "") return { ok: true, credential: new Credential(value) };
2577
+ const keys = Object.keys(parsed);
2578
+ return {
2579
+ ok: false,
2580
+ failure: {
2581
+ kind: "bad-response",
2582
+ said: said(
2583
+ `a JSON answer with no token in "value" (${keys.length === 0 ? "no keys" : `keys: ${keys.join(", ")}`})`,
2584
+ requestToken
2585
+ )
2586
+ }
2587
+ };
2588
+ }
2589
+ function said(text, requestToken) {
2590
+ const redacted = (requestToken === "" ? text : text.replaceAll(requestToken, "[redacted]")).replace(
2591
+ JWT_PATTERN,
2592
+ "[redacted]"
2593
+ );
2594
+ const line = redacted.replace(/\s+/g, " ").trim();
2595
+ return line.length <= SAID_LIMIT ? line : `${line.slice(0, SAID_LIMIT - 1)}\u2026`;
2596
+ }
2597
+
2598
+ // src/credential/live/github-actions-token-gateway.ts
2599
+ function liveGitHubActionsTokenGateway(options) {
2600
+ const timeoutMs = options.timeoutMs ?? 1e4;
2601
+ return { request: () => request(options.env, timeoutMs) };
2602
+ }
2603
+ async function request(env, timeoutMs) {
2604
+ const url = env["ACTIONS_ID_TOKEN_REQUEST_URL"];
2605
+ const token = env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];
2606
+ const missing = [
2607
+ ...url === void 0 || url === "" ? ["ACTIONS_ID_TOKEN_REQUEST_URL"] : [],
2608
+ ...token === void 0 || token === "" ? ["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] : []
2609
+ ];
2610
+ if (url === void 0 || token === void 0 || missing.length > 0)
2611
+ return { ok: false, failure: { kind: "variables-missing", missing } };
2612
+ const signal = AbortSignal.timeout(timeoutMs);
2613
+ const seconds = timeoutMs / 1e3;
2614
+ try {
2615
+ const response = await fetch(url, {
2616
+ headers: { authorization: `Bearer ${token}`, accept: "application/json" },
2617
+ signal
2618
+ });
2619
+ return classifyTokenResponse({ status: response.status, body: await response.text() }, token);
2620
+ } catch (error) {
2621
+ if (signal.aborted) return { ok: false, failure: { kind: "timeout", seconds } };
2622
+ return { ok: false, failure: { kind: "unreachable", said: said(errorMessage2(error), token) } };
2623
+ }
2624
+ }
2625
+ function errorMessage2(error) {
2626
+ if (!(error instanceof Error)) return String(error);
2627
+ const cause = error.cause;
2628
+ return cause instanceof Error && cause.message !== "" ? `${error.message}: ${cause.message}` : error.message;
2629
+ }
2630
+
2631
+ // src/credential/live/vercel-cli-gateway.ts
2632
+ import { execFile as execFile2 } from "node:child_process";
2633
+ import { tmpdir } from "node:os";
2634
+
2635
+ // src/credential/live/vercel-process.ts
2636
+ var VERCEL_TIMEOUT_MS = 3e4;
2637
+ var VERCEL_TIMEOUT_SECONDS = VERCEL_TIMEOUT_MS / 1e3;
2638
+
2639
+ // src/credential/live/vercel-output.ts
2640
+ var OUTDATED = /unknown or unexpected option: --format|Please specify a valid subcommand/;
2641
+ var UNREACHABLE = /internet connectivity|could not be resolved|\b(?:ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENETUNREACH)\b|fetch failed|socket hang up/i;
2642
+ var PROJECT_NOT_FOUND = /There is no project for|No such project exists/;
2643
+ var SCOPE_NOT_FOUND = "The specified scope does not exist";
2644
+ var ACCOUNT_ACCESS = "You do not have access to the specified account";
2645
+ var ERROR_LINE = /^(?:> )?Error: (.*)$/m;
2646
+ function parseToken(stdout) {
2647
+ const parsed = parseJsonObject(stdout);
2648
+ const token = parsed?.["token"];
2649
+ return typeof token === "string" && token !== "" ? token : void 0;
2650
+ }
2651
+ function errorText(run) {
2652
+ const parsed = parseJsonObject(run.stdout);
2653
+ const message = parsed?.["message"];
2654
+ if (typeof message === "string") {
2655
+ const reason = parsed?.["reason"];
2656
+ return typeof reason === "string" && reason !== "" ? `${message} (${reason})` : message;
2657
+ }
2658
+ const errorLine = ERROR_LINE.exec(run.stderr)?.[1]?.trim();
2659
+ if (errorLine !== void 0 && errorLine !== "") return errorLine;
2660
+ return lastLine(run.stderr) ?? "";
2661
+ }
2662
+ function whoamiUser(stdout) {
2663
+ return lastLine(stdout);
2664
+ }
2665
+ var MINT_STEP = { command: "project token" };
2666
+ function classifyMint(run) {
2667
+ if (run.ok) {
2668
+ const token = parseToken(run.stdout);
2669
+ if (token !== void 0) return { kind: "token", token };
2670
+ } else if (run.reason === "not-found") {
2671
+ return { kind: "failure", failure: { kind: "vercel-not-found" } };
2672
+ } else if (run.reason === "timeout") {
2673
+ return { kind: "failure", failure: { kind: "timeout", step: MINT_STEP, seconds: VERCEL_TIMEOUT_SECONDS } };
2674
+ }
2675
+ const said2 = errorText(run) || "`vercel project token` printed no token";
2676
+ const output = `${run.stdout}
2677
+ ${run.stderr}`;
2678
+ if (UNREACHABLE.test(output)) return { kind: "failure", failure: { kind: "unreachable", step: MINT_STEP, said: said2 } };
2679
+ if (OUTDATED.test(output)) return { kind: "failure", failure: { kind: "outdated-cli", said: said2 } };
2680
+ if (PROJECT_NOT_FOUND.test(output)) return { kind: "failure", failure: { kind: "project-not-found", said: said2 } };
2681
+ if (output.includes(SCOPE_NOT_FOUND) || output.includes(ACCOUNT_ACCESS)) return { kind: "needs-whoami", said: said2 };
2682
+ return { kind: "failure", failure: { kind: "unrecognized", said: said2 } };
2683
+ }
2684
+ function classifyWhoami(run, mintSaid) {
2685
+ if (run.ok) return { kind: "no-team-access", said: mintSaid, user: whoamiUser(run.stdout) };
2686
+ const step = { command: "whoami", mintSaid };
2687
+ if (run.reason === "not-found") return { kind: "vercel-not-found" };
2688
+ if (run.reason === "timeout") return { kind: "timeout", step, seconds: VERCEL_TIMEOUT_SECONDS };
2689
+ const whoamiSaid = errorText(run) || "it failed without an error message";
2690
+ if (UNREACHABLE.test(`${run.stdout}
2691
+ ${run.stderr}`)) return { kind: "unreachable", step, said: whoamiSaid };
2692
+ return { kind: "login-lapsed", said: mintSaid, whoamiSaid };
2693
+ }
2694
+ function parseJsonObject(text) {
2695
+ try {
2696
+ const parsed = JSON.parse(text);
2697
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : void 0;
2698
+ } catch {
2699
+ return void 0;
2700
+ }
2701
+ }
2702
+ function lastLine(text) {
2703
+ return text.split("\n").map((line) => line.trim()).filter((line) => line !== "").at(-1);
2704
+ }
2705
+
2706
+ // src/credential/live/vercel-cli-gateway.ts
2707
+ function mintArgs(target) {
2708
+ return ["project", "token", target.project, "--scope", target.team, "--format=json"];
2709
+ }
2710
+ function liveCredentialGateway() {
2711
+ return {
2712
+ async mint(target) {
2713
+ const minted = classifyMint(await runVercel(mintArgs(target)));
2714
+ switch (minted.kind) {
2715
+ case "token":
2716
+ return { ok: true, credential: new Credential(minted.token) };
2717
+ case "failure":
2718
+ return { ok: false, failure: minted.failure };
2719
+ case "needs-whoami":
2720
+ return { ok: false, failure: classifyWhoami(await runVercel(["whoami"]), minted.said) };
2721
+ }
2722
+ }
2723
+ };
2724
+ }
2725
+ function runVercel(args) {
2726
+ return new Promise((resolve) => {
2727
+ try {
2728
+ execFile2(
2729
+ "vercel",
2730
+ args,
2731
+ {
2732
+ cwd: tmpdir(),
2733
+ env: { ...process.env, NO_COLOR: "1", NO_UPDATE_NOTIFIER: "1" },
2734
+ timeout: VERCEL_TIMEOUT_MS,
2735
+ maxBuffer: 16 * 1024 * 1024,
2736
+ encoding: "utf8"
2737
+ },
2738
+ (error, stdout, stderr) => {
2739
+ resolve(error === null ? { ok: true, stdout, stderr } : failedRun(error, stdout, stderr));
2740
+ }
2741
+ );
2742
+ } catch (error) {
2743
+ resolve(failedRun(error, "", ""));
2744
+ }
2745
+ });
2746
+ }
2747
+ function failedRun(error, stdout, stderr) {
2748
+ const fields = typeof error === "object" && error !== null ? error : {};
2749
+ const out = typeof stdout === "string" ? stdout : "";
2750
+ const err = typeof stderr === "string" ? stderr : "";
2751
+ if (fields["killed"] === true) return { ok: false, reason: "timeout", stdout: out, stderr: err };
2752
+ if (fields["code"] === "ENOENT") return { ok: false, reason: "not-found", stdout: out, stderr: err };
2753
+ return { ok: false, reason: "exit", stdout: out, stderr: err };
2754
+ }
2755
+
2756
+ // src/credential/source.ts
2757
+ var REQUESTING_TOKEN_LINE = "Requesting a GitHub Actions OIDC token\u2026";
2758
+ function credentialSourceFor(choice, context, progress) {
2759
+ if (choice.source === "github-actions")
2760
+ return githubActionsSource({
2761
+ gateway: context.githubActionsTokens,
2762
+ clock: context.clock,
2763
+ timer: context.timer,
2764
+ progress
2765
+ });
2766
+ const { target } = choice;
2767
+ return mintSource(target, async () => {
2768
+ await progress.emit({ kind: "minting", target });
2769
+ const minted = await context.credentials.mint(target);
2770
+ await progress.emit({ kind: "minted", target, ok: minted.ok });
2771
+ return minted;
2772
+ });
2773
+ }
2774
+ function mintSource(target, mint) {
2775
+ let outcome;
2776
+ return {
2777
+ obtain() {
2778
+ outcome ??= (async () => {
2779
+ const minted = await mint();
2780
+ return minted.ok ? minted : { ok: false, failure: { source: "mint", failure: minted.failure, target } };
2781
+ })();
2782
+ return outcome;
2783
+ },
2784
+ origin() {
2785
+ return { source: "mint", target };
2786
+ }
2787
+ };
2788
+ }
2789
+ var TOKEN_REFRESH_MS = 4 * 6e4;
2790
+ var RETRY_WAITS_MS = [1e3, 2e3];
2791
+ function githubActionsSource(context) {
2792
+ let held;
2793
+ let inFlight;
2794
+ const request2 = async () => {
2795
+ await context.progress.emit({ kind: "requesting-token" });
2796
+ for (let attempt = 1; ; attempt += 1) {
2797
+ const sentAt = context.clock.now().getTime();
2798
+ const outcome = await context.gateway.request();
2799
+ if (outcome.ok) {
2800
+ held = { credential: outcome.credential, sentAt };
2801
+ return outcome;
2802
+ }
2803
+ const { failure } = outcome;
2804
+ if (failure.kind === "variables-missing") return { ok: false, failure: { source: "github-actions", failure } };
2805
+ const wait = RETRY_WAITS_MS[attempt - 1];
2806
+ if (wait === void 0 || !isRetryable(failure))
2807
+ return {
2808
+ ok: false,
2809
+ failure: { source: "github-actions", failure: { kind: "request-failed", attempts: attempt, last: failure } }
2810
+ };
2811
+ await context.timer.sleep(wait);
2812
+ }
2813
+ };
2814
+ return {
2815
+ obtain() {
2816
+ if (held !== void 0 && context.clock.now().getTime() - held.sentAt < TOKEN_REFRESH_MS)
2817
+ return Promise.resolve({ ok: true, credential: held.credential });
2818
+ if (inFlight === void 0) {
2819
+ held = void 0;
2820
+ inFlight = (async () => {
2821
+ try {
2822
+ return await request2();
2823
+ } finally {
2824
+ inFlight = void 0;
2825
+ }
2826
+ })();
2827
+ }
2828
+ return inFlight;
2829
+ },
2830
+ origin(credential) {
2831
+ return { source: "github-actions", claims: credential.githubActionsClaims() };
2832
+ }
2833
+ };
2834
+ }
2835
+ function isRetryable(failure) {
2836
+ switch (failure.kind) {
2837
+ case "unreachable":
2838
+ case "timeout":
2839
+ return true;
2840
+ case "http-error":
2841
+ return failure.status === 502 || failure.status === 503 || failure.status === 504;
2842
+ case "bad-response":
2843
+ return false;
2844
+ }
2845
+ }
2846
+
2847
+ // src/credential/target.ts
2848
+ function mintTargetText(target) {
2849
+ return `Vercel project ${target.project} on team ${target.team}`;
2850
+ }
2851
+
2852
+ // src/config/credential-settle.ts
2853
+ import { z as z4 } from "zod";
2854
+ var credentialErrors = defineErrors({
2855
+ missingTarget: {
2856
+ exitCode: 2,
2857
+ description: "The command may mint a credential, and neither a flag nor storm.config.ts names the control plane team or project.",
2858
+ schema: z4.object({
2859
+ /** The settings no flag or config file gave. */
2860
+ missing: z4.array(z4.enum(["scope", "project"]))
2861
+ }),
2862
+ render: ({ missing }) => ({
2863
+ message: `No control plane ${missing.map((key) => key === "scope" ? "team" : "project").join(" or ")} to mint a credential for.`,
2864
+ next: [
2865
+ {
2866
+ type: "text",
2867
+ text: `Give ${missing.map((key) => `--${key}`).join(" and ")}, or set ${missing.join(" and ")} in storm.config.ts.`
2868
+ }
2869
+ ]
2870
+ })
2871
+ }
2872
+ });
2873
+ function requireTarget(scope, project) {
2874
+ if (scope === void 0 || project === void 0)
2875
+ return refused(
2876
+ credentialErrors.missingTarget({
2877
+ missing: [
2878
+ ...scope === void 0 ? ["scope"] : [],
2879
+ ...project === void 0 ? ["project"] : []
2880
+ ]
2881
+ })
2882
+ );
2883
+ return { ok: true, target: { team: scope.value, project: project.value } };
2884
+ }
2885
+ function settleCredential(source, scope, project) {
2886
+ if (source === "github-actions") return { ok: true, credential: { source } };
2887
+ const required = requireTarget(scope, project);
2888
+ if (!required.ok) return required;
2889
+ return { ok: true, credential: { source, target: required.target } };
2890
+ }
2891
+
2892
+ // src/config/credential-resolver.ts
2893
+ var credentialSourceErrors = defineErrors({
2894
+ mintFailed: {
2895
+ exitCode: 1,
2896
+ description: "The vercel CLI couldn't mint a credential for the team and project.",
2897
+ schema: z5.object({ team: z5.string(), project: z5.string(), cause: z5.string(), fix: z5.string() }),
2898
+ render: ({ cause, fix }) => ({
2899
+ message: `Couldn't mint a credential: ${cause}.`,
2900
+ next: [{ type: "text", text: fix }]
2901
+ })
2902
+ },
2903
+ tokenRequestFailed: {
2904
+ exitCode: 1,
2905
+ description: "With --credential github-actions, the GitHub Actions OIDC token request failed.",
2906
+ schema: z5.object(tokenRequestFailureShape),
2907
+ render: ({ detail, fix }) => ({
2908
+ message: `Couldn't request a GitHub Actions OIDC token: ${detail}.`,
2909
+ next: [{ type: "text", text: fix }]
2910
+ })
2911
+ }
2912
+ });
2913
+ function credentialSourceError(failure) {
2914
+ return failure.source === "mint" ? credentialSourceErrors.mintFailed({ ...failure.target, ...describeMintFailure(failure.failure, failure.target) }) : credentialSourceErrors.tokenRequestFailed(tokenRequestFailureFacts(failure.failure));
2915
+ }
2916
+ function credentialResolver(gateways) {
2917
+ return {
2918
+ source(choice, target, report = {}) {
2919
+ const chosen = settleCredential(choice, target.scope, target.project);
2920
+ if (!chosen.ok) return chosen;
2921
+ const { progress } = report;
2922
+ const source = credentialSourceFor(chosen.credential, gateways, {
2923
+ emit: async (event) => {
2924
+ if (event.kind === "minting") await progress?.(`Minting a credential for ${mintTargetText(event.target)}\u2026`);
2925
+ else if (event.kind === "requesting-token") await progress?.(REQUESTING_TOKEN_LINE);
2926
+ }
2927
+ });
2928
+ return {
2929
+ ok: true,
2930
+ source: {
2931
+ async obtain() {
2932
+ const got = await source.obtain();
2933
+ return got.ok ? got : { ok: false, refusal: credentialSourceError(got.failure) };
2934
+ },
2935
+ origin: (credential) => source.origin(credential)
2936
+ }
2937
+ };
2938
+ }
2939
+ };
2940
+ }
2941
+
2942
+ // src/config/errors.ts
2943
+ import { z as z6 } from "zod";
2944
+ var problemSchema = z6.object({
2945
+ /** The key the problem is about; null when it is about the whole file. */
2946
+ key: z6.string().nullable(),
2947
+ /** Where Node said the import failed; null otherwise. */
2948
+ location: z6.object({ line: z6.number(), column: z6.number().nullable() }).nullable(),
2949
+ /** What is wrong, worded to follow the key, or the file name when there is no key. */
2950
+ problem: z6.string()
2951
+ });
2952
+ function configProblemLine(file, { key, location, problem }) {
2953
+ const sentence = `${problem.replace(/\.$/, "")}.`;
2954
+ if (key !== null) return `${file}: ${key} ${sentence}`;
2955
+ if (location !== null)
2956
+ return `${file}:${location.line}${location.column === null ? "" : `:${location.column}`} ${sentence}`;
2957
+ return `${file}: ${sentence}`;
2958
+ }
2959
+ var optionValueSchema = z6.object({
2960
+ /** The option's key path, such as resources.<key>.ttl. */
2961
+ key: z6.string(),
2962
+ /** Its value, as text. */
2963
+ value: z6.string(),
2964
+ /** Where it came from: the command's own flag for the option, the config file or the default. */
2965
+ source: z6.enum(["flag", "file", "default"])
2966
+ });
2967
+ var optionProblemSchema = z6.object({
2968
+ /** The key path of the option the problem is about, such as resources.<key>.ttl. */
2969
+ key: z6.string(),
2970
+ /** What is wrong, worded to follow the key path, as the resource's rule words it. */
2971
+ problem: z6.string(),
2972
+ /** Each value the problem is about, with its source; empty for a required option nothing gave. */
2973
+ values: z6.array(optionValueSchema)
2974
+ });
2975
+ function optionValueText({ key, value, source }, configFile) {
2976
+ switch (source) {
2977
+ case "flag":
2978
+ return `${key} is ${value} from the command line`;
2979
+ case "file":
2980
+ return `${key} is ${value} in ${configFile ?? "storm.config.ts"}`;
2981
+ case "default":
2982
+ return `${key} is ${value} by default`;
2983
+ }
2984
+ }
2985
+ function optionProblemLine({ key, problem, values }, configFile) {
2986
+ const where2 = values.map((value) => optionValueText(value, configFile));
2987
+ const sources = where2.length === 0 ? "" : `: ${where2.length === 1 ? where2.join("") : `${where2.slice(0, -1).join(", ")} and ${where2.at(-1) ?? ""}`}`;
2988
+ return `${key} ${problem.replace(/\.$/, "")}${sources}.`;
2989
+ }
2990
+ var configErrors = defineErrors({
2991
+ invalidConfig: {
2992
+ exitCode: 2,
2993
+ description: "storm.config.ts can't be used: it can't be imported, doesn't default-export an object, has an unknown key, or a value in it is invalid. storm checks the whole file whenever a command loads it.",
2994
+ schema: z6.object({
2995
+ /** The config file's absolute path. */
2996
+ file: z6.string(),
2997
+ problems: z6.array(problemSchema)
2998
+ }),
2999
+ render: ({ file, problems }) => {
3000
+ const [first, ...rest] = problems;
3001
+ return {
3002
+ message: first === void 0 ? `${file} can't be used.` : configProblemLine(file, first),
3003
+ ...rest.length === 0 ? {} : { rows: [["Also", rest.map((problem) => configProblemLine(file, problem))]] },
3004
+ next: [{ type: "text", text: `Fix ${file}, then retry.` }]
3005
+ };
3006
+ }
3007
+ },
3008
+ invalidResourceOptions: {
3009
+ exitCode: 2,
3010
+ description: "A resource's options, once its defaults, storm.config.ts and the flags are merged, don't fit together, as the resource's own checks say, or one it requires is missing: such as resources.<key>.ttl not longer than its minTimeLeft. Each problem names the values it is about and where each came from.",
3011
+ schema: z6.object({
3012
+ /** The config file that applied; null when none did. */
3013
+ configFile: z6.string().nullable(),
3014
+ problems: z6.array(optionProblemSchema)
3015
+ }),
3016
+ render: ({ configFile, problems }) => {
3017
+ const [first, ...rest] = problems;
3018
+ return {
3019
+ message: first === void 0 ? "A resource's options don't fit together." : optionProblemLine(first, configFile),
3020
+ ...rest.length === 0 ? {} : { rows: [["Also", rest.map((problem) => optionProblemLine(problem, configFile))]] },
3021
+ next: [
3022
+ {
3023
+ type: "text",
3024
+ text: `Change the options on the command line or in ${configFile ?? "storm.config.ts"}, then retry.`
3025
+ }
3026
+ ]
3027
+ };
3028
+ }
3029
+ }
3030
+ });
3031
+
3032
+ // src/config/live/config-gateway.ts
3033
+ import { stat } from "node:fs/promises";
3034
+ import { basename, join as join3 } from "node:path";
3035
+ import { pathToFileURL } from "node:url";
3036
+ function liveConfigGateway() {
3037
+ return {
3038
+ hasConfigFile: async (directory) => await kind(join3(directory, CONFIG_FILE_NAME)) === "file",
3039
+ isWorktreeRoot: async (directory) => await kind(join3(directory, ".git")) !== void 0,
3040
+ importConfig: async (path) => {
3041
+ try {
3042
+ const module = await import(pathToFileURL(path).href);
3043
+ return "default" in module ? { kind: "default-export", value: module["default"] } : { kind: "no-default-export" };
3044
+ } catch (error) {
3045
+ return importFailure(error, path);
3046
+ }
3047
+ }
3048
+ };
3049
+ }
3050
+ async function kind(path) {
3051
+ try {
3052
+ return (await stat(path)).isFile() ? "file" : "other";
3053
+ } catch {
3054
+ return void 0;
3055
+ }
3056
+ }
3057
+ function importFailure(error, path) {
3058
+ if (!(error instanceof Error)) return { kind: "import-failed", message: String(error) };
3059
+ const location = errorLocation(error, basename(path));
3060
+ return { kind: "import-failed", message: error.message, ...location === void 0 ? {} : { location } };
3061
+ }
3062
+ function errorLocation(error, name) {
3063
+ const lines = (error.stack ?? "").split("\n");
3064
+ const escaped = name.replaceAll(".", "\\.");
3065
+ if (error instanceof SyntaxError) {
3066
+ const line = new RegExp(`${escaped}:(\\d+)$`).exec(lines[0] ?? "")?.[1];
3067
+ if (line === void 0) return void 0;
3068
+ const frame = lines.slice(1);
3069
+ const carets = frame.slice(0, frame.indexOf("")).find((text) => /^ *\^+$/.test(text));
3070
+ return carets === void 0 ? { line: Number(line) } : { line: Number(line), column: carets.indexOf("^") + 1 };
3071
+ }
3072
+ for (const text of lines) {
3073
+ const frame = new RegExp(`${escaped}:(\\d+):(\\d+)\\)?$`).exec(text);
3074
+ if (frame !== null) return { line: Number(frame[1]), column: Number(frame[2]) };
3075
+ }
3076
+ return void 0;
3077
+ }
3078
+
3079
+ // src/config/typed-options.ts
3080
+ function givenOptionsOf(_definition, values) {
3081
+ return values;
3082
+ }
3083
+ function settingsOf(_definition, settings) {
3084
+ return settings;
3085
+ }
3086
+ function resourceOptionsOf(_definition, value) {
3087
+ return value;
3088
+ }
3089
+
3090
+ // src/config/recipe-run.ts
3091
+ var NOT_PRESENT = Object.freeze({ present: false });
3092
+ function recipeRun(resources) {
3093
+ const run = {
3094
+ get: ({ definition }) => {
3095
+ const key = defaultResourceKey(definition);
3096
+ const resource = Object.hasOwn(resources, key) ? resources[key] : void 0;
3097
+ if (resource === void 0 || resource.definition !== definition.name) return NOT_PRESENT;
3098
+ return Object.freeze({
3099
+ present: true,
3100
+ value: resourceOptionsOf(definition, Object.freeze({ ...resource.options }))
3101
+ });
3102
+ }
3103
+ };
3104
+ return { run: Object.freeze(run), resourceKeys: Object.keys(resources) };
3105
+ }
3106
+
3107
+ // src/config/resolve.ts
3108
+ function resolveSettings(flags, file) {
3109
+ const pick = (flag, fromFile) => flag !== void 0 ? { value: flag, source: "flag" } : fromFile === void 0 ? void 0 : { value: fromFile, source: "file" };
3110
+ return {
3111
+ scope: pick(flags.scope, file?.scope),
3112
+ project: pick(flags.project, file?.project),
3113
+ runner: pick(void 0, file?.runner)
3114
+ };
3115
+ }
3116
+ function optionSource(definition, option, file, flags) {
3117
+ const fromFile = file ?? {};
3118
+ const fromFlags = flags ?? {};
3119
+ if (fromFlags[option] !== void 0) return "flag";
3120
+ if (fromFile[option] !== void 0) return "file";
3121
+ return definition.options[option]?.default === void 0 ? void 0 : "default";
3122
+ }
3123
+ function mergeResourceOptions(definition, key, file, flags) {
3124
+ const fromFile = file ?? {};
3125
+ const fromFlags = flags ?? {};
3126
+ const merged = [];
3127
+ const problems = [];
3128
+ for (const [option, rule] of Object.entries(definition.options)) {
3129
+ const source = optionSource(definition, option, file, flags);
3130
+ if (source === "flag") merged.push([option, { value: fromFlags[option], source }]);
3131
+ else if (source === "file") merged.push([option, { value: fromFile[option], source }]);
3132
+ else if (source === "default") merged.push([option, "default"]);
3133
+ else if (rule.required === true) {
3134
+ problems.push({
3135
+ key: optionKeyPath(key, option),
3136
+ problem: `is required; give it in ${resourceCall(definition.name)}`,
3137
+ values: []
3138
+ });
3139
+ }
3140
+ }
3141
+ if (problems.length > 0) return { ok: false, problems };
3142
+ return {
3143
+ ok: true,
3144
+ settings: (run) => (
3145
+ // Every option with a default or marked required is in `merged`, so it is what `definition.check` takes.
3146
+ settingsOf(
3147
+ definition,
3148
+ Object.fromEntries(
3149
+ merged.map(([option, given]) => [
3150
+ option,
3151
+ given === "default" ? { value: defaultValue(definition, option, run), source: "default" } : given
3152
+ ])
3153
+ )
3154
+ )
3155
+ )
3156
+ };
3157
+ }
3158
+ function isDefaultFunction(given) {
3159
+ return typeof given === "function";
3160
+ }
3161
+ function defaultValue(definition, option, run) {
3162
+ const rule = definition.options[option];
3163
+ if (rule === void 0 || !isDefaultFunction(rule.default)) return rule?.default;
3164
+ const checked = rule.schema.safeParse(rule.default(run));
3165
+ if (checked.success) return checked.data;
3166
+ const problems = checked.error.issues.map(({ message }) => message).join("; ");
3167
+ throw new Error(
3168
+ `${definition.name}'s option ${option} has a default that gave a value its schema refuses: ${problems}`
3169
+ );
3170
+ }
3171
+ function mergeRunResources(definitions, file, flags) {
3172
+ const resources = [];
3173
+ const problems = [];
3174
+ for (const { key, definition, given, flagged } of runResources(definitions, file, flags)) {
3175
+ const merged = mergeResourceOptions(definition, key, given, flagged);
3176
+ if (merged.ok) resources.push({ key, definition, settings: merged.settings });
3177
+ else problems.push(...merged.problems);
3178
+ }
3179
+ if (problems.length > 0) return { ok: false, problems };
3180
+ const options = Object.fromEntries(
3181
+ resources.map(({ key, definition, settings }) => [
3182
+ key,
3183
+ { definition: definition.name, options: plainValues(settings(NOT_COUNTED)) }
3184
+ ])
3185
+ );
3186
+ return { ok: true, options, plan: (run) => planResources(resources, run) };
3187
+ }
3188
+ function planResources(resources, run) {
3189
+ const resolved = {};
3190
+ const planned = [];
3191
+ const problems = [];
3192
+ for (const { key, definition, settings: settingsFor } of resources) {
3193
+ const merged = settingsFor(run);
3194
+ const settings = merged;
3195
+ planned.push(...plannedOptions(definition, key, settings));
3196
+ const refused2 = definition.check(merged);
3197
+ if (refused2.length === 0)
3198
+ resolved[key] = {
3199
+ definition: definition.name,
3200
+ options: plainValues(settings),
3201
+ sources: Object.fromEntries(
3202
+ Object.keys(definition.options).map((option) => [option, settings[option]?.source])
3203
+ )
3204
+ };
3205
+ else
3206
+ for (const { option, problem, involves } of refused2)
3207
+ problems.push({
3208
+ key: optionKeyPath(key, option),
3209
+ problem,
3210
+ values: involves.flatMap((each) => {
3211
+ const setting = settings[each];
3212
+ return setting === void 0 ? [] : [{ key: optionKeyPath(key, each), value: setting.value, source: setting.source }];
3213
+ })
3214
+ });
3215
+ }
3216
+ if (problems.length > 0) return { ok: false, problems };
3217
+ return { ok: true, value: resolved, planned };
3218
+ }
3219
+ function runResources(definitions, file, flags) {
3220
+ const resources = Object.entries(file ?? {});
3221
+ return definitions.flatMap((definition) => {
3222
+ const defaultKey = defaultResourceKey(definition);
3223
+ const flagged = flags[definition.name];
3224
+ const fromFile = resources.flatMap(
3225
+ ([key, resource]) => resource.definition === definition.name ? [{ key, definition, given: resource.options, flagged: key === defaultKey ? flagged : void 0 }] : []
3226
+ );
3227
+ const flagOnly = flagged !== void 0 && !fromFile.some(({ key }) => key === defaultKey) ? [{ key: defaultKey, definition, given: void 0, flagged }] : [];
3228
+ return [...fromFile, ...flagOnly];
3229
+ });
3230
+ }
3231
+ function plainValues(settings) {
3232
+ return Object.fromEntries(
3233
+ Object.entries(settings).flatMap(([option, setting]) => setting === void 0 ? [] : [[option, setting.value]])
3234
+ );
3235
+ }
3236
+ function plannedOptions(definition, key, settings) {
3237
+ return Object.entries(definition.options).flatMap(([option, rule]) => {
3238
+ const setting = settings[option];
3239
+ if (!isDefaultFunction(rule.default) || setting === void 0) return [];
3240
+ const { value, source } = setting;
3241
+ const path = optionKeyPath(key, option);
3242
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean")
3243
+ throw new Error(`${path} has a default that is a function, so it must take a string, number or boolean`);
3244
+ return [{ path, value, source }];
3245
+ });
3246
+ }
3247
+
3248
+ // src/config/settings-file.ts
3249
+ async function loadSettingsFile(gateway, cwd, definitions) {
3250
+ const loaded = await loadConfig(gateway, cwd, definitions);
3251
+ if (loaded.kind === "invalid") return refused(invalidConfig(loaded.path, loaded.problems));
3252
+ return loaded.kind === "loaded" ? { ok: true, path: loaded.path, values: loaded.values, definitions } : { ok: true, path: null, values: void 0, definitions };
3253
+ }
3254
+ function fileSettings(file, flags) {
3255
+ return resolveSettings(flags, file.values?.settings);
3256
+ }
3257
+ function fileOptions(file, definition) {
3258
+ if (!file.definitions.includes(definition))
3259
+ throw new Error(`The config file wasn't checked against ${definition.name}`);
3260
+ const given = file.values?.resources[defaultResourceKey(definition)];
3261
+ return given === void 0 || given.definition !== definition.name ? void 0 : givenOptionsOf(definition, given.options);
3262
+ }
3263
+ function settleRunResources(file, flags) {
3264
+ const merged = mergeRunResources(file.definitions, file.values?.resources, flags);
3265
+ if (!merged.ok) return refused(invalidResourceOptions(file.path, merged.problems));
3266
+ return {
3267
+ ok: true,
3268
+ options: merged.options,
3269
+ plan(run) {
3270
+ const resolved = merged.plan(run);
3271
+ if (!resolved.ok) return refused(invalidResourceOptions(file.path, resolved.problems));
3272
+ return { ok: true, resources: resolved.value, planned: resolved.planned };
3273
+ }
3274
+ };
3275
+ }
3276
+ function invalidConfig(file, problems) {
3277
+ return configErrors.invalidConfig({
3278
+ file,
3279
+ problems: problems.map(({ key, location, problem }) => ({
3280
+ key,
3281
+ location: location === null ? null : { line: location.line, column: location.column ?? null },
3282
+ problem
3283
+ }))
3284
+ });
3285
+ }
3286
+ function invalidResourceOptions(configFile, problems) {
3287
+ return configErrors.invalidResourceOptions({
3288
+ configFile,
3289
+ problems: problems.map(({ key, problem, values }) => ({
3290
+ key,
3291
+ problem,
3292
+ values: values.map(({ key: valueKey, value, source }) => ({ key: valueKey, value: valueText(value), source }))
3293
+ }))
3294
+ });
3295
+ }
3296
+ function valueText(value) {
3297
+ return typeof value === "string" ? value : describeValue(value);
3298
+ }
3299
+
3300
+ // src/config/resolver.ts
3301
+ function configResolver(launcher) {
3302
+ return {
3303
+ async load(definition, options, target) {
3304
+ const file = await loadSettingsFile(launcher.gateway, launcher.cwd, launcher.definitions);
3305
+ if (!file.ok) return file;
3306
+ const settings = fileSettings(file, target);
3307
+ const key = defaultResourceKey(definition);
3308
+ const merged = mergeResourceOptions(definition, key, fileOptions(file, definition), options);
3309
+ if (!merged.ok) return { ok: false, refusal: invalidResourceOptions(file.path, merged.problems) };
3310
+ return {
3311
+ ok: true,
3312
+ options: merged.settings(NOT_COUNTED),
3313
+ target: { scope: settings.scope, project: settings.project },
3314
+ configFile: file.path
3315
+ };
3316
+ }
3317
+ };
3318
+ }
3319
+
3320
+ export {
3321
+ liveGitHubActionsTokenGateway,
3322
+ liveCredentialGateway,
3323
+ credentialSourceFor,
3324
+ mintTargetText,
3325
+ credentialErrors,
3326
+ requireTarget,
3327
+ settleCredential,
3328
+ credentialSourceErrors,
3329
+ credentialResolver,
3330
+ configErrors,
3331
+ liveCheckoutGateway,
3332
+ parseKeepTime,
3333
+ systemTimer,
3334
+ systemClock,
3335
+ RUN_PAYLOAD_VARIABLE,
3336
+ testEventLine,
3337
+ parseTestEvent,
3338
+ redactSecrets,
3339
+ lineSplitter,
3340
+ runStepTakesSecret,
3341
+ liveRunnerSandboxGateway,
3342
+ liveRunnerTerminal,
3343
+ localUserName,
3344
+ RUNNER_SNAPSHOTS_SUBPATH,
3345
+ liveRunnerSnapshotCacheGateway,
3346
+ unavailableRunnerSnapshotCacheGateway,
3347
+ prepareRunner,
3348
+ SANDBOX_TEST_EVENTS_PATH,
3349
+ RUNNER_SECRET_MIN_LENGTH,
3350
+ readRunnerSecrets,
3351
+ openRunnerSession,
3352
+ CONFIG_FILE_NAME,
3353
+ liveConfigGateway,
3354
+ findConfigFile,
3355
+ recipeRun,
3356
+ loadSettingsFile,
3357
+ fileSettings,
3358
+ settleRunResources,
3359
+ invalidConfig,
3360
+ configResolver
3361
+ };