nitro 3.0.0 → 3.0.1-alpha.1

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 (293) hide show
  1. package/dist/_build/common.mjs +68 -0
  2. package/dist/_build/common2.mjs +772 -0
  3. package/dist/_build/rolldown.mjs +206 -0
  4. package/dist/_build/rollup.mjs +289 -0
  5. package/dist/_build/vite.build.mjs +56 -0
  6. package/dist/_build/vite.plugin.mjs +768 -0
  7. package/dist/_chunks/ANM1K1bE.mjs +304 -0
  8. package/dist/_chunks/B-D1JOIz.mjs +1355 -0
  9. package/dist/_chunks/BX9-zVkM.mjs +59 -0
  10. package/dist/_chunks/Bqks5huO.mjs +31 -0
  11. package/dist/_chunks/C7CbzoI1.mjs +39 -0
  12. package/dist/_dev.d.mts +12 -0
  13. package/dist/_dev.mjs +705 -0
  14. package/dist/_libs/acorn.mjs +5034 -0
  15. package/dist/_libs/c12.mjs +2858 -0
  16. package/dist/_libs/chokidar.mjs +1561 -0
  17. package/dist/_libs/citty.mjs +333 -0
  18. package/dist/_libs/commondir.mjs +22 -0
  19. package/dist/_libs/compatx.mjs +46 -0
  20. package/dist/_libs/confbox.mjs +2920 -0
  21. package/dist/_libs/deepmerge.mjs +86 -0
  22. package/dist/_libs/dot-prop.mjs +138 -0
  23. package/dist/_libs/duplexer.mjs +71 -0
  24. package/dist/_libs/escape-string-regexp.mjs +8 -0
  25. package/dist/_libs/estree-walker.mjs +330 -0
  26. package/dist/_libs/etag.mjs +80 -0
  27. package/dist/_libs/fdir.mjs +514 -0
  28. package/dist/_libs/function-bind.mjs +63 -0
  29. package/dist/_libs/gen-mapping.mjs +612 -0
  30. package/dist/_libs/giget.mjs +19289 -0
  31. package/dist/_libs/gzip-size.mjs +21 -0
  32. package/dist/_libs/hasown.mjs +14 -0
  33. package/dist/_libs/httpxy.mjs +410 -0
  34. package/dist/_libs/is-core-module.mjs +220 -0
  35. package/dist/_libs/is-module.mjs +13 -0
  36. package/dist/_libs/is-reference.mjs +32 -0
  37. package/dist/_libs/js-tokens.mjs +382 -0
  38. package/dist/_libs/klona.mjs +38 -0
  39. package/dist/_libs/knitwork.mjs +124 -0
  40. package/dist/_libs/local-pkg.mjs +1686 -0
  41. package/dist/_libs/magic-string.mjs +939 -0
  42. package/dist/_libs/mime.mjs +1391 -0
  43. package/dist/_libs/node-fetch-native.mjs +173 -0
  44. package/dist/_libs/path-parse.mjs +47 -0
  45. package/dist/_libs/pathe.mjs +41 -0
  46. package/dist/_libs/picomatch.mjs +1673 -0
  47. package/dist/_libs/plugin-alias.mjs +64 -0
  48. package/dist/_libs/plugin-commonjs.mjs +1491 -0
  49. package/dist/_libs/plugin-inject.mjs +135 -0
  50. package/dist/_libs/plugin-json.mjs +36 -0
  51. package/dist/_libs/plugin-node-resolve.mjs +1553 -0
  52. package/dist/_libs/plugin-replace.mjs +104 -0
  53. package/dist/_libs/pretty-bytes.mjs +116 -0
  54. package/dist/_libs/remapping.mjs +117 -0
  55. package/dist/_libs/rou3.mjs +319 -0
  56. package/dist/_libs/std-env.mjs +158 -0
  57. package/dist/_libs/strip-literal.mjs +51 -0
  58. package/dist/_libs/tinyglobby.mjs +292 -0
  59. package/dist/_libs/tsconfck.mjs +832 -0
  60. package/dist/_libs/ultrahtml.mjs +138 -0
  61. package/dist/_libs/unimport.mjs +3520 -0
  62. package/dist/_libs/untyped.mjs +271 -0
  63. package/dist/_libs/unwasm.mjs +5836 -0
  64. package/dist/_libs/vite-plugin-fullstack.mjs +561 -0
  65. package/dist/_presets.mjs +1752 -0
  66. package/dist/builder.d.mts +63 -0
  67. package/dist/builder.mjs +33 -0
  68. package/dist/cli/_chunks/build.mjs +48 -0
  69. package/dist/cli/_chunks/common.mjs +15 -0
  70. package/dist/cli/_chunks/detect-acorn.mjs +12 -0
  71. package/dist/cli/_chunks/dev.mjs +68 -0
  72. package/dist/cli/_chunks/dist.mjs +3 -0
  73. package/dist/cli/_chunks/dist2.mjs +3 -0
  74. package/dist/cli/_chunks/dist3.mjs +3 -0
  75. package/dist/cli/_chunks/dist4.mjs +4 -0
  76. package/dist/cli/_chunks/dist5.mjs +4 -0
  77. package/dist/cli/_chunks/esm.mjs +3 -0
  78. package/dist/cli/_chunks/json5.mjs +4 -0
  79. package/dist/cli/_chunks/jsonc.mjs +4 -0
  80. package/dist/cli/_chunks/list.mjs +27 -0
  81. package/dist/cli/_chunks/multipart-parser.mjs +6 -0
  82. package/dist/cli/_chunks/prepare.mjs +19 -0
  83. package/dist/cli/_chunks/run.mjs +55 -0
  84. package/dist/cli/_chunks/task.mjs +16 -0
  85. package/dist/cli/_chunks/toml.mjs +4 -0
  86. package/dist/cli/_chunks/yaml.mjs +4 -0
  87. package/dist/cli/index.d.mts +1 -1
  88. package/dist/cli/index.mjs +20 -476
  89. package/dist/node_modules/@poppinss/dumper/build/formatters/html/main.js +1 -1
  90. package/dist/node_modules/@poppinss/dumper/package.json +1 -1
  91. package/dist/node_modules/@sindresorhus/is/distribution/index.js +1 -1
  92. package/dist/node_modules/@sindresorhus/is/package.json +1 -1
  93. package/dist/node_modules/@speed-highlight/core/dist/index.js +2 -2
  94. package/dist/node_modules/@speed-highlight/core/dist/terminal.js +2 -2
  95. package/dist/node_modules/@speed-highlight/core/package.json +7 -3
  96. package/dist/node_modules/cookie-es/dist/index.mjs +262 -0
  97. package/dist/node_modules/cookie-es/package.json +37 -0
  98. package/dist/node_modules/hookable/dist/index.mjs +243 -266
  99. package/dist/node_modules/hookable/package.json +29 -26
  100. package/dist/node_modules/rendu/dist/index.mjs +380 -0
  101. package/dist/node_modules/rendu/package.json +47 -0
  102. package/dist/node_modules/youch/build/{chunk-VE4LENUR.js → chunk-F4I6KX4R.js} +2 -1
  103. package/dist/node_modules/youch/build/{chunk-JAN2TFI2.js → chunk-YYEJ3AGB.js} +4 -1
  104. package/dist/node_modules/youch/build/index.js +16 -8
  105. package/dist/node_modules/youch/build/public/error_stack/script.js +20 -22
  106. package/dist/node_modules/youch/build/public/header/script.js +0 -2
  107. package/dist/node_modules/youch/build/public/layout/script.js +0 -8
  108. package/dist/node_modules/youch/build/public/layout/style.css +4 -0
  109. package/dist/node_modules/youch/package.json +16 -17
  110. package/dist/presets/_nitro/runtime/nitro-dev.d.mts +1 -0
  111. package/dist/presets/_nitro/runtime/nitro-dev.mjs +48 -42
  112. package/dist/presets/_nitro/runtime/nitro-prerenderer.d.mts +2 -2
  113. package/dist/presets/_nitro/runtime/nitro-prerenderer.mjs +10 -14
  114. package/dist/presets/_nitro/runtime/service-worker.d.mts +1 -0
  115. package/dist/presets/_nitro/runtime/service-worker.mjs +15 -12
  116. package/dist/presets/aws-amplify/runtime/aws-amplify.d.mts +1 -0
  117. package/dist/presets/aws-amplify/runtime/aws-amplify.mjs +7 -6
  118. package/dist/presets/aws-lambda/runtime/_utils.d.mts +8 -13
  119. package/dist/presets/aws-lambda/runtime/_utils.mjs +95 -81
  120. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.d.mts +1 -2
  121. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.mjs +26 -28
  122. package/dist/presets/aws-lambda/runtime/aws-lambda.mjs +8 -8
  123. package/dist/presets/azure/runtime/_utils.mjs +43 -43
  124. package/dist/presets/azure/runtime/azure-swa.d.mts +2 -2
  125. package/dist/presets/azure/runtime/azure-swa.mjs +24 -22
  126. package/dist/presets/bun/runtime/bun.d.mts +2 -0
  127. package/dist/presets/bun/runtime/bun.mjs +34 -21
  128. package/dist/presets/cloudflare/runtime/_module-handler.d.mts +10 -7
  129. package/dist/presets/cloudflare/runtime/_module-handler.mjs +80 -88
  130. package/dist/presets/cloudflare/runtime/cloudflare-durable.d.mts +6 -14
  131. package/dist/presets/cloudflare/runtime/cloudflare-durable.mjs +60 -63
  132. package/dist/presets/cloudflare/runtime/cloudflare-module.d.mts +1 -7
  133. package/dist/presets/cloudflare/runtime/cloudflare-module.mjs +14 -16
  134. package/dist/presets/cloudflare/runtime/cloudflare-pages.d.mts +12 -12
  135. package/dist/presets/cloudflare/runtime/cloudflare-pages.mjs +40 -42
  136. package/dist/presets/cloudflare/runtime/plugin.dev.d.mts +2 -2
  137. package/dist/presets/cloudflare/runtime/plugin.dev.mjs +89 -82
  138. package/dist/presets/cloudflare/runtime/shims/workers.dev.mjs +27 -0
  139. package/dist/presets/deno/runtime/deno-deploy.d.mts +4 -0
  140. package/dist/presets/deno/runtime/deno-deploy.mjs +15 -12
  141. package/dist/presets/deno/runtime/deno-server.d.mts +0 -3
  142. package/dist/presets/deno/runtime/deno-server.mjs +32 -52
  143. package/dist/presets/netlify/runtime/netlify-edge.d.mts +2 -1
  144. package/dist/presets/netlify/runtime/netlify-edge.mjs +15 -12
  145. package/dist/presets/netlify/runtime/netlify.mjs +12 -18
  146. package/dist/presets/node/runtime/node-cluster.d.mts +3 -1
  147. package/dist/presets/node/runtime/node-cluster.mjs +50 -54
  148. package/dist/presets/node/runtime/node-middleware.d.mts +2 -3
  149. package/dist/presets/node/runtime/node-middleware.mjs +9 -8
  150. package/dist/presets/node/runtime/node-server.mjs +37 -34
  151. package/dist/presets/standard/runtime/server.d.mts +1 -3
  152. package/dist/presets/standard/runtime/server.mjs +2 -4
  153. package/dist/presets/stormkit/runtime/stormkit.d.mts +13 -13
  154. package/dist/presets/stormkit/runtime/stormkit.mjs +21 -21
  155. package/dist/presets/vercel/runtime/vercel.node.d.mts +3 -0
  156. package/dist/presets/vercel/runtime/vercel.node.mjs +15 -0
  157. package/dist/presets/vercel/runtime/{vercel.d.mts → vercel.web.d.mts} +3 -3
  158. package/dist/presets/vercel/runtime/vercel.web.mjs +20 -0
  159. package/dist/presets/winterjs/runtime/winterjs.d.mts +2 -0
  160. package/dist/presets/winterjs/runtime/winterjs.mjs +73 -69
  161. package/dist/presets/zeabur/runtime/zeabur.d.mts +1 -1
  162. package/dist/presets/zeabur/runtime/zeabur.mjs +1 -1
  163. package/dist/runtime/app.d.mts +1 -0
  164. package/dist/runtime/app.mjs +1 -0
  165. package/dist/runtime/cache.d.mts +1 -0
  166. package/dist/runtime/cache.mjs +1 -0
  167. package/dist/runtime/config.d.mts +3 -0
  168. package/dist/runtime/config.mjs +4 -0
  169. package/dist/runtime/context.d.mts +1 -0
  170. package/dist/runtime/context.mjs +1 -0
  171. package/dist/runtime/database.d.mts +1 -0
  172. package/dist/runtime/database.mjs +1 -0
  173. package/dist/runtime/internal/app.d.mts +11 -1
  174. package/dist/runtime/internal/app.mjs +188 -140
  175. package/dist/runtime/internal/cache.d.mts +9 -5
  176. package/dist/runtime/internal/cache.mjs +248 -219
  177. package/dist/runtime/internal/context.d.mts +9 -9
  178. package/dist/runtime/internal/context.mjs +17 -10
  179. package/dist/runtime/internal/database.mjs +8 -10
  180. package/dist/runtime/internal/error/dev.d.mts +5 -4
  181. package/dist/runtime/internal/error/dev.mjs +106 -105
  182. package/dist/runtime/internal/error/hooks.d.mts +1 -0
  183. package/dist/runtime/internal/error/hooks.mjs +9 -0
  184. package/dist/runtime/internal/error/prod.d.mts +5 -4
  185. package/dist/runtime/internal/error/prod.mjs +51 -59
  186. package/dist/runtime/internal/error/utils.d.mts +4 -4
  187. package/dist/runtime/internal/error/utils.mjs +1 -1
  188. package/dist/runtime/internal/meta.d.mts +1 -1
  189. package/dist/runtime/internal/meta.mjs +1 -1
  190. package/dist/runtime/internal/plugin.d.mts +2 -2
  191. package/dist/runtime/internal/plugin.mjs +1 -1
  192. package/dist/runtime/internal/route-rules.d.mts +8 -8
  193. package/dist/runtime/internal/route-rules.mjs +54 -52
  194. package/dist/runtime/internal/routes/dev-tasks.d.mts +1 -2
  195. package/dist/runtime/internal/routes/dev-tasks.mjs +16 -18
  196. package/dist/runtime/internal/routes/openapi.d.mts +1 -0
  197. package/dist/runtime/internal/routes/openapi.mjs +81 -87
  198. package/dist/runtime/internal/routes/renderer-template.d.mts +1 -1
  199. package/dist/runtime/internal/routes/renderer-template.dev.d.mts +1 -2
  200. package/dist/runtime/internal/routes/renderer-template.dev.mjs +15 -17
  201. package/dist/runtime/internal/routes/renderer-template.mjs +1 -1
  202. package/dist/runtime/internal/routes/scalar.d.mts +1 -0
  203. package/dist/runtime/internal/routes/scalar.mjs +22 -23
  204. package/dist/runtime/internal/routes/swagger.d.mts +1 -0
  205. package/dist/runtime/internal/routes/swagger.mjs +9 -11
  206. package/dist/runtime/internal/runtime-config.d.mts +4 -4
  207. package/dist/runtime/internal/runtime-config.mjs +40 -35
  208. package/dist/runtime/internal/static.mjs +63 -74
  209. package/dist/runtime/internal/storage.mjs +2 -2
  210. package/dist/runtime/internal/task.d.mts +6 -6
  211. package/dist/runtime/internal/task.mjs +56 -60
  212. package/dist/runtime/internal/vite/dev-entry.mjs +11 -1
  213. package/dist/runtime/internal/vite/dev-worker.mjs +9 -57
  214. package/dist/runtime/internal/vite/ssr-renderer.mjs +3 -1
  215. package/{lib/runtime-meta.d.mts → dist/runtime/meta.d.mts} +1 -1
  216. package/dist/runtime/meta.mjs +26 -0
  217. package/dist/runtime/nitro.d.mts +12 -0
  218. package/dist/runtime/nitro.mjs +32 -0
  219. package/dist/runtime/runtime-config.d.mts +1 -0
  220. package/dist/runtime/runtime-config.mjs +1 -0
  221. package/dist/runtime/storage.d.mts +1 -0
  222. package/dist/runtime/storage.mjs +1 -0
  223. package/dist/runtime/task.d.mts +1 -0
  224. package/dist/runtime/task.mjs +1 -0
  225. package/dist/runtime/vite-runtime.d.mts +8 -0
  226. package/dist/runtime/vite-runtime.mjs +9 -0
  227. package/dist/types/index.d.mts +2625 -2297
  228. package/dist/types/index.mjs +1 -1
  229. package/dist/vite.d.mts +49 -51
  230. package/dist/vite.mjs +44 -68
  231. package/lib/tsconfig.json +27 -0
  232. package/package.json +86 -76
  233. package/dist/_chunks/app.mjs +0 -19797
  234. package/dist/_chunks/build.mjs +0 -84
  235. package/dist/_chunks/build2.mjs +0 -318
  236. package/dist/_chunks/build3.mjs +0 -6452
  237. package/dist/_chunks/detect-acorn.mjs +0 -503
  238. package/dist/_chunks/index.mjs +0 -22242
  239. package/dist/_chunks/index2.mjs +0 -297
  240. package/dist/_chunks/index3.mjs +0 -1058
  241. package/dist/_chunks/index4.mjs +0 -1206
  242. package/dist/_chunks/info.mjs +0 -11157
  243. package/dist/_chunks/json5.mjs +0 -68
  244. package/dist/_chunks/jsonc.mjs +0 -51
  245. package/dist/_chunks/pathe.M-eThtNZ.mjs +0 -204
  246. package/dist/_chunks/plugin.mjs +0 -960
  247. package/dist/_chunks/server.mjs +0 -254
  248. package/dist/_chunks/snapshot.mjs +0 -284
  249. package/dist/_chunks/toml.mjs +0 -259
  250. package/dist/_chunks/yaml.mjs +0 -86
  251. package/dist/cli/build.mjs +0 -54
  252. package/dist/cli/common.mjs +0 -13
  253. package/dist/cli/dev.mjs +0 -95
  254. package/dist/cli/index2.mjs +0 -17
  255. package/dist/cli/list.mjs +0 -34
  256. package/dist/cli/prepare.mjs +0 -24
  257. package/dist/cli/run.mjs +0 -60
  258. package/dist/index.d.mts +0 -52
  259. package/dist/index.mjs +0 -55
  260. package/dist/node_modules/cookie/dist/index.js +0 -239
  261. package/dist/node_modules/cookie/package.json +0 -42
  262. package/dist/node_modules/klona/dist/index.mjs +0 -81
  263. package/dist/node_modules/klona/full/index.mjs +0 -53
  264. package/dist/node_modules/klona/package.json +0 -74
  265. package/dist/node_modules/std-env/dist/index.mjs +0 -1
  266. package/dist/node_modules/std-env/package.json +0 -46
  267. package/dist/presets/vercel/runtime/vercel.mjs +0 -17
  268. package/dist/presets.mjs +0 -2460
  269. package/dist/runtime/index.d.mts +0 -11
  270. package/dist/runtime/index.mjs +0 -17
  271. package/dist/runtime/internal/debug.d.mts +0 -2
  272. package/dist/runtime/internal/debug.mjs +0 -5
  273. package/dist/runtime/internal/empty.d.mts +0 -0
  274. package/dist/runtime/internal/index.d.mts +0 -3
  275. package/dist/runtime/internal/index.mjs +0 -3
  276. package/dist/runtime/internal/lib/http-graceful-shutdown.d.mts +0 -16
  277. package/dist/runtime/internal/lib/http-graceful-shutdown.mjs +0 -213
  278. package/dist/runtime/internal/renderer.d.mts +0 -3
  279. package/dist/runtime/internal/renderer.mjs +0 -36
  280. package/dist/runtime/internal/shutdown.d.mts +0 -9
  281. package/dist/runtime/internal/shutdown.mjs +0 -34
  282. package/dist/runtime/internal/utils.d.mts +0 -1
  283. package/dist/runtime/internal/utils.mjs +0 -15
  284. package/dist/runtime/internal/vite/dev-entry.d.mts +0 -1
  285. package/dist/runtime/internal/vite/dev-worker.d.mts +0 -1
  286. package/dist/runtime/internal/vite/prod-setup.d.mts +0 -4
  287. package/dist/runtime/internal/vite/prod-setup.mjs +0 -55
  288. package/dist/runtime/internal/vite/ssr-renderer.d.mts +0 -4
  289. package/lib/config.d.mts +0 -9
  290. package/lib/config.mjs +0 -5
  291. package/lib/meta.d.mts +0 -5
  292. package/lib/meta.mjs +0 -21
  293. package/lib/runtime-meta.mjs +0 -38
@@ -0,0 +1,768 @@
1
+ import { C as isAbsolute$1, O as relative$1, T as normalize$1, b as basename$1, h as resolveModulePath, k as resolve$1, n as debounce, w as join$1, x as dirname$1 } from "../_libs/c12.mjs";
2
+ import { f as sanitizeFilePath } from "../_libs/local-pkg.mjs";
3
+ import { t as formatCompatibilityDate } from "../_libs/compatx.mjs";
4
+ import { n as T, r as a } from "../_libs/std-env.mjs";
5
+ import { a as createNitro, n as prepare, r as copyPublicAssets } from "../_chunks/B-D1JOIz.mjs";
6
+ import { n as prettyPath } from "../_chunks/C7CbzoI1.mjs";
7
+ import { i as scanHandlers } from "../_chunks/ANM1K1bE.mjs";
8
+ import { n as writeBuildInfo, t as getBuildInfo } from "./common.mjs";
9
+ import { i as NodeDevWorker, r as NitroDevApp } from "../_dev.mjs";
10
+ import { i as watch$1 } from "../_libs/chokidar.mjs";
11
+ import { t as alias } from "../_libs/plugin-alias.mjs";
12
+ import { t as inject } from "../_libs/plugin-inject.mjs";
13
+ import { n as baseBuildConfig, t as baseBuildPlugins } from "./common2.mjs";
14
+ import { t as assetsPlugin } from "../_libs/vite-plugin-fullstack.mjs";
15
+ import consola$1 from "consola";
16
+ import { join, resolve } from "node:path";
17
+ import { existsSync, watch } from "node:fs";
18
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
19
+ import { defu } from "defu";
20
+ import { runtimeDependencies, runtimeDir } from "nitro/meta";
21
+ import { colors } from "consola/utils";
22
+ import { NodeRequest, sendNodeResponse } from "srvx/node";
23
+ import { DevEnvironment } from "vite";
24
+ import { spawn } from "node:child_process";
25
+
26
+ //#region src/build/vite/rollup.ts
27
+ /**
28
+ * Removed from base rollup config:
29
+ * - nodeResolve
30
+ * - commonjs
31
+ * - esbuild
32
+ * - sourcemapMinify
33
+ * - json
34
+ * - raw
35
+ *
36
+ * TODO: Reuse with rollup:
37
+ * - chunkFileNames
38
+ * - moduleSideEffects
39
+ */
40
+ const getViteRollupConfig = (ctx) => {
41
+ const nitro$1 = ctx.nitro;
42
+ const base = baseBuildConfig(nitro$1);
43
+ const chunkNamePrefixes = [
44
+ [runtimeDir, "nitro"],
45
+ [base.presetsDir, "nitro"],
46
+ ["\0nitro-wasm:", "wasm"],
47
+ ["\0", "virtual"]
48
+ ];
49
+ function getChunkGroup(id) {
50
+ if (id.startsWith(runtimeDir) || id.startsWith(base.presetsDir)) return "nitro";
51
+ }
52
+ let config = {
53
+ input: nitro$1.options.entry,
54
+ external: [...base.env.external],
55
+ plugins: [
56
+ ctx.pluginConfig.experimental?.vite?.virtualBundle && virtualBundlePlugin(ctx._serviceBundles),
57
+ ...baseBuildPlugins(nitro$1, base),
58
+ alias({ entries: base.aliases }),
59
+ !ctx._isRolldown && inject(base.env.inject)
60
+ ].filter(Boolean),
61
+ ...ctx._isRolldown ? { transform: { inject: base.env.inject } } : {},
62
+ treeshake: { moduleSideEffects(id) {
63
+ return nitro$1.options.moduleSideEffects.some((p) => id.startsWith(p));
64
+ } },
65
+ output: {
66
+ dir: nitro$1.options.output.serverDir,
67
+ entryFileNames: "index.mjs",
68
+ chunkFileNames(chunk) {
69
+ const id = normalize$1(chunk.moduleIds.at(-1) || "");
70
+ for (const [dir, name] of chunkNamePrefixes) if (id.startsWith(dir)) return `chunks/${name}/[name].mjs`;
71
+ const routeHandler = nitro$1.options.handlers.find((h) => id.startsWith(h.handler)) || nitro$1.scannedHandlers.find((h) => id.startsWith(h.handler));
72
+ if (routeHandler?.route) return `chunks/routes/${routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "").replace(/[^a-zA-Z0-9/_-]/g, "_") || "/"}/[name].mjs`.replace(/\/+/g, "/");
73
+ if (Object.entries(nitro$1.options.tasks).find(([_, task]) => task.handler === id)) return `chunks/tasks/[name].mjs`;
74
+ return `chunks/_/[name].mjs`;
75
+ },
76
+ manualChunks(id) {
77
+ return getChunkGroup(id);
78
+ },
79
+ inlineDynamicImports: nitro$1.options.inlineDynamicImports,
80
+ format: "esm",
81
+ exports: "auto",
82
+ intro: "",
83
+ outro: "",
84
+ generatedCode: { ...ctx._isRolldown ? {} : { constBindings: true } },
85
+ sanitizeFileName: sanitizeFilePath,
86
+ ...ctx._isRolldown ? {} : { sourcemapExcludeSources: true },
87
+ sourcemapIgnoreList(relativePath) {
88
+ return relativePath.includes("node_modules");
89
+ }
90
+ }
91
+ };
92
+ config = defu(nitro$1.options.rollupConfig, config);
93
+ if (config.output.inlineDynamicImports) delete config.output.manualChunks;
94
+ return {
95
+ config,
96
+ base
97
+ };
98
+ };
99
+ function virtualBundlePlugin(bundles) {
100
+ let _modules = null;
101
+ const getModules = () => {
102
+ if (_modules) return _modules;
103
+ _modules = /* @__PURE__ */ new Map();
104
+ for (const bundle of Object.values(bundles)) for (const [fileName, content] of Object.entries(bundle)) if (content.type === "chunk") {
105
+ const virtualModule = {
106
+ code: content.code,
107
+ map: null
108
+ };
109
+ const maybeMap = bundle[`${fileName}.map`];
110
+ if (maybeMap && maybeMap.type === "asset") virtualModule.map = maybeMap.source;
111
+ _modules.set(fileName, virtualModule);
112
+ _modules.set(resolve$1(fileName), virtualModule);
113
+ }
114
+ return _modules;
115
+ };
116
+ return {
117
+ name: "virtual-bundle",
118
+ resolveId(id, importer) {
119
+ const modules = getModules();
120
+ if (modules.has(id)) return resolve$1(id);
121
+ if (importer) {
122
+ const resolved = resolve$1(dirname$1(importer), id);
123
+ if (modules.has(resolved)) return resolved;
124
+ }
125
+ return null;
126
+ },
127
+ load(id) {
128
+ const m = getModules().get(id);
129
+ if (!m) return null;
130
+ return m;
131
+ }
132
+ };
133
+ }
134
+
135
+ //#endregion
136
+ //#region src/build/vite/prod.ts
137
+ const BuilderNames = {
138
+ nitro: colors.magenta("Nitro"),
139
+ client: colors.green("Client"),
140
+ ssr: colors.blue("SSR")
141
+ };
142
+ async function buildEnvironments(ctx, builder) {
143
+ const nitro$1 = ctx.nitro;
144
+ for (const [envName, env] of Object.entries(builder.environments)) {
145
+ const fmtName = BuilderNames[envName] || (envName.length <= 3 ? envName.toUpperCase() : envName[0].toUpperCase() + envName.slice(1));
146
+ if (envName === "nitro" || !env.config.build.rollupOptions.input || env.isBuilt) {
147
+ if (![
148
+ "nitro",
149
+ "ssr",
150
+ "client"
151
+ ].includes(envName)) nitro$1.logger.info(env.isBuilt ? `Skipping ${fmtName} (already built)` : `Skipping ${fmtName} (no input defined)`);
152
+ continue;
153
+ }
154
+ if (!a && !T) console.log();
155
+ nitro$1.logger.start(`Building [${fmtName}]`);
156
+ await builder.build(env);
157
+ }
158
+ const nitroOptions = ctx.nitro.options;
159
+ const clientInput = builder.environments.client?.config?.build?.rollupOptions?.input;
160
+ if (nitroOptions.renderer?.template && nitroOptions.renderer?.template === clientInput) {
161
+ const outputPath = resolve$1(nitroOptions.output.publicDir, basename$1(clientInput));
162
+ if (existsSync(outputPath)) {
163
+ const html = await readFile(outputPath, "utf8").then((r) => r.replace("<!--ssr-outlet-->", `{{{ globalThis.__nitro_vite_envs__?.["ssr"]?.fetch($REQUEST) || "" }}}`));
164
+ await rm(outputPath);
165
+ const tmp = resolve$1(nitroOptions.buildDir, "vite/index.html");
166
+ await mkdir(dirname$1(tmp), { recursive: true });
167
+ await writeFile(tmp, html, "utf8");
168
+ nitroOptions.renderer.template = tmp;
169
+ }
170
+ }
171
+ await builder.writeAssetsManifest?.();
172
+ if (!a && !T) console.log();
173
+ const buildInfo = [["preset", nitro$1.options.preset], ["compatibility", formatCompatibilityDate(nitro$1.options.compatibilityDate)]].filter((e) => e[1]);
174
+ nitro$1.logger.start(`Building [${BuilderNames.nitro}] ${colors.dim(`(${buildInfo.map(([k, v]) => `${k}: \`${v}\``).join(", ")})`)}`);
175
+ await copyPublicAssets(nitro$1);
176
+ const assetDirs = new Set(Object.values(builder.environments).filter((env) => env.config.consumer === "client").map((env) => env.config.build.assetsDir).filter(Boolean));
177
+ for (const assetsDir of assetDirs) {
178
+ if (!existsSync(resolve$1(nitro$1.options.output.publicDir, assetsDir))) continue;
179
+ const rule = ctx.nitro.options.routeRules[`/${assetsDir}/**`] ??= {};
180
+ if (!rule.headers?.["cache-control"]) rule.headers = {
181
+ ...rule.headers,
182
+ "cache-control": `public, max-age=31536000, immutable`
183
+ };
184
+ }
185
+ ctx.nitro.routing.sync();
186
+ await builder.build(builder.environments.nitro);
187
+ await nitro$1.close();
188
+ await nitro$1.hooks.callHook("compiled", nitro$1);
189
+ await writeBuildInfo(nitro$1);
190
+ const rOutput = relative$1(process.cwd(), nitro$1.options.output.dir);
191
+ const rewriteRelativePaths = (input) => {
192
+ return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`);
193
+ };
194
+ if (!a && !T) console.log();
195
+ if (nitro$1.options.commands.preview) nitro$1.logger.success(`You can preview this build using \`${rewriteRelativePaths(nitro$1.options.commands.preview)}\``);
196
+ if (nitro$1.options.commands.deploy) nitro$1.logger.success(`You can deploy this build using \`${rewriteRelativePaths(nitro$1.options.commands.deploy)}\``);
197
+ }
198
+ function prodSetup(ctx) {
199
+ return `
200
+ function lazyService(loader) {
201
+ let promise, mod
202
+ return {
203
+ fetch(req) {
204
+ if (mod) { return mod.fetch(req) }
205
+ if (!promise) {
206
+ promise = loader().then(_mod => (mod = _mod.default || _mod))
207
+ }
208
+ return promise.then(mod => mod.fetch(req))
209
+ }
210
+ }
211
+ }
212
+
213
+ const services = {
214
+ ${Object.keys(ctx.services).map((name) => {
215
+ let entry;
216
+ if (ctx.pluginConfig.experimental?.vite?.virtualBundle) entry = ctx._entryPoints[name];
217
+ else entry = resolve$1(ctx.nitro.options.buildDir, "vite/services", name, ctx._entryPoints[name]);
218
+ return [name, entry];
219
+ }).map(([name, entry]) => `[${JSON.stringify(name)}]: lazyService(() => import(${JSON.stringify(entry)}))`).join(",\n")}
220
+ };
221
+
222
+ globalThis.__nitro_vite_envs__ = services;
223
+ `;
224
+ }
225
+
226
+ //#endregion
227
+ //#region src/build/vite/dev.ts
228
+ function createFetchableDevEnvironment(name, config, devServer, entry) {
229
+ return new FetchableDevEnvironment(name, config, {
230
+ hot: true,
231
+ transport: createTransport(name, devServer)
232
+ }, devServer, entry);
233
+ }
234
+ var FetchableDevEnvironment = class extends DevEnvironment {
235
+ devServer;
236
+ constructor(name, config, context, devServer, entry) {
237
+ super(name, config, context);
238
+ this.devServer = devServer;
239
+ this.devServer.sendMessage({
240
+ type: "custom",
241
+ event: "nitro:vite-env",
242
+ data: {
243
+ name,
244
+ entry
245
+ }
246
+ });
247
+ }
248
+ async dispatchFetch(request) {
249
+ return this.devServer.fetch(request);
250
+ }
251
+ async init(...args) {
252
+ await this.devServer.init?.();
253
+ return super.init(...args);
254
+ }
255
+ };
256
+ function createTransport(name, hooks) {
257
+ const listeners = /* @__PURE__ */ new WeakMap();
258
+ return {
259
+ send: (data) => hooks.sendMessage({
260
+ ...data,
261
+ viteEnv: name
262
+ }),
263
+ on: (event, handler) => {
264
+ if (event === "connection") return;
265
+ const listener = (value) => {
266
+ if (value?.type === "custom" && value.event === event && value.viteEnv === name) handler(value.data, { send: (payload) => hooks.sendMessage({
267
+ ...payload,
268
+ viteEnv: name
269
+ }) });
270
+ };
271
+ listeners.set(handler, listener);
272
+ hooks.onMessage(listener);
273
+ },
274
+ off: (event, handler) => {
275
+ if (event === "connection") return;
276
+ const listener = listeners.get(handler);
277
+ if (listener) {
278
+ hooks.offMessage(listener);
279
+ listeners.delete(handler);
280
+ }
281
+ }
282
+ };
283
+ }
284
+ async function configureViteDevServer(ctx, server) {
285
+ const nitro$1 = ctx.nitro;
286
+ const nitroEnv$1 = server.environments.nitro;
287
+ const nitroConfigFile = nitro$1.options._c12.configFile;
288
+ if (nitroConfigFile) server.config.configFileDependencies.push(nitroConfigFile);
289
+ if (nitro$1.options.features.websocket ?? nitro$1.options.experimental.websocket) server.httpServer.on("upgrade", (req, socket, head) => {
290
+ if (req.url?.startsWith("/?token")) return;
291
+ ctx.devWorker?.upgrade(req, socket, head);
292
+ });
293
+ const reload = debounce(async () => {
294
+ await scanHandlers(nitro$1);
295
+ nitro$1.routing.sync();
296
+ nitroEnv$1.moduleGraph.invalidateAll();
297
+ nitroEnv$1.hot.send({ type: "full-reload" });
298
+ });
299
+ const scanDirs = nitro$1.options.scanDirs.flatMap((dir) => [
300
+ join$1(dir, nitro$1.options.apiDir || "api"),
301
+ join$1(dir, nitro$1.options.routesDir || "routes"),
302
+ join$1(dir, "middleware"),
303
+ join$1(dir, "plugins"),
304
+ join$1(dir, "modules")
305
+ ]);
306
+ const watchReloadEvents = new Set([
307
+ "add",
308
+ "addDir",
309
+ "unlink",
310
+ "unlinkDir"
311
+ ]);
312
+ const scanDirsWatcher = watch$1(scanDirs, { ignoreInitial: true }).on("all", (event, path$1, stat$1) => {
313
+ if (watchReloadEvents.has(event)) reload();
314
+ });
315
+ const rootDirWatcher = watch(nitro$1.options.rootDir, { persistent: false }, (_event, filename) => {
316
+ if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) reload();
317
+ });
318
+ nitro$1.hooks.hook("close", () => {
319
+ scanDirsWatcher.close();
320
+ rootDirWatcher.close();
321
+ });
322
+ const hostIPC = { async transformHTML(html) {
323
+ return server.transformIndexHtml("/", html).then((r) => r.replace("<!--ssr-outlet-->", `{{{ globalThis.__nitro_vite_envs__?.["ssr"]?.fetch($REQUEST) || "" }}}`));
324
+ } };
325
+ nitroEnv$1.devServer.onMessage(async (payload) => {
326
+ if (payload.type === "custom" && payload.event === "nitro:vite-invoke") {
327
+ const res = await hostIPC[payload.data.name](payload.data.data).then((data) => ({ data })).catch((error) => ({ error }));
328
+ nitroEnv$1.devServer.sendMessage({
329
+ type: "custom",
330
+ event: "nitro:vite-invoke-response",
331
+ data: {
332
+ id: payload.data.id,
333
+ data: res
334
+ }
335
+ });
336
+ }
337
+ });
338
+ const nitroDevMiddleware = async (nodeReq, nodeRes, next) => {
339
+ if (/^\/@(?:vite|fs|id)\//.test(nodeReq.url) || nodeReq._nitroHandled) return next();
340
+ nodeReq._nitroHandled = true;
341
+ const req = new NodeRequest({
342
+ req: nodeReq,
343
+ res: nodeRes
344
+ });
345
+ const devAppRes = await ctx.devApp.fetch(req);
346
+ if (nodeRes.writableEnded || nodeRes.headersSent) return;
347
+ if (devAppRes.status !== 404) return await sendNodeResponse(nodeRes, devAppRes);
348
+ const envRes = await nitroEnv$1.dispatchFetch(req);
349
+ if (nodeRes.writableEnded || nodeRes.headersSent) return;
350
+ if (envRes.status !== 404) return await sendNodeResponse(nodeRes, envRes);
351
+ return next();
352
+ };
353
+ server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) {
354
+ const fetchDest = req.headers["sec-fetch-dest"];
355
+ if (fetchDest) res.setHeader("vary", "sec-fetch-dest");
356
+ if (!((req.url || "").match(/\.([a-z0-9]+)(?:[?#]|$)/i)?.[1] || "") && (!fetchDest || /^(document|iframe|frame|empty)$/.test(fetchDest))) nitroDevMiddleware(req, res, next);
357
+ else next();
358
+ });
359
+ return () => {
360
+ server.middlewares.use(nitroDevMiddleware);
361
+ };
362
+ }
363
+
364
+ //#endregion
365
+ //#region src/build/vite/env.ts
366
+ function createDevWorker(ctx) {
367
+ return new NodeDevWorker({
368
+ name: "nitro-vite",
369
+ entry: resolve(runtimeDir, "internal/vite/dev-worker.mjs"),
370
+ hooks: {},
371
+ data: {
372
+ server: true,
373
+ globals: { __NITRO_RUNTIME_CONFIG__: ctx.nitro.options.runtimeConfig }
374
+ }
375
+ });
376
+ }
377
+ function createNitroEnvironment(ctx) {
378
+ return {
379
+ consumer: "server",
380
+ build: {
381
+ rollupOptions: ctx.rollupConfig.config,
382
+ minify: ctx.nitro.options.minify,
383
+ emptyOutDir: false,
384
+ sourcemap: ctx.nitro.options.sourcemap,
385
+ commonjsOptions: { ...ctx.nitro.options.commonJS }
386
+ },
387
+ resolve: {
388
+ noExternal: ctx.nitro.options.dev ? [...ctx.rollupConfig.base.noExternal, ...runtimeDependencies] : true,
389
+ conditions: ctx.nitro.options.exportConditions,
390
+ externalConditions: ctx.nitro.options.exportConditions
391
+ },
392
+ dev: { createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(envName, envConfig, ctx.devWorker, resolve(runtimeDir, "internal/vite/dev-entry.mjs")) }
393
+ };
394
+ }
395
+ function createServiceEnvironment(ctx, name, serviceConfig) {
396
+ return {
397
+ consumer: "server",
398
+ build: {
399
+ rollupOptions: { input: serviceConfig.entry },
400
+ minify: ctx.nitro.options.minify,
401
+ sourcemap: ctx.nitro.options.sourcemap,
402
+ outDir: join(ctx.nitro.options.buildDir, "vite/services", name),
403
+ emptyOutDir: true
404
+ },
405
+ resolve: {
406
+ conditions: ctx.nitro.options.exportConditions,
407
+ externalConditions: ctx.nitro.options.exportConditions
408
+ },
409
+ dev: { createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(envName, envConfig, ctx.devWorker, tryResolve(serviceConfig.entry)) }
410
+ };
411
+ }
412
+ function createServiceEnvironments(ctx) {
413
+ return Object.fromEntries(Object.entries(ctx.services).map(([name, config]) => [name, createServiceEnvironment(ctx, name, config)]));
414
+ }
415
+ function tryResolve(id) {
416
+ if (/^[~#/\0]/.test(id) || isAbsolute$1(id)) return id;
417
+ return resolveModulePath(id, {
418
+ suffixes: ["", "/index"],
419
+ extensions: [
420
+ "",
421
+ ".ts",
422
+ ".mjs",
423
+ ".cjs",
424
+ ".js",
425
+ ".mts",
426
+ ".cts"
427
+ ],
428
+ try: true
429
+ }) || id;
430
+ }
431
+
432
+ //#endregion
433
+ //#region src/build/vite/preview.ts
434
+ function nitroPreviewPlugin(ctx) {
435
+ return {
436
+ name: "nitro:preview",
437
+ apply: (_config, configEnv) => !!configEnv.isPreview,
438
+ config(config) {
439
+ return { preview: { port: config.preview?.port || 3e3 } };
440
+ },
441
+ async configurePreviewServer(server) {
442
+ const { outputDir, buildInfo } = await getBuildInfo(server.config.root);
443
+ if (!buildInfo) throw this.error("Cannot load nitro build info. Make sure to build first.");
444
+ const info = [
445
+ ["Build Directory:", prettyPath(outputDir)],
446
+ ["Date:", buildInfo.date && new Date(buildInfo.date).toLocaleString()],
447
+ ["Nitro Version:", buildInfo.versions.nitro],
448
+ ["Nitro Preset:", buildInfo.preset],
449
+ buildInfo.framework?.name !== "nitro" && ["Framework:", buildInfo.framework?.name + (buildInfo.framework?.version ? ` (v${buildInfo.framework.version})` : "")]
450
+ ].filter((i) => i && i[1]);
451
+ consola$1.box({
452
+ title: " [Build Info] ",
453
+ message: info.map((i) => `- ${i[0]} ${i[1]}`).join("\n")
454
+ });
455
+ if (!buildInfo.commands?.preview) {
456
+ consola$1.warn("No nitro build preview command found for this preset.");
457
+ return;
458
+ }
459
+ const dotEnvEntries = await loadPreviewDotEnv(server.config.root);
460
+ if (dotEnvEntries.length > 0) consola$1.box({
461
+ title: " [Environment Variables] ",
462
+ message: [
463
+ "Loaded variables from .env files (preview mode only).",
464
+ "Set platform environment variables for production:",
465
+ ...dotEnvEntries.map(([key, val]) => ` - ${key}`)
466
+ ].join("\n")
467
+ });
468
+ const [command, ...args] = buildInfo.commands.preview.split(" ");
469
+ consola$1.info(`Spawning preview server...`);
470
+ consola$1.info(buildInfo.commands?.preview);
471
+ console.log("");
472
+ const { getRandomPort } = await import("get-port-please");
473
+ const randomPort = await getRandomPort();
474
+ const child = spawn(command, args, {
475
+ stdio: "inherit",
476
+ cwd: outputDir,
477
+ env: {
478
+ ...process.env,
479
+ ...Object.fromEntries(dotEnvEntries),
480
+ PORT: String(randomPort)
481
+ }
482
+ });
483
+ for (const sig of ["SIGINT", "SIGHUP"]) process.once(sig, () => {
484
+ consola$1.info(`Stopping preview server...`);
485
+ if (child.killed === false) {
486
+ child.kill(sig);
487
+ process.exit();
488
+ }
489
+ });
490
+ child.on("exit", (code) => {
491
+ if (code && code !== 0) consola$1.error(`[nitro] Preview server exited with code ${code}`);
492
+ });
493
+ const { createProxyServer } = await import("../cli/_chunks/dist3.mjs");
494
+ const proxy = createProxyServer({ target: `http://localhost:${randomPort}` });
495
+ server.middlewares.use((req, res, next) => {
496
+ if (child && !child.killed) proxy.web(req, res).catch(next);
497
+ else res.end(`Nitro preview server is not running.`);
498
+ });
499
+ }
500
+ };
501
+ }
502
+ async function loadPreviewDotEnv(root) {
503
+ const { loadDotenv } = await import("../cli/_chunks/dist2.mjs");
504
+ const env = await loadDotenv({
505
+ cwd: root,
506
+ fileName: [
507
+ ".env.preview",
508
+ ".env.production",
509
+ ".env"
510
+ ]
511
+ });
512
+ return Object.entries(env).filter(([_key, val]) => val);
513
+ }
514
+
515
+ //#endregion
516
+ //#region src/build/vite/plugin.ts
517
+ const DEFAULT_EXTENSIONS = [
518
+ ".ts",
519
+ ".js",
520
+ ".mts",
521
+ ".mjs",
522
+ ".tsx",
523
+ ".jsx"
524
+ ];
525
+ const debug = process.env.NITRO_DEBUG ? (...args) => console.log("[nitro]", ...args) : () => {};
526
+ function nitro(pluginConfig = {}) {
527
+ const ctx = createContext(pluginConfig);
528
+ return [
529
+ nitroInit(ctx),
530
+ nitroEnv(ctx),
531
+ nitroMain(ctx),
532
+ nitroPrepare(ctx),
533
+ nitroService(ctx),
534
+ nitroPreviewPlugin(ctx),
535
+ pluginConfig.experimental?.vite?.assetsImport !== false && assetsPlugin({ experimental: { clientBuildFallback: false } })
536
+ ].filter(Boolean);
537
+ }
538
+ function nitroInit(ctx) {
539
+ return {
540
+ name: "nitro:init",
541
+ sharedDuringBuild: true,
542
+ apply: (_config, configEnv) => !configEnv.isPreview,
543
+ async config(config, configEnv) {
544
+ ctx._isRolldown = !!this.meta.rolldownVersion;
545
+ if (!ctx._initialized) {
546
+ debug("[init] Initializing nitro");
547
+ ctx._initialized = true;
548
+ await setupNitroContext(ctx, configEnv, config);
549
+ }
550
+ },
551
+ applyToEnvironment(env) {
552
+ if (env.name === "nitro" && ctx.nitro?.options.dev) {
553
+ debug("[init] Adding rollup plugins for dev");
554
+ return [...ctx.rollupConfig?.config.plugins || []];
555
+ }
556
+ }
557
+ };
558
+ }
559
+ function nitroEnv(ctx) {
560
+ return {
561
+ name: "nitro:env",
562
+ sharedDuringBuild: true,
563
+ apply: (_config, configEnv) => !configEnv.isPreview,
564
+ async config(userConfig, _configEnv) {
565
+ debug("[env] Extending config (environments)");
566
+ const environments = {
567
+ ...createServiceEnvironments(ctx),
568
+ nitro: createNitroEnvironment(ctx)
569
+ };
570
+ environments.client = {
571
+ consumer: userConfig.environments?.client?.consumer ?? "client",
572
+ build: { rollupOptions: { input: userConfig.environments?.client?.build?.rollupOptions?.input ?? useNitro(ctx).options.renderer?.template } }
573
+ };
574
+ debug("[env] Environments:", Object.keys(environments).join(", "));
575
+ return { environments };
576
+ },
577
+ configEnvironment(name, config) {
578
+ if (config.consumer === "client") {
579
+ debug("[env] Configuring client environment", name === "client" ? "" : ` (${name})`);
580
+ config.build.emptyOutDir = false;
581
+ config.build.outDir = useNitro(ctx).options.output.publicDir;
582
+ } else if (ctx.pluginConfig.experimental?.vite?.virtualBundle && name in (ctx.services || {})) {
583
+ debug("[env] Configuring service environment for virtual:", name);
584
+ config.build ??= {};
585
+ config.build.write = config.build.write ?? false;
586
+ }
587
+ }
588
+ };
589
+ }
590
+ function nitroMain(ctx) {
591
+ return {
592
+ name: "nitro:main",
593
+ sharedDuringBuild: true,
594
+ apply: (_config, configEnv) => !configEnv.isPreview,
595
+ async config(userConfig, _configEnv) {
596
+ debug("[main] Extending config (appType, resolve, server)");
597
+ if (!ctx.rollupConfig) throw new Error("Nitro rollup config is not initialized yet.");
598
+ return {
599
+ appType: userConfig.appType || "custom",
600
+ resolve: { alias: ctx.rollupConfig.base.aliases },
601
+ builder: { sharedConfigBuild: true },
602
+ experimental: { enableNativePlugin: false },
603
+ server: {
604
+ port: Number.parseInt(process.env.PORT || "") || userConfig.server?.port || useNitro(ctx).options.devServer?.port || 3e3,
605
+ cors: false
606
+ }
607
+ };
608
+ },
609
+ buildApp: {
610
+ order: "post",
611
+ handler(builder) {
612
+ debug("[main] Building environments");
613
+ return buildEnvironments(ctx, builder);
614
+ }
615
+ },
616
+ generateBundle: { handler(_options, bundle) {
617
+ const environment = this.environment;
618
+ debug("[main] Generating manifest and entry points for environment:", environment.name);
619
+ const isRegisteredService = Object.keys(ctx.services).includes(environment.name);
620
+ let entryFile;
621
+ for (const [_name, file] of Object.entries(bundle)) if (file.type === "chunk" && isRegisteredService && file.isEntry) if (entryFile === void 0) entryFile = file.fileName;
622
+ else this.warn(`Multiple entry points found for service "${environment.name}"`);
623
+ if (isRegisteredService) {
624
+ if (entryFile === void 0) this.error(`No entry point found for service "${this.environment.name}".`);
625
+ ctx._entryPoints[this.environment.name] = entryFile;
626
+ ctx._serviceBundles[this.environment.name] = bundle;
627
+ }
628
+ } },
629
+ configureServer: (server) => {
630
+ debug("[main] Configuring dev server");
631
+ return configureViteDevServer(ctx, server);
632
+ },
633
+ async hotUpdate({ server, modules, timestamp }) {
634
+ const env = this.environment;
635
+ if (ctx.pluginConfig.experimental?.vite.serverReload === false || env.config.consumer === "client") return;
636
+ const clientEnvs = Object.values(server.environments).filter((env$1) => env$1.config.consumer === "client");
637
+ let hasServerOnlyModule = false;
638
+ const invalidated = /* @__PURE__ */ new Set();
639
+ for (const mod of modules) if (mod.id && !clientEnvs.some((env$1) => env$1.moduleGraph.getModuleById(mod.id))) {
640
+ hasServerOnlyModule = true;
641
+ env.moduleGraph.invalidateModule(mod, invalidated, timestamp, false);
642
+ }
643
+ if (hasServerOnlyModule) {
644
+ env.hot.send({ type: "full-reload" });
645
+ server.ws.send({ type: "full-reload" });
646
+ return [];
647
+ }
648
+ }
649
+ };
650
+ }
651
+ function nitroPrepare(ctx) {
652
+ return {
653
+ name: "nitro:prepare",
654
+ sharedDuringBuild: true,
655
+ applyToEnvironment: (env) => env.name === "nitro",
656
+ buildApp: {
657
+ order: "pre",
658
+ async handler() {
659
+ debug("[prepare] Preparing output directory");
660
+ const nitro$1 = ctx.nitro;
661
+ await prepare(nitro$1);
662
+ }
663
+ }
664
+ };
665
+ }
666
+ function nitroService(ctx) {
667
+ return {
668
+ name: "nitro:service",
669
+ enforce: "pre",
670
+ sharedDuringBuild: true,
671
+ applyToEnvironment: (env) => env.name === "nitro",
672
+ resolveId: { async handler(id) {
673
+ if (id === "#nitro-vite-setup") return {
674
+ id,
675
+ moduleSideEffects: true
676
+ };
677
+ } },
678
+ load: { async handler(id) {
679
+ if (id === "#nitro-vite-setup") return prodSetup(ctx);
680
+ } }
681
+ };
682
+ }
683
+ function createContext(pluginConfig) {
684
+ return {
685
+ pluginConfig,
686
+ services: {},
687
+ _entryPoints: {},
688
+ _serviceBundles: {}
689
+ };
690
+ }
691
+ function useNitro(ctx) {
692
+ if (!ctx.nitro) throw new Error("Nitro instance is not initialized yet.");
693
+ return ctx.nitro;
694
+ }
695
+ async function setupNitroContext(ctx, configEnv, userConfig) {
696
+ const nitroConfig = {
697
+ dev: configEnv.command === "serve",
698
+ rootDir: userConfig.root,
699
+ ...defu(ctx.pluginConfig, ctx.pluginConfig.config, userConfig.nitro)
700
+ };
701
+ nitroConfig.modules ??= [];
702
+ for (const plugin of flattenPlugins(userConfig.plugins || [])) if (plugin.nitro) nitroConfig.modules.push(plugin.nitro);
703
+ nitroConfig.builder = ctx._isRolldown ? "rolldown-vite" : "vite";
704
+ debug("[init] Using builder:", nitroConfig.builder);
705
+ ctx.nitro = ctx.pluginConfig._nitro || await createNitro(nitroConfig);
706
+ ctx.nitro.options.builder = ctx._isRolldown ? "rolldown-vite" : "vite";
707
+ if (!ctx.services?.ssr) if (userConfig.environments?.ssr === void 0) {
708
+ const ssrEntry = resolveModulePath("./entry-server", {
709
+ from: [
710
+ "app",
711
+ "src",
712
+ ""
713
+ ].flatMap((d) => [ctx.nitro.options.rootDir, ...ctx.nitro.options.scanDirs].map((s) => join$1(s, d) + "/")),
714
+ extensions: DEFAULT_EXTENSIONS,
715
+ try: true
716
+ });
717
+ if (ssrEntry) {
718
+ ctx.services.ssr = { entry: ssrEntry };
719
+ ctx.nitro.logger.info(`Using \`${prettyPath(ssrEntry)}\` as vite ssr entry.`);
720
+ }
721
+ } else {
722
+ let ssrEntry = getEntry(userConfig.environments.ssr.build?.rollupOptions?.input);
723
+ if (typeof ssrEntry === "string") {
724
+ ssrEntry = resolveModulePath(ssrEntry, {
725
+ from: [ctx.nitro.options.rootDir, ...ctx.nitro.options.scanDirs],
726
+ extensions: DEFAULT_EXTENSIONS,
727
+ suffixes: ["", "/index"],
728
+ try: true
729
+ }) || ssrEntry;
730
+ ctx.services.ssr = { entry: ssrEntry };
731
+ }
732
+ }
733
+ if (!ctx.nitro.options.renderer?.handler && !ctx.nitro.options.renderer?.template && ctx.services.ssr?.entry) {
734
+ ctx.nitro.options.renderer ??= {};
735
+ ctx.nitro.options.renderer.handler = resolve$1(runtimeDir, "internal/vite/ssr-renderer");
736
+ ctx.nitro.routing.sync();
737
+ }
738
+ const publicDistDir = ctx._publicDistDir = userConfig.build?.outDir || resolve$1(ctx.nitro.options.buildDir, "vite/public");
739
+ ctx.nitro.options.publicAssets.push({
740
+ dir: publicDistDir,
741
+ maxAge: 0,
742
+ baseURL: "/",
743
+ fallthrough: true
744
+ });
745
+ if (!ctx.nitro.options.dev) ctx.nitro.options.unenv.push({
746
+ meta: { name: "nitro-vite" },
747
+ polyfill: ["#nitro-vite-setup"]
748
+ });
749
+ await ctx.nitro.hooks.callHook("build:before", ctx.nitro);
750
+ ctx.rollupConfig = await getViteRollupConfig(ctx);
751
+ await ctx.nitro.hooks.callHook("rollup:before", ctx.nitro, ctx.rollupConfig.config);
752
+ if (ctx.nitro.options.dev && !ctx.devWorker) {
753
+ ctx.devWorker = createDevWorker(ctx);
754
+ ctx.nitro.fetch = (req) => ctx.devWorker.fetch(req);
755
+ }
756
+ if (ctx.nitro.options.dev && !ctx.devApp) ctx.devApp = new NitroDevApp(ctx.nitro);
757
+ }
758
+ function getEntry(input) {
759
+ if (typeof input === "string") return input;
760
+ else if (Array.isArray(input) && input.length > 0) return input[0];
761
+ else if (input && "index" in input) return input.index;
762
+ }
763
+ function flattenPlugins(plugins) {
764
+ return plugins.flatMap((plugin) => Array.isArray(plugin) ? flattenPlugins(plugin) : [plugin]).filter((p) => p && !(p instanceof Promise));
765
+ }
766
+
767
+ //#endregion
768
+ export { nitro as t };