nitro-nightly 3.1.0-20251028-004953-57503e42 → 3.1.0-20251028-110430-e607b753

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 (155) hide show
  1. package/dist/_build/assets.mjs +235 -0
  2. package/dist/_build/build.mjs +21 -0
  3. package/dist/_build/config.mjs +124 -0
  4. package/dist/_build/info.mjs +39 -0
  5. package/dist/_build/plugins.mjs +1041 -0
  6. package/dist/_build/prepare.mjs +17 -0
  7. package/dist/{_chunks/build2.mjs → _build/rolldown.mjs} +238 -64
  8. package/dist/_build/rollup.mjs +404 -0
  9. package/dist/_build/snapshot.mjs +61 -0
  10. package/dist/_build/types.mjs +268 -0
  11. package/dist/_build/vite.mjs +3266 -0
  12. package/dist/{cli → _cli}/build.mjs +2 -3
  13. package/dist/_cli/dev.mjs +205 -0
  14. package/dist/{cli/index2.mjs → _cli/index.mjs} +1 -2
  15. package/dist/{cli → _cli}/list.mjs +2 -3
  16. package/dist/{cli → _cli}/prepare.mjs +2 -3
  17. package/dist/{cli → _cli}/run.mjs +2 -3
  18. package/dist/_deps/@jridgewell/gen-mapping.mjs +189 -0
  19. package/dist/_deps/@jridgewell/remapping.mjs +137 -0
  20. package/dist/_deps/@jridgewell/resolve-uri.mjs +231 -0
  21. package/dist/_deps/@jridgewell/sourcemap-codec.mjs +173 -0
  22. package/dist/_deps/@jridgewell/trace-mapping.mjs +170 -0
  23. package/dist/_deps/@pi0/vite-plugin-fullstack.mjs +575 -0
  24. package/dist/_deps/@rollup/plugin-alias.mjs +89 -0
  25. package/dist/_deps/@rollup/plugin-commonjs.mjs +2376 -0
  26. package/dist/{_chunks/index2.mjs → _deps/@rollup/plugin-inject.mjs} +5 -90
  27. package/dist/_deps/@rollup/plugin-json.mjs +37 -0
  28. package/dist/_deps/@rollup/plugin-node-resolve.mjs +1386 -0
  29. package/dist/_deps/@rollup/plugin-replace.mjs +133 -0
  30. package/dist/_deps/@rollup/pluginutils.mjs +346 -0
  31. package/dist/_deps/acorn.mjs +6225 -0
  32. package/dist/_deps/c12.mjs +510 -0
  33. package/dist/_deps/chokidar.mjs +1428 -0
  34. package/dist/_deps/citty.mjs +460 -0
  35. package/dist/_deps/commondir.mjs +77 -0
  36. package/dist/_deps/compatx.mjs +76 -0
  37. package/dist/_deps/confbox.mjs +300 -0
  38. package/dist/_deps/debug.mjs +885 -0
  39. package/dist/_deps/deepmerge.mjs +147 -0
  40. package/dist/_deps/depd.mjs +550 -0
  41. package/dist/_deps/dot-prop.mjs +282 -0
  42. package/dist/_deps/dotenv.mjs +555 -0
  43. package/dist/_deps/duplexer.mjs +1 -0
  44. package/dist/_deps/ee-first.mjs +104 -0
  45. package/dist/_deps/encodeurl.mjs +69 -0
  46. package/dist/_deps/escape-html.mjs +87 -0
  47. package/dist/_deps/escape-string-regexp.mjs +13 -0
  48. package/dist/_deps/estree-walker.mjs +433 -0
  49. package/dist/_deps/etag.mjs +147 -0
  50. package/dist/_deps/exsolve.mjs +1416 -0
  51. package/dist/_deps/fdir.mjs +569 -0
  52. package/dist/_deps/fresh.mjs +145 -0
  53. package/dist/_deps/function-bind.mjs +106 -0
  54. package/dist/{_chunks/index4.mjs → _deps/giget.mjs} +21 -776
  55. package/dist/_deps/gzip-size.mjs +19 -0
  56. package/dist/_deps/hasown.mjs +19 -0
  57. package/dist/_deps/http-errors.mjs +307 -0
  58. package/dist/_deps/httpxy.mjs +580 -0
  59. package/dist/_deps/inherits.mjs +57 -0
  60. package/dist/_deps/is-core-module.mjs +596 -0
  61. package/dist/_deps/is-module.mjs +25 -0
  62. package/dist/_deps/is-reference.mjs +31 -0
  63. package/dist/_deps/js-tokens.mjs +411 -0
  64. package/dist/_deps/knitwork.mjs +172 -0
  65. package/dist/_deps/local-pkg.mjs +163 -0
  66. package/dist/_deps/magic-string.mjs +1296 -0
  67. package/dist/_deps/mime-db.mjs +11685 -0
  68. package/dist/_deps/mime-types.mjs +287 -0
  69. package/dist/_deps/mime.mjs +1172 -0
  70. package/dist/_deps/mlly.mjs +2413 -0
  71. package/dist/_deps/ms.mjs +172 -0
  72. package/dist/_deps/node-fetch-native.mjs +3 -0
  73. package/dist/_deps/nypm.mjs +219 -0
  74. package/dist/_deps/on-finished.mjs +246 -0
  75. package/dist/_deps/parseurl.mjs +168 -0
  76. package/dist/_deps/path-parse.mjs +85 -0
  77. package/dist/{_chunks/pathe.M-eThtNZ.mjs → _deps/pathe.mjs} +48 -1
  78. package/dist/_deps/perfect-debounce.mjs +88 -0
  79. package/dist/_deps/picomatch.mjs +2144 -0
  80. package/dist/_deps/pkg-types.mjs +247 -0
  81. package/dist/_deps/pretty-bytes.mjs +180 -0
  82. package/dist/_deps/quansync.mjs +99 -0
  83. package/dist/_deps/range-parser.mjs +171 -0
  84. package/dist/_deps/rc9.mjs +219 -0
  85. package/dist/_deps/readdirp.mjs +245 -0
  86. package/dist/_deps/resolve.mjs +1260 -0
  87. package/dist/_deps/rou3.mjs +326 -0
  88. package/dist/_deps/send.mjs +1022 -0
  89. package/dist/_deps/serve-static.mjs +228 -0
  90. package/dist/_deps/setprototypeof.mjs +26 -0
  91. package/dist/_deps/statuses.mjs +457 -0
  92. package/dist/_deps/strip-literal.mjs +67 -0
  93. package/dist/_deps/supports-color.mjs +44 -0
  94. package/dist/_deps/tinyexec.mjs +552 -0
  95. package/dist/_deps/tinyglobby.mjs +293 -0
  96. package/dist/_deps/toidentifier.mjs +41 -0
  97. package/dist/_deps/ultrahtml.mjs +3 -0
  98. package/dist/_deps/unimport.mjs +2267 -0
  99. package/dist/_deps/unplugin-utils.mjs +65 -0
  100. package/dist/_deps/unplugin.mjs +1294 -0
  101. package/dist/_deps/untyped.mjs +375 -0
  102. package/dist/{_chunks/info.mjs → _deps/unwasm.mjs} +8 -4122
  103. package/dist/_deps/webpack-virtual-modules.mjs +360 -0
  104. package/dist/_presets/_all.mjs +59 -0
  105. package/dist/_presets/_nitro.mjs +74 -0
  106. package/dist/_presets/_resolve.mjs +64 -0
  107. package/dist/_presets/_static.mjs +69 -0
  108. package/dist/_presets/_types.mjs +3 -0
  109. package/dist/_presets/_utils.mjs +31 -0
  110. package/dist/_presets/alwaysdata.mjs +17 -0
  111. package/dist/_presets/aws-amplify.mjs +111 -0
  112. package/dist/_presets/aws-lambda.mjs +23 -0
  113. package/dist/_presets/azure.mjs +162 -0
  114. package/dist/_presets/bun.mjs +19 -0
  115. package/dist/_presets/cleavr.mjs +15 -0
  116. package/dist/_presets/cloudflare.mjs +608 -0
  117. package/dist/_presets/deno.mjs +196 -0
  118. package/dist/_presets/digitalocean.mjs +14 -0
  119. package/dist/_presets/firebase.mjs +47 -0
  120. package/dist/_presets/flightcontrol.mjs +14 -0
  121. package/dist/_presets/genezio.mjs +13 -0
  122. package/dist/_presets/heroku.mjs +14 -0
  123. package/dist/_presets/iis.mjs +194 -0
  124. package/dist/_presets/index.mjs +62 -0
  125. package/dist/_presets/koyeb.mjs +14 -0
  126. package/dist/_presets/netlify.mjs +241 -0
  127. package/dist/_presets/node.mjs +54 -0
  128. package/dist/_presets/platform.mjs +14 -0
  129. package/dist/_presets/render.mjs +14 -0
  130. package/dist/_presets/standard.mjs +23 -0
  131. package/dist/_presets/stormkit.mjs +18 -0
  132. package/dist/_presets/vercel.mjs +365 -0
  133. package/dist/_presets/winterjs.mjs +22 -0
  134. package/dist/_presets/zeabur.mjs +69 -0
  135. package/dist/_presets/zerops.mjs +27 -0
  136. package/dist/cli/index.mjs +7 -464
  137. package/dist/index.mjs +122 -34
  138. package/dist/vite.mjs +118 -44
  139. package/package.json +1 -1
  140. package/dist/_chunks/app.mjs +0 -19797
  141. package/dist/_chunks/build.mjs +0 -86
  142. package/dist/_chunks/build3.mjs +0 -6538
  143. package/dist/_chunks/detect-acorn.mjs +0 -503
  144. package/dist/_chunks/index.mjs +0 -22256
  145. package/dist/_chunks/index3.mjs +0 -1062
  146. package/dist/_chunks/json5.mjs +0 -68
  147. package/dist/_chunks/jsonc.mjs +0 -51
  148. package/dist/_chunks/plugin.mjs +0 -1560
  149. package/dist/_chunks/server.mjs +0 -254
  150. package/dist/_chunks/snapshot.mjs +0 -376
  151. package/dist/_chunks/toml.mjs +0 -259
  152. package/dist/_chunks/yaml.mjs +0 -86
  153. package/dist/cli/dev.mjs +0 -95
  154. package/dist/presets.mjs +0 -2494
  155. /package/dist/{cli → _cli}/common.mjs +0 -0
@@ -1,1560 +0,0 @@
1
- import { s as sanitizeFilePath, f as formatCompatibilityDate, d as copyPublicAssets, a as scanHandlers, r as resolveModulePath, e as prettyPath, M as MagicString, i as stripLiteral, j as prepare, k as createNitro } from './index.mjs';
2
- import { fileURLToPath } from 'node:url';
3
- import { colors } from 'consola/utils';
4
- import { defu } from 'defu';
5
- import 'ufo';
6
- import fs, { existsSync, watch as watch$1 } from 'node:fs';
7
- import { readFile, rm, mkdir, writeFile, readlink } from 'node:fs/promises';
8
- import 'node:zlib';
9
- import 'node:worker_threads';
10
- import consola from 'consola';
11
- import { isTest, isCI } from 'std-env';
12
- import 'h3';
13
- import 'undici';
14
- import 'nitro/meta';
15
- import { NodeRequest, sendNodeResponse } from 'srvx/node';
16
- import { d as debounce, w as watch, a as NodeDevWorker, c as createProxyServer, N as NitroDevApp } from './app.mjs';
17
- import 'klona/full';
18
- import { runtimeDir, runtimeDependencies } from 'nitro/runtime/meta';
19
- import 'ofetch';
20
- import { a as alias, i as inject } from './index2.mjs';
21
- import { b as baseBuildConfig, d as baseBuildPlugins, r as replace, e as writeBuildInfo } from './info.mjs';
22
- import { r as resolve, d as dirname, n as normalize, b as basename, a as relative, j as join, i as isAbsolute } from './pathe.M-eThtNZ.mjs';
23
- import 'hookable';
24
- import 'jiti';
25
- import 'klona';
26
- import 'unstorage';
27
- import 'ohash';
28
- import path, { resolve as resolve$1, join as join$1 } from 'node:path';
29
- import 'youch-core';
30
- import 'youch';
31
- import 'source-map';
32
- import 'srvx';
33
- import { DevEnvironment, normalizePath, isCSSRequest } from 'vite';
34
- import { getRandomPort } from 'get-port-please';
35
- import { spawn } from 'node:child_process';
36
- import assert from 'node:assert/strict';
37
- import 'node:assert';
38
- import { createHash } from 'node:crypto';
39
-
40
- const getViteRollupConfig = (ctx) => {
41
- const nitro = ctx.nitro;
42
- const base = baseBuildConfig(nitro);
43
- const chunkNamePrefixes = [
44
- [nitro.options.buildDir, "build"],
45
- [base.buildServerDir, "app"],
46
- [runtimeDir, "nitro"],
47
- [base.presetsDir, "nitro"],
48
- ["\0nitro-wasm:", "wasm"],
49
- ["\0", "virtual"]
50
- ];
51
- function getChunkGroup(id) {
52
- if (id.startsWith(runtimeDir) || id.startsWith(base.presetsDir)) {
53
- return "nitro";
54
- }
55
- }
56
- let config = {
57
- input: nitro.options.entry,
58
- external: [...base.env.external],
59
- plugins: [
60
- ctx.pluginConfig.experimental?.virtualBundle && virtualBundlePlugin(ctx._serviceBundles),
61
- ...baseBuildPlugins(nitro, base),
62
- alias({ entries: base.aliases }),
63
- replace({
64
- delimiters: base.replaceDelimiters,
65
- preventAssignment: true,
66
- values: base.replacements
67
- }),
68
- inject(base.env.inject)
69
- ].filter(Boolean),
70
- treeshake: {
71
- moduleSideEffects(id) {
72
- const normalizedId = normalize(id);
73
- const idWithoutNodeModules = normalizedId.split("node_modules/").pop();
74
- if (!idWithoutNodeModules) {
75
- return false;
76
- }
77
- if (normalizedId.startsWith(runtimeDir) || idWithoutNodeModules.startsWith(runtimeDir)) {
78
- return true;
79
- }
80
- return nitro.options.moduleSideEffects.some(
81
- (m) => normalizedId.startsWith(m) || idWithoutNodeModules.startsWith(m)
82
- );
83
- }
84
- },
85
- output: {
86
- dir: nitro.options.output.serverDir,
87
- entryFileNames: "index.mjs",
88
- chunkFileNames(chunk) {
89
- const id = normalize(chunk.moduleIds.at(-1) || "");
90
- for (const [dir, name] of chunkNamePrefixes) {
91
- if (id.startsWith(dir)) {
92
- return `chunks/${name}/[name].mjs`;
93
- }
94
- }
95
- const routeHandler = nitro.options.handlers.find(
96
- (h) => id.startsWith(h.handler)
97
- ) || nitro.scannedHandlers.find((h) => id.startsWith(h.handler));
98
- if (routeHandler?.route) {
99
- const path = routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "") || "/";
100
- return `chunks/routes/${path}/[name].mjs`.replace(/\/+/g, "/");
101
- }
102
- const taskHandler = Object.entries(nitro.options.tasks).find(
103
- ([_, task]) => task.handler === id
104
- );
105
- if (taskHandler) {
106
- return `chunks/tasks/[name].mjs`;
107
- }
108
- return `chunks/_/[name].mjs`;
109
- },
110
- manualChunks(id) {
111
- return getChunkGroup(id);
112
- },
113
- inlineDynamicImports: nitro.options.inlineDynamicImports,
114
- format: "esm",
115
- exports: "auto",
116
- intro: "",
117
- outro: "",
118
- generatedCode: {
119
- constBindings: true
120
- },
121
- sanitizeFileName: sanitizeFilePath,
122
- sourcemapExcludeSources: true,
123
- sourcemapIgnoreList(relativePath) {
124
- return relativePath.includes("node_modules");
125
- }
126
- }
127
- };
128
- config = defu(nitro.options.rollupConfig, config);
129
- if (config.output.inlineDynamicImports) {
130
- delete config.output.manualChunks;
131
- }
132
- return { config, base };
133
- };
134
- function virtualBundlePlugin(bundles) {
135
- let _modules = null;
136
- const getModules = () => {
137
- if (_modules) {
138
- return _modules;
139
- }
140
- _modules = /* @__PURE__ */ new Map();
141
- for (const bundle of Object.values(bundles)) {
142
- for (const [fileName, content] of Object.entries(bundle)) {
143
- if (content.type === "chunk") {
144
- const virtualModule = {
145
- code: content.code,
146
- map: null
147
- };
148
- const maybeMap = bundle[`${fileName}.map`];
149
- if (maybeMap && maybeMap.type === "asset") {
150
- virtualModule.map = maybeMap.source;
151
- }
152
- _modules.set(fileName, virtualModule);
153
- _modules.set(resolve(fileName), virtualModule);
154
- }
155
- }
156
- }
157
- return _modules;
158
- };
159
- return {
160
- name: "virtual-bundle",
161
- resolveId(id, importer) {
162
- const modules = getModules();
163
- if (modules.has(id)) {
164
- return resolve(id);
165
- }
166
- if (importer) {
167
- const resolved = resolve(dirname(importer), id);
168
- if (modules.has(resolved)) {
169
- return resolved;
170
- }
171
- }
172
- return null;
173
- },
174
- load(id) {
175
- const modules = getModules();
176
- const m = modules.get(id);
177
- if (!m) {
178
- return null;
179
- }
180
- return m;
181
- }
182
- };
183
- }
184
-
185
- const BuilderNames = {
186
- nitro: colors.magenta("Nitro"),
187
- client: colors.green("Client"),
188
- ssr: colors.blue("SSR")
189
- };
190
- async function buildEnvironments(ctx, builder) {
191
- const nitro = ctx.nitro;
192
- for (const [envName, env] of Object.entries(builder.environments)) {
193
- const fmtName = BuilderNames[envName] || (envName.length <= 3 ? envName.toUpperCase() : envName[0].toUpperCase() + envName.slice(1));
194
- if (envName === "nitro" || !env.config.build.rollupOptions.input || env.isBuilt) {
195
- if (!["nitro", "ssr", "client"].includes(envName)) {
196
- nitro.logger.info(
197
- env.isBuilt ? `Skipping ${fmtName} (already built)` : `Skipping ${fmtName} (no input defined)`
198
- );
199
- }
200
- continue;
201
- }
202
- if (!isTest && !isCI) console.log();
203
- nitro.logger.start(`Building [${fmtName}]`);
204
- await builder.build(env);
205
- }
206
- const nitroOptions = ctx.nitro.options;
207
- const clientInput = builder.environments.client?.config?.build?.rollupOptions?.input;
208
- if (nitroOptions.renderer?.template && nitroOptions.renderer?.template === clientInput) {
209
- const outputPath = resolve(
210
- nitroOptions.output.publicDir,
211
- basename(clientInput)
212
- );
213
- if (existsSync(outputPath)) {
214
- const html = await readFile(outputPath, "utf8").then(
215
- (r) => r.replace(
216
- "<!--ssr-outlet-->",
217
- `{{{ fetch($REQUEST, { viteEnv: "ssr" }) }}}`
218
- )
219
- );
220
- await rm(outputPath);
221
- const tmp = resolve(nitroOptions.buildDir, "vite/index.html");
222
- await mkdir(dirname(tmp), { recursive: true });
223
- await writeFile(tmp, html, "utf8");
224
- nitroOptions.renderer.template = tmp;
225
- }
226
- }
227
- await builder.writeAssetsManifest?.();
228
- if (!isTest && !isCI) console.log();
229
- const buildInfo = [
230
- ["preset", nitro.options.preset],
231
- ["compatibility", formatCompatibilityDate(nitro.options.compatibilityDate)]
232
- ].filter((e) => e[1]);
233
- nitro.logger.start(
234
- `Building [${BuilderNames.nitro}] ${colors.dim(`(${buildInfo.map(([k, v]) => `${k}: \`${v}\``).join(", ")})`)}`
235
- );
236
- await copyPublicAssets(nitro);
237
- await builder.build(builder.environments.nitro);
238
- await nitro.close();
239
- await nitro.hooks.callHook("compiled", nitro);
240
- await writeBuildInfo(nitro);
241
- const rOutput = relative(process.cwd(), nitro.options.output.dir);
242
- const rewriteRelativePaths = (input) => {
243
- return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`);
244
- };
245
- if (!isTest && !isCI) console.log();
246
- if (nitro.options.commands.preview) {
247
- nitro.logger.success(
248
- `You can preview this build using \`${rewriteRelativePaths(
249
- nitro.options.commands.preview
250
- )}\``
251
- );
252
- }
253
- if (nitro.options.commands.deploy) {
254
- nitro.logger.success(
255
- `You can deploy this build using \`${rewriteRelativePaths(
256
- nitro.options.commands.deploy
257
- )}\``
258
- );
259
- }
260
- }
261
- function prodSetup(ctx) {
262
- const services = ctx.pluginConfig.services || {};
263
- const serviceNames = Object.keys(services);
264
- const serviceEntries = serviceNames.map((name) => {
265
- let entry;
266
- if (ctx.pluginConfig.experimental?.virtualBundle) {
267
- entry = ctx._entryPoints[name];
268
- } else {
269
- entry = resolve(
270
- ctx.nitro.options.buildDir,
271
- "vite/services",
272
- name,
273
- ctx._entryPoints[name]
274
- );
275
- }
276
- return [name, entry];
277
- });
278
- return (
279
- /* js */
280
- `
281
- import { setupVite } from "${resolve(runtimeDir, "internal/vite/prod-setup.mjs")}";
282
-
283
- const manifest = ${JSON.stringify(ctx._manifest || {})};
284
-
285
- function lazyService(loader) {
286
- let promise, mod
287
- return {
288
- fetch(req) {
289
- if (mod) { return mod.fetch(req) }
290
- if (!promise) {
291
- promise = loader().then(_mod => (mod = _mod.default || _mod))
292
- }
293
- return promise.then(mod => mod.fetch(req))
294
- }
295
- }
296
- }
297
-
298
- const services = {
299
- ${serviceEntries.map(
300
- ([name, entry]) => (
301
- /* js */
302
- `[${JSON.stringify(name)}]: lazyService(() => import(${JSON.stringify(entry)}))`
303
- )
304
- ).join(",\n")}
305
- };
306
-
307
- setupVite({ manifest, services });
308
- `
309
- );
310
- }
311
-
312
- function createFetchableDevEnvironment(name, config, devServer, entry) {
313
- const transport = createTransport(name, devServer);
314
- const context = { hot: true, transport };
315
- return new FetchableDevEnvironment(name, config, context, devServer, entry);
316
- }
317
- class FetchableDevEnvironment extends DevEnvironment {
318
- devServer;
319
- constructor(name, config, context, devServer, entry) {
320
- super(name, config, context);
321
- this.devServer = devServer;
322
- this.devServer.sendMessage({
323
- type: "custom",
324
- event: "nitro:vite-env",
325
- data: { name, entry }
326
- });
327
- }
328
- async dispatchFetch(request) {
329
- return this.devServer.fetch(request);
330
- }
331
- async init(...args) {
332
- await this.devServer.init?.();
333
- return super.init(...args);
334
- }
335
- }
336
- function createTransport(name, hooks) {
337
- const listeners = /* @__PURE__ */ new WeakMap();
338
- return {
339
- send: (data) => hooks.sendMessage({ ...data, viteEnv: name }),
340
- on: (event, handler) => {
341
- if (event === "connection") return;
342
- const listener = (value) => {
343
- if (value?.type === "custom" && value.event === event && value.viteEnv === name) {
344
- handler(value.data, {
345
- send: (payload) => hooks.sendMessage({ ...payload, viteEnv: name })
346
- });
347
- }
348
- };
349
- listeners.set(handler, listener);
350
- hooks.onMessage(listener);
351
- },
352
- off: (event, handler) => {
353
- if (event === "connection") return;
354
- const listener = listeners.get(handler);
355
- if (listener) {
356
- hooks.offMessage(listener);
357
- listeners.delete(handler);
358
- }
359
- }
360
- };
361
- }
362
- async function configureViteDevServer(ctx, server) {
363
- const nitro = ctx.nitro;
364
- const nitroEnv = server.environments.nitro;
365
- const nitroConfigFile = nitro.options._c12.configFile;
366
- if (nitroConfigFile) {
367
- server.config.configFileDependencies.push(nitroConfigFile);
368
- }
369
- const reload = debounce(async () => {
370
- await scanHandlers(nitro);
371
- nitro.routing.sync();
372
- nitroEnv.moduleGraph.invalidateAll();
373
- nitroEnv.hot.send({ type: "full-reload" });
374
- });
375
- const scanDirs = nitro.options.scanDirs.flatMap((dir) => [
376
- join(dir, nitro.options.apiDir || "api"),
377
- join(dir, nitro.options.routesDir || "routes"),
378
- join(dir, "middleware"),
379
- join(dir, "plugins"),
380
- join(dir, "modules")
381
- ]);
382
- const watchReloadEvents = /* @__PURE__ */ new Set(["add", "addDir", "unlink", "unlinkDir"]);
383
- const scanDirsWatcher = watch(scanDirs, {
384
- ignoreInitial: true
385
- }).on("all", (event, path, stat) => {
386
- if (watchReloadEvents.has(event)) {
387
- reload();
388
- }
389
- });
390
- const srcDirWatcher = watch$1(
391
- nitro.options.srcDir,
392
- { persistent: false },
393
- (_event, filename) => {
394
- if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) {
395
- reload();
396
- }
397
- }
398
- );
399
- nitro.hooks.hook("close", () => {
400
- scanDirsWatcher.close();
401
- srcDirWatcher.close();
402
- });
403
- const hostIPC = {
404
- async transformHTML(html) {
405
- return server.transformIndexHtml("/", html).then(
406
- (r) => r.replace(
407
- "<!--ssr-outlet-->",
408
- `{{{ fetch($REQUEST, { viteEnv: "ssr" }) }}}`
409
- )
410
- );
411
- }
412
- };
413
- nitroEnv.devServer.onMessage(async (payload) => {
414
- if (payload.type === "custom" && payload.event === "nitro:vite-invoke") {
415
- const methodName = payload.data.name;
416
- const res = await hostIPC[methodName](payload.data.data).then((data) => ({ data })).catch((error) => ({ error }));
417
- nitroEnv.devServer.sendMessage({
418
- type: "custom",
419
- event: "nitro:vite-invoke-response",
420
- data: { id: payload.data.id, data: res }
421
- });
422
- }
423
- });
424
- const nitroDevMiddleware = async (nodeReq, nodeRes, next) => {
425
- if (/^\/@(?:vite|fs|id)\//.test(nodeReq.url) || nodeReq._nitroHandled) {
426
- return next();
427
- }
428
- nodeReq._nitroHandled = true;
429
- const req = new NodeRequest({ req: nodeReq, res: nodeRes });
430
- const devAppRes = await ctx.devApp.fetch(req);
431
- if (nodeRes.writableEnded || nodeRes.headersSent) {
432
- return;
433
- }
434
- if (devAppRes.status !== 404) {
435
- return await sendNodeResponse(nodeRes, devAppRes);
436
- }
437
- const envRes = await nitroEnv.dispatchFetch(req);
438
- if (nodeRes.writableEnded || nodeRes.headersSent) {
439
- return;
440
- }
441
- if (envRes.status !== 404) {
442
- return await sendNodeResponse(nodeRes, envRes);
443
- }
444
- return next();
445
- };
446
- server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) {
447
- const fetchDest = req.headers["sec-fetch-dest"];
448
- if (fetchDest) {
449
- res.setHeader("vary", "sec-fetch-dest");
450
- }
451
- const ext = (req.url || "").match(/\.([a-z0-9]+)(?:[?#]|$)/i)?.[1] || "";
452
- if (!ext && (!fetchDest || /^(document|iframe|frame|empty)$/.test(fetchDest))) {
453
- nitroDevMiddleware(req, res, next);
454
- } else {
455
- next();
456
- }
457
- });
458
- return () => {
459
- server.middlewares.use(nitroDevMiddleware);
460
- };
461
- }
462
-
463
- function createDevWorker(ctx) {
464
- return new NodeDevWorker({
465
- name: "nitro-vite",
466
- entry: resolve$1(runtimeDir, "internal/vite/dev-worker.mjs"),
467
- hooks: {},
468
- data: {
469
- server: true,
470
- globals: {
471
- __NITRO_RUNTIME_CONFIG__: ctx.nitro.options.runtimeConfig
472
- }
473
- }
474
- });
475
- }
476
- function createNitroEnvironment(ctx) {
477
- return {
478
- consumer: "server",
479
- build: {
480
- rollupOptions: ctx.rollupConfig.config,
481
- minify: ctx.nitro.options.minify,
482
- emptyOutDir: false,
483
- commonjsOptions: {
484
- strictRequires: "auto",
485
- // TODO: set to true (default) in v3
486
- esmExternals: (id) => !id.startsWith("unenv/"),
487
- requireReturnsDefault: "auto",
488
- ...ctx.nitro.options.commonJS
489
- }
490
- },
491
- resolve: {
492
- noExternal: ctx.nitro.options.dev ? (
493
- // Workaround for dev: external dependencies are not resolvable with respect to nodeModulePaths
494
- new RegExp(runtimeDependencies.join("|"))
495
- ) : void 0,
496
- conditions: ctx.nitro.options.exportConditions,
497
- externalConditions: ctx.nitro.options.exportConditions
498
- },
499
- dev: {
500
- createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(
501
- envName,
502
- envConfig,
503
- ctx.devWorker,
504
- resolve$1(runtimeDir, "internal/vite/dev-entry.mjs")
505
- )
506
- }
507
- };
508
- }
509
- function createServiceEnvironment(ctx, name, serviceConfig) {
510
- return {
511
- consumer: "server",
512
- build: {
513
- rollupOptions: { input: serviceConfig.entry },
514
- minify: ctx.nitro.options.minify,
515
- outDir: join$1(ctx.nitro.options.buildDir, "vite", "services", name),
516
- emptyOutDir: true
517
- },
518
- resolve: {
519
- conditions: ctx.nitro.options.exportConditions,
520
- externalConditions: ctx.nitro.options.exportConditions
521
- },
522
- dev: {
523
- createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(
524
- envName,
525
- envConfig,
526
- ctx.devWorker,
527
- tryResolve(serviceConfig.entry)
528
- )
529
- }
530
- };
531
- }
532
- function createServiceEnvironments(ctx) {
533
- return Object.fromEntries(
534
- Object.entries(ctx.pluginConfig.services || {}).map(([name, config]) => [
535
- name,
536
- createServiceEnvironment(ctx, name, config)
537
- ])
538
- );
539
- }
540
- function tryResolve(id) {
541
- if (/^[~#/\0]/.test(id) || isAbsolute(id)) {
542
- return id;
543
- }
544
- const resolved = resolveModulePath(id, {
545
- suffixes: ["", "/index"],
546
- extensions: ["", ".ts", ".mjs", ".cjs", ".js", ".mts", ".cts"],
547
- try: true
548
- });
549
- return resolved || id;
550
- }
551
-
552
- function nitroPreviewPlugin(ctx) {
553
- return {
554
- name: "nitro:preview",
555
- apply: (_config, configEnv) => !!configEnv.isPreview,
556
- config(config) {
557
- return {
558
- preview: {
559
- port: config.preview?.port || 3e3
560
- }
561
- };
562
- },
563
- async configurePreviewServer(server) {
564
- const buildInfoPath = resolve(
565
- server.config.root,
566
- "node_modules/.nitro/last-build",
567
- "nitro.json"
568
- );
569
- if (!existsSync(buildInfoPath)) {
570
- console.warn(
571
- `[nitro] No build found. Please build your project before previewing.`
572
- );
573
- return;
574
- }
575
- const realBuildDir = await readlink("node_modules/.nitro/last-build");
576
- const buildInfo = JSON.parse(
577
- await readFile(buildInfoPath, "utf8")
578
- );
579
- const info = [
580
- ["Build Directory:", prettyPath(realBuildDir)],
581
- ["Date:", buildInfo.date && new Date(buildInfo.date).toLocaleString()],
582
- ["Nitro Version:", buildInfo.versions.nitro],
583
- ["Nitro Preset:", buildInfo.preset],
584
- buildInfo.framework?.name !== "nitro" && [
585
- "Framework:",
586
- buildInfo.framework?.name + (buildInfo.framework?.version ? ` (v${buildInfo.framework.version})` : "")
587
- ]
588
- ].filter((i) => i && i[1]);
589
- consola.box({
590
- title: " [Build Info] ",
591
- message: info.map((i) => `- ${i[0]} ${i[1]}`).join("\n")
592
- });
593
- if (!buildInfo.commands?.preview) {
594
- consola.warn("[nitro] No preview command found for this preset..");
595
- return;
596
- }
597
- const randomPort = await getRandomPort();
598
- consola.info(`Spawning preview server...`);
599
- const [command, ...args] = buildInfo.commands.preview.split(" ");
600
- let child;
601
- consola.info(buildInfo.commands?.preview);
602
- child = spawn(command, args, {
603
- stdio: "inherit",
604
- cwd: realBuildDir,
605
- env: {
606
- ...process.env,
607
- PORT: String(randomPort)
608
- }
609
- });
610
- process.on("exit", () => {
611
- child?.kill();
612
- child = void 0;
613
- });
614
- child.on("exit", (code) => {
615
- if (code && code !== 0) {
616
- consola.error(`[nitro] Preview server exited with code ${code}`);
617
- }
618
- });
619
- const proxy = createProxyServer({
620
- target: `http://localhost:${randomPort}`
621
- });
622
- server.middlewares.use((req, res, next) => {
623
- if (child && !child.killed) {
624
- proxy.web(req, res).catch(next);
625
- } else {
626
- res.end(`Nitro preview server is not running.`);
627
- }
628
- });
629
- }
630
- };
631
- }
632
-
633
- //#region src/plugins/shared.ts
634
- function parseIdQuery(id) {
635
- if (!id.includes("?")) return {
636
- filename: id,
637
- query: {}
638
- };
639
- const [filename, rawQuery] = id.split(`?`, 2);
640
- const query = Object.fromEntries(new URLSearchParams(rawQuery));
641
- return {
642
- filename,
643
- query
644
- };
645
- }
646
- function toAssetsVirtual(options) {
647
- return `virtual:fullstack/assets?${new URLSearchParams(options)}&lang.js`;
648
- }
649
- function parseAssetsVirtual(id) {
650
- if (id.startsWith("\0virtual:fullstack/assets?")) return parseIdQuery(id).query;
651
- }
652
-
653
- //#endregion
654
- //#region src/plugins/utils.ts
655
- function createVirtualPlugin(name, load) {
656
- name = "virtual:" + name;
657
- return {
658
- name: `rsc:virtual-${name}`,
659
- resolveId: { handler(source, _importer, _options) {
660
- return source === name ? "\0" + name : void 0;
661
- } },
662
- load: { handler(id, options) {
663
- if (id === "\0" + name) return load.apply(this, [id, options]);
664
- } }
665
- };
666
- }
667
- function normalizeRelativePath(s) {
668
- s = normalizePath(s);
669
- return s[0] === "." ? s : "./" + s;
670
- }
671
- function hashString(v) {
672
- return createHash("sha256").update(v).digest().toString("hex").slice(0, 12);
673
- }
674
-
675
- //#endregion
676
- //#region src/plugins/vite-utils.ts
677
- const VALID_ID_PREFIX = `/@id/`;
678
- const NULL_BYTE_PLACEHOLDER = `__x00__`;
679
- const FS_PREFIX = `/@fs/`;
680
- function wrapId(id) {
681
- return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
682
- }
683
- function withTrailingSlash(path$1) {
684
- if (path$1[path$1.length - 1] !== "/") return `${path$1}/`;
685
- return path$1;
686
- }
687
- const postfixRE = /[?#].*$/;
688
- function cleanUrl(url) {
689
- return url.replace(postfixRE, "");
690
- }
691
- function splitFileAndPostfix(path$1) {
692
- const file = cleanUrl(path$1);
693
- return {
694
- file,
695
- postfix: path$1.slice(file.length)
696
- };
697
- }
698
- const windowsSlashRE = /\\/g;
699
- function slash(p) {
700
- return p.replace(windowsSlashRE, "/");
701
- }
702
- const isWindows = typeof process !== "undefined" && process.platform === "win32";
703
- function injectQuery(url, queryToInject) {
704
- const { file, postfix } = splitFileAndPostfix(url);
705
- const normalizedFile = isWindows ? slash(file) : file;
706
- return `${normalizedFile}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`;
707
- }
708
- function normalizeResolvedIdToUrl(environment, url, resolved) {
709
- const root = environment.config.root;
710
- const depsOptimizer = environment.depsOptimizer;
711
- if (resolved.id.startsWith(withTrailingSlash(root))) url = resolved.id.slice(root.length);
712
- else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || resolved.id !== "/@react-refresh" && path.isAbsolute(resolved.id) && fs.existsSync(cleanUrl(resolved.id))) url = path.posix.join(FS_PREFIX, resolved.id);
713
- else url = resolved.id;
714
- if (url[0] !== "." && url[0] !== "/") url = wrapId(resolved.id);
715
- return url;
716
- }
717
- function normalizeViteImportAnalysisUrl(environment, id) {
718
- let url = normalizeResolvedIdToUrl(environment, id, { id });
719
- if (environment.config.consumer === "client") {
720
- const mod = environment.moduleGraph.getModuleById(id);
721
- if (mod && mod.lastHMRTimestamp > 0) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
722
- }
723
- return url;
724
- }
725
- function evalValue(rawValue) {
726
- const fn = new Function(`
727
- var console, exports, global, module, process, require
728
- return (\n${rawValue}\n)
729
- `);
730
- return fn();
731
- }
732
- const directRequestRE = /(\?|&)direct=?(?:&|$)/;
733
- function assetsPlugin(pluginOpts) {
734
- let server;
735
- let resolvedConfig;
736
- const importAssetsMetaMap = {};
737
- const bundleMap = {};
738
- async function processAssetsImport(ctx, id, options) {
739
- if (ctx.environment.mode === "dev") {
740
- const result = {
741
- entry: void 0,
742
- js: [],
743
- css: []
744
- };
745
- const environment = server.environments[options.environment];
746
- assert(environment, `Unknown environment: ${options.environment}`);
747
- if (options.environment === "client") result.entry = normalizeViteImportAnalysisUrl(environment, id);
748
- if (environment.name !== "client") {
749
- const collected = await collectCss(environment, id, { eager: pluginOpts?.experimental?.devEagerTransform ?? true });
750
- result.css = collected.hrefs.map((href, i) => ({
751
- href,
752
- "data-vite-dev-id": collected.ids[i]
753
- }));
754
- }
755
- return JSON.stringify(result);
756
- } else {
757
- const map = importAssetsMetaMap[options.environment] ??= {};
758
- const meta = {
759
- id,
760
- key: path.relative(resolvedConfig.root, id),
761
- importerEnvironment: ctx.environment.name,
762
- isEntry: !!(map[id]?.isEntry || options.isEntry)
763
- };
764
- map[id] = meta;
765
- return `__assets_manifest[${JSON.stringify(options.environment)}][${JSON.stringify(meta.key)}]`;
766
- }
767
- }
768
- let writeAssetsManifestCalled = false;
769
- async function writeAssetsManifest(builder) {
770
- if (writeAssetsManifestCalled) return;
771
- writeAssetsManifestCalled = true;
772
- const manifest = {};
773
- for (const [environmentName, metas] of Object.entries(importAssetsMetaMap)) {
774
- const bundle = bundleMap[environmentName];
775
- const assetDepsMap = collectAssetDeps(bundle);
776
- for (const [id, meta] of Object.entries(metas)) {
777
- const found = assetDepsMap[id];
778
- if (!found) {
779
- builder.config.logger.error(`[vite-plugin-fullstack] failed to find built chunk for ${meta.id} imported by ${meta.importerEnvironment} environment`);
780
- return;
781
- }
782
- const result = {
783
- js: [],
784
- css: []
785
- };
786
- const { chunk, deps } = found;
787
- if (environmentName === "client") {
788
- result.entry = `/${chunk.fileName}`;
789
- result.js = deps.js.map((fileName) => ({ href: `/${fileName}` }));
790
- }
791
- result.css = deps.css.map((fileName) => ({ href: `/${fileName}` }));
792
- if (!builder.environments[environmentName].config.build.cssCodeSplit) {
793
- const singleCss = Object.values(bundle).find((v) => v.type === "asset" && v.originalFileNames.includes("style.css"));
794
- if (singleCss) result.css.push({ href: `/${singleCss.fileName}` });
795
- }
796
- (manifest[environmentName] ??= {})[meta.key] = result;
797
- }
798
- }
799
- const importerEnvironments = new Set(Object.values(importAssetsMetaMap).flatMap((metas) => Object.values(metas)).flatMap((meta) => meta.importerEnvironment));
800
- for (const environmentName of importerEnvironments) {
801
- const outDir = builder.environments[environmentName].config.build.outDir;
802
- fs.writeFileSync(path.join(outDir, BUILD_ASSETS_MANIFEST_NAME), `export default ${JSON.stringify(manifest, null, 2)};`);
803
- const clientOutDir = builder.environments["client"].config.build.outDir;
804
- for (const asset of Object.values(bundleMap[environmentName])) if (asset.type === "asset") {
805
- const srcFile = path.join(outDir, asset.fileName);
806
- const destFile = path.join(clientOutDir, asset.fileName);
807
- fs.mkdirSync(path.dirname(destFile), { recursive: true });
808
- fs.copyFileSync(srcFile, destFile);
809
- }
810
- }
811
- }
812
- return [
813
- {
814
- name: "fullstack:assets",
815
- sharedDuringBuild: true,
816
- configureServer(server_) {
817
- server = server_;
818
- },
819
- configResolved(config) {
820
- resolvedConfig = config;
821
- },
822
- configEnvironment(name) {
823
- const serverEnvironments = pluginOpts?.serverEnvironments ?? ["ssr"];
824
- if (serverEnvironments.includes(name)) return { build: { emitAssets: true } };
825
- },
826
- transform: { async handler(code, id, _options) {
827
- if (!code.includes("import.meta.vite.assets")) return;
828
- const output = new MagicString(code);
829
- const strippedCode = stripLiteral(code);
830
- const newImports = /* @__PURE__ */ new Set();
831
- for (const match of code.matchAll(/import\.meta\.vite\.assets\(([\s\S]*?)\)/dg)) {
832
- const [start, end] = match.indices[0];
833
- if (!strippedCode.slice(start, end).includes("import.meta.vite.assets")) continue;
834
- if (this.environment.name === "client") {
835
- const replacement$1 = `(${JSON.stringify(EMPTY_ASSETS)})`;
836
- output.update(start, end, replacement$1);
837
- continue;
838
- }
839
- const argCode = match[1].trim();
840
- const options = {
841
- import: id,
842
- environment: void 0,
843
- asEntry: false
844
- };
845
- if (argCode) {
846
- const argValue = evalValue(argCode);
847
- Object.assign(options, argValue);
848
- }
849
- const environments = options.environment ? [options.environment] : ["client", this.environment.name];
850
- const importedNames = [];
851
- for (const environment of environments) {
852
- const importSource = toAssetsVirtual({
853
- import: options.import,
854
- importer: id,
855
- environment,
856
- entry: options.asEntry ? "1" : ""
857
- });
858
- const hash = hashString(importSource);
859
- const importedName = `__assets_${hash}`;
860
- newImports.add(`;import ${importedName} from ${JSON.stringify(importSource)};\n`);
861
- importedNames.push(importedName);
862
- }
863
- let replacement = importedNames[0];
864
- if (importedNames.length > 1) {
865
- newImports.add(`;import * as __assets_runtime from "virtual:fullstack/runtime";\n`);
866
- replacement = `__assets_runtime.mergeAssets(${importedNames.join(", ")})`;
867
- }
868
- output.update(start, end, `(${replacement})`);
869
- }
870
- if (output.hasChanged()) {
871
- for (const newImport of newImports) output.append(newImport);
872
- return {
873
- code: output.toString(),
874
- map: output.generateMap({ hires: "boundary" })
875
- };
876
- }
877
- } },
878
- resolveId: { handler(source) {
879
- if (source.startsWith("virtual:fullstack/assets?")) return "\0" + source;
880
- if (source === "virtual:fullstack/assets-manifest") {
881
- assert.notEqual(this.environment.name, "client");
882
- assert.equal(this.environment.mode, "build");
883
- return {
884
- id: source,
885
- external: true
886
- };
887
- }
888
- if (source === "virtual:fullstack/runtime") return { id: source };
889
- } },
890
- load: { async handler(id) {
891
- if (id === "virtual:fullstack/runtime") return runtimeUtils();
892
- const parsed = parseAssetsVirtual(id);
893
- if (!parsed) return;
894
- assert.notEqual(this.environment.name, "client");
895
- const resolved = await this.resolve(parsed.import, parsed.importer);
896
- assert(resolved, `Failed to resolve: ${parsed.import}`);
897
- const s = new MagicString("");
898
- const code = await processAssetsImport(this, resolved.id, {
899
- environment: parsed.environment,
900
- isEntry: !!parsed.entry
901
- });
902
- s.append(`export default ${code};\n`);
903
- if (this.environment.mode === "build") s.prepend(`import __assets_manifest from "virtual:fullstack/assets-manifest";\n`);
904
- return s.toString();
905
- } },
906
- renderChunk(code, chunk) {
907
- if (code.includes("virtual:fullstack/assets-manifest")) {
908
- const replacement = normalizeRelativePath(path.relative(path.join(chunk.fileName, ".."), BUILD_ASSETS_MANIFEST_NAME));
909
- code = code.replaceAll("virtual:fullstack/assets-manifest", () => replacement);
910
- return { code };
911
- }
912
- return;
913
- },
914
- writeBundle(_options, bundle) {
915
- bundleMap[this.environment.name] = bundle;
916
- },
917
- buildStart() {
918
- if (this.environment.mode == "build" && this.environment.name === "client") {
919
- const metas = importAssetsMetaMap["client"];
920
- if (metas) {
921
- for (const meta of Object.values(importAssetsMetaMap["client"])) if (meta.isEntry) this.emitFile({
922
- type: "chunk",
923
- id: meta.id,
924
- preserveSignature: "exports-only"
925
- });
926
- }
927
- }
928
- },
929
- buildApp: {
930
- order: "pre",
931
- async handler(builder) {
932
- builder.writeAssetsManifest = async () => {
933
- await writeAssetsManifest(builder);
934
- };
935
- }
936
- }
937
- },
938
- {
939
- name: "fullstack:write-assets-manifest-post",
940
- buildApp: {
941
- order: "post",
942
- async handler(builder) {
943
- await builder.writeAssetsManifest();
944
- }
945
- }
946
- },
947
- {
948
- name: "fullstack:assets-query",
949
- sharedDuringBuild: true,
950
- resolveId: {
951
- order: "pre",
952
- handler(source) {
953
- const { query } = parseIdQuery(source);
954
- const value = query["assets"];
955
- if (typeof value !== "undefined") {
956
- if (this.environment.name === "client") return `\0virtual:fullstack/empty-assets`;
957
- }
958
- if (source === "virtual:fullstack/runtime") return source;
959
- }
960
- },
961
- load: { async handler(id) {
962
- if (id === "\0virtual:fullstack/empty-assets") return `export default ${JSON.stringify(EMPTY_ASSETS)}`;
963
- if (id === "virtual:fullstack/runtime") return runtimeUtils();
964
- const { filename, query } = parseIdQuery(id);
965
- const value = query["assets"];
966
- if (typeof value !== "undefined") {
967
- const s = new MagicString("");
968
- const codes = [];
969
- if (value) {
970
- const code = await processAssetsImport(this, filename, {
971
- environment: value,
972
- isEntry: value === "client"
973
- });
974
- codes.push(code);
975
- } else {
976
- const code1 = await processAssetsImport(this, filename, {
977
- environment: "client",
978
- isEntry: false
979
- });
980
- const code2 = await processAssetsImport(this, filename, {
981
- environment: this.environment.name,
982
- isEntry: false
983
- });
984
- codes.push(code1, code2);
985
- }
986
- s.append(`
987
- import * as __assets_runtime from "virtual:fullstack/runtime";\n
988
- export default __assets_runtime.mergeAssets(${codes.join(", ")});
989
- `);
990
- if (this.environment.mode === "build") s.prepend(`import __assets_manifest from "virtual:fullstack/assets-manifest";\n`);
991
- return {
992
- code: s.toString(),
993
- moduleSideEffects: false
994
- };
995
- }
996
- } },
997
- hotUpdate(ctx) {
998
- if (this.environment.name === "rsc") {
999
- const mods = collectModuleDependents(ctx.modules);
1000
- for (const mod of mods) if (mod.id) {
1001
- const ids = [
1002
- `${mod.id}?assets`,
1003
- `${mod.id}?assets=client`,
1004
- `${mod.id}?assets=${this.environment.name}`
1005
- ];
1006
- for (const id of ids) invalidteModuleById(this.environment, id);
1007
- }
1008
- }
1009
- }
1010
- },
1011
- {
1012
- ...createVirtualPlugin("fullstack/client-fallback", () => "export {}"),
1013
- configEnvironment: {
1014
- order: "post",
1015
- handler(name, config, _env) {
1016
- if (name === "client") {
1017
- const clientBuildFallback = pluginOpts?.experimental?.clientBuildFallback ?? true;
1018
- if (clientBuildFallback && !config.build?.rollupOptions?.input) return { build: { rollupOptions: { input: { __fallback: "virtual:fullstack/client-fallback" } } } };
1019
- }
1020
- }
1021
- },
1022
- generateBundle(_optoins, bundle) {
1023
- if (this.environment.name !== "client") return;
1024
- for (const [k, v] of Object.entries(bundle)) if (v.type === "chunk" && v.name === "__fallback") delete bundle[k];
1025
- }
1026
- },
1027
- patchViteClientPlugin(),
1028
- patchVueScopeCssHmr(),
1029
- patchCssLinkSelfAccept()
1030
- ];
1031
- }
1032
- const EMPTY_ASSETS = {
1033
- js: [],
1034
- css: []
1035
- };
1036
- const BUILD_ASSETS_MANIFEST_NAME = "__fullstack_assets_manifest.js";
1037
- async function collectCss(environment, entryId, options) {
1038
- const visited = /* @__PURE__ */ new Set();
1039
- const cssIds = /* @__PURE__ */ new Set();
1040
- async function recurse(id) {
1041
- if (visited.has(id) || parseAssetsVirtual(id) || "assets" in parseIdQuery(id).query) return;
1042
- visited.add(id);
1043
- const mod = environment.moduleGraph.getModuleById(id);
1044
- if (!mod) return;
1045
- if (options.eager && !mod?.transformResult) try {
1046
- await environment.transformRequest(id);
1047
- } catch (e) {
1048
- console.error(`[collectCss] Failed to transform '${id}'`, e);
1049
- }
1050
- for (const next of mod?.importedModules ?? []) if (next.id) if (isCSSRequest(next.id)) {
1051
- if (hasSpecialCssQuery(next.id)) continue;
1052
- cssIds.add(next.id);
1053
- } else await recurse(next.id);
1054
- }
1055
- await recurse(entryId);
1056
- const hrefs = [...cssIds].map((id) => normalizeViteImportAnalysisUrl(environment, id));
1057
- return {
1058
- ids: [...cssIds],
1059
- hrefs
1060
- };
1061
- }
1062
- function invalidteModuleById(environment, id) {
1063
- const mod = environment.moduleGraph.getModuleById(id);
1064
- if (mod) environment.moduleGraph.invalidateModule(mod);
1065
- return mod;
1066
- }
1067
- function collectModuleDependents(mods) {
1068
- const visited = /* @__PURE__ */ new Set();
1069
- function recurse(mod) {
1070
- if (visited.has(mod)) return;
1071
- visited.add(mod);
1072
- for (const importer of mod.importers) recurse(importer);
1073
- }
1074
- for (const mod of mods) recurse(mod);
1075
- return [...visited];
1076
- }
1077
- function hasSpecialCssQuery(id) {
1078
- return /[?&](url|inline|raw)(\b|=|&|$)/.test(id);
1079
- }
1080
- function collectAssetDeps(bundle) {
1081
- const chunkToDeps = /* @__PURE__ */ new Map();
1082
- for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") chunkToDeps.set(chunk, collectAssetDepsInner(chunk.fileName, bundle));
1083
- const idToDeps = {};
1084
- for (const [chunk, deps] of chunkToDeps.entries()) for (const id of chunk.moduleIds) idToDeps[id] = {
1085
- chunk,
1086
- deps
1087
- };
1088
- return idToDeps;
1089
- }
1090
- function collectAssetDepsInner(fileName, bundle) {
1091
- const visited = /* @__PURE__ */ new Set();
1092
- const css = [];
1093
- function recurse(k) {
1094
- if (visited.has(k)) return;
1095
- visited.add(k);
1096
- const v = bundle[k];
1097
- assert(v, `Not found '${k}' in the bundle`);
1098
- if (v.type === "chunk") {
1099
- css.push(...v.viteMetadata?.importedCss ?? []);
1100
- for (const k2 of v.imports) if (k2 in bundle) recurse(k2);
1101
- }
1102
- }
1103
- recurse(fileName);
1104
- return {
1105
- js: [...visited],
1106
- css: [...new Set(css)]
1107
- };
1108
- }
1109
- function patchViteClientPlugin() {
1110
- const viteClientPath = normalizePath(fileURLToPath(import.meta.resolve("vite/dist/client/client.mjs")));
1111
- function endIndexOf(code, searchValue) {
1112
- const i = code.lastIndexOf(searchValue);
1113
- return i === -1 ? i : i + searchValue.length;
1114
- }
1115
- return {
1116
- name: "fullstack:patch-vite-client",
1117
- transform: { handler(code, id) {
1118
- if (id === viteClientPath) {
1119
- if (code.includes("linkSheetsMap")) return;
1120
- const s = new MagicString(code);
1121
- s.prependLeft(code.indexOf("const sheetsMap"), `\
1122
- const linkSheetsMap = new Map();
1123
- document
1124
- .querySelectorAll('link[rel="stylesheet"][data-vite-dev-id]')
1125
- .forEach((el) => {
1126
- linkSheetsMap.set(el.getAttribute('data-vite-dev-id'), el)
1127
- });
1128
- `);
1129
- s.appendLeft(endIndexOf(code, `function updateStyle(id, content) {`), `if (linkSheetsMap.has(id)) { return }`);
1130
- s.appendLeft(endIndexOf(code, `function removeStyle(id) {`), `
1131
- const link = linkSheetsMap.get(id);
1132
- if (link) {
1133
- document
1134
- .querySelectorAll(
1135
- 'link[rel="stylesheet"][data-vite-dev-id]',
1136
- )
1137
- .forEach((el) => {
1138
- if (el.getAttribute('data-vite-dev-id') === id) {
1139
- el.remove()
1140
- }
1141
- })
1142
- linkSheetsMap.delete(id)
1143
- }
1144
- `);
1145
- return s.toString();
1146
- }
1147
- } }
1148
- };
1149
- }
1150
- function patchVueScopeCssHmr() {
1151
- return {
1152
- name: "fullstack:patch-vue-scoped-css-hmr",
1153
- configureServer(server) {
1154
- server.middlewares.use((req, _res, next) => {
1155
- if (req.headers.accept?.includes("text/css") && req.url?.includes("&lang.css=")) req.url = req.url.replace("&lang.css=", "?lang.css");
1156
- next();
1157
- });
1158
- }
1159
- };
1160
- }
1161
- function patchCssLinkSelfAccept() {
1162
- return {
1163
- name: "fullstack:patch-css-link-self-accept",
1164
- apply: "serve",
1165
- transform: {
1166
- order: "post",
1167
- handler(_code, id, _options) {
1168
- if (this.environment.name === "client" && this.environment.mode === "dev" && isCSSRequest(id) && directRequestRE.test(id)) {
1169
- const mod = this.environment.moduleGraph.getModuleById(id);
1170
- if (mod && !mod.isSelfAccepting) mod.isSelfAccepting = true;
1171
- }
1172
- }
1173
- }
1174
- };
1175
- }
1176
- function runtimeUtils() {
1177
- return `
1178
- export function mergeAssets(...args) {
1179
- const js = uniqBy(args.flatMap((h) => h.js), (a) => a.href);
1180
- const css = uniqBy(args.flatMap((h) => h.css), (a) => a.href);
1181
- const entry = args.filter((arg) => arg.entry)?.[0]?.entry;
1182
- const raw = { entry, js, css };
1183
- return { ...raw, merge: (...args$1) => mergeAssets(raw, ...args$1) };
1184
- }
1185
- function uniqBy(array, key) {
1186
- const seen = new Set();
1187
- return array.filter((item) => {
1188
- const k = key(item);
1189
- if (seen.has(k)) return false;
1190
- seen.add(k);
1191
- return true;
1192
- });
1193
- }`;
1194
- }
1195
-
1196
- const DEFAULT_EXTENSIONS = [".ts", ".js", ".mts", ".mjs", ".tsx", ".jsx"];
1197
- const debug = process.env.NITRO_DEBUG ? (...args) => console.log("[nitro]", ...args) : () => {
1198
- };
1199
- function nitro(pluginConfig = {}) {
1200
- const ctx = createContext(pluginConfig);
1201
- return [
1202
- nitroInit(ctx),
1203
- nitroEnv(ctx),
1204
- nitroMain(ctx),
1205
- nitroPrepare(ctx),
1206
- nitroService(ctx),
1207
- nitroPreviewPlugin(),
1208
- pluginConfig.experimental?.assetsImport !== false && assetsPlugin({
1209
- experimental: {
1210
- // See https://github.com/hi-ogawa/vite-plugins/pull/1289
1211
- clientBuildFallback: false
1212
- }
1213
- })
1214
- ];
1215
- }
1216
- function nitroInit(ctx) {
1217
- return {
1218
- name: "nitro:init",
1219
- sharedDuringBuild: true,
1220
- apply: (_config, configEnv) => !configEnv.isPreview,
1221
- async config(config, configEnv) {
1222
- if (!ctx._initialized) {
1223
- debug("[init] Initializing nitro");
1224
- ctx._initialized = true;
1225
- await setupNitroContext(ctx, configEnv, config);
1226
- }
1227
- },
1228
- applyToEnvironment(env) {
1229
- if (env.name === "nitro" && ctx.nitro?.options.dev) {
1230
- debug("[init] Adding rollup plugins for dev");
1231
- return [...ctx.rollupConfig?.config.plugins || []];
1232
- }
1233
- }
1234
- };
1235
- }
1236
- function nitroEnv(ctx) {
1237
- return {
1238
- name: "nitro:env",
1239
- sharedDuringBuild: true,
1240
- apply: (_config, configEnv) => !configEnv.isPreview,
1241
- async config(userConfig, _configEnv) {
1242
- debug("[env] Extending config (environments)");
1243
- const environments = {
1244
- ...createServiceEnvironments(ctx),
1245
- nitro: createNitroEnvironment(ctx)
1246
- };
1247
- environments.client = {
1248
- consumer: userConfig.environments?.client?.consumer ?? "client",
1249
- build: {
1250
- rollupOptions: {
1251
- input: userConfig.environments?.client?.build?.rollupOptions?.input ?? useNitro(ctx).options.renderer?.template
1252
- }
1253
- }
1254
- };
1255
- debug("[env] Environments:", Object.keys(environments).join(", "));
1256
- return {
1257
- environments
1258
- };
1259
- },
1260
- configEnvironment(name, config) {
1261
- if (config.consumer === "client") {
1262
- debug(
1263
- "[env] Configuring client environment",
1264
- name === "client" ? "" : ` (${name})`
1265
- );
1266
- config.build.emptyOutDir = false;
1267
- config.build.outDir = useNitro(ctx).options.output.publicDir;
1268
- } else {
1269
- if (ctx.pluginConfig.experimental?.virtualBundle && name in (ctx.pluginConfig.services || {})) {
1270
- debug("[env] Configuring service environment for virtual:", name);
1271
- config.build ??= {};
1272
- config.build.write = config.build.write ?? false;
1273
- }
1274
- }
1275
- }
1276
- };
1277
- }
1278
- function nitroMain(ctx) {
1279
- return {
1280
- name: "nitro:main",
1281
- sharedDuringBuild: true,
1282
- apply: (_config, configEnv) => !configEnv.isPreview,
1283
- async config(userConfig, _configEnv) {
1284
- debug("[main] Extending config (appType, resolve, server)");
1285
- if (!ctx.rollupConfig) {
1286
- throw new Error("Nitro rollup config is not initialized yet.");
1287
- }
1288
- return {
1289
- appType: userConfig.appType || "custom",
1290
- resolve: {
1291
- // TODO: environment specific aliases not working
1292
- // https://github.com/vitejs/vite/pull/17583 (seems not effective)
1293
- alias: ctx.rollupConfig.base.aliases
1294
- },
1295
- builder: {
1296
- sharedConfigBuild: true
1297
- },
1298
- server: {
1299
- port: Number.parseInt(process.env.PORT || "") || userConfig.server?.port || useNitro(ctx).options.devServer?.port || 3e3
1300
- }
1301
- };
1302
- },
1303
- configResolved(config) {
1304
- if (config.command === "build") {
1305
- debug("[main] Inferring caching routes");
1306
- for (const env of Object.values(config.environments)) {
1307
- if (env.consumer === "client") {
1308
- const rule = ctx.nitro.options.routeRules[`/${env.build.assetsDir}/**`] ??= {};
1309
- if (!rule.headers?.["cache-control"]) {
1310
- rule.headers = {
1311
- ...rule.headers,
1312
- "cache-control": `public, max-age=31536000, immutable`
1313
- };
1314
- }
1315
- }
1316
- }
1317
- }
1318
- debug("[main] Syncing nitro routes");
1319
- ctx.nitro.routing.sync();
1320
- },
1321
- buildApp: {
1322
- order: "post",
1323
- handler(builder) {
1324
- debug("[main] Building environments");
1325
- return buildEnvironments(ctx, builder);
1326
- }
1327
- },
1328
- generateBundle: {
1329
- handler(_options, bundle) {
1330
- const environment = this.environment;
1331
- debug(
1332
- "[main] Generating manifest and entry points for environment:",
1333
- environment.name
1334
- );
1335
- const { root } = environment.config;
1336
- const services = ctx.pluginConfig.services || {};
1337
- const serviceNames = Object.keys(services);
1338
- const isRegisteredService = serviceNames.includes(environment.name);
1339
- let entryFile;
1340
- for (const [_name, file] of Object.entries(bundle)) {
1341
- if (file.type === "chunk") {
1342
- if (isRegisteredService && file.isEntry) {
1343
- if (entryFile === void 0) {
1344
- entryFile = file.fileName;
1345
- } else {
1346
- this.warn(
1347
- `Multiple entry points found for service "${environment.name}"`
1348
- );
1349
- }
1350
- }
1351
- const filteredModuleIds = file.moduleIds.filter(
1352
- (id) => id.startsWith(root)
1353
- );
1354
- for (const id of filteredModuleIds) {
1355
- const originalFile = relative(root, id);
1356
- ctx._manifest[originalFile] = { file: file.fileName };
1357
- }
1358
- }
1359
- }
1360
- if (isRegisteredService) {
1361
- if (entryFile === void 0) {
1362
- this.error(
1363
- `No entry point found for service "${this.environment.name}".`
1364
- );
1365
- }
1366
- ctx._entryPoints[this.environment.name] = entryFile;
1367
- ctx._serviceBundles[this.environment.name] = bundle;
1368
- }
1369
- }
1370
- },
1371
- configureServer: (server) => {
1372
- debug("[main] Configuring dev server");
1373
- return configureViteDevServer(ctx, server);
1374
- }
1375
- };
1376
- }
1377
- function nitroPrepare(ctx) {
1378
- return {
1379
- name: "nitro:prepare",
1380
- sharedDuringBuild: true,
1381
- applyToEnvironment: (env) => env.name === "nitro",
1382
- buildApp: {
1383
- // Clean the output directory before any environment is built
1384
- order: "pre",
1385
- async handler() {
1386
- debug("[prepare] Preparing output directory");
1387
- const nitro2 = ctx.nitro;
1388
- await prepare(nitro2);
1389
- }
1390
- }
1391
- };
1392
- }
1393
- function nitroService(ctx) {
1394
- return {
1395
- name: "nitro:service",
1396
- enforce: "pre",
1397
- sharedDuringBuild: true,
1398
- applyToEnvironment: (env) => env.name === "nitro",
1399
- resolveId: {
1400
- async handler(id, importer, options) {
1401
- if (id === "#nitro-vite-setup") {
1402
- return { id, moduleSideEffects: true };
1403
- }
1404
- if (id === "#nitro-vite-services") {
1405
- return id;
1406
- }
1407
- if (runtimeDependencies.some(
1408
- (dep) => id === dep || id.startsWith(`${dep}/`)
1409
- )) {
1410
- const resolved = await this.resolve(id, importer, {
1411
- ...options,
1412
- skipSelf: true
1413
- });
1414
- return resolved || resolveModulePath(id, {
1415
- from: ctx.nitro.options.nodeModulesDirs,
1416
- conditions: ctx.nitro.options.exportConditions,
1417
- try: true
1418
- });
1419
- }
1420
- if (importer?.startsWith("\0virtual:#nitro-internal-virtual")) {
1421
- const internalRes = await this.resolve(id, import.meta.url, {
1422
- ...options,
1423
- custom: { ...options.custom, skipNoExternals: true }
1424
- });
1425
- if (internalRes) {
1426
- return internalRes;
1427
- }
1428
- const resolvedFromRoot = await this.resolve(
1429
- id,
1430
- ctx.nitro.options.rootDir,
1431
- { ...options, custom: { ...options.custom, skipNoExternals: true } }
1432
- );
1433
- if (resolvedFromRoot) {
1434
- return resolvedFromRoot;
1435
- }
1436
- const ids = [id];
1437
- if (!/^[./@#]/.test(id)) {
1438
- ids.push(`./${id}`);
1439
- }
1440
- for (const _id of ids) {
1441
- const resolved = resolveModulePath(_id, {
1442
- from: process.cwd(),
1443
- extensions: DEFAULT_EXTENSIONS,
1444
- suffixes: ["", "/index"],
1445
- try: true
1446
- });
1447
- if (resolved) {
1448
- return resolved;
1449
- }
1450
- }
1451
- }
1452
- }
1453
- },
1454
- load: {
1455
- async handler(id) {
1456
- if (id === "#nitro-vite-setup") {
1457
- return prodSetup(ctx);
1458
- }
1459
- }
1460
- }
1461
- };
1462
- }
1463
- function createContext(pluginConfig) {
1464
- return {
1465
- pluginConfig,
1466
- _entryPoints: {},
1467
- _manifest: {},
1468
- _serviceBundles: {}
1469
- };
1470
- }
1471
- function useNitro(ctx) {
1472
- if (!ctx.nitro) {
1473
- throw new Error("Nitro instance is not initialized yet.");
1474
- }
1475
- return ctx.nitro;
1476
- }
1477
- async function setupNitroContext(ctx, configEnv, userConfig) {
1478
- ctx.nitro = ctx.pluginConfig._nitro || await createNitro({
1479
- dev: configEnv.mode === "development",
1480
- rootDir: userConfig.root,
1481
- ...defu(ctx.pluginConfig.config, userConfig.nitro)
1482
- });
1483
- if (!ctx.pluginConfig.services?.ssr) {
1484
- ctx.pluginConfig.services ??= {};
1485
- if (userConfig.environments?.ssr === void 0) {
1486
- const ssrEntry = resolveModulePath("./entry-server", {
1487
- from: ["", "app", "src"].flatMap(
1488
- (d) => ctx.nitro.options.scanDirs.map((s) => join(s, d) + "/")
1489
- ),
1490
- extensions: DEFAULT_EXTENSIONS,
1491
- try: true
1492
- });
1493
- if (ssrEntry) {
1494
- ctx.pluginConfig.services.ssr = { entry: ssrEntry };
1495
- ctx.nitro.logger.info(
1496
- `Using \`${prettyPath(ssrEntry)}\` as vite ssr entry.`
1497
- );
1498
- }
1499
- } else {
1500
- let ssrEntry = getEntry(
1501
- userConfig.environments.ssr.build?.rollupOptions?.input
1502
- );
1503
- if (typeof ssrEntry === "string") {
1504
- ssrEntry = resolveModulePath(ssrEntry, {
1505
- from: ctx.nitro.options.scanDirs,
1506
- extensions: DEFAULT_EXTENSIONS,
1507
- suffixes: ["", "/index"],
1508
- try: true
1509
- }) || ssrEntry;
1510
- ctx.pluginConfig.services.ssr = { entry: ssrEntry };
1511
- } else {
1512
- throw new TypeError(`Invalid input type for SSR entry point.`);
1513
- }
1514
- }
1515
- }
1516
- if (!ctx.nitro.options.renderer?.entry && !ctx.nitro.options.renderer?.template && ctx.pluginConfig.services.ssr?.entry) {
1517
- ctx.nitro.options.renderer ??= {};
1518
- ctx.nitro.options.renderer.entry = resolve(
1519
- runtimeDir,
1520
- "internal/vite/ssr-renderer"
1521
- );
1522
- }
1523
- const publicDistDir = ctx._publicDistDir = userConfig.build?.outDir || resolve(ctx.nitro.options.buildDir, "vite/public");
1524
- ctx.nitro.options.publicAssets.push({
1525
- dir: publicDistDir,
1526
- maxAge: 0,
1527
- baseURL: "/",
1528
- fallthrough: true
1529
- });
1530
- if (!ctx.nitro.options.dev) {
1531
- ctx.nitro.options.unenv.push({
1532
- meta: { name: "nitro-vite" },
1533
- polyfill: ["#nitro-vite-setup"]
1534
- });
1535
- }
1536
- await ctx.nitro.hooks.callHook("build:before", ctx.nitro);
1537
- ctx.rollupConfig = await getViteRollupConfig(ctx);
1538
- await ctx.nitro.hooks.callHook(
1539
- "rollup:before",
1540
- ctx.nitro,
1541
- ctx.rollupConfig.config
1542
- );
1543
- if (ctx.nitro.options.dev && !ctx.devWorker) {
1544
- ctx.devWorker = createDevWorker(ctx);
1545
- }
1546
- if (ctx.nitro.options.dev && !ctx.devApp) {
1547
- ctx.devApp = new NitroDevApp(ctx.nitro);
1548
- }
1549
- }
1550
- function getEntry(input) {
1551
- if (typeof input === "string") {
1552
- return input;
1553
- } else if (Array.isArray(input) && input.length > 0) {
1554
- return input[0];
1555
- } else if (input && "index" in input) {
1556
- return input.index;
1557
- }
1558
- }
1559
-
1560
- export { nitro as n };