@nimbus-sh/worker 0.1.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 (408) hide show
  1. package/README.md +219 -0
  2. package/dist/_shared/bytes.d.ts +18 -0
  3. package/dist/_shared/bytes.d.ts.map +1 -0
  4. package/dist/_shared/bytes.js +17 -0
  5. package/dist/_shared/cache-stats.d.ts +146 -0
  6. package/dist/_shared/cache-stats.d.ts.map +1 -0
  7. package/dist/_shared/cache-stats.js +162 -0
  8. package/dist/_shared/exports-resolver.d.ts +76 -0
  9. package/dist/_shared/exports-resolver.d.ts.map +1 -0
  10. package/dist/_shared/exports-resolver.js +284 -0
  11. package/dist/_shared/install-phase.d.ts +47 -0
  12. package/dist/_shared/install-phase.d.ts.map +1 -0
  13. package/dist/_shared/install-phase.js +1 -0
  14. package/dist/_shared/real-node-imports.d.ts +38 -0
  15. package/dist/_shared/real-node-imports.d.ts.map +1 -0
  16. package/dist/_shared/real-node-imports.js +46 -0
  17. package/dist/_shared/retry.d.ts +93 -0
  18. package/dist/_shared/retry.d.ts.map +1 -0
  19. package/dist/_shared/retry.js +161 -0
  20. package/dist/_shared/session-id.d.ts +39 -0
  21. package/dist/_shared/session-id.d.ts.map +1 -0
  22. package/dist/_shared/session-id.js +127 -0
  23. package/dist/_shared/session-router.d.ts +104 -0
  24. package/dist/_shared/session-router.d.ts.map +1 -0
  25. package/dist/_shared/session-router.js +165 -0
  26. package/dist/_shared/w7-frame.d.ts +93 -0
  27. package/dist/_shared/w7-frame.d.ts.map +1 -0
  28. package/dist/_shared/w7-frame.js +402 -0
  29. package/dist/auth/index.d.ts +16 -0
  30. package/dist/auth/index.d.ts.map +1 -0
  31. package/dist/auth/index.js +15 -0
  32. package/dist/auth/middleware.d.ts +85 -0
  33. package/dist/auth/middleware.d.ts.map +1 -0
  34. package/dist/auth/middleware.js +150 -0
  35. package/dist/auth/token.d.ts +96 -0
  36. package/dist/auth/token.d.ts.map +1 -0
  37. package/dist/auth/token.js +226 -0
  38. package/dist/auth/types.d.ts +141 -0
  39. package/dist/auth/types.d.ts.map +1 -0
  40. package/dist/auth/types.js +114 -0
  41. package/dist/bindings/d1.d.ts +102 -0
  42. package/dist/bindings/d1.d.ts.map +1 -0
  43. package/dist/bindings/d1.js +549 -0
  44. package/dist/bindings/kv.d.ts +82 -0
  45. package/dist/bindings/kv.d.ts.map +1 -0
  46. package/dist/bindings/kv.js +290 -0
  47. package/dist/bindings/r2.d.ts +137 -0
  48. package/dist/bindings/r2.d.ts.map +1 -0
  49. package/dist/bindings/r2.js +379 -0
  50. package/dist/cirrus-npm-cjs.generated.d.ts +17 -0
  51. package/dist/cirrus-npm-cjs.generated.d.ts.map +1 -0
  52. package/dist/cirrus-npm-cjs.generated.js +41 -0
  53. package/dist/cirrus-plugin-react.generated.d.ts +34 -0
  54. package/dist/cirrus-plugin-react.generated.d.ts.map +1 -0
  55. package/dist/cirrus-plugin-react.generated.js +33 -0
  56. package/dist/constants.d.ts +34 -0
  57. package/dist/constants.d.ts.map +1 -0
  58. package/dist/constants.js +116 -0
  59. package/dist/esbuild-wasm-bundle.generated.d.ts +41 -0
  60. package/dist/esbuild-wasm-bundle.generated.d.ts.map +1 -0
  61. package/dist/esbuild-wasm-bundle.generated.js +40 -0
  62. package/dist/facets/cirrus-real.d.ts +147 -0
  63. package/dist/facets/cirrus-real.d.ts.map +1 -0
  64. package/dist/facets/cirrus-real.js +981 -0
  65. package/dist/facets/inner-do-registry.d.ts +41 -0
  66. package/dist/facets/inner-do-registry.d.ts.map +1 -0
  67. package/dist/facets/inner-do-registry.js +51 -0
  68. package/dist/facets/manager.d.ts +314 -0
  69. package/dist/facets/manager.d.ts.map +1 -0
  70. package/dist/facets/manager.js +2681 -0
  71. package/dist/facets/process.d.ts +318 -0
  72. package/dist/facets/process.d.ts.map +1 -0
  73. package/dist/facets/process.js +567 -0
  74. package/dist/facets/real-vite-fs-shim.d.ts +151 -0
  75. package/dist/facets/real-vite-fs-shim.d.ts.map +1 -0
  76. package/dist/facets/real-vite-fs-shim.js +1279 -0
  77. package/dist/facets/real-vite-hmr.d.ts +142 -0
  78. package/dist/facets/real-vite-hmr.d.ts.map +1 -0
  79. package/dist/facets/real-vite-hmr.js +476 -0
  80. package/dist/facets/vite-dev-server.d.ts +293 -0
  81. package/dist/facets/vite-dev-server.d.ts.map +1 -0
  82. package/dist/facets/vite-dev-server.js +2580 -0
  83. package/dist/facets/wasm-swap-registry.d.ts +261 -0
  84. package/dist/facets/wasm-swap-registry.d.ts.map +1 -0
  85. package/dist/facets/wasm-swap-registry.js +551 -0
  86. package/dist/facets/ws-terminal.d.ts +107 -0
  87. package/dist/facets/ws-terminal.d.ts.map +1 -0
  88. package/dist/facets/ws-terminal.js +207 -0
  89. package/dist/git/commands.d.ts +13 -0
  90. package/dist/git/commands.d.ts.map +1 -0
  91. package/dist/git/commands.js +633 -0
  92. package/dist/git/network-facet.d.ts +61 -0
  93. package/dist/git/network-facet.d.ts.map +1 -0
  94. package/dist/git/network-facet.js +700 -0
  95. package/dist/git-bundle.generated.d.ts +16 -0
  96. package/dist/git-bundle.generated.d.ts.map +1 -0
  97. package/dist/git-bundle.generated.js +15 -0
  98. package/dist/index.d.ts +41 -0
  99. package/dist/index.d.ts.map +1 -0
  100. package/dist/index.js +73 -0
  101. package/dist/loaders/child-process/spawn-facet.d.ts +90 -0
  102. package/dist/loaders/child-process/spawn-facet.d.ts.map +1 -0
  103. package/dist/loaders/child-process/spawn-facet.js +103 -0
  104. package/dist/loaders/child-process/spawn-pool.d.ts +110 -0
  105. package/dist/loaders/child-process/spawn-pool.d.ts.map +1 -0
  106. package/dist/loaders/child-process/spawn-pool.js +161 -0
  107. package/dist/loaders/fanout-pool.d.ts +195 -0
  108. package/dist/loaders/fanout-pool.d.ts.map +1 -0
  109. package/dist/loaders/fanout-pool.js +326 -0
  110. package/dist/loaders/generated-workers.d.ts +26 -0
  111. package/dist/loaders/generated-workers.d.ts.map +1 -0
  112. package/dist/loaders/generated-workers.js +25 -0
  113. package/dist/loaders/index.d.ts +15 -0
  114. package/dist/loaders/index.d.ts.map +1 -0
  115. package/dist/loaders/index.js +13 -0
  116. package/dist/loaders/loader-pool.d.ts +273 -0
  117. package/dist/loaders/loader-pool.d.ts.map +1 -0
  118. package/dist/loaders/loader-pool.js +624 -0
  119. package/dist/loaders/npm-resolve-preamble.d.ts +34 -0
  120. package/dist/loaders/npm-resolve-preamble.d.ts.map +1 -0
  121. package/dist/loaders/npm-resolve-preamble.js +237 -0
  122. package/dist/loaders/pre-bundle-preamble.d.ts +41 -0
  123. package/dist/loaders/pre-bundle-preamble.d.ts.map +1 -0
  124. package/dist/loaders/pre-bundle-preamble.js +114 -0
  125. package/dist/loaders/vendor/codegen.d.ts +24 -0
  126. package/dist/loaders/vendor/codegen.d.ts.map +1 -0
  127. package/dist/loaders/vendor/codegen.js +44 -0
  128. package/dist/loaders/vendor/errors.d.ts +24 -0
  129. package/dist/loaders/vendor/errors.d.ts.map +1 -0
  130. package/dist/loaders/vendor/errors.js +46 -0
  131. package/dist/loaders/vendor/index.d.ts +16 -0
  132. package/dist/loaders/vendor/index.d.ts.map +1 -0
  133. package/dist/loaders/vendor/index.js +11 -0
  134. package/dist/loaders/vendor/pool.d.ts +88 -0
  135. package/dist/loaders/vendor/pool.d.ts.map +1 -0
  136. package/dist/loaders/vendor/pool.js +353 -0
  137. package/dist/loaders/vendor/primitives.d.ts +11 -0
  138. package/dist/loaders/vendor/primitives.d.ts.map +1 -0
  139. package/dist/loaders/vendor/primitives.js +33 -0
  140. package/dist/loaders/vendor/serialize.d.ts +3 -0
  141. package/dist/loaders/vendor/serialize.d.ts.map +1 -0
  142. package/dist/loaders/vendor/serialize.js +25 -0
  143. package/dist/loaders/vendor/types.d.ts +60 -0
  144. package/dist/loaders/vendor/types.d.ts.map +1 -0
  145. package/dist/loaders/vendor/types.js +4 -0
  146. package/dist/npm/cache.d.ts +136 -0
  147. package/dist/npm/cache.d.ts.map +1 -0
  148. package/dist/npm/cache.js +429 -0
  149. package/dist/npm/install-batch-facet.d.ts +129 -0
  150. package/dist/npm/install-batch-facet.d.ts.map +1 -0
  151. package/dist/npm/install-batch-facet.js +598 -0
  152. package/dist/npm/install-facet.d.ts +29 -0
  153. package/dist/npm/install-facet.d.ts.map +1 -0
  154. package/dist/npm/install-facet.js +9 -0
  155. package/dist/npm/installer.d.ts +239 -0
  156. package/dist/npm/installer.d.ts.map +1 -0
  157. package/dist/npm/installer.js +2022 -0
  158. package/dist/npm/npx-install.d.ts +74 -0
  159. package/dist/npm/npx-install.d.ts.map +1 -0
  160. package/dist/npm/npx-install.js +302 -0
  161. package/dist/npm/pre-bundle-facet.d.ts +168 -0
  162. package/dist/npm/pre-bundle-facet.d.ts.map +1 -0
  163. package/dist/npm/pre-bundle-facet.js +653 -0
  164. package/dist/npm/r2-cache.d.ts +286 -0
  165. package/dist/npm/r2-cache.d.ts.map +1 -0
  166. package/dist/npm/r2-cache.js +506 -0
  167. package/dist/npm/resolve-facet.d.ts +202 -0
  168. package/dist/npm/resolve-facet.d.ts.map +1 -0
  169. package/dist/npm/resolve-facet.js +833 -0
  170. package/dist/npm/resolve-one-facet.d.ts +204 -0
  171. package/dist/npm/resolve-one-facet.d.ts.map +1 -0
  172. package/dist/npm/resolve-one-facet.js +437 -0
  173. package/dist/npm/resolver.d.ts +109 -0
  174. package/dist/npm/resolver.d.ts.map +1 -0
  175. package/dist/npm/resolver.js +899 -0
  176. package/dist/npm/tarball-stream.d.ts +85 -0
  177. package/dist/npm/tarball-stream.d.ts.map +1 -0
  178. package/dist/npm/tarball-stream.js +205 -0
  179. package/dist/npm/tarball.d.ts +51 -0
  180. package/dist/npm/tarball.d.ts.map +1 -0
  181. package/dist/npm/tarball.js +185 -0
  182. package/dist/observability/diag-counters.d.ts +292 -0
  183. package/dist/observability/diag-counters.d.ts.map +1 -0
  184. package/dist/observability/diag-counters.js +302 -0
  185. package/dist/observability/heap-estimate.d.ts +166 -0
  186. package/dist/observability/heap-estimate.d.ts.map +1 -0
  187. package/dist/observability/heap-estimate.js +192 -0
  188. package/dist/observability/heavy-alloc-coord.d.ts +95 -0
  189. package/dist/observability/heavy-alloc-coord.d.ts.map +1 -0
  190. package/dist/observability/heavy-alloc-coord.js +149 -0
  191. package/dist/observability/oom-classify.d.ts +56 -0
  192. package/dist/observability/oom-classify.d.ts.map +1 -0
  193. package/dist/observability/oom-classify.js +118 -0
  194. package/dist/observability/oom-discriminator.d.ts +192 -0
  195. package/dist/observability/oom-discriminator.d.ts.map +1 -0
  196. package/dist/observability/oom-discriminator.js +233 -0
  197. package/dist/real-vite-bundle.generated.d.ts +46 -0
  198. package/dist/real-vite-bundle.generated.d.ts.map +1 -0
  199. package/dist/real-vite-bundle.generated.js +53 -0
  200. package/dist/replica/routing.d.ts +171 -0
  201. package/dist/replica/routing.d.ts.map +1 -0
  202. package/dist/replica/routing.js +288 -0
  203. package/dist/replica/suspension.d.ts +36 -0
  204. package/dist/replica/suspension.d.ts.map +1 -0
  205. package/dist/replica/suspension.js +49 -0
  206. package/dist/router/index.d.ts +156 -0
  207. package/dist/router/index.d.ts.map +1 -0
  208. package/dist/router/index.js +220 -0
  209. package/dist/runtime/assets-loader.d.ts +71 -0
  210. package/dist/runtime/assets-loader.d.ts.map +1 -0
  211. package/dist/runtime/assets-loader.js +128 -0
  212. package/dist/runtime/barrel-detect.d.ts +46 -0
  213. package/dist/runtime/barrel-detect.d.ts.map +1 -0
  214. package/dist/runtime/barrel-detect.js +73 -0
  215. package/dist/runtime/barrel-synthesizer.d.ts +181 -0
  216. package/dist/runtime/barrel-synthesizer.d.ts.map +1 -0
  217. package/dist/runtime/barrel-synthesizer.js +541 -0
  218. package/dist/runtime/bun-repl.d.ts +46 -0
  219. package/dist/runtime/bun-repl.d.ts.map +1 -0
  220. package/dist/runtime/bun-repl.js +326 -0
  221. package/dist/runtime/bun-runner.d.ts +66 -0
  222. package/dist/runtime/bun-runner.d.ts.map +1 -0
  223. package/dist/runtime/bun-runner.js +219 -0
  224. package/dist/runtime/clang-runner.d.ts +38 -0
  225. package/dist/runtime/clang-runner.d.ts.map +1 -0
  226. package/dist/runtime/clang-runner.js +1033 -0
  227. package/dist/runtime/comment-strip.d.ts +37 -0
  228. package/dist/runtime/comment-strip.d.ts.map +1 -0
  229. package/dist/runtime/comment-strip.js +74 -0
  230. package/dist/runtime/esbuild-service.d.ts +201 -0
  231. package/dist/runtime/esbuild-service.d.ts.map +1 -0
  232. package/dist/runtime/esbuild-service.js +1444 -0
  233. package/dist/runtime/esbuild-wasm-bytes.d.ts +87 -0
  234. package/dist/runtime/esbuild-wasm-bytes.d.ts.map +1 -0
  235. package/dist/runtime/esbuild-wasm-bytes.js +131 -0
  236. package/dist/runtime/framework-detect.d.ts +71 -0
  237. package/dist/runtime/framework-detect.d.ts.map +1 -0
  238. package/dist/runtime/framework-detect.js +178 -0
  239. package/dist/runtime/long-running-handle.d.ts +133 -0
  240. package/dist/runtime/long-running-handle.d.ts.map +1 -0
  241. package/dist/runtime/long-running-handle.js +192 -0
  242. package/dist/runtime/node-repl.d.ts +36 -0
  243. package/dist/runtime/node-repl.d.ts.map +1 -0
  244. package/dist/runtime/node-repl.js +293 -0
  245. package/dist/runtime/node-runner.d.ts +111 -0
  246. package/dist/runtime/node-runner.d.ts.map +1 -0
  247. package/dist/runtime/node-runner.js +194 -0
  248. package/dist/runtime/node-shims.d.ts +24 -0
  249. package/dist/runtime/node-shims.d.ts.map +1 -0
  250. package/dist/runtime/node-shims.js +3019 -0
  251. package/dist/runtime/package-manager.d.ts +118 -0
  252. package/dist/runtime/package-manager.d.ts.map +1 -0
  253. package/dist/runtime/package-manager.js +420 -0
  254. package/dist/runtime/port-registry.d.ts +80 -0
  255. package/dist/runtime/port-registry.d.ts.map +1 -0
  256. package/dist/runtime/port-registry.js +166 -0
  257. package/dist/runtime/process-logs-api.d.ts +102 -0
  258. package/dist/runtime/process-logs-api.d.ts.map +1 -0
  259. package/dist/runtime/process-logs-api.js +253 -0
  260. package/dist/runtime/process-logs.d.ts +311 -0
  261. package/dist/runtime/process-logs.d.ts.map +1 -0
  262. package/dist/runtime/process-logs.js +656 -0
  263. package/dist/runtime/process-table.d.ts +65 -0
  264. package/dist/runtime/process-table.d.ts.map +1 -0
  265. package/dist/runtime/process-table.js +107 -0
  266. package/dist/runtime/project-detect.d.ts +21 -0
  267. package/dist/runtime/project-detect.d.ts.map +1 -0
  268. package/dist/runtime/project-detect.js +46 -0
  269. package/dist/runtime/python-repl.d.ts +66 -0
  270. package/dist/runtime/python-repl.d.ts.map +1 -0
  271. package/dist/runtime/python-repl.js +563 -0
  272. package/dist/runtime/python-runner.d.ts +50 -0
  273. package/dist/runtime/python-runner.d.ts.map +1 -0
  274. package/dist/runtime/python-runner.js +870 -0
  275. package/dist/runtime/repl-session.d.ts +160 -0
  276. package/dist/runtime/repl-session.d.ts.map +1 -0
  277. package/dist/runtime/repl-session.js +393 -0
  278. package/dist/runtime/require-resolver.d.ts +52 -0
  279. package/dist/runtime/require-resolver.d.ts.map +1 -0
  280. package/dist/runtime/require-resolver.js +690 -0
  281. package/dist/runtime/router-basename.d.ts +36 -0
  282. package/dist/runtime/router-basename.d.ts.map +1 -0
  283. package/dist/runtime/router-basename.js +310 -0
  284. package/dist/runtime/ruby-repl.d.ts +43 -0
  285. package/dist/runtime/ruby-repl.d.ts.map +1 -0
  286. package/dist/runtime/ruby-repl.js +229 -0
  287. package/dist/runtime/ruby-runner.d.ts +62 -0
  288. package/dist/runtime/ruby-runner.d.ts.map +1 -0
  289. package/dist/runtime/ruby-runner.js +737 -0
  290. package/dist/runtime/runtime-catalog.d.ts +99 -0
  291. package/dist/runtime/runtime-catalog.d.ts.map +1 -0
  292. package/dist/runtime/runtime-catalog.js +183 -0
  293. package/dist/runtime/runtime-registry.d.ts +136 -0
  294. package/dist/runtime/runtime-registry.d.ts.map +1 -0
  295. package/dist/runtime/runtime-registry.js +318 -0
  296. package/dist/runtime/streams.d.ts +13 -0
  297. package/dist/runtime/streams.d.ts.map +1 -0
  298. package/dist/runtime/streams.js +402 -0
  299. package/dist/runtime/wasi-instance.d.ts +190 -0
  300. package/dist/runtime/wasi-instance.d.ts.map +1 -0
  301. package/dist/runtime/wasi-instance.js +2044 -0
  302. package/dist/runtime/wasm-runner.d.ts +117 -0
  303. package/dist/runtime/wasm-runner.d.ts.map +1 -0
  304. package/dist/runtime/wasm-runner.js +705 -0
  305. package/dist/session/bindings.d.ts +168 -0
  306. package/dist/session/bindings.d.ts.map +1 -0
  307. package/dist/session/bindings.js +524 -0
  308. package/dist/session/ctx-exports.d.ts +16 -0
  309. package/dist/session/ctx-exports.d.ts.map +1 -0
  310. package/dist/session/ctx-exports.js +22 -0
  311. package/dist/session/diag.d.ts +62 -0
  312. package/dist/session/diag.d.ts.map +1 -0
  313. package/dist/session/diag.js +118 -0
  314. package/dist/session/fs-watch.d.ts +132 -0
  315. package/dist/session/fs-watch.d.ts.map +1 -0
  316. package/dist/session/fs-watch.js +255 -0
  317. package/dist/session/helpers.d.ts +150 -0
  318. package/dist/session/helpers.d.ts.map +1 -0
  319. package/dist/session/helpers.js +472 -0
  320. package/dist/session/hibernation.d.ts +145 -0
  321. package/dist/session/hibernation.d.ts.map +1 -0
  322. package/dist/session/hibernation.js +385 -0
  323. package/dist/session/init-phases.d.ts +87 -0
  324. package/dist/session/init-phases.d.ts.map +1 -0
  325. package/dist/session/init-phases.js +137 -0
  326. package/dist/session/init.d.ts +46 -0
  327. package/dist/session/init.d.ts.map +1 -0
  328. package/dist/session/init.js +3579 -0
  329. package/dist/session/keys.d.ts +56 -0
  330. package/dist/session/keys.d.ts.map +1 -0
  331. package/dist/session/keys.js +55 -0
  332. package/dist/session/nimbus-session.d.ts +434 -0
  333. package/dist/session/nimbus-session.d.ts.map +1 -0
  334. package/dist/session/nimbus-session.js +1084 -0
  335. package/dist/session/programmatic.d.ts +105 -0
  336. package/dist/session/programmatic.d.ts.map +1 -0
  337. package/dist/session/programmatic.js +326 -0
  338. package/dist/session/replica-routes.d.ts +68 -0
  339. package/dist/session/replica-routes.d.ts.map +1 -0
  340. package/dist/session/replica-routes.js +77 -0
  341. package/dist/session/routes.d.ts +29 -0
  342. package/dist/session/routes.d.ts.map +1 -0
  343. package/dist/session/routes.js +1331 -0
  344. package/dist/session/rpc.d.ts +323 -0
  345. package/dist/session/rpc.d.ts.map +1 -0
  346. package/dist/session/rpc.js +808 -0
  347. package/dist/session/state-store.d.ts +210 -0
  348. package/dist/session/state-store.d.ts.map +1 -0
  349. package/dist/session/state-store.js +459 -0
  350. package/dist/session/supervisor-rpc.d.ts +269 -0
  351. package/dist/session/supervisor-rpc.d.ts.map +1 -0
  352. package/dist/session/supervisor-rpc.js +437 -0
  353. package/dist/session/ws-hibernation-config.d.ts +64 -0
  354. package/dist/session/ws-hibernation-config.d.ts.map +1 -0
  355. package/dist/session/ws-hibernation-config.js +89 -0
  356. package/dist/session/ws.d.ts +95 -0
  357. package/dist/session/ws.d.ts.map +1 -0
  358. package/dist/session/ws.js +395 -0
  359. package/dist/shell/features.d.ts +410 -0
  360. package/dist/shell/features.d.ts.map +1 -0
  361. package/dist/shell/features.js +1885 -0
  362. package/dist/shell/unix-commands.d.ts +15 -0
  363. package/dist/shell/unix-commands.d.ts.map +1 -0
  364. package/dist/shell/unix-commands.js +3703 -0
  365. package/dist/stubs/lifo-ui.d.ts +10 -0
  366. package/dist/stubs/lifo-ui.d.ts.map +1 -0
  367. package/dist/stubs/lifo-ui.js +1 -0
  368. package/dist/tailwind-play.generated.d.ts +19 -0
  369. package/dist/tailwind-play.generated.d.ts.map +1 -0
  370. package/dist/tailwind-play.generated.js +18 -0
  371. package/dist/vfs/dev-provider.d.ts +64 -0
  372. package/dist/vfs/dev-provider.d.ts.map +1 -0
  373. package/dist/vfs/dev-provider.js +191 -0
  374. package/dist/vfs/events.d.ts +51 -0
  375. package/dist/vfs/events.d.ts.map +1 -0
  376. package/dist/vfs/events.js +127 -0
  377. package/dist/vfs/path.d.ts +30 -0
  378. package/dist/vfs/path.d.ts.map +1 -0
  379. package/dist/vfs/path.js +41 -0
  380. package/dist/vfs/seed-project.d.ts +62 -0
  381. package/dist/vfs/seed-project.d.ts.map +1 -0
  382. package/dist/vfs/seed-project.js +1045 -0
  383. package/dist/vfs/sqlite-vfs.d.ts +435 -0
  384. package/dist/vfs/sqlite-vfs.d.ts.map +1 -0
  385. package/dist/vfs/sqlite-vfs.js +1670 -0
  386. package/dist/vfs/symlink-registry.d.ts +64 -0
  387. package/dist/vfs/symlink-registry.d.ts.map +1 -0
  388. package/dist/vfs/symlink-registry.js +137 -0
  389. package/dist/wrangler/nimbus-wrangler.d.ts +157 -0
  390. package/dist/wrangler/nimbus-wrangler.d.ts.map +1 -0
  391. package/dist/wrangler/nimbus-wrangler.js +931 -0
  392. package/package.json +77 -0
  393. package/public/_assets/cirrus-plugin-react.bundle.js +70740 -0
  394. package/public/_assets/esbuild-0.24.2.wasm +0 -0
  395. package/public/_assets/real-vite-bundle.js +101478 -0
  396. package/public/_assets/rollup.wasm +0 -0
  397. package/public/favicon.svg +8 -0
  398. package/public/index.html +565 -0
  399. package/public/s/index.html +2379 -0
  400. package/scripts/bundle-esbuild-wasm.mjs +244 -0
  401. package/scripts/bundle-facet-workers.mjs +137 -0
  402. package/scripts/bundle-git.mjs +118 -0
  403. package/scripts/bundle-npm-cjs.mjs +363 -0
  404. package/scripts/bundle-plugin-react.mjs +480 -0
  405. package/scripts/bundle-real-vite.mjs +959 -0
  406. package/scripts/bundle-runtime.mjs +600 -0
  407. package/scripts/bundle-tailwind-play.mjs +130 -0
  408. package/scripts/patch-lifo-ui.mjs +131 -0
@@ -0,0 +1,959 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * bundle-real-vite.mjs — Phase 0 spike bundler for real Vite in a facet.
4
+ *
5
+ * Pre-bundles the real `vite` npm package into a single ESM string that
6
+ * we can inject into a dynamic worker loaded via env.LOADER.load(). The
7
+ * facet imports it via `import * as vite from './real-vite.bundle.js'`.
8
+ *
9
+ * Strategy (matches PHASE2-REAL-VITE-PLAN.md §2):
10
+ * - Install vite from npm if missing
11
+ * - Bundle vite/dist/node/index.js with esbuild (platform=neutral)
12
+ * - Stub out all native-binding imports: rolldown/*, lightningcss,
13
+ * @swc/core, fsevents, #module-sync-enabled
14
+ * - Keep node:* imports external — the facet gets nodejs_compat so
15
+ * workerd provides them
16
+ * - Write to src/real-vite-bundle.generated.ts as a TS string export
17
+ *
18
+ * This is a FEASIBILITY SPIKE: the bundle will let Vite import, but any
19
+ * call path that hits a stubbed function (most of build/*, some of
20
+ * dev/* via bundleConfigFile) will throw. That's expected. The Phase 0
21
+ * question is "can the import+createServer+listen path survive?"
22
+ */
23
+
24
+ import { promises as fs } from 'node:fs';
25
+ import path from 'node:path';
26
+ import { fileURLToPath } from 'node:url';
27
+ import { createRequire } from 'node:module';
28
+ import esbuild from 'esbuild';
29
+
30
+ const require = createRequire(import.meta.url);
31
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
32
+ const ROOT = path.resolve(__dirname, '..');
33
+ const OUT = path.join(ROOT, 'src', 'real-vite-bundle.generated.ts');
34
+ // [sdk-phase-1] Large blobs ship via the ASSETS binding instead of inline.
35
+ // Cuts Worker-bundle size from ~13 MB → ~5 MB while keeping the
36
+ // (small) version constant + browser-runtime mjs files inline.
37
+ const ASSETS_DIR = path.join(ROOT, 'public', '_assets');
38
+ const ASSET_PATH_VITE_BUNDLE = '/_assets/real-vite-bundle.js';
39
+ const ASSET_PATH_ROLLUP_WASM = '/_assets/rollup.wasm';
40
+ // [sdk-phase-1] In the monorepo, bun hoists vite + @rollup/wasm-node
41
+ // to the workspace root. Walk up to find them.
42
+ function findPkgDir(start, pkgName) {
43
+ let dir = start;
44
+ while (true) {
45
+ const candidate = path.join(dir, 'node_modules', pkgName);
46
+ try { require('node:fs').statSync(candidate); return candidate; }
47
+ catch {}
48
+ const parent = path.dirname(dir);
49
+ if (parent === dir) return null;
50
+ dir = parent;
51
+ }
52
+ }
53
+
54
+ // Keep node:* modules external — workerd provides them via nodejs_compat.
55
+ // Any module in this list is passed through as-is in the bundle.
56
+ const NODE_BUILTINS = [
57
+ 'node:assert', 'node:buffer', 'node:child_process', 'node:crypto',
58
+ 'node:dns', 'node:events', 'node:fs', 'node:fs/promises', 'node:http',
59
+ 'node:https', 'node:module', 'node:net', 'node:os', 'node:path',
60
+ 'node:perf_hooks', 'node:process', 'node:querystring', 'node:readline',
61
+ 'node:stream', 'node:string_decoder', 'node:timers', 'node:timers/promises',
62
+ 'node:tls', 'node:tty', 'node:url', 'node:util', 'node:v8',
63
+ 'node:worker_threads', 'node:zlib', 'node:http2', 'node:stream/web',
64
+ 'node:stream/promises', 'node:async_hooks', 'node:vm', 'node:diagnostics_channel',
65
+ 'node:inspector', 'node:constants',
66
+ // bare specifiers that also need to pass through
67
+ 'fs', 'path', 'url', 'util', 'os', 'net', 'crypto', 'child_process',
68
+ 'dns', 'tty', 'worker_threads', 'assert', 'process', 'v8', 'events',
69
+ 'http', 'https', 'zlib', 'stream', 'buffer', 'readline', 'module',
70
+ 'string_decoder', 'timers', 'querystring', 'perf_hooks', 'http2',
71
+ 'tls', 'async_hooks',
72
+ // Virtual wrappers consumed by the fs-shim — resolved to real node:fs
73
+ // at facet load time via LOADER.load's modules map.
74
+ 'real-node-fs.js', 'real-node-fs-promises.js',
75
+ // Phase 1: the REAL fs-shim (not the inline Phase 0 wrapper) lives
76
+ // in src/real-vite-fs-shim.ts and is supplied as LOADER modules
77
+ // 'cirrus-fs.js' + 'cirrus-fs-promises.js'. Vite's `node:fs` /
78
+ // `node:fs/promises` imports are rewritten to those specifiers.
79
+ 'cirrus-fs.js', 'cirrus-fs-promises.js',
80
+ // Phase 2: ws (Vite HMR server) + chokidar (Vite file-watcher) shims.
81
+ 'cirrus-ws.js', 'cirrus-chokidar.js',
82
+ ];
83
+
84
+ // Modules we fully replace with stubs. These are native-binding-backed or
85
+ // otherwise won't run inside workerd.
86
+ const HARD_STUBS = [
87
+ 'rolldown',
88
+ 'rolldown/parseAst',
89
+ 'rolldown/plugins',
90
+ 'rolldown/utils',
91
+ 'rolldown/filter',
92
+ 'rolldown/experimental',
93
+ 'rolldown/config',
94
+ 'lightningcss',
95
+ '@swc/core',
96
+ 'fsevents',
97
+ ];
98
+
99
+ // esbuild gets its own stub (separate from HARD_STUBS because it
100
+ // needs a different set of thrower functions). In real-vite mode
101
+ // no esbuild call is ever reachable: vite:esbuild transform is
102
+ // patched to use our CJS→ESM intercept, replaceDefine is patched
103
+ // to use regex replacement, optimizeDeps is disabled, and vite
104
+ // build is blocked (rolldown needs node:wasi). Bundling the real
105
+ // esbuild-wasm adds ~2.3 MB of JS + WASM to the facet for zero
106
+ // runtime benefit — big contributor to the facet OOM at 137.
107
+ const ESBUILD_STUB_SRC = `
108
+ const thrower = (name) => () => { throw new Error('[cirrus-real] esbuild.' + name + ' stubbed — real-vite facet does not ship esbuild runtime'); };
109
+ export const transform = thrower('transform');
110
+ export const transformSync = thrower('transformSync');
111
+ export const build = thrower('build');
112
+ export const buildSync = thrower('buildSync');
113
+ export const context = thrower('context');
114
+ export const formatMessages = async () => [];
115
+ export const formatMessagesSync = () => [];
116
+ export const analyzeMetafile = async () => '';
117
+ export const analyzeMetafileSync = () => '';
118
+ export const stop = () => {};
119
+ export const version = '0.0.0-cirrus-stub';
120
+ export const initialize = async () => {};
121
+ export default { transform, transformSync, build, buildSync, context, formatMessages, formatMessagesSync, analyzeMetafile, analyzeMetafileSync, stop, version, initialize };
122
+ `;
123
+
124
+ function stubSource() {
125
+ // Minimal stub: every named export throws if ever actually called, and
126
+ // plugin-factory-style exports return harmless no-op plugins so the
127
+ // config phase doesn't blow up. Vite imports these statically from
128
+ // rolldown/parseAst, rolldown/plugins, rolldown/utils, rolldown/filter,
129
+ // rolldown/experimental at the TOP of its bundle — they MUST import
130
+ // cleanly or the whole module graph fails to load.
131
+ return `
132
+ const NOOP_PLUGIN = (name) => ({ name: 'real-vite-spike-stub-' + name });
133
+ const thrower = (name) => () => { throw new Error('[real-vite-spike] ' + name + ' is stubbed (native binding)'); };
134
+ // parseAst/parseAstAsync are invoked by vite.parseAst / parseAstAsync.
135
+ // They'll throw if reached — but Vite can boot without ever calling them
136
+ // if we avoid the build path.
137
+ export const parseAst = thrower('rolldown.parseAst');
138
+ export const parseAstAsync = async (...a) => parseAst(...a);
139
+ export const rolldown = thrower('rolldown');
140
+ export const VERSION = '0.0.0-stub';
141
+ export const TsconfigCache = class { constructor() {} get() { return null; } set() {} };
142
+ export const Visitor = class {};
143
+ export const minify = thrower('minify');
144
+ export const minifySync = thrower('minifySync');
145
+ export const parse = thrower('parse');
146
+ export const parseSync = thrower('parseSync');
147
+ export const transformSync = thrower('transformSync');
148
+ export const esmExternalRequirePlugin = () => NOOP_PLUGIN('esmExternalRequirePlugin');
149
+ export const exactRegex = (r) => r;
150
+ export const makeIdFiltersToMatchWithQuery = () => [];
151
+ export const prefixRegex = (r) => r;
152
+ export const withFilter = (x) => x;
153
+ // rolldown/experimental exports — these are called as plugin factories by Vite internals.
154
+ export const dev = () => {};
155
+ export const oxcRuntimePlugin = () => NOOP_PLUGIN('oxcRuntimePlugin');
156
+ export const resolveTsconfig = () => null;
157
+ export const scan = async () => ({});
158
+ export const viteAliasPlugin = () => NOOP_PLUGIN('viteAliasPlugin');
159
+ export const viteBuildImportAnalysisPlugin = () => NOOP_PLUGIN('viteBuildImportAnalysisPlugin');
160
+ export const viteDynamicImportVarsPlugin = () => NOOP_PLUGIN('viteDynamicImportVarsPlugin');
161
+ export const viteImportGlobPlugin = () => NOOP_PLUGIN('viteImportGlobPlugin');
162
+ export const viteJsonPlugin = () => NOOP_PLUGIN('viteJsonPlugin');
163
+ export const viteLoadFallbackPlugin = () => NOOP_PLUGIN('viteLoadFallbackPlugin');
164
+ export const viteManifestPlugin = () => NOOP_PLUGIN('viteManifestPlugin');
165
+ export const viteModulePreloadPolyfillPlugin = () => NOOP_PLUGIN('viteModulePreloadPolyfillPlugin');
166
+ export const viteReporterPlugin = () => NOOP_PLUGIN('viteReporterPlugin');
167
+ export const viteResolvePlugin = () => NOOP_PLUGIN('viteResolvePlugin');
168
+ export const viteTransformPlugin = () => NOOP_PLUGIN('viteTransformPlugin');
169
+ export const viteWasmFallbackPlugin = () => NOOP_PLUGIN('viteWasmFallbackPlugin');
170
+ export const viteWebWorkerPostPlugin = () => NOOP_PLUGIN('viteWebWorkerPostPlugin');
171
+ // lightningcss
172
+ export const transform = thrower('lightningcss.transform');
173
+ export const bundle = thrower('lightningcss.bundle');
174
+ export const bundleAsync = async (...a) => thrower('lightningcss.bundleAsync')();
175
+ // generic fallback
176
+ export default { __stubbed: true };
177
+ `.trim();
178
+ }
179
+
180
+ // Phase 1: removed — the fs-shim now lives in src/real-vite-fs-shim.ts
181
+ // and is supplied as 'cirrus-fs.js' / 'cirrus-fs-promises.js' LOADER
182
+ // modules. Keeping the shim out-of-bundle lets us iterate on it
183
+ // without rebuilding the 2.5 MB vite.bundle.js every time.
184
+ // ── (legacy inline shim generator, unused) ────────────────────────
185
+ function _unusedFsShimSource(flavor /* 'sync' | 'promises' */) {
186
+ if (flavor === 'promises') {
187
+ return `
188
+ import * as _real from 'real-node-fs-promises.js';
189
+ const _syn = globalThis.__cirrusRealSynthetic || new Map();
190
+ globalThis.__cirrusRealSynthetic = _syn;
191
+ function _norm(p) {
192
+ if (typeof p !== 'string') {
193
+ try { p = p.pathname || String(p); } catch { return null; }
194
+ }
195
+ return p.replace(/^file:\\/\\//, '');
196
+ }
197
+ const _readFile = _real.readFile;
198
+ export const readFile = async function(p, ...rest) {
199
+ const n = _norm(p);
200
+ if (n != null && _syn.has(n)) {
201
+ const c = _syn.get(n);
202
+ const opts = rest[0], enc = typeof opts === 'string' ? opts : opts?.encoding;
203
+ return enc ? c : new TextEncoder().encode(c);
204
+ }
205
+ return _readFile.call(_real, p, ...rest);
206
+ };
207
+ export const { writeFile, stat, readdir, mkdir, unlink, access, lstat, realpath, rm, rmdir, rename, cp, copyFile, appendFile, chmod, chown, open, constants, utimes } = _real;
208
+ export default { ..._real, readFile };
209
+ `;
210
+ }
211
+ return `
212
+ import * as _real from 'real-node-fs.js';
213
+ const _syn = globalThis.__cirrusRealSynthetic || new Map();
214
+ globalThis.__cirrusRealSynthetic = _syn;
215
+ function _norm(p) {
216
+ if (typeof p !== 'string') {
217
+ try { p = p.pathname || String(p); } catch { return null; }
218
+ }
219
+ return p.replace(/^file:\\/\\//, '');
220
+ }
221
+ const _rfs = _real.readFileSync, _ex = _real.existsSync, _st = _real.statSync, _rp = _real.realpathSync;
222
+ export const readFileSync = function(p, ...rest) {
223
+ const n = _norm(p);
224
+ if (n != null && _syn.has(n)) {
225
+ const c = _syn.get(n);
226
+ const opts = rest[0], enc = typeof opts === 'string' ? opts : opts?.encoding;
227
+ if (enc) return c;
228
+ // Callers that don't pass an encoding expect a Buffer in Node; in
229
+ // workerd, Buffer.from(string, 'utf-8') Just Works. We return the
230
+ // Buffer so JSON.parse(readFileSync(path)) — Vite's common pattern
231
+ // on its own package.json — treats the bytes as a UTF-8 string.
232
+ try { return globalThis.Buffer.from(c, 'utf-8'); }
233
+ catch { return new TextEncoder().encode(c); }
234
+ }
235
+ return _rfs.call(_real, p, ...rest);
236
+ };
237
+ export const existsSync = function(p) {
238
+ const n = _norm(p);
239
+ if (n != null && _syn.has(n)) return true;
240
+ try { return _ex.call(_real, p); } catch { return false; }
241
+ };
242
+ export const statSync = function(p, ...rest) {
243
+ const n = _norm(p);
244
+ if (n != null && _syn.has(n)) {
245
+ const size = _syn.get(n).length;
246
+ return {
247
+ isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false,
248
+ size, mtime: new Date(0), ctime: new Date(0), atime: new Date(0),
249
+ mtimeMs: 0, ctimeMs: 0, atimeMs: 0, birthtimeMs: 0,
250
+ mode: 0o100644, uid: 0, gid: 0, ino: 0, nlink: 1, dev: 0, rdev: 0, blksize: 4096, blocks: 1,
251
+ };
252
+ }
253
+ try { return _st.call(_real, p, ...rest); }
254
+ catch (e) { if (rest[0]?.throwIfNoEntry === false) return undefined; throw e; }
255
+ };
256
+ export const realpathSync = function(p, ...rest) {
257
+ const n = _norm(p);
258
+ if (n != null && _syn.has(n)) return n;
259
+ try { return _rp.call(_real, p, ...rest); } catch { return n || p; }
260
+ };
261
+ // Promise API passthrough (Vite reads fs.promises.readFile too)
262
+ const _pReadFile = _real.promises?.readFile;
263
+ const _pStat = _real.promises?.stat;
264
+ export const promises = {
265
+ ..._real.promises,
266
+ readFile: async (p, ...rest) => {
267
+ const n = _norm(p);
268
+ if (n != null && _syn.has(n)) {
269
+ const c = _syn.get(n);
270
+ const opts = rest[0], enc = typeof opts === 'string' ? opts : opts?.encoding;
271
+ return enc ? c : new TextEncoder().encode(c);
272
+ }
273
+ return _pReadFile.call(_real.promises, p, ...rest);
274
+ },
275
+ stat: async (p, ...rest) => {
276
+ const n = _norm(p);
277
+ if (n != null && _syn.has(n)) return statSync(p);
278
+ return _pStat.call(_real.promises, p, ...rest);
279
+ },
280
+ };
281
+ // All other top-level fs exports passthrough. We list the common ones
282
+ // explicitly so esbuild's ESM checker can verify all of Vite's + deps'
283
+ // named imports. Anything not listed here will fail at bundle time.
284
+ export const { readFile, writeFile, writeFileSync, readdir, readdirSync, mkdir, mkdirSync, unlink, unlinkSync, access, accessSync, lstat, lstatSync, stat, realpath, rm, rmSync, rmdir, rmdirSync, rename, renameSync, cp, cpSync, copyFile, copyFileSync, appendFile, appendFileSync, chmod, chmodSync, chown, chownSync, open, openSync, close, closeSync, read, readSync, write, writeSync, createReadStream, createWriteStream, watch, watchFile, unwatchFile, constants, utimes, utimesSync, Stats, Dirent, ReadStream, WriteStream, truncate, truncateSync, symlink, symlinkSync, link, linkSync, mkdtemp, mkdtempSync, fsync, fsyncSync, fdatasync, fdatasyncSync, readv, readvSync, writev, writevSync, ftruncate, ftruncateSync, futimes, futimesSync, fchmod, fchmodSync, fchown, fchownSync, fstat, fstatSync, opendir, opendirSync, Dir } = _real;
285
+ export default { ..._real, readFileSync, existsSync, statSync, realpathSync, promises };
286
+ `;
287
+ }
288
+
289
+ const stubPlugin = {
290
+ name: 'real-vite-stubs',
291
+ setup(build) {
292
+ for (const s of HARD_STUBS) {
293
+ const re = new RegExp('^' + s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\\\//g, '\\/') + '$');
294
+ build.onResolve({ filter: re }, (args) => ({ path: args.path, namespace: 'real-vite-stub' }));
295
+ }
296
+ // Stub esbuild out of the bundle entirely (see ESBUILD_STUB_SRC
297
+ // comment). Saves ~2.3 MB.
298
+ build.onResolve({ filter: /^esbuild$/ }, (args) => ({
299
+ path: args.path, namespace: 'real-vite-esbuild-stub',
300
+ }));
301
+ build.onLoad({ filter: /.*/, namespace: 'real-vite-esbuild-stub' }, () => ({
302
+ contents: ESBUILD_STUB_SRC, loader: 'js',
303
+ }));
304
+ // Vite imports "#module-sync-enabled" as a subpath import conditionally.
305
+ build.onResolve({ filter: /^#module-sync-enabled$/ }, (args) => ({
306
+ path: args.path, namespace: 'real-vite-stub-bool-false',
307
+ }));
308
+ build.onLoad({ filter: /.*/, namespace: 'real-vite-stub' }, () => ({
309
+ contents: stubSource(), loader: 'js',
310
+ }));
311
+ build.onLoad({ filter: /.*/, namespace: 'real-vite-stub-bool-false' }, () => ({
312
+ contents: 'export default false;', loader: 'js',
313
+ }));
314
+
315
+ // FS shim: intercept node:fs / node:fs/promises at bundle time.
316
+ // In Phase 0 we inlined a small shim here. In Phase 1 we route
317
+ // EVERY node:fs import in the Vite bundle to a separate
318
+ // 'cirrus-fs.js' / 'cirrus-fs-promises.js' module supplied at
319
+ // facet-load time via LOADER.load's modules map. Keeping the
320
+ // shim out-of-bundle means we can iterate on it (add VFS-backed
321
+ // reads, watch events, etc.) WITHOUT rebuilding the 2.5 MB
322
+ // vite.bundle.js.
323
+ build.onResolve({ filter: /^node:fs$|^fs$/ }, () => ({
324
+ path: 'cirrus-fs.js', external: true,
325
+ }));
326
+ build.onResolve({ filter: /^node:fs\/promises$|^fs\/promises$/ }, () => ({
327
+ path: 'cirrus-fs-promises.js', external: true,
328
+ }));
329
+
330
+ // Phase 2: ws + chokidar shims. Externalize so the facet supplies
331
+ // our WebSocket-server / file-watcher implementations at load time.
332
+ build.onResolve({ filter: /^ws$/ }, () => ({
333
+ path: 'cirrus-ws.js', external: true,
334
+ }));
335
+ build.onResolve({ filter: /^chokidar$/ }, () => ({
336
+ path: 'cirrus-chokidar.js', external: true,
337
+ }));
338
+ },
339
+ };
340
+
341
+ // Vite 6.x (esbuild + Rollup, pure JS stack, no mandatory rolldown).
342
+ // Vite 7/8 made oxc + rolldown mandatory plugins in the dev-server
343
+ // resolve/load chain — both rely on native Rust binaries and a
344
+ // wasm32-wasi fallback that workerd can't host (no node:wasi).
345
+ // Vite 6 is the LAST version with a pure-JS dev server and — unlike
346
+ // Vite 5 — supports modern React (uses up-to-date esbuild).
347
+ //
348
+ // See PHASE2-REAL-VITE-PLAN.md §1.2: "rolldown cannot be instantiated
349
+ // inside a DO/facet today". Phase 0 confirmed this at plugin-init;
350
+ // Phase 1 e2e testing confirmed Vite 8 dev ALSO depends on these
351
+ // plugins for URL → file path resolution (oxcResolvePlugin).
352
+ const PINNED_VITE_MAJOR = '6';
353
+ const PINNED_VITE_VERSION = '^6.4.0';
354
+
355
+ async function ensureViteInstalled() {
356
+ // [sdk-phase-1] node_modules hoisted to workspace root.
357
+ const viteDir = findPkgDir(ROOT, 'vite');
358
+ const wasmRollupDir = findPkgDir(ROOT, '@rollup/wasm-node');
359
+ const vitePkg = viteDir ? path.join(viteDir, 'package.json') : null;
360
+ const wasmRollupPkg = wasmRollupDir ? path.join(wasmRollupDir, 'package.json') : null;
361
+ let needsInstall = !vitePkg || !wasmRollupPkg;
362
+ if (!needsInstall) {
363
+ try {
364
+ const parsed = JSON.parse(await fs.readFile(vitePkg, 'utf8'));
365
+ if (!parsed.version || !parsed.version.startsWith(PINNED_VITE_MAJOR + '.')) {
366
+ console.log(`[bundle-real-vite] found vite@${parsed.version}; reinstalling as ${PINNED_VITE_VERSION}...`);
367
+ needsInstall = true;
368
+ }
369
+ } catch { needsInstall = true; }
370
+ try {
371
+ await fs.access(wasmRollupPkg);
372
+ } catch { needsInstall = true; }
373
+ }
374
+ if (!needsInstall) return;
375
+ const { execSync } = await import('node:child_process');
376
+ // Install at the workspace root so bun hoists naturally.
377
+ const installCwd = path.resolve(ROOT, '..', '..');
378
+ execSync(`bun add --no-save vite@${PINNED_VITE_VERSION} @rollup/wasm-node`, {
379
+ cwd: installCwd, stdio: 'inherit',
380
+ });
381
+ }
382
+
383
+ async function main() {
384
+ await ensureViteInstalled();
385
+
386
+ console.log('[bundle-real-vite] bundling vite/dist/node/index.js...');
387
+ // [sdk-phase-1] Re-locate hoisted packages.
388
+ const viteDir = findPkgDir(ROOT, 'vite');
389
+ const wasmRollupDir = findPkgDir(ROOT, '@rollup/wasm-node');
390
+ if (!viteDir) throw new Error('bundle-real-vite: vite not found in any node_modules ancestor');
391
+ if (!wasmRollupDir) throw new Error('bundle-real-vite: @rollup/wasm-node not found');
392
+
393
+ // Pre-read the rollup-wasm binary and embed it as a base64 string.
394
+ // The rollup wasm-node binding does `readFileSync(__dirname + '/bindings_wasm_bg.wasm')`;
395
+ // we answer that via our fs shim by seeding a synthetic entry that
396
+ // decodes the base64 back to a Uint8Array. This avoids bundling
397
+ // the wasm as a separate LOADER module (which doesn't accept .wasm).
398
+ let wasmBase64 = '';
399
+ try {
400
+ const wasmBytes = await fs.readFile(
401
+ path.join(wasmRollupDir, 'dist/wasm-node/bindings_wasm_bg.wasm'),
402
+ );
403
+ wasmBase64 = wasmBytes.toString('base64');
404
+ console.log(`[bundle-real-vite] rollup wasm binary: ${(wasmBytes.length / 1024).toFixed(1)} KB`);
405
+ } catch (e) {
406
+ console.warn('[bundle-real-vite] could not read rollup wasm binary:', e?.message);
407
+ }
408
+
409
+ const result = await esbuild.build({
410
+ entryPoints: [path.join(viteDir, 'dist/node/index.js')],
411
+ bundle: true,
412
+ format: 'esm',
413
+ platform: 'neutral',
414
+ target: 'es2022',
415
+ external: NODE_BUILTINS,
416
+ plugins: [stubPlugin],
417
+ write: false,
418
+ mainFields: ['module', 'main'],
419
+ conditions: ['import', 'node'],
420
+ logLevel: 'warning',
421
+ keepNames: true,
422
+ minify: false,
423
+ // Alias rollup → @rollup/wasm-node. Rollup 4's native.js loads a
424
+ // platform-specific Rust binding via require(); workerd can't
425
+ // load .node addons. @rollup/wasm-node ships a pure-WASM binding
426
+ // that imports via require('./wasm-node/bindings_wasm.js') —
427
+ // pure JS + a .wasm file, no native code.
428
+ alias: {
429
+ 'rollup': '@rollup/wasm-node',
430
+ 'rollup/dist/native.js': '@rollup/wasm-node/dist/native.js',
431
+ 'rollup/dist/parseAst.js': '@rollup/wasm-node/dist/parseAst.js',
432
+ // NOTE: no esbuild alias. `esbuild` is stubbed via the
433
+ // onResolve filter above. Saves ~2.3 MB of JS + WASM that
434
+ // the facet would otherwise hold in memory for code paths
435
+ // we never run (optimizeDeps + build + esbuildPlugin.transform
436
+ // are all patched or disabled).
437
+ },
438
+ // When loaded via LOADER.load() with modules:{'vite.bundle.js':...},
439
+ // workerd sets import.meta.url to undefined (or a non-file URL),
440
+ // which breaks createRequire(import.meta.url). Force a synthetic
441
+ // file URL at build time so the bundle is self-contained.
442
+ define: {
443
+ 'import.meta.url': JSON.stringify('file:///vite.bundle.js'),
444
+ // Bundled CJS modules inside vite (rollup's native.js etc.)
445
+ // reference __dirname / __filename. esbuild's __commonJS
446
+ // wrapper doesn't inject them; we define them to plausible
447
+ // synthetic paths here so the modules load without throwing.
448
+ '__dirname': JSON.stringify('/'),
449
+ '__filename': JSON.stringify('/vite.bundle.js'),
450
+ },
451
+ // Leave dynamic import specifiers alone; we'll deal with them at
452
+ // runtime via the shim.
453
+ });
454
+
455
+ let bundle = result.outputFiles[0].text;
456
+ console.log(`[bundle-real-vite] pre-patch size: ${(bundle.length / 1024).toFixed(1)} KB`);
457
+
458
+ // ── Post-process: rewrite __require2(...) calls ─────────────────────
459
+ // esbuild leaves `createRequire("file:///vite.bundle.js")` in the
460
+ // bundle (we can't eliminate it — Vite's code uses it deliberately),
461
+ // and inside bundled CJS wrappers this createRequire gets called as
462
+ // `__require2("picomatch")` etc. workerd's createRequire throws on
463
+ // bare module names it can't find in node_modules, which fails
464
+ // uncatchably from inside module-init blocks.
465
+ //
466
+ // We inject a shim that consults a map of bundled __commonJS module
467
+ // ids first, falling back to the real createRequire only for node:
468
+ // builtins (which workerd DOES resolve). Modules NOT bundled get
469
+ // replaced with empty-exports stubs.
470
+ //
471
+ // The shim references require_* factory functions emitted by esbuild
472
+ // for each __commonJSMin module. We pattern-match them by name to
473
+ // build a lookup table.
474
+ const factoryNames = new Set();
475
+ for (const m of bundle.matchAll(/\b(require_[a-zA-Z0-9_$]+)\s*=\s*__commonJS/g)) {
476
+ factoryNames.add(m[1]);
477
+ }
478
+ // Map bare module names → factory function names (heuristic: strip
479
+ // non-alphanum + lowercase).
480
+ const wantBundled = new Set(['picomatch', 'postcss']);
481
+ const nameToFactory = {};
482
+ for (const want of wantBundled) {
483
+ const candidates = [
484
+ 'require_' + want,
485
+ 'require_' + want.replace(/[^a-z0-9]/gi, '_'),
486
+ 'require_picocolors2', // not used but placeholder
487
+ ];
488
+ const hit = candidates.find((n) => factoryNames.has(n));
489
+ if (hit) nameToFactory[want] = hit;
490
+ }
491
+ console.log('[bundle-real-vite] bundled CJS factories resolved:', nameToFactory);
492
+
493
+ const shimInjection = `
494
+ // ── Cirrus real-vite bundler: __require2 + __require shim ───────
495
+ // Injected by scripts/bundle-real-vite.mjs.
496
+ //
497
+ // 1. __cirrusRealRequireShim resolves a small whitelist of bundled
498
+ // CJS factories (picomatch/postcss inside readdirp/chokidar) —
499
+ // consumed by the post-patched __require2 call sites.
500
+ // 2. __cirrusRealCjsRequire is a general CJS require polyfill that
501
+ // works inside workerd. esbuild's built-in __require polyfill
502
+ // uses \`typeof require !== "undefined" ? require : throw\`, which
503
+ // always throws in workerd because the global \`require\` doesn't
504
+ // exist in ESM contexts. We replace the polyfill below.
505
+ ;(() => {
506
+ const _origCreateRequire = globalThis.__origCreateRequire || null;
507
+ const _bundledFactories = { ${Object.entries(nameToFactory)
508
+ .map(([k, v]) => `${JSON.stringify(k)}: () => ${v}()`)
509
+ .join(', ')} };
510
+ const _stubModule = { __stubbed: true };
511
+ const _stubsFor = new Set(['bufferutil', 'utf-8-validate', 'fsevents', 'sugarss']);
512
+ globalThis.__cirrusRealRequireShim = function(name) {
513
+ if (_bundledFactories[name]) return _bundledFactories[name]();
514
+ if (_stubsFor.has(name)) return _stubModule;
515
+ throw new Error('[cirrus-real] __require2("' + name + '") — not bundled');
516
+ };
517
+
518
+ // CJS require polyfill. Build a createRequire-backed fallback for
519
+ // node:* builtins. Non-builtin specifiers throw loudly so we see
520
+ // which deps still need bundling.
521
+ let _cjsRequire = null;
522
+ globalThis.__cirrusRealCjsRequire = function(name) {
523
+ if (_bundledFactories[name]) return _bundledFactories[name]();
524
+ if (_stubsFor.has(name)) return _stubModule;
525
+ if (!_cjsRequire) {
526
+ try {
527
+ const { createRequire } = globalThis.require
528
+ ? { createRequire: globalThis.require('node:module').createRequire }
529
+ : (() => {
530
+ // ESM-only path: import node:module statically up top? No,
531
+ // we can't do that from injected JS. Use a synchronous
532
+ // createRequire workaround: workerd DOES populate a
533
+ // top-level createRequire for certain contexts.
534
+ try { return require('node:module'); } catch { return null; }
535
+ })();
536
+ _cjsRequire = createRequire ? createRequire('file:///vite.bundle.js') : null;
537
+ } catch { _cjsRequire = null; }
538
+ }
539
+ if (_cjsRequire) {
540
+ try { return _cjsRequire(name); } catch (e) {
541
+ throw new Error('[cirrus-real] __require("' + name + '") failed: ' + (e?.message || e));
542
+ }
543
+ }
544
+ throw new Error('[cirrus-real] __require("' + name + '") — no CJS require available');
545
+ };
546
+ })();
547
+ `;
548
+
549
+ // Replace esbuild's __require polyfill. The polyfill as emitted
550
+ // tries \`typeof require !== "undefined" ? require : throw\`, which
551
+ // ALWAYS throws in workerd ESM context (no global require). Our
552
+ // replacement uses createRequire(import.meta.url) + a fallback to
553
+ // our bundled-factory lookup + a safe shim for the rewritten
554
+ // cirrus-fs.js / cirrus-fs-promises.js specifiers.
555
+ //
556
+ // We also swallow the cirrus-fs aliases: rollup's native.js uses
557
+ // \`require('fs').existsSync\` to detect a sideload; in our facet
558
+ // rollup is never used for dev, so an empty-ish fs-module is fine.
559
+ const rollupNativePatches = [];
560
+ let requirePolyfillPatches = 0;
561
+ bundle = bundle.replace(
562
+ /var __require = [\s\S]*?throw Error\('Dynamic require of "' \+ x \+ '" is not supported'\);\s*\}\);/,
563
+ () => {
564
+ requirePolyfillPatches++;
565
+ return `var __require = /* @__PURE__ */ (function() {
566
+ // Lazy-init: __cirrusNodeCreateRequire is set by main.js BEFORE
567
+ // the bundle evaluates, but we defer the createRequire() call
568
+ // until first use so module-init order doesn't matter.
569
+ let _cjsRequire = null;
570
+ function _getRequire() {
571
+ if (_cjsRequire) return _cjsRequire;
572
+ const cr = globalThis.__cirrusNodeCreateRequire;
573
+ if (cr) {
574
+ try { _cjsRequire = cr("file:///vite.bundle.js"); } catch (e) {
575
+ console.warn('[cirrus-real __require] createRequire failed:', e?.message);
576
+ }
577
+ }
578
+ return _cjsRequire;
579
+ }
580
+ // A table of known-safe stubs for CJS modules that vite's bundled
581
+ // deps try to require but that workerd can't satisfy via
582
+ // createRequire. Returning an empty-ish object lets the dep
583
+ // load without crashing.
584
+ // Rollup's native + wasm-node bindings require 'fs' / 'cirrus-fs.js'
585
+ // for a handful of read paths at module-init. Return the actual fs
586
+ // shim (via the global seeded by synthetic.js) so they get a
587
+ // working module, not an empty stub.
588
+ const _stubs = {};
589
+ Object.defineProperty(_stubs, 'cirrus-fs.js', {
590
+ get() { return globalThis.__cirrusRealFsShim || { existsSync: () => false }; },
591
+ });
592
+ Object.defineProperty(_stubs, 'cirrus-fs-promises.js', {
593
+ get() { return (globalThis.__cirrusRealFsShim || {}).promises || {}; },
594
+ });
595
+ return function __require(name) {
596
+ if (_stubs[name]) return _stubs[name];
597
+ if (globalThis.__cirrusNodeBuiltinTable && globalThis.__cirrusNodeBuiltinTable[name]) {
598
+ return globalThis.__cirrusNodeBuiltinTable[name];
599
+ }
600
+ if (globalThis.__cirrusRealRequireShim) {
601
+ try { return globalThis.__cirrusRealRequireShim(name); }
602
+ catch (_e) { /* fall through */ }
603
+ }
604
+ // VFS-backed userspace modules (e.g. react-refresh/babel loaded
605
+ // dynamically by @vitejs/plugin-react at transform time). Lives
606
+ // in cirrus-real.ts' main.js synthetic init.
607
+ if (globalThis.__cirrusRealUserspaceRequire) {
608
+ try {
609
+ const mod = globalThis.__cirrusRealUserspaceRequire(name);
610
+ if (mod) return mod;
611
+ } catch (_e) { /* fall through */ }
612
+ }
613
+ const req = _getRequire();
614
+ if (req) {
615
+ try { return req(name); }
616
+ catch (e) { throw Error('[cirrus-real __require] failed resolving "' + name + '": ' + (e?.message || e)); }
617
+ }
618
+ throw Error('[cirrus-real __require] no createRequire available for "' + name + '"');
619
+ };
620
+ })();`;
621
+ },
622
+ );
623
+ // Replace every `__require2("bare")` with `__cirrusRealRequireShim("bare")`
624
+ // for the targeted bare-name deps. Node builtins like 'node:fs' we
625
+ // leave alone — workerd handles them.
626
+ const NODE_BUILTINS_RE = /^(?:node:)?(?:fs|fs\/promises|http|http2|https|net|tls|path|url|util|events|stream|buffer|crypto|os|zlib|child_process|module|assert|perf_hooks|readline|querystring|dns|tty|worker_threads|v8|process|async_hooks|timers|string_decoder)$/;
627
+ const targets = [...wantBundled, ...['bufferutil', 'utf-8-validate', 'fsevents', 'sugarss']];
628
+ let patchCount = 0;
629
+ for (const t of targets) {
630
+ // Escape regex metacharacters in the target name, then build the
631
+ // '__require2("name")' pattern.
632
+ const escaped = t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
633
+ const re = new RegExp('__require2\\("' + escaped + '"\\)', 'g');
634
+ bundle = bundle.replace(re, (_m) => { patchCount++; return `__cirrusRealRequireShim(${JSON.stringify(t)})`; });
635
+ }
636
+ // ── Post-process: redirect chokidar + ws to our shims ────────────
637
+ // Vite's bundle INLINES chokidar + ws as CJS modules, so we can't
638
+ // externalize them via esbuild. Instead we replace the single
639
+ // `var import_chokidar = __toESM2(require_chokidar(), 1);` line
640
+ // with a call to our shim accessor, and similarly rewrite the
641
+ // WebSocketServerRaw binding to point at globalThis.__cirrusWsModule
642
+ // (which the facet entrypoint seeds from cirrus-ws.js BEFORE the
643
+ // bundle evaluates).
644
+ let chokidarPatches = 0;
645
+ // Vite 8 (legacy, not shipped but kept for future upgrades):
646
+ // var import_chokidar = /* @__PURE__ */ __toESM2(require_chokidar(), 1);
647
+ bundle = bundle.replace(
648
+ /var\s+import_chokidar\s*=\s*\/\*\s*@__PURE__\s*\*\/\s*__toESM2?\(require_chokidar\(\),\s*1\);/g,
649
+ () => {
650
+ chokidarPatches++;
651
+ return `var import_chokidar = /* @__PURE__ */ (function(){ const m = globalThis.__cirrusChokidarModule; if (!m) throw new Error('cirrus-chokidar not seeded'); return { default: m.default || m, ...m }; })();`;
652
+ },
653
+ );
654
+ // Vite 5 (current target): two assignments in series —
655
+ // chokidarExports = /* @__PURE__ */ requireChokidar();
656
+ // chokidar = /* @__PURE__ */ getDefaultExportFromCjs2(chokidarExports);
657
+ // We replace the first one; the second stays but consumes our shim.
658
+ bundle = bundle.replace(
659
+ /chokidarExports\s*=\s*\/\*\s*@__PURE__\s*\*\/\s*requireChokidar\(\);/g,
660
+ () => {
661
+ chokidarPatches++;
662
+ return `chokidarExports = (globalThis.__cirrusChokidarModule || (() => { throw new Error('cirrus-chokidar not seeded'); })());`;
663
+ },
664
+ );
665
+ // Vite 6 has a SECOND chokidar instance (`chokidar2`) built inline
666
+ // with its own FSWatcher class + watch factory. Replace
667
+ // chokidar2 = {};
668
+ // with a pre-seeded copy pointing at our shim, and no-op the
669
+ // subsequent `chokidar2.watch = watch2; chokidar2.FSWatcher = FSWatcher;`
670
+ // assignments (which would otherwise overwrite our shim).
671
+ bundle = bundle.replace(
672
+ /(\bchokidar2)\s*=\s*\{\s*\};/g,
673
+ () => {
674
+ chokidarPatches++;
675
+ return `chokidar2 = (globalThis.__cirrusChokidarModule || {});`;
676
+ },
677
+ );
678
+ // Suppress overwrites of chokidar2.{watch,FSWatcher} — they'd
679
+ // replace our seeded module with the in-bundle (native) classes.
680
+ const beforeChok2Guard = chokidarPatches;
681
+ bundle = bundle.replace(
682
+ /\bchokidar2\.(watch|FSWatcher)\s*=\s*\w+;/g,
683
+ () => { chokidarPatches++; return `/* cirrus: chokidar2 override suppressed */;`; },
684
+ );
685
+
686
+ let wssPatches = 0;
687
+ // Vite 8: var WebSocketServerRaw = process.versions.bun ? ... : import_websocket_server.default;
688
+ bundle = bundle.replace(
689
+ /var\s+WebSocketServerRaw\s*=\s*process\.versions\.bun\s*\?[^;]+;/g,
690
+ () => {
691
+ wssPatches++;
692
+ return `var WebSocketServerRaw = (globalThis.__cirrusWsModule?.WebSocketServer) || (function(){ throw new Error('cirrus-ws not seeded'); })();`;
693
+ },
694
+ );
695
+ // Vite 5 has ws inlined differently. The WebSocketServer class is
696
+ // bundled DIRECTLY (no require wrapper); Vite refers to it as
697
+ // `WebSocketServer` from the bundled ws CJS module. The reference
698
+ // looks like: `let WebSocketServer = wsExports.WebSocketServer;`
699
+ bundle = bundle.replace(
700
+ /(let|var|const)\s+WebSocketServer\s*=\s*wsExports\.WebSocketServer;/g,
701
+ () => {
702
+ wssPatches++;
703
+ return `var WebSocketServer = (globalThis.__cirrusWsModule?.WebSocketServer) || (function(){ throw new Error('cirrus-ws not seeded'); })();`;
704
+ },
705
+ );
706
+ // Vite 5 ws routing. The bundle:
707
+ // 1. Defines WebSocketServer = class extends EventEmitter {...}
708
+ // (the real ws package inlined as a CJS module via __commonJS).
709
+ // 2. websocketServer = WebSocketServer;
710
+ // 3. WebSocketServerRaw_ = getDefaultExportFromCjs2(websocketServer);
711
+ // 4. WebSocketServerRaw = process.versions.bun ? ... : WebSocketServerRaw_;
712
+ // 5. Usage: new WebSocketServerRaw({noServer: true}).
713
+ //
714
+ // We substitute step 4 — assigning WebSocketServerRaw from our shim.
715
+ // This preserves the rest of ws's module so nothing errors at
716
+ // module-init, but any `new WebSocketServerRaw(...)` construction
717
+ // hits our CirrusWsServer instead.
718
+ bundle = bundle.replace(
719
+ /WebSocketServerRaw\s*=\s*process\.versions\.bun\s*\?[\s\S]*?:\s*WebSocketServerRaw_;/g,
720
+ () => {
721
+ wssPatches++;
722
+ return `WebSocketServerRaw = (globalThis.__cirrusWsModule?.WebSocketServer) || (function(){ throw new Error('cirrus-ws not seeded'); })();`;
723
+ },
724
+ );
725
+
726
+ // esbuild's lib/main.js has a "bundling guard" that throws if it
727
+ // detects its source has been bundled. When we call vite.createServer,
728
+ // Vite's module-init evaluates the bundled esbuild module and
729
+ // (even without calling esbuild.build) the guard tries to spawn a
730
+ // binary on the first esbuild API call. Patch the guard so any
731
+ // attempt to spawn returns a harmless stub.
732
+ let esbuildGuardPatches = 0;
733
+ bundle = bundle.replace(
734
+ /esbuildCommandAndArgs\s*=\s*\/\*\s*@__PURE__\s*\*\/\s*__name\(\(\)\s*=>\s*\{[\s\S]{0,2000}?\},\s*"esbuildCommandAndArgs"\)/,
735
+ () => {
736
+ esbuildGuardPatches++;
737
+ return `esbuildCommandAndArgs = /* @__PURE__ */ __name(() => { throw new Error('[cirrus-real] esbuild.build is not available inside the real-vite facet. Use @vitejs/plugin-react (Babel) or a pure-JS plugin for JSX.'); }, "esbuildCommandAndArgs")`;
738
+ },
739
+ );
740
+
741
+ // Patch es-module-lexer's `function k(A){try{return (0, eval)(A)}catch(A){}}`.
742
+ // The bundled lexer uses indirect-eval to "unescape" import specifier
743
+ // strings (input: `"react"`, output: `react`). In workerd, eval is
744
+ // disallowed OUTSIDE startup scope (compatibility flag
745
+ // `allow_eval_during_startup` is default-on, but it's a STARTUP-only
746
+ // permission — transform handlers run post-startup so eval silently
747
+ // returns undefined via the catch). The result: every parsed import
748
+ // has `.n = undefined`, which makes vite:import-analysis treat all
749
+ // specifiers as "non-string" and wrap them in
750
+ // `__vite__injectQuery(...)` string literals — totally breaks
751
+ // `import X from 'react'` resolution.
752
+ //
753
+ // Fix: replace `(0, eval)(A)` with JSON-parse-compatible logic.
754
+ // Input `A` is always a JS string literal (double- or single-quoted).
755
+ let lexerEvalPatches = 0;
756
+ bundle = bundle.replace(
757
+ /function k\((\w+)\) \{\s*try \{\s*return \(0, eval\)\(\1\);\s*\} catch \(\w+\) \{\s*\}\s*\}/,
758
+ (_, arg) => {
759
+ lexerEvalPatches++;
760
+ // Replace with JSON-parse-based unescape. Input is a JS string
761
+ // literal: `"react"`, `'react'`, or `` `react` ``.
762
+ return `function k(${arg}) {
763
+ try {
764
+ const q = ${arg}[0];
765
+ if (q === '"') return JSON.parse(${arg});
766
+ if (q === "'") return JSON.parse('"' + ${arg}.slice(1, -1).replace(/"/g, '\\\\"').replace(/\\\\'/g, "'") + '"');
767
+ if (q === '\`') return ${arg}.slice(1, -1);
768
+ return ${arg};
769
+ } catch (_e) {
770
+ return undefined;
771
+ }
772
+ }`;
773
+ },
774
+ );
775
+ // Debug: log normalizeUrl call → see exactly what importAnalysis asks to resolve.
776
+ bundle = bundle.replace(
777
+ /const normalizeUrl = \/\* @__PURE__ \*\/ __name\(async \((\w+), (\w+), forceSkipImportAnalysis = false\) => \{/,
778
+ (_, url, pos) =>
779
+ `const normalizeUrl = /* @__PURE__ */ __name(async (${url}, ${pos}, forceSkipImportAnalysis = false) => {
780
+ if (globalThis.__cirrusResolveDebug) console.log('[normalizeUrl]', ${url}, 'importer=', importer);
781
+ `,
782
+ );
783
+
784
+ // Replace the vite:esbuild plugin's transform with a pure-JS
785
+ // implementation that:
786
+ // - passes ESM through unchanged (plugin-react already did JSX)
787
+ // - wraps CJS modules (detected by `module.exports`, `exports.X`,
788
+ // or \`require(\`) into a minimal ESM adapter that evaluates
789
+ // the CJS code in a Function wrapper and re-exports
790
+ // module.exports. Named exports are discovered via textual
791
+ // scan of `module.exports.X =` / `exports.X =` patterns and
792
+ // re-exported individually.
793
+ //
794
+ // This is necessary because real-world React packages (react,
795
+ // react-dom, scheduler, babel core, many more) ship CJS, and
796
+ // browsers can't load CJS via `<script type="module">`.
797
+ // Without this conversion, every `import React from 'react'` 404s
798
+ // at the browser. Vite's optimizeDeps normally handles this via
799
+ // esbuild, which we can't run.
800
+ let vitEsbuildTransformPatches = 0;
801
+ bundle = bundle.replace(
802
+ /(name:\s*"vite:esbuild",[\s\S]{0,200}?async transform\(code,\s*)(id\d*)(\)\s*\{)[\s\S]{0,1500}?(\}\s*\}\s*;\s*\})/,
803
+ (_, head, idArg, openBrace, tail) => {
804
+ vitEsbuildTransformPatches++;
805
+ return head + idArg + openBrace + `
806
+ /* cirrus-real: intercept CJS packages with pre-built ESM bundles. */
807
+ if (globalThis.__cirrusNpmCjsMap) {
808
+ const prebuilt = globalThis.__cirrusNpmCjsMap(${idArg});
809
+ if (prebuilt) return { code: prebuilt, map: null };
810
+ }
811
+ return { code, map: null };
812
+ ` + tail;
813
+ },
814
+ );
815
+
816
+ // replaceDefine (used by the define plugin + client-inject) also
817
+ // calls esbuild.transform to substitute `process.env.X` etc. We
818
+ // replace it with a pure-JS string-replacement implementation that
819
+ // covers the 99% case (literal identifier → literal value) and
820
+ // skips sourcemap munging. Good enough for real-vite mode where
821
+ // the only defines we set are NODE_ENV + a handful of Vite
822
+ // client-inject variables.
823
+ let replaceDefinePatches = 0;
824
+ bundle = bundle.replace(
825
+ /async function replaceDefine\((\w+), (\w+), (\w+), (\w+)\) \{[\s\S]{0,1500}?return \{\s*code: result\.code,\s*map: result\.map \|\| null\s*\};\s*\}/,
826
+ (_, env, codeArg, idArg, defineArg) => {
827
+ replaceDefinePatches++;
828
+ return `async function replaceDefine(${env}, ${codeArg}, ${idArg}, ${defineArg}) {
829
+ /* cirrus-real: pure-JS replacement for esbuild.transform-based define injection */
830
+ let out = ${codeArg};
831
+ for (const key of Object.keys(${defineArg})) {
832
+ const value = ${defineArg}[key];
833
+ const escaped = key.replace(/[.*+?^\${}()|[\\]\\\\]/g, '\\\\$&');
834
+ const re = new RegExp('(?<![\\\\w$])' + escaped + '(?![\\\\w$])', 'g');
835
+ out = out.replace(re, String(value));
836
+ }
837
+ return { code: out, map: null };
838
+ }`;
839
+ },
840
+ );
841
+
842
+ bundle = shimInjection + '\n' + bundle;
843
+ console.log(`[bundle-real-vite] __require2 patches: ${patchCount}`);
844
+ console.log(`[bundle-real-vite] chokidar patches: ${chokidarPatches}, WebSocketServerRaw patches: ${wssPatches}`);
845
+ console.log(`[bundle-real-vite] rollup-native __require shims: ${rollupNativePatches.length}`);
846
+ console.log(`[bundle-real-vite] esbuild bundling-guard patches: ${esbuildGuardPatches}`);
847
+ console.log(`[bundle-real-vite] vite:esbuild transform-disabled patches: ${vitEsbuildTransformPatches}`);
848
+ console.log(`[bundle-real-vite] replaceDefine esbuild-free patches: ${replaceDefinePatches}`);
849
+ console.log(`[bundle-real-vite] es-module-lexer eval-replacement patches: ${lexerEvalPatches}`);
850
+ console.log(`[bundle-real-vite] post-patch size: ${(bundle.length / 1024).toFixed(1)} KB`);
851
+
852
+ const viteVersion = JSON.parse(
853
+ await fs.readFile(path.join(viteDir, 'package.json'), 'utf8'),
854
+ ).version;
855
+
856
+ // Ship the REAL vite client runtime alongside the server bundle.
857
+ // Vite serves these at /@vite/client + /@vite/env at dev time.
858
+ // Without them our synthetic 'stub' gets served and the browser's
859
+ // HMR client + import.meta.env are broken.
860
+ let viteClientMjs = '// vite client not shipped';
861
+ let viteEnvMjs = '// vite env not shipped';
862
+ try {
863
+ viteClientMjs = await fs.readFile(
864
+ path.join(viteDir, 'dist/client/client.mjs'),
865
+ 'utf8',
866
+ );
867
+ viteEnvMjs = await fs.readFile(
868
+ path.join(viteDir, 'dist/client/env.mjs'),
869
+ 'utf8',
870
+ );
871
+ console.log(
872
+ `[bundle-real-vite] vite client runtime: client.mjs ${(viteClientMjs.length / 1024).toFixed(1)} KB, env.mjs ${viteEnvMjs.length}B`,
873
+ );
874
+ } catch (e) {
875
+ console.warn('[bundle-real-vite] could not read vite client files:', e?.message);
876
+ }
877
+
878
+ // [sdk-phase-1] Promote the two huge blobs (bundle + rollup-wasm) to
879
+ // the ASSETS binding. Lazy-fetched at first cirrus-real instantiation
880
+ // (same pattern as esbuild-wasm-bytes.ts). Keeps Worker bundle small.
881
+ await fs.mkdir(ASSETS_DIR, { recursive: true });
882
+ await fs.writeFile(path.join(ASSETS_DIR, 'real-vite-bundle.js'), bundle, 'utf8');
883
+ // Rollup native bindings: source is already base64 — decode + ship
884
+ // as a raw .wasm file. Consumer re-encodes if it needs base64.
885
+ const wasmBytes = Buffer.from(wasmBase64, 'base64');
886
+ await fs.writeFile(path.join(ASSETS_DIR, 'rollup.wasm'), wasmBytes);
887
+
888
+ const header = `/**
889
+ * real-vite-bundle.generated.ts — AUTO-GENERATED by scripts/bundle-real-vite.mjs
890
+ * DO NOT EDIT.
891
+ *
892
+ * Bundled Vite ${viteVersion} with native-binding stubs (rolldown,
893
+ * lightningcss, etc.). Consumed by src/cirrus-real.ts at facet spawn time.
894
+ *
895
+ * [sdk-phase-1] The large strings (REAL_VITE_BUNDLE, ROLLUP_WASM_BASE64)
896
+ * now ship via the ASSETS binding rather than inline. Use the async
897
+ * getters below. Constants + browser-runtime mjs files remain inline
898
+ * since they're small enough to not warrant a network round-trip.
899
+ */
900
+
901
+ import { loadAssetText, loadAssetBytes, type AssetsFetcher } from './runtime/assets-loader.js';
902
+
903
+ export const REAL_VITE_VERSION = ${JSON.stringify(viteVersion)};
904
+
905
+ /** Asset path for the bundled Vite source. Use {@link getRealViteBundle}. */
906
+ export const REAL_VITE_BUNDLE_PATH = ${JSON.stringify(ASSET_PATH_VITE_BUNDLE)};
907
+
908
+ /** Asset path for the rollup wasm bytes. Use {@link getRollupWasmBase64}. */
909
+ export const ROLLUP_WASM_PATH = ${JSON.stringify(ASSET_PATH_ROLLUP_WASM)};
910
+
911
+ /**
912
+ * Fetch the bundled Vite JS from the ASSETS binding. Cached per-isolate.
913
+ *
914
+ * @param env Object exposing the \`ASSETS\` binding (Fetcher).
915
+ * @returns The Vite bundle as a UTF-8 string.
916
+ * @throws {NimbusAssetLoadError} when the binding is missing or fetch fails.
917
+ */
918
+ export function getRealViteBundle(env: { ASSETS: AssetsFetcher }): Promise<string> {
919
+ return loadAssetText(env.ASSETS, REAL_VITE_BUNDLE_PATH);
920
+ }
921
+
922
+ /**
923
+ * Fetch the rollup wasm bytes + base64-encode for the synthetic-fs
924
+ * pre-seed. Cached per-isolate; the base64 string ends up the same on
925
+ * every call.
926
+ *
927
+ * @returns base64-encoded rollup wasm bytes.
928
+ */
929
+ export async function getRollupWasmBase64(env: { ASSETS: AssetsFetcher }): Promise<string> {
930
+ const bytes = await loadAssetBytes(env.ASSETS, ROLLUP_WASM_PATH);
931
+ // btoa(String.fromCharCode(...bytes)) blows the stack on 1 MB inputs.
932
+ // Build the binary string in 8 KiB chunks.
933
+ let binary = '';
934
+ const CHUNK = 8192;
935
+ for (let i = 0; i < bytes.length; i += CHUNK) {
936
+ binary += String.fromCharCode.apply(
937
+ null,
938
+ bytes.subarray(i, Math.min(i + CHUNK, bytes.length)) as unknown as number[],
939
+ );
940
+ }
941
+ return btoa(binary);
942
+ }
943
+
944
+ /**
945
+ * Vite's browser-side HMR runtime. Served to the browser at
946
+ * /@vite/client and /@vite/env during dev. Unlike the server
947
+ * bundle, these are tiny ESM files that run in-page — keep inline.
948
+ */
949
+ export const VITE_CLIENT_MJS: string = ${JSON.stringify(viteClientMjs)};
950
+ export const VITE_ENV_MJS: string = ${JSON.stringify(viteEnvMjs)};
951
+ `;
952
+ await fs.writeFile(OUT, header, 'utf8');
953
+ console.log(`[bundle-real-vite] wrote ${OUT} (${(header.length / 1024).toFixed(1)} KB shim) + ${ASSETS_DIR}/{real-vite-bundle.js (${(bundle.length / 1024 / 1024).toFixed(1)} MB), rollup.wasm (${(wasmBytes.length / 1024 / 1024).toFixed(1)} MB)}`);
954
+ }
955
+
956
+ main().catch((e) => {
957
+ console.error('[bundle-real-vite] failed:', e);
958
+ process.exit(1);
959
+ });