nitro 3.0.1-alpha.0 → 3.0.1-alpha.2

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 (316) hide show
  1. package/README.md +2 -0
  2. package/dist/_build/common.mjs +24940 -0
  3. package/dist/_build/rolldown.mjs +172 -0
  4. package/dist/_build/rollup.mjs +201 -0
  5. package/dist/_build/vite.build.mjs +16 -0
  6. package/dist/_chunks/dev.mjs +707 -0
  7. package/dist/_chunks/nitro.mjs +1191 -0
  8. package/dist/_chunks/nitro2.mjs +101 -0
  9. package/dist/_chunks/utils.mjs +254 -0
  10. package/dist/_common.mjs +45 -0
  11. package/dist/_dev.d.mts +12 -0
  12. package/dist/_libs/c12+giget+readdirp+chokidar.d.mts +214 -0
  13. package/dist/_libs/citty.mjs +363 -0
  14. package/dist/_libs/commondir+is-reference.mjs +1300 -0
  15. package/dist/_libs/compatx.d.mts +47 -0
  16. package/dist/_libs/compatx.mjs +46 -0
  17. package/dist/_libs/confbox.mjs +2509 -0
  18. package/dist/_libs/esbuild.d.mts +20 -0
  19. package/dist/_libs/escape-string-regexp.mjs +8 -0
  20. package/dist/_libs/estree-walker.mjs +187 -0
  21. package/dist/_libs/hasown+resolve+deepmerge.mjs +1972 -0
  22. package/dist/_libs/httpxy.d.mts +79 -0
  23. package/dist/_libs/httpxy.mjs +415 -0
  24. package/dist/_libs/klona.mjs +38 -0
  25. package/dist/_libs/magic-string.d.mts +220 -0
  26. package/dist/_libs/mlly.d.mts +57 -0
  27. package/dist/_libs/nypm+giget+tinyexec.mjs +3603 -0
  28. package/dist/_libs/pkg-types.d.mts +23 -0
  29. package/dist/_libs/plugin-alias.mjs +66 -0
  30. package/dist/_libs/plugin-inject.mjs +135 -0
  31. package/dist/_libs/plugin-json.mjs +36 -0
  32. package/dist/_libs/pluginutils+plugin-commonjs.d.mts +241 -0
  33. package/dist/_libs/pluginutils.mjs +652 -0
  34. package/dist/_libs/rc9+c12+dotenv.mjs +972 -0
  35. package/dist/_libs/readdirp+chokidar.mjs +1611 -0
  36. package/dist/_libs/remapping.mjs +117 -0
  37. package/dist/_libs/resolve-uri+gen-mapping.mjs +448 -0
  38. package/dist/_libs/rou3.d.mts +43 -0
  39. package/dist/_libs/rou3.mjs +322 -0
  40. package/dist/_libs/std-env.d.mts +4 -0
  41. package/dist/_libs/tsconfck.mjs +832 -0
  42. package/dist/_libs/ultrahtml.mjs +138 -0
  43. package/dist/_libs/unimport+unplugin.mjs +1785 -0
  44. package/dist/_libs/unplugin+unimport.d.mts +426 -0
  45. package/dist/_libs/unwasm.d.mts +29 -0
  46. package/dist/_presets.mjs +1802 -0
  47. package/dist/builder.d.mts +63 -0
  48. package/dist/builder.mjs +9 -0
  49. package/dist/cli/_chunks/build.mjs +48 -0
  50. package/dist/cli/_chunks/common.mjs +15 -0
  51. package/dist/cli/_chunks/dev.mjs +62 -0
  52. package/dist/cli/_chunks/list.mjs +27 -0
  53. package/dist/cli/_chunks/prepare.mjs +19 -0
  54. package/dist/cli/_chunks/run.mjs +55 -0
  55. package/dist/cli/_chunks/task.mjs +16 -0
  56. package/dist/cli/index.d.mts +1 -1
  57. package/dist/cli/index.mjs +20 -476
  58. package/dist/node_modules/@poppinss/colors/build/index.js +130 -160
  59. package/dist/node_modules/@poppinss/colors/package.json +20 -18
  60. package/dist/node_modules/@poppinss/dumper/build/formatters/html/main.js +1 -1
  61. package/dist/node_modules/@poppinss/dumper/package.json +1 -1
  62. package/dist/node_modules/@poppinss/exception/build/index.js +36 -55
  63. package/dist/node_modules/@poppinss/exception/package.json +19 -16
  64. package/dist/node_modules/@sindresorhus/is/distribution/index.js +47 -6
  65. package/dist/node_modules/@sindresorhus/is/package.json +1 -1
  66. package/dist/node_modules/@speed-highlight/core/dist/index.js +2 -2
  67. package/dist/node_modules/@speed-highlight/core/dist/terminal.js +2 -2
  68. package/dist/node_modules/@speed-highlight/core/package.json +8 -4
  69. package/dist/node_modules/cookie-es/dist/index.mjs +262 -0
  70. package/dist/node_modules/cookie-es/package.json +37 -0
  71. package/dist/node_modules/hookable/dist/index.mjs +244 -268
  72. package/dist/node_modules/hookable/package.json +29 -26
  73. package/dist/node_modules/rendu/dist/index.mjs +380 -0
  74. package/dist/node_modules/rendu/package.json +47 -0
  75. package/dist/node_modules/ufo/dist/index.mjs +16 -9
  76. package/dist/node_modules/ufo/package.json +15 -14
  77. package/dist/node_modules/unctx/package.json +16 -16
  78. package/dist/node_modules/youch/build/{chunk-4XB2BYKC.js → chunk-7QV3D5YX.js} +2 -4
  79. package/dist/node_modules/youch/build/{chunk-PUHGL6HA.js → chunk-AUGPHE32.js} +2 -4
  80. package/dist/node_modules/youch/build/{chunk-VE4LENUR.js → chunk-CM7DWJNZ.js} +4 -5
  81. package/dist/node_modules/youch/build/{chunk-JAN2TFI2.js → chunk-EJH674NB.js} +6 -5
  82. package/dist/node_modules/youch/build/{chunk-EUJBVOYB.js → chunk-OIJ3WD7L.js} +2 -4
  83. package/dist/node_modules/youch/build/{chunk-HFSXRSKS.js → chunk-P36L72PL.js} +5 -3
  84. package/dist/node_modules/youch/build/{chunk-4YEN7HVQ.js → chunk-PE3GG3TN.js} +5 -1
  85. package/dist/node_modules/youch/build/{chunk-PINJDICN.js → chunk-X53OIOJH.js} +2 -4
  86. package/dist/node_modules/youch/build/index.js +22 -15
  87. package/dist/node_modules/youch/build/public/error_info/style.css +1 -0
  88. package/dist/node_modules/youch/build/public/error_metadata/style.css +3 -0
  89. package/dist/node_modules/youch/build/public/error_stack/script.js +20 -22
  90. package/dist/node_modules/youch/build/public/error_stack/style.css +2 -3
  91. package/dist/node_modules/youch/build/public/header/script.js +0 -2
  92. package/dist/node_modules/youch/build/public/layout/script.js +0 -8
  93. package/dist/node_modules/youch/build/public/layout/style.css +4 -0
  94. package/dist/node_modules/youch/package.json +16 -17
  95. package/dist/presets/_nitro/runtime/nitro-dev.d.mts +2 -1
  96. package/dist/presets/_nitro/runtime/nitro-dev.mjs +47 -42
  97. package/dist/presets/_nitro/runtime/nitro-prerenderer.d.mts +3 -3
  98. package/dist/presets/_nitro/runtime/nitro-prerenderer.mjs +11 -15
  99. package/dist/presets/_nitro/runtime/service-worker.d.mts +2 -1
  100. package/dist/presets/_nitro/runtime/service-worker.mjs +17 -14
  101. package/dist/presets/aws-amplify/runtime/aws-amplify.d.mts +2 -1
  102. package/dist/presets/aws-amplify/runtime/aws-amplify.mjs +8 -7
  103. package/dist/presets/aws-lambda/runtime/_utils.d.mts +3 -13
  104. package/dist/presets/aws-lambda/runtime/_utils.mjs +95 -81
  105. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.d.mts +2 -3
  106. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.mjs +25 -29
  107. package/dist/presets/aws-lambda/runtime/aws-lambda.d.mts +1 -1
  108. package/dist/presets/aws-lambda/runtime/aws-lambda.mjs +9 -9
  109. package/dist/presets/azure/runtime/_utils.mjs +43 -43
  110. package/dist/presets/azure/runtime/azure-swa.d.mts +3 -3
  111. package/dist/presets/azure/runtime/azure-swa.mjs +25 -23
  112. package/dist/presets/bun/runtime/bun.d.mts +3 -1
  113. package/dist/presets/bun/runtime/bun.mjs +34 -22
  114. package/dist/presets/cloudflare/runtime/_module-handler.d.mts +12 -9
  115. package/dist/presets/cloudflare/runtime/_module-handler.mjs +84 -90
  116. package/dist/presets/cloudflare/runtime/cloudflare-durable.d.mts +7 -15
  117. package/dist/presets/cloudflare/runtime/cloudflare-durable.mjs +62 -64
  118. package/dist/presets/cloudflare/runtime/cloudflare-module.d.mts +2 -8
  119. package/dist/presets/cloudflare/runtime/cloudflare-module.mjs +15 -18
  120. package/dist/presets/cloudflare/runtime/cloudflare-pages.d.mts +13 -13
  121. package/dist/presets/cloudflare/runtime/cloudflare-pages.mjs +35 -43
  122. package/dist/presets/cloudflare/runtime/plugin.dev.d.mts +2 -2
  123. package/dist/presets/cloudflare/runtime/plugin.dev.mjs +89 -82
  124. package/dist/presets/cloudflare/runtime/shims/workers.dev.mjs +27 -0
  125. package/dist/presets/deno/runtime/deno-deploy.d.mts +5 -1
  126. package/dist/presets/deno/runtime/deno-deploy.mjs +15 -13
  127. package/dist/presets/deno/runtime/deno-server.d.mts +1 -4
  128. package/dist/presets/deno/runtime/deno-server.mjs +32 -53
  129. package/dist/presets/netlify/runtime/netlify-edge.d.mts +2 -2
  130. package/dist/presets/netlify/runtime/netlify-edge.mjs +18 -14
  131. package/dist/presets/netlify/runtime/netlify.d.mts +3 -2
  132. package/dist/presets/netlify/runtime/netlify.mjs +15 -19
  133. package/dist/presets/node/runtime/node-cluster.d.mts +3 -1
  134. package/dist/presets/node/runtime/node-cluster.mjs +49 -54
  135. package/dist/presets/node/runtime/node-middleware.d.mts +3 -4
  136. package/dist/presets/node/runtime/node-middleware.mjs +9 -9
  137. package/dist/presets/node/runtime/node-server.d.mts +1 -1
  138. package/dist/presets/node/runtime/node-server.mjs +36 -34
  139. package/dist/presets/standard/runtime/server.d.mts +2 -4
  140. package/dist/presets/standard/runtime/server.mjs +3 -5
  141. package/dist/presets/stormkit/runtime/stormkit.d.mts +14 -14
  142. package/dist/presets/stormkit/runtime/stormkit.mjs +22 -22
  143. package/dist/presets/vercel/runtime/isr.d.mts +2 -0
  144. package/dist/presets/vercel/runtime/isr.mjs +19 -0
  145. package/dist/presets/vercel/runtime/vercel.node.d.mts +3 -0
  146. package/dist/presets/vercel/runtime/vercel.node.mjs +24 -0
  147. package/dist/presets/vercel/runtime/vercel.web.d.mts +8 -0
  148. package/dist/presets/vercel/runtime/vercel.web.mjs +25 -0
  149. package/dist/presets/winterjs/runtime/winterjs.d.mts +2 -1
  150. package/dist/presets/winterjs/runtime/winterjs.mjs +74 -70
  151. package/dist/presets/zeabur/runtime/zeabur.d.mts +2 -2
  152. package/dist/presets/zeabur/runtime/zeabur.mjs +2 -2
  153. package/dist/runtime/app.d.mts +1 -0
  154. package/dist/runtime/app.mjs +1 -0
  155. package/dist/runtime/cache.d.mts +1 -0
  156. package/dist/runtime/cache.mjs +1 -0
  157. package/dist/runtime/config.d.mts +3 -0
  158. package/dist/runtime/config.mjs +4 -0
  159. package/dist/runtime/context.d.mts +1 -0
  160. package/dist/runtime/context.mjs +1 -0
  161. package/dist/runtime/database.d.mts +1 -0
  162. package/dist/runtime/database.mjs +1 -0
  163. package/dist/runtime/internal/app.d.mts +15 -1
  164. package/dist/runtime/internal/app.mjs +199 -144
  165. package/dist/runtime/internal/cache.d.mts +9 -5
  166. package/dist/runtime/internal/cache.mjs +248 -219
  167. package/dist/runtime/internal/context.d.mts +9 -9
  168. package/dist/runtime/internal/context.mjs +17 -10
  169. package/dist/runtime/internal/database.mjs +9 -11
  170. package/dist/runtime/internal/error/dev.d.mts +4 -4
  171. package/dist/runtime/internal/error/dev.mjs +106 -105
  172. package/dist/runtime/internal/error/hooks.d.mts +1 -0
  173. package/dist/runtime/internal/error/hooks.mjs +9 -0
  174. package/dist/runtime/internal/error/prod.d.mts +5 -4
  175. package/dist/runtime/internal/error/prod.mjs +51 -59
  176. package/dist/runtime/internal/error/utils.d.mts +4 -4
  177. package/dist/runtime/internal/error/utils.mjs +1 -1
  178. package/dist/runtime/internal/meta.d.mts +1 -1
  179. package/dist/runtime/internal/meta.mjs +1 -1
  180. package/dist/runtime/internal/plugin.d.mts +2 -2
  181. package/dist/runtime/internal/plugin.mjs +1 -1
  182. package/dist/runtime/internal/route-rules.d.mts +4 -8
  183. package/dist/runtime/internal/route-rules.mjs +54 -52
  184. package/dist/runtime/internal/routes/dev-tasks.d.mts +1 -2
  185. package/dist/runtime/internal/routes/dev-tasks.mjs +17 -19
  186. package/dist/runtime/internal/routes/openapi.mjs +82 -88
  187. package/dist/runtime/internal/routes/renderer-template.d.mts +1 -1
  188. package/dist/runtime/internal/routes/renderer-template.dev.d.mts +1 -2
  189. package/dist/runtime/internal/routes/renderer-template.dev.mjs +15 -17
  190. package/dist/runtime/internal/routes/renderer-template.mjs +2 -2
  191. package/dist/runtime/internal/routes/scalar.mjs +22 -23
  192. package/dist/runtime/internal/routes/swagger.mjs +9 -11
  193. package/dist/runtime/internal/runtime-config.d.mts +4 -4
  194. package/dist/runtime/internal/runtime-config.mjs +44 -39
  195. package/dist/runtime/internal/static.mjs +63 -74
  196. package/dist/runtime/internal/storage.mjs +3 -3
  197. package/dist/runtime/internal/task.d.mts +6 -6
  198. package/dist/runtime/internal/task.mjs +57 -61
  199. package/dist/runtime/internal/vite/dev-entry.mjs +11 -2
  200. package/dist/runtime/internal/vite/{dev-worker.mjs → node-runner.mjs} +54 -57
  201. package/dist/runtime/internal/vite/ssr-renderer.mjs +3 -1
  202. package/{lib/runtime-meta.d.mts → dist/runtime/meta.d.mts} +2 -2
  203. package/dist/runtime/meta.mjs +26 -0
  204. package/dist/runtime/nitro.d.mts +9 -0
  205. package/dist/runtime/nitro.mjs +32 -0
  206. package/dist/runtime/runtime-config.d.mts +1 -0
  207. package/dist/runtime/runtime-config.mjs +1 -0
  208. package/dist/runtime/storage.d.mts +1 -0
  209. package/dist/runtime/storage.mjs +1 -0
  210. package/dist/runtime/task.d.mts +1 -0
  211. package/dist/runtime/task.mjs +1 -0
  212. package/dist/runtime/virtual/_runtime_warn.mjs +5 -0
  213. package/dist/runtime/virtual/database.d.mts +8 -0
  214. package/dist/runtime/virtual/database.mjs +2 -0
  215. package/dist/runtime/virtual/error-handler.d.mts +6 -0
  216. package/dist/runtime/virtual/error-handler.mjs +9 -0
  217. package/dist/runtime/virtual/feature-flags.d.mts +7 -0
  218. package/dist/runtime/virtual/feature-flags.mjs +7 -0
  219. package/dist/runtime/virtual/plugins.d.mts +3 -0
  220. package/dist/runtime/virtual/plugins.mjs +2 -0
  221. package/dist/runtime/virtual/polyfills.d.mts +3 -0
  222. package/dist/runtime/virtual/polyfills.mjs +2 -0
  223. package/dist/runtime/virtual/public-assets.d.mts +9 -0
  224. package/dist/runtime/virtual/public-assets.mjs +8 -0
  225. package/dist/runtime/virtual/renderer-template.d.mts +4 -0
  226. package/dist/runtime/virtual/renderer-template.mjs +7 -0
  227. package/dist/runtime/virtual/routing-meta.d.mts +7 -0
  228. package/dist/runtime/virtual/routing-meta.mjs +2 -0
  229. package/dist/runtime/virtual/routing.d.mts +8 -0
  230. package/dist/runtime/virtual/routing.mjs +11 -0
  231. package/dist/runtime/virtual/runtime-config.d.mts +3 -0
  232. package/dist/runtime/virtual/runtime-config.mjs +5 -0
  233. package/dist/runtime/virtual/server-assets.d.mts +6 -0
  234. package/dist/runtime/virtual/server-assets.mjs +12 -0
  235. package/dist/runtime/virtual/storage.d.mts +3 -0
  236. package/dist/runtime/virtual/storage.mjs +5 -0
  237. package/dist/runtime/virtual/tasks.d.mts +10 -0
  238. package/dist/runtime/virtual/tasks.mjs +3 -0
  239. package/dist/runtime/vite.d.mts +8 -0
  240. package/dist/runtime/vite.mjs +9 -0
  241. package/dist/types/index.d.mts +2561 -2312
  242. package/dist/types/index.mjs +10 -0
  243. package/dist/vite.d.mts +44 -51
  244. package/dist/vite.mjs +737 -68
  245. package/lib/tsconfig.json +27 -0
  246. package/lib/vite.types.d.mts +26 -0
  247. package/lib/vite.types.mjs +2 -0
  248. package/package.json +118 -101
  249. package/dist/_chunks/app.mjs +0 -19797
  250. package/dist/_chunks/build.mjs +0 -84
  251. package/dist/_chunks/build2.mjs +0 -318
  252. package/dist/_chunks/build3.mjs +0 -6452
  253. package/dist/_chunks/detect-acorn.mjs +0 -503
  254. package/dist/_chunks/index.mjs +0 -22242
  255. package/dist/_chunks/index2.mjs +0 -297
  256. package/dist/_chunks/index3.mjs +0 -1058
  257. package/dist/_chunks/index4.mjs +0 -1206
  258. package/dist/_chunks/info.mjs +0 -11157
  259. package/dist/_chunks/json5.mjs +0 -68
  260. package/dist/_chunks/jsonc.mjs +0 -51
  261. package/dist/_chunks/pathe.M-eThtNZ.mjs +0 -204
  262. package/dist/_chunks/plugin.mjs +0 -960
  263. package/dist/_chunks/server.mjs +0 -254
  264. package/dist/_chunks/snapshot.mjs +0 -284
  265. package/dist/_chunks/toml.mjs +0 -259
  266. package/dist/_chunks/yaml.mjs +0 -86
  267. package/dist/cli/build.mjs +0 -54
  268. package/dist/cli/common.mjs +0 -13
  269. package/dist/cli/dev.mjs +0 -95
  270. package/dist/cli/index2.mjs +0 -17
  271. package/dist/cli/list.mjs +0 -34
  272. package/dist/cli/prepare.mjs +0 -24
  273. package/dist/cli/run.mjs +0 -60
  274. package/dist/index.d.mts +0 -52
  275. package/dist/index.mjs +0 -55
  276. package/dist/node_modules/cookie/dist/index.js +0 -239
  277. package/dist/node_modules/cookie/package.json +0 -42
  278. package/dist/node_modules/kleur/index.js +0 -110
  279. package/dist/node_modules/klona/dist/index.mjs +0 -81
  280. package/dist/node_modules/klona/full/index.mjs +0 -53
  281. package/dist/node_modules/klona/package.json +0 -74
  282. package/dist/node_modules/std-env/dist/index.mjs +0 -1
  283. package/dist/node_modules/std-env/package.json +0 -46
  284. package/dist/node_modules/youch/build/chunk-OSUFJZHZ.js +0 -6
  285. package/dist/presets/vercel/runtime/vercel.d.mts +0 -8
  286. package/dist/presets/vercel/runtime/vercel.mjs +0 -17
  287. package/dist/presets.mjs +0 -2460
  288. package/dist/runtime/index.d.mts +0 -11
  289. package/dist/runtime/index.mjs +0 -17
  290. package/dist/runtime/internal/debug.d.mts +0 -2
  291. package/dist/runtime/internal/debug.mjs +0 -5
  292. package/dist/runtime/internal/empty.d.mts +0 -0
  293. package/dist/runtime/internal/index.d.mts +0 -3
  294. package/dist/runtime/internal/index.mjs +0 -3
  295. package/dist/runtime/internal/lib/http-graceful-shutdown.d.mts +0 -16
  296. package/dist/runtime/internal/lib/http-graceful-shutdown.mjs +0 -213
  297. package/dist/runtime/internal/renderer.d.mts +0 -3
  298. package/dist/runtime/internal/renderer.mjs +0 -36
  299. package/dist/runtime/internal/shutdown.d.mts +0 -9
  300. package/dist/runtime/internal/shutdown.mjs +0 -34
  301. package/dist/runtime/internal/utils.d.mts +0 -1
  302. package/dist/runtime/internal/utils.mjs +0 -15
  303. package/dist/runtime/internal/vite/dev-entry.d.mts +0 -1
  304. package/dist/runtime/internal/vite/prod-setup.d.mts +0 -4
  305. package/dist/runtime/internal/vite/prod-setup.mjs +0 -55
  306. package/dist/runtime/internal/vite/ssr-renderer.d.mts +0 -4
  307. package/lib/config.d.mts +0 -9
  308. package/lib/config.mjs +0 -5
  309. package/lib/deps/ofetch.mjs +0 -1
  310. package/lib/deps/ofetch.mts +0 -1
  311. package/lib/meta.d.mts +0 -5
  312. package/lib/meta.mjs +0 -21
  313. package/lib/runtime-meta.mjs +0 -38
  314. /package/dist/runtime/{internal/vite/dev-worker.d.mts → virtual/_runtime_warn.d.mts} +0 -0
  315. /package/lib/{deps/h3.d.mts → h3.d.mts} +0 -0
  316. /package/lib/{deps/h3.mjs → h3.mjs} +0 -0
@@ -0,0 +1,707 @@
1
+ import { B as T, V as a, at as join$1, ct as resolve$1, g as writeDevBuildInfo, j as src_default, rt as extname$1 } from "../_build/common.mjs";
2
+ import { i as debounce } from "../_libs/rc9+c12+dotenv.mjs";
3
+ import { t as createProxyServer } from "../_libs/httpxy.mjs";
4
+ import { n as watch$1 } from "../_libs/readdirp+chokidar.mjs";
5
+ import consola$1 from "consola";
6
+ import { createReadStream, existsSync } from "node:fs";
7
+ import { readFile, rm, stat as stat$1 } from "node:fs/promises";
8
+ import { dirname, resolve } from "node:path";
9
+ import { joinURL } from "ufo";
10
+ import { createBrotliCompress, createGzip } from "node:zlib";
11
+ import { Worker } from "node:worker_threads";
12
+ import { H3, HTTPError, defineHandler, fromNodeHandler, getRequestIP, getRequestURL, serveStatic, toEventHandler } from "h3";
13
+ import { Agent } from "undici";
14
+ import { serve } from "srvx/node";
15
+ import { ErrorParser } from "youch-core";
16
+ import { Youch } from "youch";
17
+ import { SourceMapConsumer } from "source-map";
18
+ import { FastResponse } from "srvx";
19
+
20
+ //#region src/runner/proxy.ts
21
+ function createHTTPProxy(defaults = {}) {
22
+ const proxy = createProxyServer(defaults);
23
+ proxy.on("proxyReq", (proxyReq, req) => {
24
+ if (!proxyReq.hasHeader("x-forwarded-for")) {
25
+ const address = req.socket.remoteAddress;
26
+ if (address) proxyReq.appendHeader("x-forwarded-for", address);
27
+ }
28
+ if (!proxyReq.hasHeader("x-forwarded-port")) {
29
+ if (req?.socket?.localPort) proxyReq.setHeader("x-forwarded-port", req.socket.localPort);
30
+ }
31
+ if (!proxyReq.hasHeader("x-forwarded-Proto")) {
32
+ const encrypted = (req?.connection)?.encrypted;
33
+ proxyReq.setHeader("x-forwarded-proto", encrypted ? "https" : "http");
34
+ }
35
+ });
36
+ return {
37
+ proxy,
38
+ async handleEvent(event, opts) {
39
+ try {
40
+ return await fromNodeHandler((req, res) => proxy.web(req, res, opts))(event);
41
+ } catch (error) {
42
+ event.res.headers.set("refresh", "3");
43
+ throw new HTTPError({
44
+ status: 503,
45
+ message: "Dev server is unavailable.",
46
+ cause: error
47
+ });
48
+ }
49
+ }
50
+ };
51
+ }
52
+ async function fetchAddress(addr, input, inputInit) {
53
+ let url;
54
+ let init;
55
+ if (input instanceof Request) {
56
+ url = new URL(input.url);
57
+ init = {
58
+ method: input.method,
59
+ headers: input.headers,
60
+ body: input.body,
61
+ ...inputInit
62
+ };
63
+ } else {
64
+ url = new URL(input);
65
+ init = inputInit;
66
+ }
67
+ init = {
68
+ duplex: "half",
69
+ redirect: "manual",
70
+ ...init
71
+ };
72
+ let res;
73
+ if (addr.socketPath) {
74
+ url.protocol = "http:";
75
+ res = await fetch(url, {
76
+ ...init,
77
+ ...fetchSocketOptions(addr.socketPath)
78
+ });
79
+ } else {
80
+ const origin = `http://${addr.host}${addr.port ? `:${addr.port}` : ""}`;
81
+ const outURL = new URL(url.pathname + url.search, origin);
82
+ res = await fetch(outURL, init);
83
+ }
84
+ const headers = new Headers(res.headers);
85
+ headers.delete("transfer-encoding");
86
+ return new Response(res.body, {
87
+ status: res.status,
88
+ statusText: res.statusText,
89
+ headers
90
+ });
91
+ }
92
+ function fetchSocketOptions(socketPath) {
93
+ if ("Bun" in globalThis) return { unix: socketPath };
94
+ if ("Deno" in globalThis) return { client: Deno.createHttpClient({
95
+ transport: "unix",
96
+ path: socketPath
97
+ }) };
98
+ return { dispatcher: new Agent({ connect: { socketPath } }) };
99
+ }
100
+
101
+ //#endregion
102
+ //#region src/runner/node.ts
103
+ var NodeEnvRunner = class {
104
+ closed = false;
105
+ #name;
106
+ #entry;
107
+ #data;
108
+ #hooks;
109
+ #worker;
110
+ #address;
111
+ #proxy;
112
+ #messageListeners;
113
+ constructor(opts) {
114
+ this.#name = opts.name;
115
+ this.#entry = opts.entry;
116
+ this.#data = opts.data;
117
+ this.#hooks = opts.hooks || {};
118
+ this.#proxy = createHTTPProxy();
119
+ this.#messageListeners = /* @__PURE__ */ new Set();
120
+ this.#initWorker();
121
+ }
122
+ get ready() {
123
+ return Boolean(!this.closed && this.#address && this.#proxy && this.#worker);
124
+ }
125
+ async fetch(input, init) {
126
+ for (let i = 0; i < 5 && !(this.#address && this.#proxy); i++) await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i)));
127
+ if (!(this.#address && this.#proxy)) return new Response("Node env runner worker is unavailable", { status: 503 });
128
+ return fetchAddress(this.#address, input, init);
129
+ }
130
+ upgrade(req, socket, head) {
131
+ if (!this.ready) return;
132
+ return this.#proxy.proxy.ws(req, socket, {
133
+ target: this.#address,
134
+ xfwd: true
135
+ }, head).catch((error) => {
136
+ consola$1.error("WebSocket proxy error:", error);
137
+ });
138
+ }
139
+ sendMessage(message) {
140
+ if (!this.#worker) throw new Error("Node env worker should be initialized before sending messages.");
141
+ this.#worker.postMessage(message);
142
+ }
143
+ onMessage(listener) {
144
+ this.#messageListeners.add(listener);
145
+ }
146
+ offMessage(listener) {
147
+ this.#messageListeners.delete(listener);
148
+ }
149
+ async close(cause) {
150
+ if (this.closed) return;
151
+ this.closed = true;
152
+ this.#hooks.onClose?.(this, cause);
153
+ this.#hooks = {};
154
+ const onError = (error) => consola$1.error(error);
155
+ await this.#closeWorker().catch(onError);
156
+ await this.#closeProxy().catch(onError);
157
+ await this.#closeSocket().catch(onError);
158
+ }
159
+ [Symbol.for("nodejs.util.inspect.custom")]() {
160
+ const status = this.closed ? "closed" : this.ready ? "ready" : "pending";
161
+ return `NodeEnvRunner#${this.#name}(${status})`;
162
+ }
163
+ #initWorker() {
164
+ if (!existsSync(this.#entry)) {
165
+ this.close(`worker entry not found in "${this.#entry}".`);
166
+ return;
167
+ }
168
+ const worker = new Worker(this.#entry, {
169
+ env: { ...process.env },
170
+ workerData: {
171
+ name: this.#name,
172
+ ...this.#data
173
+ }
174
+ });
175
+ worker.once("exit", (code) => {
176
+ worker._exitCode = code;
177
+ this.close(`worker exited with code ${code}`);
178
+ });
179
+ worker.once("error", (error) => {
180
+ consola$1.error(`Worker error:`, error);
181
+ this.close(error);
182
+ });
183
+ worker.on("message", (message) => {
184
+ if (message?.address) {
185
+ this.#address = message.address;
186
+ this.#hooks.onReady?.(this, this.#address);
187
+ }
188
+ for (const listener of this.#messageListeners) listener(message);
189
+ });
190
+ this.#worker = worker;
191
+ }
192
+ async #closeProxy() {
193
+ this.#proxy?.proxy?.close(() => {});
194
+ this.#proxy = void 0;
195
+ }
196
+ async #closeSocket() {
197
+ const socketPath = this.#address?.socketPath;
198
+ if (socketPath && socketPath[0] !== "\0" && !socketPath.startsWith(String.raw`\\.\pipe`)) await rm(socketPath).catch(() => {});
199
+ this.#address = void 0;
200
+ }
201
+ async #closeWorker() {
202
+ if (!this.#worker) return;
203
+ this.#worker.postMessage({ event: "shutdown" });
204
+ if (!this.#worker._exitCode && !a && !T) await new Promise((resolve$2) => {
205
+ const gracefulShutdownTimeoutMs = Number.parseInt(process.env.NITRO_SHUTDOWN_TIMEOUT || "", 10) || 5e3;
206
+ const timeout = setTimeout(() => {
207
+ consola$1.warn(`force closing node env runner worker...`);
208
+ resolve$2();
209
+ }, gracefulShutdownTimeoutMs);
210
+ this.#worker?.on("message", (message) => {
211
+ if (message.event === "exit") {
212
+ clearTimeout(timeout);
213
+ resolve$2();
214
+ }
215
+ });
216
+ });
217
+ this.#worker.removeAllListeners();
218
+ await this.#worker.terminate().catch((error) => {
219
+ consola$1.error(error);
220
+ });
221
+ this.#worker = void 0;
222
+ }
223
+ };
224
+
225
+ //#endregion
226
+ //#region src/dev/vfs.ts
227
+ function createVFSHandler(nitro) {
228
+ return defineHandler(async (event) => {
229
+ const { socket } = event.runtime?.node?.req || {};
230
+ const ip = getRequestIP(event, { xForwardedFor: !socket?.remoteAddress && !socket?.localAddress && Object.keys(socket?.address?.() || {}).length === 0 && socket?.readable && socket?.writable && !socket?.remotePort });
231
+ if (!(ip && /^::1$|^127\.\d+\.\d+\.\d+$/.test(ip))) throw new HTTPError({
232
+ statusText: `Forbidden IP: "${ip || "?"}"`,
233
+ status: 403
234
+ });
235
+ const url = event.context.params?._ || "";
236
+ const isJson = url.endsWith(".json") || event.req.headers.get("accept")?.includes("application/json");
237
+ const id = decodeURIComponent(url.replace(/^(\.json)?\/?/, "") || "");
238
+ if (id && !nitro.vfs.has(id)) throw new HTTPError({
239
+ message: "File not found",
240
+ status: 404
241
+ });
242
+ const content = id ? await nitro.vfs.get(id)?.render() : void 0;
243
+ if (isJson) return {
244
+ rootDir: nitro.options.rootDir,
245
+ entries: [...nitro.vfs.keys()].map((id$1) => ({
246
+ id: id$1,
247
+ path: "/_vfs.json/" + encodeURIComponent(id$1)
248
+ })),
249
+ current: id ? {
250
+ id,
251
+ content
252
+ } : null
253
+ };
254
+ const directories = { [nitro.options.rootDir]: {} };
255
+ const fpaths = [...nitro.vfs.keys()];
256
+ for (const item of fpaths) {
257
+ const segments = item.replace(nitro.options.rootDir, "").split("/").filter(Boolean);
258
+ let currentDir = item.startsWith(nitro.options.rootDir) ? directories[nitro.options.rootDir] : directories;
259
+ for (const segment of segments) {
260
+ if (!currentDir[segment]) currentDir[segment] = {};
261
+ currentDir = currentDir[segment];
262
+ }
263
+ }
264
+ const generateHTML = (directory, path$1 = []) => Object.entries(directory).map(([fname, value = {}]) => {
265
+ const subpath = [...path$1, fname];
266
+ const key = subpath.join("/");
267
+ const encodedUrl = encodeURIComponent(key);
268
+ const linkClass = url === `/${encodedUrl}` ? "bg-gray-700 text-white" : "hover:bg-gray-800 text-gray-200";
269
+ return Object.keys(value).length === 0 ? `
270
+ <li class="flex flex-nowrap">
271
+ <a href="/_vfs/${encodedUrl}" class="w-full text-sm px-2 py-1 border-b border-gray-10 ${linkClass}">
272
+ ${fname}
273
+ </a>
274
+ </li>
275
+ ` : `
276
+ <li>
277
+ <details ${url.startsWith(`/${encodedUrl}`) ? "open" : ""}>
278
+ <summary class="w-full text-sm px-2 py-1 border-b border-gray-10 hover:bg-gray-800 text-gray-200">
279
+ ${fname}
280
+ </summary>
281
+ <ul class="ml-4">
282
+ ${generateHTML(value, subpath)}
283
+ </ul>
284
+ </details>
285
+ </li>
286
+ `;
287
+ }).join("");
288
+ const rootDirectory = directories[nitro.options.rootDir];
289
+ delete directories[nitro.options.rootDir];
290
+ const files = `
291
+ <div class="h-full overflow-auto border-r border-gray:10">
292
+ <p class="text-white text-bold text-center py-1 opacity-50">Virtual Files</p>
293
+ <ul class="flex flex-col">${generateHTML(rootDirectory, [nitro.options.rootDir]) + generateHTML(directories)}</ul>
294
+ </div>
295
+ `;
296
+ const file = id ? editorTemplate({
297
+ readOnly: true,
298
+ language: id.endsWith("html") ? "html" : "javascript",
299
+ theme: "vs-dark",
300
+ value: content,
301
+ wordWrap: "wordWrapColumn",
302
+ wordWrapColumn: 80
303
+ }) : `
304
+ <div class="w-full h-full flex opacity-50">
305
+ <h1 class="text-white m-auto">Select a virtual file to inspect</h1>
306
+ </div>
307
+ `;
308
+ event.res.headers.set("Content-Type", "text/html; charset=utf-8");
309
+ return `
310
+ <!doctype html>
311
+ <html>
312
+ <head>
313
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@unocss/reset/tailwind.min.css" />
314
+ <link rel="stylesheet" data-name="vs/editor/editor.main" href="${vsUrl}/editor/editor.main.min.css">
315
+ <script src="https://cdn.jsdelivr.net/npm/@unocss/runtime"><\/script>
316
+ <style>
317
+ html {
318
+ background: #1E1E1E;
319
+ color: white;
320
+ }
321
+ [un-cloak] {
322
+ display: none;
323
+ }
324
+ </style>
325
+ </head>
326
+ <body class="bg-[#1E1E1E]">
327
+ <div un-cloak class="h-screen grid grid-cols-[300px_1fr]">
328
+ ${files}
329
+ ${file}
330
+ </div>
331
+ </body>
332
+ </html>`;
333
+ });
334
+ }
335
+ const monacoUrl = `https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.30.0/min`;
336
+ const vsUrl = `${monacoUrl}/vs`;
337
+ const editorTemplate = (options) => `
338
+ <div id="editor" class="min-h-screen w-full h-full"></div>
339
+ <script src="${vsUrl}/loader.min.js"><\/script>
340
+ <script>
341
+ require.config({ paths: { vs: '${vsUrl}' } })
342
+
343
+ const proxy = URL.createObjectURL(new Blob([\`
344
+ self.MonacoEnvironment = { baseUrl: '${monacoUrl}' }
345
+ importScripts('${vsUrl}/base/worker/workerMain.min.js')
346
+ \`], { type: 'text/javascript' }))
347
+ window.MonacoEnvironment = { getWorkerUrl: () => proxy }
348
+
349
+ setTimeout(() => {
350
+ require(['vs/editor/editor.main'], function () {
351
+ monaco.editor.create(document.getElementById('editor'), ${JSON.stringify(options)})
352
+ })
353
+ }, 0);
354
+ <\/script>
355
+ `;
356
+
357
+ //#endregion
358
+ //#region src/runtime/internal/error/utils.ts
359
+ function defineNitroErrorHandler(handler) {
360
+ return handler;
361
+ }
362
+
363
+ //#endregion
364
+ //#region src/runtime/internal/error/dev.ts
365
+ var dev_default = defineNitroErrorHandler(async function defaultNitroErrorHandler(error, event) {
366
+ const res = await defaultHandler(error, event);
367
+ return new FastResponse(typeof res.body === "string" ? res.body : JSON.stringify(res.body, null, 2), res);
368
+ });
369
+ async function defaultHandler(error, event, opts) {
370
+ const isSensitive = error.unhandled;
371
+ const status = error.status || 500;
372
+ const url = getRequestURL(event, {
373
+ xForwardedHost: true,
374
+ xForwardedProto: true
375
+ });
376
+ if (status === 404) {
377
+ const baseURL = import.meta.baseURL || "/";
378
+ if (/^\/[^/]/.test(baseURL) && !url.pathname.startsWith(baseURL)) return {
379
+ status: 302,
380
+ statusText: "Found",
381
+ headers: { location: `${baseURL}${url.pathname.slice(1)}${url.search}` },
382
+ body: `Redirecting...`
383
+ };
384
+ }
385
+ await loadStackTrace(error).catch(consola$1.error);
386
+ const youch = new Youch();
387
+ if (isSensitive && !opts?.silent) {
388
+ const tags = [error.unhandled && "[unhandled]"].filter(Boolean).join(" ");
389
+ const ansiError = await (await youch.toANSI(error)).replaceAll(process.cwd(), ".");
390
+ consola$1.error(`[request error] ${tags} [${event.req.method}] ${url}\n\n`, ansiError);
391
+ }
392
+ const useJSON = opts?.json ?? !event.req.headers.get("accept")?.includes("text/html");
393
+ const headers = {
394
+ "content-type": useJSON ? "application/json" : "text/html",
395
+ "x-content-type-options": "nosniff",
396
+ "x-frame-options": "DENY",
397
+ "referrer-policy": "no-referrer",
398
+ "content-security-policy": "script-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self';"
399
+ };
400
+ if (status === 404 || !event.res.headers.has("cache-control")) headers["cache-control"] = "no-cache";
401
+ const body = useJSON ? {
402
+ error: true,
403
+ url,
404
+ status,
405
+ statusText: error.statusText,
406
+ message: error.message,
407
+ data: error.data,
408
+ stack: error.stack?.split("\n").map((line) => line.trim())
409
+ } : await youch.toHTML(error, { request: {
410
+ url: url.href,
411
+ method: event.req.method,
412
+ headers: Object.fromEntries(event.req.headers.entries())
413
+ } });
414
+ return {
415
+ status,
416
+ statusText: error.statusText,
417
+ headers,
418
+ body
419
+ };
420
+ }
421
+ async function loadStackTrace(error) {
422
+ if (!(error instanceof Error)) return;
423
+ const parsed = await new ErrorParser().defineSourceLoader(sourceLoader).parse(error);
424
+ const stack = error.message + "\n" + parsed.frames.map((frame) => fmtFrame(frame)).join("\n");
425
+ Object.defineProperty(error, "stack", { value: stack });
426
+ if (error.cause) await loadStackTrace(error.cause).catch(consola$1.error);
427
+ }
428
+ async function sourceLoader(frame) {
429
+ if (!frame.fileName || frame.fileType !== "fs" || frame.type === "native") return;
430
+ if (frame.type === "app") {
431
+ const rawSourceMap = await readFile(`${frame.fileName}.map`, "utf8").catch(() => {});
432
+ if (rawSourceMap) {
433
+ const originalPosition = (await new SourceMapConsumer(rawSourceMap)).originalPositionFor({
434
+ line: frame.lineNumber,
435
+ column: frame.columnNumber
436
+ });
437
+ if (originalPosition.source && originalPosition.line) {
438
+ frame.fileName = resolve(dirname(frame.fileName), originalPosition.source);
439
+ frame.lineNumber = originalPosition.line;
440
+ frame.columnNumber = originalPosition.column || 0;
441
+ }
442
+ }
443
+ }
444
+ const contents = await readFile(frame.fileName, "utf8").catch(() => {});
445
+ return contents ? { contents } : void 0;
446
+ }
447
+ function fmtFrame(frame) {
448
+ if (frame.type === "native") return frame.raw;
449
+ const src = `${frame.fileName || ""}:${frame.lineNumber}:${frame.columnNumber})`;
450
+ return frame.functionName ? `at ${frame.functionName} (${src}` : `at ${src}`;
451
+ }
452
+
453
+ //#endregion
454
+ //#region src/dev/app.ts
455
+ var NitroDevApp = class {
456
+ nitro;
457
+ fetch;
458
+ constructor(nitro, catchAllHandler) {
459
+ this.nitro = nitro;
460
+ const app = this.#createApp(catchAllHandler);
461
+ this.fetch = app.fetch.bind(app);
462
+ }
463
+ #createApp(catchAllHandler) {
464
+ const app = new H3({
465
+ debug: true,
466
+ onError: async (error, event) => {
467
+ const errorHandler = this.nitro.options.devErrorHandler || dev_default;
468
+ await loadStackTrace(error).catch(() => {});
469
+ return errorHandler(error, event, { defaultHandler });
470
+ }
471
+ });
472
+ for (const h of this.nitro.options.devHandlers) {
473
+ const handler = toEventHandler(h.handler);
474
+ if (!handler) {
475
+ this.nitro.logger.warn("Invalid dev handler:", h);
476
+ continue;
477
+ }
478
+ if (h.middleware || !h.route) if (h.route) app.use(h.route, handler, { method: h.method });
479
+ else app.use(handler, { method: h.method });
480
+ else app.on(h.method || "", h.route, handler, { meta: h.meta });
481
+ }
482
+ app.get("/_vfs/**", createVFSHandler(this.nitro));
483
+ for (const asset of this.nitro.options.publicAssets) {
484
+ const assetBase = joinURL(this.nitro.options.baseURL, asset.baseURL || "/");
485
+ app.use(joinURL(assetBase, "**"), (event) => serveStaticDir(event, {
486
+ dir: asset.dir,
487
+ base: assetBase,
488
+ fallthrough: asset.fallthrough
489
+ }));
490
+ }
491
+ const routes = Object.keys(this.nitro.options.devProxy).sort().reverse();
492
+ for (const route of routes) {
493
+ let opts = this.nitro.options.devProxy[route];
494
+ if (typeof opts === "string") opts = { target: opts };
495
+ const proxy = createHTTPProxy(opts);
496
+ app.all(route, proxy.handleEvent);
497
+ }
498
+ if (catchAllHandler) app.all("/**", catchAllHandler);
499
+ return app;
500
+ }
501
+ };
502
+ function serveStaticDir(event, opts) {
503
+ const dir = resolve$1(opts.dir) + "/";
504
+ const r = (id) => {
505
+ if (!id.startsWith(opts.base) || !extname$1(id)) return;
506
+ const resolved = join$1(dir, id.slice(opts.base.length));
507
+ if (resolved.startsWith(dir)) return resolved;
508
+ };
509
+ return serveStatic(event, {
510
+ fallthrough: opts.fallthrough,
511
+ getMeta: async (id) => {
512
+ const path$1 = r(id);
513
+ if (!path$1) return;
514
+ const s = await stat$1(path$1).catch(() => null);
515
+ if (!s?.isFile()) return;
516
+ const ext = extname$1(path$1);
517
+ return {
518
+ size: s.size,
519
+ mtime: s.mtime,
520
+ type: src_default.getType(ext) || "application/octet-stream"
521
+ };
522
+ },
523
+ getContents(id) {
524
+ const path$1 = r(id);
525
+ if (!path$1) return;
526
+ const stream = createReadStream(path$1);
527
+ const acceptEncoding = event.req.headers.get("accept-encoding") || "";
528
+ if (acceptEncoding.includes("br")) {
529
+ event.res.headers.set("Content-Encoding", "br");
530
+ event.res.headers.delete("Content-Length");
531
+ event.res.headers.set("Vary", "Accept-Encoding");
532
+ return stream.pipe(createBrotliCompress());
533
+ } else if (acceptEncoding.includes("gzip")) {
534
+ event.res.headers.set("Content-Encoding", "gzip");
535
+ event.res.headers.delete("Content-Length");
536
+ event.res.headers.set("Vary", "Accept-Encoding");
537
+ return stream.pipe(createGzip());
538
+ }
539
+ return stream;
540
+ }
541
+ });
542
+ }
543
+
544
+ //#endregion
545
+ //#region src/dev/server.ts
546
+ function createDevServer(nitro) {
547
+ return new NitroDevServer(nitro);
548
+ }
549
+ var NitroDevServer = class NitroDevServer extends NitroDevApp {
550
+ #entry;
551
+ #workerData = {};
552
+ #listeners = [];
553
+ #watcher;
554
+ #workers = [];
555
+ #workerIdCtr = 0;
556
+ #workerError;
557
+ #building = true;
558
+ #buildError;
559
+ #messageListeners = /* @__PURE__ */ new Set();
560
+ constructor(nitro) {
561
+ super(nitro, async (event) => {
562
+ const worker = await this.#getWorker();
563
+ if (!worker) return this.#generateError();
564
+ return worker.fetch(event.req);
565
+ });
566
+ for (const key of Object.getOwnPropertyNames(NitroDevServer.prototype)) {
567
+ const value = this[key];
568
+ if (typeof value === "function" && key !== "constructor") this[key] = value.bind(this);
569
+ }
570
+ nitro.fetch = this.fetch.bind(this);
571
+ this.#entry = resolve$1(nitro.options.output.dir, nitro.options.output.serverDir, "index.mjs");
572
+ nitro.hooks.hook("close", () => this.close());
573
+ nitro.hooks.hook("dev:start", () => {
574
+ this.#building = true;
575
+ this.#buildError = void 0;
576
+ });
577
+ nitro.hooks.hook("dev:reload", (payload) => {
578
+ this.#buildError = void 0;
579
+ this.#building = false;
580
+ if (payload?.entry) this.#entry = payload.entry;
581
+ if (payload?.workerData) this.#workerData = payload.workerData;
582
+ this.reload();
583
+ });
584
+ nitro.hooks.hook("dev:error", (cause) => {
585
+ this.#buildError = cause;
586
+ this.#building = false;
587
+ for (const worker of this.#workers) worker.close();
588
+ });
589
+ const devWatch = nitro.options.devServer.watch;
590
+ if (devWatch && devWatch.length > 0) {
591
+ const debouncedReload = debounce(() => this.reload());
592
+ this.#watcher = watch$1(devWatch, nitro.options.watchOptions);
593
+ this.#watcher.on("add", debouncedReload).on("change", debouncedReload);
594
+ }
595
+ }
596
+ async upgrade(req, socket, head) {
597
+ const worker = await this.#getWorker();
598
+ if (!worker) throw new HTTPError({
599
+ status: 503,
600
+ statusText: "No worker available."
601
+ });
602
+ if (!worker.upgrade) throw new HTTPError({
603
+ status: 501,
604
+ statusText: "Worker does not support upgrades."
605
+ });
606
+ return worker.upgrade(req, socket, head);
607
+ }
608
+ listen(opts) {
609
+ const server = serve({
610
+ ...opts,
611
+ fetch: this.fetch,
612
+ gracefulShutdown: false
613
+ });
614
+ this.#listeners.push(server);
615
+ if (server.node?.server) server.node.server.on("upgrade", (req, sock, head) => this.upgrade(req, sock, head));
616
+ return server;
617
+ }
618
+ async close() {
619
+ await Promise.all([
620
+ Promise.all(this.#listeners.map((l) => l.close())).then(() => {
621
+ this.#listeners = [];
622
+ }),
623
+ Promise.all(this.#workers.map((w) => w.close())).then(() => {
624
+ this.#workers = [];
625
+ }),
626
+ Promise.resolve(this.#watcher?.close()).then(() => {
627
+ this.#watcher = void 0;
628
+ })
629
+ ].map((p) => p.catch((error) => {
630
+ consola$1.error(error);
631
+ })));
632
+ }
633
+ reload() {
634
+ for (const worker$1 of this.#workers) worker$1.close();
635
+ const worker = new NodeEnvRunner({
636
+ name: `Nitro_${this.#workerIdCtr++}`,
637
+ entry: this.#entry,
638
+ data: this.#workerData,
639
+ hooks: {
640
+ onClose: (worker$1, cause) => {
641
+ this.#workerError = cause;
642
+ const index = this.#workers.indexOf(worker$1);
643
+ if (index !== -1) this.#workers.splice(index, 1);
644
+ },
645
+ onReady: async (_worker, addr) => {
646
+ writeDevBuildInfo(this.nitro, addr).catch(() => {});
647
+ }
648
+ }
649
+ });
650
+ if (!worker.closed) {
651
+ for (const listener of this.#messageListeners) worker.onMessage(listener);
652
+ this.#workers.unshift(worker);
653
+ }
654
+ }
655
+ sendMessage(message) {
656
+ for (const worker of this.#workers) if (!worker.closed) worker.sendMessage(message);
657
+ }
658
+ onMessage(listener) {
659
+ this.#messageListeners.add(listener);
660
+ for (const worker of this.#workers) worker.onMessage(listener);
661
+ }
662
+ offMessage(listener) {
663
+ this.#messageListeners.delete(listener);
664
+ for (const worker of this.#workers) worker.offMessage(listener);
665
+ }
666
+ async #getWorker() {
667
+ let retry = 0;
668
+ const maxRetries = a || T ? 100 : 10;
669
+ while (this.#building || ++retry < maxRetries) {
670
+ if ((this.#workers.length === 0 || this.#buildError) && !this.#building) return;
671
+ const activeWorker = this.#workers.find((w) => w.ready);
672
+ if (activeWorker) return activeWorker;
673
+ await new Promise((resolve$2) => setTimeout(resolve$2, 600));
674
+ }
675
+ }
676
+ #generateError() {
677
+ const error = this.#buildError || this.#workerError;
678
+ if (error) {
679
+ try {
680
+ error.unhandled = false;
681
+ let id = error.id || error.path;
682
+ if (id) {
683
+ const cause = error.errors?.[0];
684
+ const loc = error.location || error.loc || cause?.location || cause?.loc;
685
+ if (loc) id += `:${loc.line}:${loc.column}`;
686
+ error.stack = (error.stack || "").replace(/(^\s*at\s+.+)/m, ` at ${id}\n$1`);
687
+ }
688
+ } catch {}
689
+ return new HTTPError(error);
690
+ }
691
+ return new Response(JSON.stringify({
692
+ error: "Dev server is unavailable.",
693
+ hint: "Please reload the page and check the console for errors if the issue persists."
694
+ }, null, 2), {
695
+ status: 503,
696
+ statusText: "Dev server is unavailable",
697
+ headers: {
698
+ "Content-Type": "application/json",
699
+ "Cache-Control": "no-store",
700
+ Refresh: "3"
701
+ }
702
+ });
703
+ }
704
+ };
705
+
706
+ //#endregion
707
+ export { NodeEnvRunner as i, createDevServer as n, NitroDevApp as r, NitroDevServer as t };