@nuxt/rspack-builder-nightly 4.3.0-29461891.8f4fbecd → 4.3.0-29466366.fa21bb17

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.
package/dist/index.mjs CHANGED
@@ -1,90 +1,91 @@
1
- import pify from 'pify';
2
- import { fromNodeMiddleware, defineEventHandler, handleCors, getRequestHeader, createError, setHeader } from 'h3';
3
- import webpackDevMiddleware from 'webpack-dev-middleware';
4
- import webpackHotMiddleware from 'webpack-hot-middleware';
5
- import { defu } from 'defu';
6
- import { withTrailingSlash, parseURL, joinURL } from 'ufo';
7
- import { resolveAlias, useNitro, logger, tryImportModule, directoryToURL, useNuxt } from '@nuxt/kit';
8
- import { createUnplugin } from 'unplugin';
9
- import MagicString from 'magic-string';
10
- import { webpack, WebpackBarPlugin, builder, MiniCssExtractPlugin, TsCheckerPlugin } from '#builder';
11
- import { existsSync, readFileSync } from 'node:fs';
12
- import { createRequire } from 'node:module';
13
- import { pathToFileURL } from 'node:url';
14
- import { isAbsolute, resolve, relative, join, basename, normalize } from 'pathe';
15
- import { genArrayFromRaw, genObjectFromRawEntries, genString } from 'knitwork';
16
- import { parse, compileStyle } from '@vue/compiler-sfc';
17
- import { createHash } from 'node:crypto';
18
- import { createFsFromVolume, Volume } from 'memfs';
19
- import querystring from 'node:querystring';
20
- import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
21
- import { defineEnv } from 'unenv';
22
- import TimeFixPlugin from 'time-fix-plugin';
23
- import FriendlyErrorsWebpackPlugin from '@nuxt/friendly-errors-webpack-plugin';
24
- import escapeRegExp from 'escape-string-regexp';
25
- import { isTest } from 'std-env';
26
- import { EsbuildPlugin } from 'esbuild-loader';
27
- import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
28
- import createResolver from 'postcss-import-resolver';
29
- import { createJiti } from 'jiti';
30
- import VueLoaderPlugin from 'vue-loader/dist/pluginWebpack5.js';
31
- import { resolveModulePath } from 'exsolve';
32
- import { mkdir, writeFile } from 'node:fs/promises';
33
- import { normalizeWebpackManifest, precomputeDependencies } from 'vue-bundle-renderer';
34
- import { hash } from 'ohash';
35
- import { serialize } from 'seroval';
36
- import { parseNodeModulePath } from 'mlly';
37
- import { runtimeDependencies } from 'nuxt/meta';
1
+ import { createRequire } from "node:module";
2
+ import pify from "pify";
3
+ import { createError, defineEventHandler, fromNodeMiddleware, getRequestHeader, handleCors, setHeader } from "h3";
4
+ import webpackDevMiddleware from "webpack-dev-middleware";
5
+ import webpackHotMiddleware from "webpack-hot-middleware";
6
+ import { defu } from "defu";
7
+ import { joinURL, parseURL, withTrailingSlash } from "ufo";
8
+ import { directoryToURL, logger, resolveAlias, tryImportModule, useNitro, useNuxt } from "@nuxt/kit";
9
+ import { createUnplugin } from "unplugin";
10
+ import MagicString from "magic-string";
11
+ import { MiniCssExtractPlugin, TsCheckerPlugin, WebpackBarPlugin, builder, webpack } from "#builder";
12
+ import { existsSync, readFileSync } from "node:fs";
13
+ import { pathToFileURL } from "node:url";
14
+ import { basename, isAbsolute, join, normalize, relative, resolve } from "pathe";
15
+ import { genArrayFromRaw, genObjectFromRawEntries, genString } from "knitwork";
16
+ import { compileStyle, parse } from "@vue/compiler-sfc";
17
+ import { createHash } from "node:crypto";
18
+ import { Volume, createFsFromVolume } from "memfs";
19
+ import querystring from "node:querystring";
20
+ import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer";
21
+ import { defineEnv } from "unenv";
22
+ import TimeFixPlugin from "time-fix-plugin";
23
+ import FriendlyErrorsWebpackPlugin from "@nuxt/friendly-errors-webpack-plugin";
24
+ import escapeRegExp from "escape-string-regexp";
25
+ import { isTest } from "std-env";
26
+ import { EsbuildPlugin } from "esbuild-loader";
27
+ import CssMinimizerPlugin from "css-minimizer-webpack-plugin";
28
+ import createResolver from "postcss-import-resolver";
29
+ import { createJiti } from "jiti";
30
+ import VueLoaderPlugin from "vue-loader/dist/pluginWebpack5.js";
31
+ import { resolveModulePath } from "exsolve";
32
+ import { mkdir, writeFile } from "node:fs/promises";
33
+ import { normalizeWebpackManifest, precomputeDependencies } from "vue-bundle-renderer";
34
+ import { hash } from "ohash";
35
+ import { serialize } from "seroval";
36
+ import { parseNodeModulePath } from "mlly";
37
+ import { runtimeDependencies } from "nuxt/meta";
38
38
 
39
+ //#region ../webpack/src/plugins/dynamic-base.ts
39
40
  const defaults = {
40
- globalPublicPath: "__webpack_public_path__",
41
- sourcemap: true
41
+ globalPublicPath: "__webpack_public_path__",
42
+ sourcemap: true
42
43
  };
43
44
  const ENTRY_RE = /import ["']#build\/css["'];/;
44
45
  const DynamicBasePlugin = createUnplugin((options = {}) => {
45
- options = { ...defaults, ...options };
46
- return {
47
- name: "nuxt:dynamic-base-path",
48
- enforce: "post",
49
- transform: {
50
- filter: {
51
- id: { include: /entry/ },
52
- code: { include: ENTRY_RE }
53
- },
54
- handler(code) {
55
- const s = new MagicString(code);
56
- s.prepend(`import { buildAssetsURL } from '#internal/nuxt/paths';
57
- ${options.globalPublicPath} = buildAssetsURL();
58
- `);
59
- return {
60
- code: s.toString(),
61
- map: options.sourcemap ? s.generateMap({ hires: true }) : void 0
62
- };
63
- }
64
- }
65
- };
46
+ options = {
47
+ ...defaults,
48
+ ...options
49
+ };
50
+ return {
51
+ name: "nuxt:dynamic-base-path",
52
+ enforce: "post",
53
+ transform: {
54
+ filter: {
55
+ id: { include: /entry/ },
56
+ code: { include: ENTRY_RE }
57
+ },
58
+ handler(code) {
59
+ const s = new MagicString(code);
60
+ s.prepend(`import { buildAssetsURL } from '#internal/nuxt/paths';\n${options.globalPublicPath} = buildAssetsURL();\n`);
61
+ return {
62
+ code: s.toString(),
63
+ map: options.sourcemap ? s.generateMap({ hires: true }) : void 0
64
+ };
65
+ }
66
+ }
67
+ };
66
68
  });
67
69
 
70
+ //#endregion
71
+ //#region ../webpack/src/plugins/chunk.ts
68
72
  const pluginName = "ChunkErrorPlugin";
69
- class ChunkErrorPlugin {
70
- apply(compiler) {
71
- compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
72
- compilation.hooks.runtimeRequirementInTree.for(webpack.RuntimeGlobals.ensureChunk).tap(pluginName, (chunk) => {
73
- compilation.addRuntimeModule(
74
- chunk,
75
- new ChunkErrorRuntimeModule()
76
- );
77
- });
78
- });
79
- }
80
- }
81
- class ChunkErrorRuntimeModule extends webpack.RuntimeModule {
82
- constructor() {
83
- super("chunk preload error handler", webpack.RuntimeModule.STAGE_ATTACH);
84
- }
85
- generate() {
86
- const { ensureChunk } = webpack.RuntimeGlobals;
87
- return `
73
+ var ChunkErrorPlugin = class {
74
+ apply(compiler) {
75
+ compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
76
+ compilation.hooks.runtimeRequirementInTree.for(webpack.RuntimeGlobals.ensureChunk).tap(pluginName, (chunk) => {
77
+ compilation.addRuntimeModule(chunk, new ChunkErrorRuntimeModule());
78
+ });
79
+ });
80
+ }
81
+ };
82
+ var ChunkErrorRuntimeModule = class extends webpack.RuntimeModule {
83
+ constructor() {
84
+ super("chunk preload error handler", webpack.RuntimeModule.STAGE_ATTACH);
85
+ }
86
+ generate() {
87
+ const { ensureChunk } = webpack.RuntimeGlobals;
88
+ return `
88
89
  if (typeof ${ensureChunk} !== "undefined") {
89
90
  var _ensureChunk = ${ensureChunk};
90
91
  ${ensureChunk} = function (chunkId) {
@@ -97,543 +98,432 @@ if (typeof ${ensureChunk} !== "undefined") {
97
98
  };
98
99
  }
99
100
  `;
100
- }
101
- }
101
+ }
102
+ };
102
103
 
104
+ //#endregion
105
+ //#region ../webpack/src/plugins/ssr-styles.ts
103
106
  const CSS_URL_RE = /url\((['"]?)(\/[^)]+?)\1\)/g;
104
107
  const isVueFile = (id) => /\.vue(?:\?|$)/.test(id);
105
108
  const isCSSLike = (name) => /\.(?:css|scss|sass|less|styl(?:us)?|postcss|pcss)(?:\?|$)/.test(name);
106
- function normalizePath(nuxt, id) {
107
- if (!id) {
108
- return null;
109
- }
110
- const { pathname } = parseURL(decodeURIComponent(pathToFileURL(id).href));
111
- const rel = relative(nuxt.options.srcDir, pathname);
112
- if (rel.startsWith("..")) {
113
- return null;
114
- }
115
- return rel;
109
+ function normalizePath(nuxt$1, id) {
110
+ if (!id) return null;
111
+ const { pathname } = parseURL(decodeURIComponent(pathToFileURL(id).href));
112
+ const rel = relative(nuxt$1.options.srcDir, pathname);
113
+ if (rel.startsWith("..")) return null;
114
+ return rel;
116
115
  }
117
116
  function resolveFilePath(id) {
118
- if (!id) {
119
- return null;
120
- }
121
- return parseURL(decodeURIComponent(pathToFileURL(id).href)).pathname || null;
117
+ if (!id) return null;
118
+ return parseURL(decodeURIComponent(pathToFileURL(id).href)).pathname || null;
122
119
  }
123
120
  function sanitizeStyleAssetName(rel) {
124
- return rel.replace(/[\\/]/g, "_").replace(/\.{2,}/g, "_");
121
+ return rel.replace(/[\\/]/g, "_").replace(/\.{2,}/g, "_");
125
122
  }
126
123
  function normalizeCSSContent(css) {
127
- return css.trim().replace(/(--[^:]+):\s*'([^']*)'/g, '$1:"$2"').replace(/:\s+/g, ":").replace(/\s*\{\s*/g, "{").replace(/;\s*\}/g, "}").replace(/\s*\}\s*/g, "}");
124
+ return css.trim().replace(/(--[^:]+):\s*'([^']*)'/g, "$1:\"$2\"").replace(/:\s+/g, ":").replace(/\s*\{\s*/g, "{").replace(/;\s*\}/g, "}").replace(/\s*\}\s*/g, "}");
128
125
  }
129
126
  function extractVueStyles(filePath) {
130
- try {
131
- const src = readFileSync(filePath, "utf8");
132
- const { descriptor } = parse(src, { filename: filePath });
133
- const styles = [];
134
- const scopeId = createHash("sha256").update(filePath).digest("hex").slice(0, 8);
135
- for (let i = 0; i < descriptor.styles.length; i++) {
136
- const style = descriptor.styles[i];
137
- const result = compileStyle({
138
- source: style.content,
139
- filename: filePath,
140
- id: `data-v-${scopeId}`,
141
- scoped: style.scoped
142
- });
143
- if (!result.errors.length && result.code) {
144
- styles.push(normalizeCSSContent(result.code));
145
- }
146
- }
147
- return styles;
148
- } catch {
149
- return [];
150
- }
151
- }
152
- class SSRStylesPlugin {
153
- nuxt;
154
- clientCSSByIssuer = /* @__PURE__ */ new Map();
155
- chunksWithInlinedCSS = /* @__PURE__ */ new Set();
156
- globalCSSPaths = /* @__PURE__ */ new Set();
157
- constructor(nuxt) {
158
- this.nuxt = nuxt;
159
- this.globalCSSPaths = this.resolveGlobalCSS();
160
- nuxt.hook("build:manifest", (manifest) => {
161
- for (const [id, chunk] of Object.entries(manifest)) {
162
- if (chunk.isEntry && chunk.src) {
163
- this.chunksWithInlinedCSS.add(chunk.src);
164
- } else if (this.chunksWithInlinedCSS.has(id)) {
165
- chunk.css &&= [];
166
- }
167
- if (chunk.css?.length) {
168
- chunk.css = chunk.css.filter((cssPath) => {
169
- for (const globalPath of this.globalCSSPaths) {
170
- if (cssPath.includes(globalPath.split("/").pop() || "")) {
171
- return false;
172
- }
173
- }
174
- return true;
175
- });
176
- }
177
- }
178
- });
179
- }
180
- shouldInline(mod) {
181
- const shouldInline = this.nuxt.options.features.inlineStyles;
182
- if (typeof shouldInline === "boolean") {
183
- return shouldInline;
184
- }
185
- return shouldInline(mod.identifier());
186
- }
187
- escapeTemplateLiteral(str) {
188
- return str.replace(/[`\\$]/g, (m) => m === "$" ? "\\$" : `\\${m}`);
189
- }
190
- isBuildAsset(url) {
191
- const buildDir = withTrailingSlash(this.nuxt.options.app.buildAssetsDir || "/_nuxt/");
192
- return url.startsWith(buildDir);
193
- }
194
- isPublicAsset(url, nitro) {
195
- const cleaned = url.replace(/[?#].*$/, "");
196
- for (const dir of nitro.options.publicAssets) {
197
- const base = withTrailingSlash(dir.baseURL || "/");
198
- if (!url.startsWith(base)) {
199
- continue;
200
- }
201
- const path = cleaned.replace(base, withTrailingSlash(dir.dir));
202
- if (existsSync(path)) {
203
- return true;
204
- }
205
- }
206
- return false;
207
- }
208
- rewriteStyle(css, nitro) {
209
- let changed = false;
210
- let needsPublicAsset = false;
211
- let needsBuildAsset = false;
212
- let lastIndex = 0;
213
- let out = "`";
214
- for (const match of css.matchAll(CSS_URL_RE)) {
215
- const index = match.index ?? 0;
216
- const before = css.slice(lastIndex, index);
217
- if (before) {
218
- out += this.escapeTemplateLiteral(before);
219
- }
220
- const full = match[0];
221
- const rawUrl = match[2] || "";
222
- const stripped = rawUrl.replace(/[?#].*$/, "");
223
- if (this.isPublicAsset(stripped, nitro)) {
224
- needsPublicAsset = true;
225
- changed = true;
226
- out += "${publicAssetsURL(" + JSON.stringify(rawUrl) + ")}";
227
- } else if (this.isBuildAsset(stripped)) {
228
- needsBuildAsset = true;
229
- changed = true;
230
- out += "${buildAssetsURL(" + JSON.stringify(rawUrl) + ")}";
231
- } else {
232
- out += this.escapeTemplateLiteral(full);
233
- }
234
- lastIndex = index + full.length;
235
- }
236
- const tail = css.slice(lastIndex);
237
- if (tail) {
238
- out += this.escapeTemplateLiteral(tail);
239
- }
240
- out += "`";
241
- return {
242
- code: changed ? out : JSON.stringify(css),
243
- needsPublicAsset,
244
- needsBuildAsset
245
- };
246
- }
247
- resolveGlobalCSS() {
248
- const req = createRequire(this.nuxt.options.rootDir);
249
- const resolved = /* @__PURE__ */ new Set();
250
- const entries = this.nuxt.options.css || [];
251
- for (const entry of entries) {
252
- const src = typeof entry === "string" ? entry : entry?.src;
253
- if (!src) {
254
- continue;
255
- }
256
- const path = this.resolveCSSRequest(src, req);
257
- if (path) {
258
- resolved.add(path);
259
- }
260
- }
261
- return resolved;
262
- }
263
- resolveCSSRequest(request, req) {
264
- const candidates = /* @__PURE__ */ new Set();
265
- const resolved = resolveAlias(request, this.nuxt.options.alias);
266
- if (isAbsolute(resolved)) {
267
- candidates.add(resolved);
268
- } else {
269
- candidates.add(resolve(this.nuxt.options.srcDir, resolved));
270
- }
271
- try {
272
- candidates.add(req.resolve(request));
273
- } catch {
274
- }
275
- for (const candidate of candidates) {
276
- const path = resolveFilePath(candidate);
277
- if (path) {
278
- return path;
279
- }
280
- }
281
- return null;
282
- }
283
- normalizeResourcePath(resource) {
284
- if (!resource) {
285
- return null;
286
- }
287
- const withoutQuery = resource.split("?")[0];
288
- return resolveFilePath(withoutQuery);
289
- }
290
- apply(compiler) {
291
- if (this.nuxt.options.dev) {
292
- return;
293
- }
294
- const isClient = compiler.options.name === "client";
295
- const isServer = compiler.options.name === "server";
296
- if (!isClient && !isServer) {
297
- return;
298
- }
299
- compiler.hooks.thisCompilation.tap("SSRStylesPlugin", (compilation) => {
300
- this.collectCSS(compilation);
301
- if (isClient) {
302
- this.removeGlobalCSSFromClient(compilation);
303
- }
304
- if (isServer) {
305
- this.emitServerStyles(compilation);
306
- }
307
- });
308
- }
309
- emitServerStyles(compilation) {
310
- const { webpack } = compilation.compiler;
311
- const stage = webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE;
312
- compilation.hooks.processAssets.tap({ name: "SSRStylesPlugin", stage }, () => {
313
- const nitro = useNitro();
314
- const collected = new Map(this.clientCSSByIssuer);
315
- const entryModules = /* @__PURE__ */ new Set();
316
- for (const entrypoint of compilation.entrypoints.values()) {
317
- const primaryChunk = typeof entrypoint.getEntrypointChunk === "function" ? entrypoint.getEntrypointChunk() : void 0;
318
- const chunks = primaryChunk ? [primaryChunk] : entrypoint.chunks;
319
- for (const chunk of chunks) {
320
- for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) {
321
- if ("resource" in mod && typeof mod.resource === "string") {
322
- const resolved = resolveFilePath(mod.resource);
323
- if (resolved) {
324
- const rel = normalizePath(this.nuxt, resolved);
325
- if (rel) {
326
- entryModules.add(rel);
327
- } else {
328
- entryModules.add(resolved);
329
- }
330
- }
331
- }
332
- }
333
- }
334
- }
335
- for (const module of compilation.modules) {
336
- const normal = module;
337
- const resource = normal.resource;
338
- if (!resource || !isVueFile(resource)) {
339
- continue;
340
- }
341
- const rel = normalizePath(this.nuxt, resource);
342
- if (!rel) {
343
- continue;
344
- }
345
- if (collected.has(rel)) {
346
- continue;
347
- }
348
- const vueStyles = extractVueStyles(resolveFilePath(resource) || resource);
349
- if (vueStyles.length) {
350
- collected.set(rel, new Set(vueStyles));
351
- }
352
- }
353
- const emitted = {};
354
- const rawSource = webpack.sources.RawSource;
355
- for (const [rel, cssSet] of collected.entries()) {
356
- if (!cssSet.size) {
357
- continue;
358
- }
359
- const stylesArray = Array.from(cssSet);
360
- const transformed = stylesArray.map((style) => this.rewriteStyle(style, nitro));
361
- const needsPublicAssets = transformed.some((t) => t.needsPublicAsset);
362
- const needsBuildAssets = transformed.some((t) => t.needsBuildAsset);
363
- const imports = [];
364
- if (needsPublicAssets || needsBuildAssets) {
365
- const names = [];
366
- if (needsBuildAssets) {
367
- names.push("buildAssetsURL");
368
- }
369
- if (needsPublicAssets) {
370
- names.push("publicAssetsURL");
371
- }
372
- imports.push(`import { ${names.join(", ")} } from '#internal/nuxt/paths'`);
373
- }
374
- const moduleSource = [
375
- ...imports,
376
- `export default ${genArrayFromRaw(transformed.map((t) => t.code))}`
377
- ].filter(Boolean).join("\n");
378
- const styleModuleName = `${sanitizeStyleAssetName(rel)}-styles.mjs`;
379
- compilation.emitAsset(styleModuleName, new rawSource(moduleSource));
380
- emitted[rel] = styleModuleName;
381
- this.chunksWithInlinedCSS.add(rel);
382
- }
383
- const stylesSource = [
384
- "const interopDefault = r => r.default || r || []",
385
- `export default ${genObjectFromRawEntries(
386
- Object.entries(emitted).map(([key, value]) => [key, `() => import('./${value}').then(interopDefault)`])
387
- )}`
388
- ].join("\n");
389
- compilation.emitAsset("styles.mjs", new rawSource(stylesSource));
390
- const entryIds = Array.from(this.chunksWithInlinedCSS).filter((id) => entryModules.has(id));
391
- nitro.options.virtual["#internal/nuxt/entry-ids.mjs"] = () => `export default ${JSON.stringify(entryIds)}`;
392
- nitro.options._config.virtual ||= {};
393
- nitro.options._config.virtual["#internal/nuxt/entry-ids.mjs"] = nitro.options.virtual["#internal/nuxt/entry-ids.mjs"];
394
- });
395
- }
396
- findIssuerPath(compilation, mod) {
397
- let issuer = compilation.moduleGraph.getIssuer(mod);
398
- while (issuer) {
399
- if ("resource" in issuer && typeof issuer.resource === "string") {
400
- return issuer.resource;
401
- }
402
- issuer = compilation.moduleGraph.getIssuer(issuer);
403
- }
404
- return null;
405
- }
406
- removeGlobalCSSFromClient(compilation) {
407
- const stage = 650;
408
- compilation.hooks.processAssets.tap({ name: "SSRStylesPlugin:RemoveGlobalCSS", stage }, () => {
409
- for (const chunk of compilation.chunks) {
410
- if (chunk.name === "nuxt-global-css") {
411
- const cssAssets = [];
412
- for (const file of Array.from(chunk.files)) {
413
- const filename = String(file);
414
- if (isCSSLike(filename)) {
415
- const asset = compilation.getAsset(filename);
416
- const source = asset?.source;
417
- const content = source && typeof source.source === "function" ? source.source() : null;
418
- const text = typeof content === "string" ? content : content instanceof Buffer ? content.toString("utf8") : "";
419
- if (text) {
420
- cssAssets.push(text);
421
- }
422
- }
423
- }
424
- if (cssAssets.length > 0) {
425
- for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) {
426
- const issuerPath = this.findIssuerPath(compilation, mod) || ("resource" in mod && typeof mod.resource === "string" ? mod.resource : null);
427
- const normalized = normalizePath(this.nuxt, issuerPath);
428
- if (!normalized) {
429
- continue;
430
- }
431
- const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
432
- for (const css of cssAssets) {
433
- set.add(normalizeCSSContent(css));
434
- }
435
- this.clientCSSByIssuer.set(normalized, set);
436
- }
437
- }
438
- for (const file of Array.from(chunk.files)) {
439
- const filename = String(file);
440
- if (isCSSLike(filename)) {
441
- compilation.deleteAsset(filename);
442
- chunk.files.delete(file);
443
- }
444
- }
445
- }
446
- }
447
- });
448
- }
449
- collectCSS(compilation) {
450
- const { webpack } = compilation.compiler;
451
- const isServer = compilation.compiler.options.name === "server";
452
- const stage = isServer ? webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS : webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER;
453
- const chunkCSSMeta = /* @__PURE__ */ new Map();
454
- compilation.hooks.processAssets.tap({ name: "SSRStylesPlugin", stage }, () => {
455
- const cssAssetsByChunk = /* @__PURE__ */ new Map();
456
- for (const chunk of compilation.chunks) {
457
- const cssAssets = [];
458
- const chunkCSSFiles = [];
459
- for (const file of chunk.files) {
460
- if (!isCSSLike(file)) {
461
- continue;
462
- }
463
- chunkCSSFiles.push(file);
464
- const asset = compilation.getAsset(file);
465
- const source = asset?.source;
466
- const content = source && typeof source.source === "function" ? source.source() : null;
467
- const text = typeof content === "string" ? content : content instanceof Buffer ? content.toString("utf8") : "";
468
- if (text) {
469
- cssAssets.push(text);
470
- }
471
- }
472
- if (chunkCSSFiles.length) {
473
- const chunkCSSModules = Array.from(compilation.chunkGraph.getChunkModulesIterable(chunk));
474
- chunkCSSMeta.set(chunk, { files: chunkCSSFiles, modules: chunkCSSModules });
475
- }
476
- if (cssAssets.length) {
477
- cssAssetsByChunk.set(chunk, cssAssets);
478
- }
479
- }
480
- for (const [chunk, cssAssets] of cssAssetsByChunk) {
481
- for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) {
482
- if (!this.shouldInline(mod)) {
483
- continue;
484
- }
485
- const issuerPath = this.findIssuerPath(compilation, mod) || ("resource" in mod && typeof mod.resource === "string" ? mod.resource : null);
486
- const normalized = normalizePath(this.nuxt, issuerPath);
487
- if (!normalized) {
488
- continue;
489
- }
490
- const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
491
- for (const css of cssAssets) {
492
- set.add(normalizeCSSContent(css));
493
- }
494
- this.clientCSSByIssuer.set(normalized, set);
495
- }
496
- }
497
- for (const mod of compilation.modules) {
498
- if (!this.shouldInline(mod)) {
499
- continue;
500
- }
501
- const issuerPath = this.findIssuerPath(compilation, mod);
502
- const normalized = normalizePath(this.nuxt, issuerPath);
503
- if (!normalized) {
504
- continue;
505
- }
506
- const cssChunks = this.getModuleCSS(mod, compilation);
507
- if (!cssChunks.length) {
508
- continue;
509
- }
510
- const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
511
- set.add(cssChunks.join("\n"));
512
- this.clientCSSByIssuer.set(normalized, set);
513
- }
514
- });
515
- }
516
- getModuleCSS(mod, _compilation) {
517
- const cssModule = mod;
518
- const cssChunks = [];
519
- if (mod.type === "css/mini-extract" && Array.isArray(cssModule.content)) {
520
- for (const part of cssModule.content) {
521
- const css = part?.[1];
522
- if (css && typeof css === "string") {
523
- cssChunks.push(normalizeCSSContent(css));
524
- }
525
- }
526
- }
527
- return cssChunks;
528
- }
127
+ try {
128
+ const { descriptor } = parse(readFileSync(filePath, "utf8"), { filename: filePath });
129
+ const styles = [];
130
+ const scopeId = createHash("sha256").update(filePath).digest("hex").slice(0, 8);
131
+ for (let i = 0; i < descriptor.styles.length; i++) {
132
+ const style$1 = descriptor.styles[i];
133
+ const result = compileStyle({
134
+ source: style$1.content,
135
+ filename: filePath,
136
+ id: `data-v-${scopeId}`,
137
+ scoped: style$1.scoped
138
+ });
139
+ if (!result.errors.length && result.code) styles.push(normalizeCSSContent(result.code));
140
+ }
141
+ return styles;
142
+ } catch {
143
+ return [];
144
+ }
529
145
  }
146
+ var SSRStylesPlugin = class {
147
+ nuxt;
148
+ clientCSSByIssuer = /* @__PURE__ */ new Map();
149
+ chunksWithInlinedCSS = /* @__PURE__ */ new Set();
150
+ globalCSSPaths = /* @__PURE__ */ new Set();
151
+ constructor(nuxt$1) {
152
+ this.nuxt = nuxt$1;
153
+ this.globalCSSPaths = this.resolveGlobalCSS();
154
+ nuxt$1.hook("build:manifest", (manifest) => {
155
+ for (const [id, chunk] of Object.entries(manifest)) {
156
+ if (chunk.isEntry && chunk.src) this.chunksWithInlinedCSS.add(chunk.src);
157
+ else if (this.chunksWithInlinedCSS.has(id)) chunk.css &&= [];
158
+ if (chunk.css?.length) chunk.css = chunk.css.filter((cssPath) => {
159
+ for (const globalPath of this.globalCSSPaths) if (cssPath.includes(globalPath.split("/").pop() || "")) return false;
160
+ return true;
161
+ });
162
+ }
163
+ });
164
+ }
165
+ shouldInline(mod) {
166
+ const shouldInline = this.nuxt.options.features.inlineStyles;
167
+ if (typeof shouldInline === "boolean") return shouldInline;
168
+ return shouldInline(mod.identifier());
169
+ }
170
+ escapeTemplateLiteral(str) {
171
+ return str.replace(/[`\\$]/g, (m) => m === "$" ? "\\$" : `\\${m}`);
172
+ }
173
+ isBuildAsset(url) {
174
+ const buildDir = withTrailingSlash(this.nuxt.options.app.buildAssetsDir || "/_nuxt/");
175
+ return url.startsWith(buildDir);
176
+ }
177
+ isPublicAsset(url, nitro) {
178
+ const cleaned = url.replace(/[?#].*$/, "");
179
+ for (const dir of nitro.options.publicAssets) {
180
+ const base$1 = withTrailingSlash(dir.baseURL || "/");
181
+ if (!url.startsWith(base$1)) continue;
182
+ if (existsSync(cleaned.replace(base$1, withTrailingSlash(dir.dir)))) return true;
183
+ }
184
+ return false;
185
+ }
186
+ rewriteStyle(css, nitro) {
187
+ let changed = false;
188
+ let needsPublicAsset = false;
189
+ let needsBuildAsset = false;
190
+ let lastIndex = 0;
191
+ let out = "`";
192
+ for (const match of css.matchAll(CSS_URL_RE)) {
193
+ const index = match.index ?? 0;
194
+ const before = css.slice(lastIndex, index);
195
+ if (before) out += this.escapeTemplateLiteral(before);
196
+ const full = match[0];
197
+ const rawUrl = match[2] || "";
198
+ const stripped = rawUrl.replace(/[?#].*$/, "");
199
+ if (this.isPublicAsset(stripped, nitro)) {
200
+ needsPublicAsset = true;
201
+ changed = true;
202
+ out += "${publicAssetsURL(" + JSON.stringify(rawUrl) + ")}";
203
+ } else if (this.isBuildAsset(stripped)) {
204
+ needsBuildAsset = true;
205
+ changed = true;
206
+ out += "${buildAssetsURL(" + JSON.stringify(rawUrl) + ")}";
207
+ } else out += this.escapeTemplateLiteral(full);
208
+ lastIndex = index + full.length;
209
+ }
210
+ const tail = css.slice(lastIndex);
211
+ if (tail) out += this.escapeTemplateLiteral(tail);
212
+ out += "`";
213
+ return {
214
+ code: changed ? out : JSON.stringify(css),
215
+ needsPublicAsset,
216
+ needsBuildAsset
217
+ };
218
+ }
219
+ resolveGlobalCSS() {
220
+ const req = createRequire(this.nuxt.options.rootDir);
221
+ const resolved = /* @__PURE__ */ new Set();
222
+ const entries = this.nuxt.options.css || [];
223
+ for (const entry of entries) {
224
+ const src = typeof entry === "string" ? entry : entry?.src;
225
+ if (!src) continue;
226
+ const path = this.resolveCSSRequest(src, req);
227
+ if (path) resolved.add(path);
228
+ }
229
+ return resolved;
230
+ }
231
+ resolveCSSRequest(request, req) {
232
+ const candidates = /* @__PURE__ */ new Set();
233
+ const resolved = resolveAlias(request, this.nuxt.options.alias);
234
+ if (isAbsolute(resolved)) candidates.add(resolved);
235
+ else candidates.add(resolve(this.nuxt.options.srcDir, resolved));
236
+ try {
237
+ candidates.add(req.resolve(request));
238
+ } catch {}
239
+ for (const candidate of candidates) {
240
+ const path = resolveFilePath(candidate);
241
+ if (path) return path;
242
+ }
243
+ return null;
244
+ }
245
+ normalizeResourcePath(resource) {
246
+ if (!resource) return null;
247
+ const withoutQuery = resource.split("?")[0];
248
+ return resolveFilePath(withoutQuery);
249
+ }
250
+ apply(compiler) {
251
+ if (this.nuxt.options.dev) return;
252
+ const isClient = compiler.options.name === "client";
253
+ const isServer = compiler.options.name === "server";
254
+ if (!isClient && !isServer) return;
255
+ compiler.hooks.thisCompilation.tap("SSRStylesPlugin", (compilation) => {
256
+ this.collectCSS(compilation);
257
+ if (isClient) this.removeGlobalCSSFromClient(compilation);
258
+ if (isServer) this.emitServerStyles(compilation);
259
+ });
260
+ }
261
+ emitServerStyles(compilation) {
262
+ const { webpack: webpack$1 } = compilation.compiler;
263
+ const stage = webpack$1.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE;
264
+ compilation.hooks.processAssets.tap({
265
+ name: "SSRStylesPlugin",
266
+ stage
267
+ }, () => {
268
+ const nitro = useNitro();
269
+ const collected = new Map(this.clientCSSByIssuer);
270
+ const entryModules = /* @__PURE__ */ new Set();
271
+ for (const entrypoint of compilation.entrypoints.values()) {
272
+ const primaryChunk = typeof entrypoint.getEntrypointChunk === "function" ? entrypoint.getEntrypointChunk() : void 0;
273
+ const chunks = primaryChunk ? [primaryChunk] : entrypoint.chunks;
274
+ for (const chunk of chunks) for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) if ("resource" in mod && typeof mod.resource === "string") {
275
+ const resolved = resolveFilePath(mod.resource);
276
+ if (resolved) {
277
+ const rel = normalizePath(this.nuxt, resolved);
278
+ if (rel) entryModules.add(rel);
279
+ else entryModules.add(resolved);
280
+ }
281
+ }
282
+ }
283
+ for (const module of compilation.modules) {
284
+ const resource = module.resource;
285
+ if (!resource || !isVueFile(resource)) continue;
286
+ const rel = normalizePath(this.nuxt, resource);
287
+ if (!rel) continue;
288
+ if (collected.has(rel)) continue;
289
+ const vueStyles = extractVueStyles(resolveFilePath(resource) || resource);
290
+ if (vueStyles.length) collected.set(rel, new Set(vueStyles));
291
+ }
292
+ const emitted = {};
293
+ const rawSource = webpack$1.sources.RawSource;
294
+ for (const [rel, cssSet] of collected.entries()) {
295
+ if (!cssSet.size) continue;
296
+ const transformed = Array.from(cssSet).map((style$1) => this.rewriteStyle(style$1, nitro));
297
+ const needsPublicAssets = transformed.some((t) => t.needsPublicAsset);
298
+ const needsBuildAssets = transformed.some((t) => t.needsBuildAsset);
299
+ const imports = [];
300
+ if (needsPublicAssets || needsBuildAssets) {
301
+ const names = [];
302
+ if (needsBuildAssets) names.push("buildAssetsURL");
303
+ if (needsPublicAssets) names.push("publicAssetsURL");
304
+ imports.push(`import { ${names.join(", ")} } from '#internal/nuxt/paths'`);
305
+ }
306
+ const moduleSource = [...imports, `export default ${genArrayFromRaw(transformed.map((t) => t.code))}`].filter(Boolean).join("\n");
307
+ const styleModuleName = `${sanitizeStyleAssetName(rel)}-styles.mjs`;
308
+ compilation.emitAsset(styleModuleName, new rawSource(moduleSource));
309
+ emitted[rel] = styleModuleName;
310
+ this.chunksWithInlinedCSS.add(rel);
311
+ }
312
+ const stylesSource = ["const interopDefault = r => r.default || r || []", `export default ${genObjectFromRawEntries(Object.entries(emitted).map(([key, value]) => [key, `() => import('./${value}').then(interopDefault)`]))}`].join("\n");
313
+ compilation.emitAsset("styles.mjs", new rawSource(stylesSource));
314
+ const entryIds = Array.from(this.chunksWithInlinedCSS).filter((id) => entryModules.has(id));
315
+ nitro.options.virtual["#internal/nuxt/entry-ids.mjs"] = () => `export default ${JSON.stringify(entryIds)}`;
316
+ nitro.options._config.virtual ||= {};
317
+ nitro.options._config.virtual["#internal/nuxt/entry-ids.mjs"] = nitro.options.virtual["#internal/nuxt/entry-ids.mjs"];
318
+ });
319
+ }
320
+ findIssuerPath(compilation, mod) {
321
+ let issuer = compilation.moduleGraph.getIssuer(mod);
322
+ while (issuer) {
323
+ if ("resource" in issuer && typeof issuer.resource === "string") return issuer.resource;
324
+ issuer = compilation.moduleGraph.getIssuer(issuer);
325
+ }
326
+ return null;
327
+ }
328
+ removeGlobalCSSFromClient(compilation) {
329
+ compilation.hooks.processAssets.tap({
330
+ name: "SSRStylesPlugin:RemoveGlobalCSS",
331
+ stage: 650
332
+ }, () => {
333
+ for (const chunk of compilation.chunks) if (chunk.name === "nuxt-global-css") {
334
+ const cssAssets = [];
335
+ for (const file of Array.from(chunk.files)) {
336
+ const filename = String(file);
337
+ if (isCSSLike(filename)) {
338
+ const source = compilation.getAsset(filename)?.source;
339
+ const content = source && typeof source.source === "function" ? source.source() : null;
340
+ const text = typeof content === "string" ? content : content instanceof Buffer ? content.toString("utf8") : "";
341
+ if (text) cssAssets.push(text);
342
+ }
343
+ }
344
+ if (cssAssets.length > 0) for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) {
345
+ const issuerPath = this.findIssuerPath(compilation, mod) || ("resource" in mod && typeof mod.resource === "string" ? mod.resource : null);
346
+ const normalized = normalizePath(this.nuxt, issuerPath);
347
+ if (!normalized) continue;
348
+ const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
349
+ for (const css of cssAssets) set.add(normalizeCSSContent(css));
350
+ this.clientCSSByIssuer.set(normalized, set);
351
+ }
352
+ for (const file of Array.from(chunk.files)) {
353
+ const filename = String(file);
354
+ if (isCSSLike(filename)) {
355
+ compilation.deleteAsset(filename);
356
+ chunk.files.delete(file);
357
+ }
358
+ }
359
+ }
360
+ });
361
+ }
362
+ collectCSS(compilation) {
363
+ const { webpack: webpack$1 } = compilation.compiler;
364
+ const stage = compilation.compiler.options.name === "server" ? webpack$1.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS : webpack$1.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER;
365
+ const chunkCSSMeta = /* @__PURE__ */ new Map();
366
+ compilation.hooks.processAssets.tap({
367
+ name: "SSRStylesPlugin",
368
+ stage
369
+ }, () => {
370
+ const cssAssetsByChunk = /* @__PURE__ */ new Map();
371
+ for (const chunk of compilation.chunks) {
372
+ const cssAssets = [];
373
+ const chunkCSSFiles = [];
374
+ for (const file of chunk.files) {
375
+ if (!isCSSLike(file)) continue;
376
+ chunkCSSFiles.push(file);
377
+ const source = compilation.getAsset(file)?.source;
378
+ const content = source && typeof source.source === "function" ? source.source() : null;
379
+ const text = typeof content === "string" ? content : content instanceof Buffer ? content.toString("utf8") : "";
380
+ if (text) cssAssets.push(text);
381
+ }
382
+ if (chunkCSSFiles.length) {
383
+ const chunkCSSModules = Array.from(compilation.chunkGraph.getChunkModulesIterable(chunk));
384
+ chunkCSSMeta.set(chunk, {
385
+ files: chunkCSSFiles,
386
+ modules: chunkCSSModules
387
+ });
388
+ }
389
+ if (cssAssets.length) cssAssetsByChunk.set(chunk, cssAssets);
390
+ }
391
+ for (const [chunk, cssAssets] of cssAssetsByChunk) for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) {
392
+ if (!this.shouldInline(mod)) continue;
393
+ const issuerPath = this.findIssuerPath(compilation, mod) || ("resource" in mod && typeof mod.resource === "string" ? mod.resource : null);
394
+ const normalized = normalizePath(this.nuxt, issuerPath);
395
+ if (!normalized) continue;
396
+ const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
397
+ for (const css of cssAssets) set.add(normalizeCSSContent(css));
398
+ this.clientCSSByIssuer.set(normalized, set);
399
+ }
400
+ for (const mod of compilation.modules) {
401
+ if (!this.shouldInline(mod)) continue;
402
+ const issuerPath = this.findIssuerPath(compilation, mod);
403
+ const normalized = normalizePath(this.nuxt, issuerPath);
404
+ if (!normalized) continue;
405
+ const cssChunks = this.getModuleCSS(mod, compilation);
406
+ if (!cssChunks.length) continue;
407
+ const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
408
+ set.add(cssChunks.join("\n"));
409
+ this.clientCSSByIssuer.set(normalized, set);
410
+ }
411
+ });
412
+ }
413
+ getModuleCSS(mod, _compilation) {
414
+ const cssModule = mod;
415
+ const cssChunks = [];
416
+ if (mod.type === "css/mini-extract" && Array.isArray(cssModule.content)) for (const part of cssModule.content) {
417
+ const css = part?.[1];
418
+ if (css && typeof css === "string") cssChunks.push(normalizeCSSContent(css));
419
+ }
420
+ return cssChunks;
421
+ }
422
+ };
530
423
 
424
+ //#endregion
425
+ //#region ../webpack/src/utils/mfs.ts
531
426
  function createMFS() {
532
- const fs = createFsFromVolume(new Volume());
533
- const _fs = { ...fs };
534
- _fs.join = join;
535
- _fs.exists = (p) => Promise.resolve(_fs.existsSync(p));
536
- _fs.readFile = pify(_fs.readFile);
537
- return _fs;
427
+ const _fs = { ...createFsFromVolume(new Volume()) };
428
+ _fs.join = join;
429
+ _fs.exists = (p) => Promise.resolve(_fs.existsSync(p));
430
+ _fs.readFile = pify(_fs.readFile);
431
+ return _fs;
538
432
  }
539
433
 
434
+ //#endregion
435
+ //#region ../webpack/src/utils/index.ts
436
+ /** @since 3.9.0 */
540
437
  function toArray(value) {
541
- return Array.isArray(value) ? value : [value];
438
+ return Array.isArray(value) ? value : [value];
542
439
  }
543
440
 
544
- function createWebpackConfigContext(nuxt) {
545
- return {
546
- nuxt,
547
- options: nuxt.options,
548
- userConfig: nuxt.options.webpack,
549
- config: {},
550
- name: "base",
551
- isDev: nuxt.options.dev,
552
- isServer: false,
553
- isClient: false,
554
- alias: {},
555
- transpile: []
556
- };
441
+ //#endregion
442
+ //#region ../webpack/src/utils/config.ts
443
+ function createWebpackConfigContext(nuxt$1) {
444
+ return {
445
+ nuxt: nuxt$1,
446
+ options: nuxt$1.options,
447
+ userConfig: nuxt$1.options.webpack,
448
+ config: {},
449
+ name: "base",
450
+ isDev: nuxt$1.options.dev,
451
+ isServer: false,
452
+ isClient: false,
453
+ alias: {},
454
+ transpile: []
455
+ };
557
456
  }
558
457
  async function applyPresets(ctx, presets) {
559
- for (const preset of toArray(presets)) {
560
- if (Array.isArray(preset)) {
561
- await preset[0](ctx, preset[1]);
562
- } else {
563
- await preset(ctx);
564
- }
565
- }
458
+ for (const preset of toArray(presets)) if (Array.isArray(preset)) await preset[0](ctx, preset[1]);
459
+ else await preset(ctx);
566
460
  }
567
461
  function fileName(ctx, key) {
568
- let fileName2 = ctx.userConfig.filenames[key];
569
- if (typeof fileName2 === "function") {
570
- fileName2 = fileName2(ctx);
571
- }
572
- if (typeof fileName2 === "string" && ctx.options.dev) {
573
- const hash = /\[(chunkhash|contenthash|hash)(?::\d+)?\]/.exec(fileName2);
574
- if (hash) {
575
- logger.warn(`Notice: Please do not use ${hash[1]} in dev mode to prevent memory leak`);
576
- }
577
- }
578
- return fileName2;
462
+ let fileName$1 = ctx.userConfig.filenames[key];
463
+ if (typeof fileName$1 === "function") fileName$1 = fileName$1(ctx);
464
+ if (typeof fileName$1 === "string" && ctx.options.dev) {
465
+ const hash$1 = /\[(chunkhash|contenthash|hash)(?::\d+)?\]/.exec(fileName$1);
466
+ if (hash$1) logger.warn(`Notice: Please do not use ${hash$1[1]} in dev mode to prevent memory leak`);
467
+ }
468
+ return fileName$1;
579
469
  }
580
470
 
471
+ //#endregion
472
+ //#region ../webpack/src/presets/assets.ts
581
473
  function assets(ctx) {
582
- ctx.config.module.rules.push(
583
- {
584
- test: /\.(png|jpe?g|gif|svg|webp)$/i,
585
- use: [{
586
- loader: "url-loader",
587
- options: {
588
- ...ctx.userConfig.loaders.imgUrl,
589
- name: fileName(ctx, "img")
590
- }
591
- }]
592
- },
593
- {
594
- test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
595
- use: [{
596
- loader: "url-loader",
597
- options: {
598
- ...ctx.userConfig.loaders.fontUrl,
599
- name: fileName(ctx, "font")
600
- }
601
- }]
602
- },
603
- {
604
- test: /\.(webm|mp4|ogv)$/i,
605
- use: [{
606
- loader: "file-loader",
607
- options: {
608
- ...ctx.userConfig.loaders.file,
609
- name: fileName(ctx, "video")
610
- }
611
- }]
612
- }
613
- );
474
+ ctx.config.module.rules.push({
475
+ test: /\.(png|jpe?g|gif|svg|webp)$/i,
476
+ use: [{
477
+ loader: "url-loader",
478
+ options: {
479
+ ...ctx.userConfig.loaders.imgUrl,
480
+ name: fileName(ctx, "img")
481
+ }
482
+ }]
483
+ }, {
484
+ test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
485
+ use: [{
486
+ loader: "url-loader",
487
+ options: {
488
+ ...ctx.userConfig.loaders.fontUrl,
489
+ name: fileName(ctx, "font")
490
+ }
491
+ }]
492
+ }, {
493
+ test: /\.(webm|mp4|ogv)$/i,
494
+ use: [{
495
+ loader: "file-loader",
496
+ options: {
497
+ ...ctx.userConfig.loaders.file,
498
+ name: fileName(ctx, "video")
499
+ }
500
+ }]
501
+ });
614
502
  }
615
503
 
616
- class WarningIgnorePlugin {
617
- filter;
618
- constructor(filter) {
619
- this.filter = filter;
620
- }
621
- apply(compiler) {
622
- compiler.hooks.done.tap("warnfix-plugin", (stats) => {
623
- stats.compilation.warnings = stats.compilation.warnings.filter(this.filter);
624
- });
625
- }
626
- }
504
+ //#endregion
505
+ //#region ../webpack/src/plugins/warning-ignore.ts
506
+ var WarningIgnorePlugin = class {
507
+ filter;
508
+ constructor(filter) {
509
+ this.filter = filter;
510
+ }
511
+ apply(compiler) {
512
+ compiler.hooks.done.tap("warnfix-plugin", (stats) => {
513
+ stats.compilation.warnings = stats.compilation.warnings.filter(this.filter);
514
+ });
515
+ }
516
+ };
627
517
 
518
+ //#endregion
519
+ //#region ../webpack/src/plugins/vue/util.ts
520
+ /**
521
+ * This file is based on Vue.js (MIT) webpack plugins
522
+ * https://github.com/vuejs/vue/blob/dev/src/server/webpack-plugin/util.js
523
+ */
628
524
  const validate = (compiler) => {
629
- if (compiler.options.target !== "node") {
630
- logger.warn('webpack config `target` should be "node".');
631
- }
632
- if (!compiler.options.externals) {
633
- logger.info(
634
- "It is recommended to externalize dependencies in the server build for better build performance."
635
- );
636
- }
525
+ if (compiler.options.target !== "node") logger.warn("webpack config `target` should be \"node\".");
526
+ if (!compiler.options.externals) logger.info("It is recommended to externalize dependencies in the server build for better build performance.");
637
527
  };
638
528
  const isJSRegExp = /\.[cm]?js(\?[^.]+)?$/;
639
529
  const isJS = (file) => isJSRegExp.test(file);
@@ -642,87 +532,66 @@ const isCSSRegExp = /\.css(?:\?[^.]+)?$/;
642
532
  const isCSS = (file) => isCSSRegExp.test(file);
643
533
  const isHotUpdate = (file) => file.includes("hot-update");
644
534
 
535
+ //#endregion
536
+ //#region ../webpack/src/plugins/rollup-compat-dynamic-import.ts
645
537
  const DYNAMIC_IMPORT_RE = /import\([^)]*\+\s*__webpack_require__[^+]*\)\.then/;
646
538
  const DYNAMIC_IMPORT_REPLACE_RE = /import\([^)]*\+\s*(__webpack_require__[^+]*)\)\.then/g;
647
539
  const HELPER_FILENAME = "_dynamic-import-helper.mjs";
648
- const HELPER_IMPORT = `import { _rollupDynamicImport } from "./${HELPER_FILENAME}";
649
- `;
650
- class RollupCompatDynamicImportPlugin {
651
- apply(compiler) {
652
- compiler.hooks.compilation.tap("RollupCompatDynamicImportPlugin", (compilation) => {
653
- compilation.hooks.processAssets.tapAsync(
654
- {
655
- name: "RollupCompatDynamicImportPlugin",
656
- stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
657
- },
658
- (assets, callback) => {
659
- try {
660
- const targetFiles = /* @__PURE__ */ new Set();
661
- for (const chunk of compilation.chunks) {
662
- if (chunk.canBeInitial() || chunk.hasRuntime()) {
663
- for (const file of chunk.files || []) {
664
- targetFiles.add(file);
665
- }
666
- }
667
- }
668
- for (const [filename, asset] of Object.entries(assets)) {
669
- if (!isJS(filename)) {
670
- continue;
671
- }
672
- if (!targetFiles.has(filename)) {
673
- continue;
674
- }
675
- const source = asset.source();
676
- const originalCode = typeof source === "string" ? source : source.toString();
677
- if (!DYNAMIC_IMPORT_RE.test(originalCode)) {
678
- continue;
679
- }
680
- const transformedCode = this.transformDynamicImports(originalCode);
681
- if (transformedCode !== originalCode) {
682
- assets[filename] = new compiler.webpack.sources.RawSource(transformedCode);
683
- }
684
- }
685
- this.generateDynamicImportHelper(compilation);
686
- callback();
687
- } catch (error) {
688
- callback(error);
689
- }
690
- }
691
- );
692
- });
693
- }
694
- transformDynamicImports(source) {
695
- let transformed = source;
696
- let needsHelperImport = false;
697
- transformed = transformed.replace(DYNAMIC_IMPORT_REPLACE_RE, (match, filename) => {
698
- needsHelperImport = true;
699
- return `_rollupDynamicImport(${filename}).then`;
700
- });
701
- if (needsHelperImport && !transformed.includes(HELPER_IMPORT)) {
702
- transformed = HELPER_IMPORT + transformed;
703
- }
704
- return transformed;
705
- }
706
- generateDynamicImportHelper(compilation) {
707
- const chunkFiles = [];
708
- for (const chunk of compilation.chunks) {
709
- if (chunk.hasRuntime()) {
710
- continue;
711
- }
712
- for (const filename of chunk.files) {
713
- if (filename && isJS(filename)) {
714
- chunkFiles.push(filename);
715
- }
716
- }
717
- }
718
- if (chunkFiles.length === 0) {
719
- return;
720
- }
721
- const helperContent = this.generateHelperContent(chunkFiles);
722
- compilation.emitAsset(HELPER_FILENAME, new compilation.compiler.webpack.sources.RawSource(helperContent));
723
- }
724
- generateHelperContent(chunkFiles) {
725
- return `
540
+ const HELPER_IMPORT = `import { _rollupDynamicImport } from "./${HELPER_FILENAME}";\n`;
541
+ /**
542
+ * Webpack plugin that generates rollup-compatible dynamic imports.
543
+ * This plugin uses webpack's native compilation hooks to override dynamic import generation
544
+ * and create rollup-compatible code directly during webpack's compilation process.
545
+ */
546
+ var RollupCompatDynamicImportPlugin = class {
547
+ apply(compiler) {
548
+ compiler.hooks.compilation.tap("RollupCompatDynamicImportPlugin", (compilation) => {
549
+ compilation.hooks.processAssets.tapAsync({
550
+ name: "RollupCompatDynamicImportPlugin",
551
+ stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
552
+ }, (assets$1, callback) => {
553
+ try {
554
+ const targetFiles = /* @__PURE__ */ new Set();
555
+ for (const chunk of compilation.chunks) if (chunk.canBeInitial() || chunk.hasRuntime()) for (const file of chunk.files || []) targetFiles.add(file);
556
+ for (const [filename, asset] of Object.entries(assets$1)) {
557
+ if (!isJS(filename)) continue;
558
+ if (!targetFiles.has(filename)) continue;
559
+ const source = asset.source();
560
+ const originalCode = typeof source === "string" ? source : source.toString();
561
+ if (!DYNAMIC_IMPORT_RE.test(originalCode)) continue;
562
+ const transformedCode = this.transformDynamicImports(originalCode);
563
+ if (transformedCode !== originalCode) assets$1[filename] = new compiler.webpack.sources.RawSource(transformedCode);
564
+ }
565
+ this.generateDynamicImportHelper(compilation);
566
+ callback();
567
+ } catch (error) {
568
+ callback(error);
569
+ }
570
+ });
571
+ });
572
+ }
573
+ transformDynamicImports(source) {
574
+ let transformed = source;
575
+ let needsHelperImport = false;
576
+ transformed = transformed.replace(DYNAMIC_IMPORT_REPLACE_RE, (match, filename) => {
577
+ needsHelperImport = true;
578
+ return `_rollupDynamicImport(${filename}).then`;
579
+ });
580
+ if (needsHelperImport && !transformed.includes(HELPER_IMPORT)) transformed = HELPER_IMPORT + transformed;
581
+ return transformed;
582
+ }
583
+ generateDynamicImportHelper(compilation) {
584
+ const chunkFiles = [];
585
+ for (const chunk of compilation.chunks) {
586
+ if (chunk.hasRuntime()) continue;
587
+ for (const filename of chunk.files) if (filename && isJS(filename)) chunkFiles.push(filename);
588
+ }
589
+ if (chunkFiles.length === 0) return;
590
+ const helperContent = this.generateHelperContent(chunkFiles);
591
+ compilation.emitAsset(HELPER_FILENAME, new compilation.compiler.webpack.sources.RawSource(helperContent));
592
+ }
593
+ generateHelperContent(chunkFiles) {
594
+ return `
726
595
  // Rollup-compatible dynamic import helper generated by webpack
727
596
  // This helper enables rollup to consume webpack chunks directly
728
597
 
@@ -739,1095 +608,926 @@ export function _rollupDynamicImport(chunkId) {
739
608
  return chunk()
740
609
  }
741
610
  `;
742
- }
743
- }
611
+ }
612
+ };
744
613
 
614
+ //#endregion
615
+ //#region ../webpack/src/presets/base.ts
745
616
  async function base(ctx) {
746
- await applyPresets(ctx, [
747
- baseAlias,
748
- baseConfig,
749
- basePlugins,
750
- baseResolve,
751
- baseTranspile
752
- ]);
617
+ await applyPresets(ctx, [
618
+ baseAlias,
619
+ baseConfig,
620
+ basePlugins,
621
+ baseResolve,
622
+ baseTranspile
623
+ ]);
753
624
  }
754
625
  function baseConfig(ctx) {
755
- ctx.config = defu({}, {
756
- name: ctx.name,
757
- entry: { app: [resolve(ctx.options.appDir, ctx.options.experimental.asyncEntry ? "entry.async" : "entry")] },
758
- module: { rules: [] },
759
- plugins: [],
760
- externals: [],
761
- optimization: {
762
- ...ctx.userConfig.optimization,
763
- minimizer: []
764
- },
765
- experiments: {
766
- ...ctx.userConfig.experiments
767
- },
768
- mode: ctx.isDev ? "development" : "production",
769
- cache: getCache(ctx),
770
- output: getOutput(ctx),
771
- stats: statsMap[ctx.nuxt.options.logLevel] ?? statsMap.info,
772
- ...ctx.config
773
- });
626
+ ctx.config = defu({}, {
627
+ name: ctx.name,
628
+ entry: { app: [resolve(ctx.options.appDir, ctx.options.experimental.asyncEntry ? "entry.async" : "entry")] },
629
+ module: { rules: [] },
630
+ plugins: [],
631
+ externals: [],
632
+ optimization: {
633
+ ...ctx.userConfig.optimization,
634
+ minimizer: []
635
+ },
636
+ experiments: { ...ctx.userConfig.experiments },
637
+ mode: ctx.isDev ? "development" : "production",
638
+ cache: getCache(ctx),
639
+ output: getOutput(ctx),
640
+ stats: statsMap[ctx.nuxt.options.logLevel] ?? statsMap.info,
641
+ ...ctx.config
642
+ });
774
643
  }
775
644
  function basePlugins(ctx) {
776
- ctx.config.plugins ||= [];
777
- if (ctx.options.dev) {
778
- if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") {
779
- ctx.config.plugins.push(new TimeFixPlugin());
780
- }
781
- }
782
- ctx.config.plugins.push(...ctx.userConfig.plugins || []);
783
- if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") {
784
- ctx.config.plugins.push(new WarningIgnorePlugin(getWarningIgnoreFilter(ctx)));
785
- }
786
- ctx.config.plugins.push(new webpack.DefinePlugin(getEnv(ctx)));
787
- if (ctx.isServer || ctx.isDev && ctx.userConfig.friendlyErrors) {
788
- ctx.config.plugins.push(
789
- new FriendlyErrorsWebpackPlugin({
790
- clearConsole: false,
791
- reporter: "consola",
792
- logLevel: "ERROR"
793
- // TODO
794
- })
795
- );
796
- }
797
- if (ctx.nuxt.options.webpack.profile) {
798
- const colors = {
799
- client: "green",
800
- server: "orange",
801
- modern: "blue"
802
- };
803
- ctx.config.plugins.push(new WebpackBarPlugin({
804
- name: ctx.name,
805
- color: colors[ctx.name],
806
- reporters: ["stats"],
807
- // @ts-expect-error TODO: this is a valid option for Webpack.ProgressPlugin and needs to be declared for WebpackBar
808
- stats: !ctx.isDev,
809
- reporter: {
810
- reporter: {
811
- change: (_, { shortPath }) => {
812
- if (!ctx.isServer) {
813
- ctx.nuxt.callHook(`${builder}:change`, shortPath);
814
- }
815
- },
816
- done: (_, { stats }) => {
817
- if (stats.hasErrors()) {
818
- ctx.nuxt.callHook(`${builder}:error`);
819
- } else {
820
- logger.success(`Finished building ${stats.compilation.name ?? "Nuxt app"}`);
821
- }
822
- },
823
- allDone: () => {
824
- ctx.nuxt.callHook(`${builder}:done`);
825
- },
826
- progress: ({ webpackbar }) => {
827
- ctx.nuxt.callHook(`${builder}:progress`, webpackbar.statesArray);
828
- }
829
- }
830
- }
831
- }));
832
- }
833
- if (ctx.isServer && !ctx.isDev) {
834
- ctx.config.plugins.push(new RollupCompatDynamicImportPlugin());
835
- }
645
+ ctx.config.plugins ||= [];
646
+ if (ctx.options.dev) {
647
+ if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") ctx.config.plugins.push(new TimeFixPlugin());
648
+ }
649
+ ctx.config.plugins.push(...ctx.userConfig.plugins || []);
650
+ if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") ctx.config.plugins.push(new WarningIgnorePlugin(getWarningIgnoreFilter(ctx)));
651
+ ctx.config.plugins.push(new webpack.DefinePlugin(getEnv(ctx)));
652
+ if (ctx.isServer || ctx.isDev && ctx.userConfig.friendlyErrors) ctx.config.plugins.push(new FriendlyErrorsWebpackPlugin({
653
+ clearConsole: false,
654
+ reporter: "consola",
655
+ logLevel: "ERROR"
656
+ }));
657
+ if (ctx.nuxt.options.webpack.profile) ctx.config.plugins.push(new WebpackBarPlugin({
658
+ name: ctx.name,
659
+ color: {
660
+ client: "green",
661
+ server: "orange",
662
+ modern: "blue"
663
+ }[ctx.name],
664
+ reporters: ["stats"],
665
+ stats: !ctx.isDev,
666
+ reporter: { reporter: {
667
+ change: (_, { shortPath }) => {
668
+ if (!ctx.isServer) ctx.nuxt.callHook(`${builder}:change`, shortPath);
669
+ },
670
+ done: (_, { stats }) => {
671
+ if (stats.hasErrors()) ctx.nuxt.callHook(`${builder}:error`);
672
+ else logger.success(`Finished building ${stats.compilation.name ?? "Nuxt app"}`);
673
+ },
674
+ allDone: () => {
675
+ ctx.nuxt.callHook(`${builder}:done`);
676
+ },
677
+ progress: ({ webpackbar }) => {
678
+ ctx.nuxt.callHook(`${builder}:progress`, webpackbar.statesArray);
679
+ }
680
+ } }
681
+ }));
682
+ if (ctx.isServer && !ctx.isDev) ctx.config.plugins.push(new RollupCompatDynamicImportPlugin());
836
683
  }
837
684
  function baseAlias(ctx) {
838
- ctx.alias = {
839
- "#app": ctx.options.appDir,
840
- [basename(ctx.nuxt.options.dir.assets)]: resolve(ctx.nuxt.options.srcDir, ctx.nuxt.options.dir.assets),
841
- ...ctx.options.alias,
842
- ...ctx.alias
843
- };
844
- if (ctx.isClient) {
845
- ctx.alias["nitro/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
846
- ctx.alias["#internal/nitro"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
847
- ctx.alias["nitropack/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
848
- }
685
+ ctx.alias = {
686
+ "#app": ctx.options.appDir,
687
+ [basename(ctx.nuxt.options.dir.assets)]: resolve(ctx.nuxt.options.srcDir, ctx.nuxt.options.dir.assets),
688
+ ...ctx.options.alias,
689
+ ...ctx.alias
690
+ };
691
+ if (ctx.isClient) {
692
+ ctx.alias["nitro/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
693
+ ctx.alias["#internal/nitro"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
694
+ ctx.alias["nitropack/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
695
+ }
849
696
  }
850
697
  function baseResolve(ctx) {
851
- const webpackModulesDir = ["node_modules"].concat(ctx.options.modulesDir);
852
- ctx.config.resolve = {
853
- extensions: [".wasm", ".mjs", ".js", ".ts", ".json", ".vue", ".jsx", ".tsx"],
854
- alias: ctx.alias,
855
- modules: webpackModulesDir,
856
- fullySpecified: false,
857
- ...ctx.config.resolve
858
- };
859
- ctx.config.resolveLoader = {
860
- modules: webpackModulesDir,
861
- ...ctx.config.resolveLoader
862
- };
698
+ const webpackModulesDir = ["node_modules"].concat(ctx.options.modulesDir);
699
+ ctx.config.resolve = {
700
+ extensions: [
701
+ ".wasm",
702
+ ".mjs",
703
+ ".js",
704
+ ".ts",
705
+ ".json",
706
+ ".vue",
707
+ ".jsx",
708
+ ".tsx"
709
+ ],
710
+ alias: ctx.alias,
711
+ modules: webpackModulesDir,
712
+ fullySpecified: false,
713
+ ...ctx.config.resolve
714
+ };
715
+ ctx.config.resolveLoader = {
716
+ modules: webpackModulesDir,
717
+ ...ctx.config.resolveLoader
718
+ };
863
719
  }
864
720
  function baseTranspile(ctx) {
865
- const transpile = [
866
- /\.vue\.js/i,
867
- // include SFCs in node_modules
868
- /consola\/src/,
869
- /vue-demi/,
870
- /(^|\/)nuxt\/(src\/|dist\/)?(app|[^/]+\/runtime)($|\/)/
871
- ];
872
- for (let pattern of ctx.options.build.transpile) {
873
- if (typeof pattern === "function") {
874
- const result = pattern(ctx);
875
- if (result) {
876
- pattern = result;
877
- }
878
- }
879
- if (typeof pattern === "string") {
880
- transpile.push(new RegExp(escapeRegExp(normalize(pattern))));
881
- } else if (pattern instanceof RegExp) {
882
- transpile.push(pattern);
883
- }
884
- }
885
- ctx.transpile = [...transpile, ...ctx.transpile];
721
+ const transpile = [
722
+ /\.vue\.js/i,
723
+ /consola\/src/,
724
+ /vue-demi/,
725
+ /(^|\/)nuxt\/(src\/|dist\/)?(app|[^/]+\/runtime)($|\/)/
726
+ ];
727
+ for (let pattern of ctx.options.build.transpile) {
728
+ if (typeof pattern === "function") {
729
+ const result = pattern(ctx);
730
+ if (result) pattern = result;
731
+ }
732
+ if (typeof pattern === "string") transpile.push(new RegExp(escapeRegExp(normalize(pattern))));
733
+ else if (pattern instanceof RegExp) transpile.push(pattern);
734
+ }
735
+ ctx.transpile = [...transpile, ...ctx.transpile];
886
736
  }
887
737
  function getCache(ctx) {
888
- if (!ctx.options.dev) {
889
- return false;
890
- }
738
+ if (!ctx.options.dev) return false;
891
739
  }
892
740
  function getOutput(ctx) {
893
- return {
894
- path: resolve(ctx.options.buildDir, "dist", ctx.isServer ? "server" : joinURL("client", ctx.options.app.buildAssetsDir)),
895
- filename: fileName(ctx, "app"),
896
- chunkFilename: fileName(ctx, "chunk"),
897
- publicPath: joinURL(ctx.options.app.baseURL, ctx.options.app.buildAssetsDir)
898
- };
741
+ return {
742
+ path: resolve(ctx.options.buildDir, "dist", ctx.isServer ? "server" : joinURL("client", ctx.options.app.buildAssetsDir)),
743
+ filename: fileName(ctx, "app"),
744
+ chunkFilename: fileName(ctx, "chunk"),
745
+ publicPath: joinURL(ctx.options.app.baseURL, ctx.options.app.buildAssetsDir)
746
+ };
899
747
  }
900
748
  function getWarningIgnoreFilter(ctx) {
901
- const filters = [
902
- // Hide warnings about plugins without a default export (#1179)
903
- (warn) => warn.name === "ModuleDependencyWarning" && warn.message.includes("export 'default'") && warn.message.includes("nuxt_plugin_"),
904
- ...ctx.userConfig.warningIgnoreFilters || []
905
- ];
906
- return (warn) => !filters.some((ignoreFilter) => ignoreFilter(warn));
749
+ const filters = [(warn) => warn.name === "ModuleDependencyWarning" && warn.message.includes("export 'default'") && warn.message.includes("nuxt_plugin_"), ...ctx.userConfig.warningIgnoreFilters || []];
750
+ return (warn) => !filters.some((ignoreFilter) => ignoreFilter(warn));
907
751
  }
908
752
  function getEnv(ctx) {
909
- const _env = {
910
- "process.env.NODE_ENV": JSON.stringify(ctx.config.mode),
911
- "__NUXT_VERSION__": JSON.stringify(ctx.nuxt._version),
912
- "__NUXT_ASYNC_CONTEXT__": ctx.options.experimental.asyncContext,
913
- "process.env.VUE_ENV": JSON.stringify(ctx.name),
914
- "process.dev": ctx.options.dev,
915
- "process.test": isTest,
916
- "process.browser": ctx.isClient,
917
- "process.client": ctx.isClient,
918
- "process.server": ctx.isServer,
919
- "import.meta.dev": ctx.options.dev,
920
- "import.meta.test": isTest,
921
- "import.meta.browser": ctx.isClient,
922
- "import.meta.client": ctx.isClient,
923
- "import.meta.server": ctx.isServer
924
- };
925
- if (ctx.isClient) {
926
- _env["process.prerender"] = false;
927
- _env["process.nitro"] = false;
928
- _env["import.meta.prerender"] = false;
929
- _env["import.meta.nitro"] = false;
930
- } else {
931
- _env["process.prerender"] = "(()=>process.prerender)()";
932
- _env["process.nitro"] = "(()=>process.nitro)()";
933
- _env["import.meta.prerender"] = "(()=>import.meta.prerender)()";
934
- _env["import.meta.nitro"] = "(()=>import.meta.nitro)()";
935
- }
936
- if (ctx.userConfig.aggressiveCodeRemoval) {
937
- _env["typeof process"] = JSON.stringify(ctx.isServer ? "object" : "undefined");
938
- _env["typeof window"] = _env["typeof document"] = JSON.stringify(!ctx.isServer ? "object" : "undefined");
939
- }
940
- return _env;
753
+ const _env = {
754
+ "process.env.NODE_ENV": JSON.stringify(ctx.config.mode),
755
+ "__NUXT_VERSION__": JSON.stringify(ctx.nuxt._version),
756
+ "__NUXT_ASYNC_CONTEXT__": ctx.options.experimental.asyncContext,
757
+ "process.env.VUE_ENV": JSON.stringify(ctx.name),
758
+ "process.dev": ctx.options.dev,
759
+ "process.test": isTest,
760
+ "process.browser": ctx.isClient,
761
+ "process.client": ctx.isClient,
762
+ "process.server": ctx.isServer,
763
+ "import.meta.dev": ctx.options.dev,
764
+ "import.meta.test": isTest,
765
+ "import.meta.browser": ctx.isClient,
766
+ "import.meta.client": ctx.isClient,
767
+ "import.meta.server": ctx.isServer
768
+ };
769
+ if (ctx.isClient) {
770
+ _env["process.prerender"] = false;
771
+ _env["process.nitro"] = false;
772
+ _env["import.meta.prerender"] = false;
773
+ _env["import.meta.nitro"] = false;
774
+ } else {
775
+ _env["process.prerender"] = "(()=>process.prerender)()";
776
+ _env["process.nitro"] = "(()=>process.nitro)()";
777
+ _env["import.meta.prerender"] = "(()=>import.meta.prerender)()";
778
+ _env["import.meta.nitro"] = "(()=>import.meta.nitro)()";
779
+ }
780
+ if (ctx.userConfig.aggressiveCodeRemoval) {
781
+ _env["typeof process"] = JSON.stringify(ctx.isServer ? "object" : "undefined");
782
+ _env["typeof window"] = _env["typeof document"] = JSON.stringify(!ctx.isServer ? "object" : "undefined");
783
+ }
784
+ return _env;
941
785
  }
942
786
  const statsMap = {
943
- silent: "none",
944
- info: "normal",
945
- verbose: "verbose"
787
+ silent: "none",
788
+ info: "normal",
789
+ verbose: "verbose"
946
790
  };
947
791
 
792
+ //#endregion
793
+ //#region ../webpack/src/presets/esbuild.ts
948
794
  function esbuild(ctx) {
949
- const target = ctx.isServer ? "es2020" : "chrome85";
950
- ctx.config.optimization.minimizer.push(new EsbuildPlugin());
951
- ctx.config.module.rules.push(
952
- {
953
- test: /\.m?[jt]s$/i,
954
- loader: "esbuild-loader",
955
- exclude: (file) => {
956
- const lastSegment = file.split("node_modules", 2)[1];
957
- if (!lastSegment) {
958
- return false;
959
- }
960
- return !ctx.transpile.some((module) => module.test(lastSegment));
961
- },
962
- resolve: {
963
- fullySpecified: false
964
- },
965
- options: {
966
- target,
967
- ...ctx.nuxt.options.webpack.loaders.esbuild,
968
- loader: "ts"
969
- }
970
- },
971
- {
972
- test: /\.m?[jt]sx$/,
973
- loader: "esbuild-loader",
974
- options: {
975
- target,
976
- ...ctx.nuxt.options.webpack.loaders.esbuild,
977
- loader: "tsx"
978
- }
979
- }
980
- );
795
+ const target = ctx.isServer ? "es2020" : "chrome85";
796
+ ctx.config.optimization.minimizer.push(new EsbuildPlugin());
797
+ ctx.config.module.rules.push({
798
+ test: /\.m?[jt]s$/i,
799
+ loader: "esbuild-loader",
800
+ exclude: (file) => {
801
+ const lastSegment = file.split("node_modules", 2)[1];
802
+ if (!lastSegment) return false;
803
+ return !ctx.transpile.some((module) => module.test(lastSegment));
804
+ },
805
+ resolve: { fullySpecified: false },
806
+ options: {
807
+ target,
808
+ ...ctx.nuxt.options.webpack.loaders.esbuild,
809
+ loader: "ts"
810
+ }
811
+ }, {
812
+ test: /\.m?[jt]sx$/,
813
+ loader: "esbuild-loader",
814
+ options: {
815
+ target,
816
+ ...ctx.nuxt.options.webpack.loaders.esbuild,
817
+ loader: "tsx"
818
+ }
819
+ });
981
820
  }
982
821
 
822
+ //#endregion
823
+ //#region ../webpack/src/presets/pug.ts
983
824
  function pug(ctx) {
984
- ctx.config.module.rules.push({
985
- test: /\.pug$/i,
986
- oneOf: [
987
- {
988
- resourceQuery: /^\?vue/i,
989
- use: [{
990
- loader: "pug-plain-loader",
991
- options: ctx.userConfig.loaders.pugPlain
992
- }]
993
- },
994
- {
995
- use: [
996
- "raw-loader",
997
- {
998
- loader: "pug-plain-loader",
999
- options: ctx.userConfig.loaders.pugPlain
1000
- }
1001
- ]
1002
- }
1003
- ]
1004
- });
825
+ ctx.config.module.rules.push({
826
+ test: /\.pug$/i,
827
+ oneOf: [{
828
+ resourceQuery: /^\?vue/i,
829
+ use: [{
830
+ loader: "pug-plain-loader",
831
+ options: ctx.userConfig.loaders.pugPlain
832
+ }]
833
+ }, { use: ["raw-loader", {
834
+ loader: "pug-plain-loader",
835
+ options: ctx.userConfig.loaders.pugPlain
836
+ }] }]
837
+ });
1005
838
  }
1006
839
 
840
+ //#endregion
841
+ //#region ../webpack/src/utils/postcss.ts
1007
842
  const isPureObject = (obj) => obj !== null && !Array.isArray(obj) && typeof obj === "object";
1008
843
  function sortPlugins({ plugins, order }) {
1009
- const names = Object.keys(plugins);
1010
- return typeof order === "function" ? order(names) : order || names;
844
+ const names = Object.keys(plugins);
845
+ return typeof order === "function" ? order(names) : order || names;
1011
846
  }
1012
- async function getPostcssConfig(nuxt) {
1013
- if (!nuxt.options.webpack.postcss || !nuxt.options.postcss) {
1014
- return false;
1015
- }
1016
- const postcssOptions = defu({}, nuxt.options.postcss, {
1017
- plugins: {
1018
- /**
1019
- * https://github.com/postcss/postcss-import
1020
- */
1021
- "postcss-import": {
1022
- resolve: createResolver({
1023
- alias: { ...nuxt.options.alias },
1024
- modules: nuxt.options.modulesDir
1025
- })
1026
- },
1027
- /**
1028
- * https://github.com/postcss/postcss-url
1029
- */
1030
- "postcss-url": {}
1031
- },
1032
- sourceMap: nuxt.options.webpack.cssSourceMap
1033
- });
1034
- const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
1035
- if (!Array.isArray(postcssOptions.plugins) && isPureObject(postcssOptions.plugins)) {
1036
- const plugins = [];
1037
- for (const pluginName of sortPlugins(postcssOptions)) {
1038
- const pluginOptions = postcssOptions.plugins[pluginName];
1039
- if (!pluginOptions) {
1040
- continue;
1041
- }
1042
- let pluginFn;
1043
- for (const parentURL of nuxt.options.modulesDir) {
1044
- pluginFn = await jiti.import(pluginName, { parentURL: parentURL.replace(/\/node_modules\/?$/, ""), try: true, default: true });
1045
- if (typeof pluginFn === "function") {
1046
- plugins.push(pluginFn(pluginOptions));
1047
- break;
1048
- }
1049
- }
1050
- if (typeof pluginFn !== "function") {
1051
- console.warn(`[nuxt] could not import postcss plugin \`${pluginName}\`. Please report this as a bug.`);
1052
- }
1053
- }
1054
- postcssOptions.plugins = plugins;
1055
- }
1056
- return {
1057
- sourceMap: nuxt.options.webpack.cssSourceMap,
1058
- ...nuxt.options.webpack.postcss,
1059
- postcssOptions
1060
- };
847
+ async function getPostcssConfig(nuxt$1) {
848
+ if (!nuxt$1.options.webpack.postcss || !nuxt$1.options.postcss) return false;
849
+ const postcssOptions = defu({}, nuxt$1.options.postcss, {
850
+ plugins: {
851
+ "postcss-import": { resolve: createResolver({
852
+ alias: { ...nuxt$1.options.alias },
853
+ modules: nuxt$1.options.modulesDir
854
+ }) },
855
+ "postcss-url": {}
856
+ },
857
+ sourceMap: nuxt$1.options.webpack.cssSourceMap
858
+ });
859
+ const jiti = createJiti(nuxt$1.options.rootDir, { alias: nuxt$1.options.alias });
860
+ if (!Array.isArray(postcssOptions.plugins) && isPureObject(postcssOptions.plugins)) {
861
+ const plugins = [];
862
+ for (const pluginName$1 of sortPlugins(postcssOptions)) {
863
+ const pluginOptions = postcssOptions.plugins[pluginName$1];
864
+ if (!pluginOptions) continue;
865
+ let pluginFn;
866
+ for (const parentURL of nuxt$1.options.modulesDir) {
867
+ pluginFn = await jiti.import(pluginName$1, {
868
+ parentURL: parentURL.replace(/\/node_modules\/?$/, ""),
869
+ try: true,
870
+ default: true
871
+ });
872
+ if (typeof pluginFn === "function") {
873
+ plugins.push(pluginFn(pluginOptions));
874
+ break;
875
+ }
876
+ }
877
+ if (typeof pluginFn !== "function") console.warn(`[nuxt] could not import postcss plugin \`${pluginName$1}\`. Please report this as a bug.`);
878
+ }
879
+ postcssOptions.plugins = plugins;
880
+ }
881
+ return {
882
+ sourceMap: nuxt$1.options.webpack.cssSourceMap,
883
+ ...nuxt$1.options.webpack.postcss,
884
+ postcssOptions
885
+ };
1061
886
  }
1062
887
 
888
+ //#endregion
889
+ //#region ../webpack/src/presets/style.ts
1063
890
  async function style(ctx) {
1064
- await applyPresets(ctx, [
1065
- loaders,
1066
- extractCSS,
1067
- minimizer
1068
- ]);
891
+ await applyPresets(ctx, [
892
+ loaders,
893
+ extractCSS,
894
+ minimizer
895
+ ]);
1069
896
  }
1070
897
  function minimizer(ctx) {
1071
- if (ctx.userConfig.optimizeCSS && Array.isArray(ctx.config.optimization.minimizer)) {
1072
- ctx.config.optimization.minimizer.push(new CssMinimizerPlugin({
1073
- ...ctx.userConfig.optimizeCSS
1074
- }));
1075
- }
898
+ if (ctx.userConfig.optimizeCSS && Array.isArray(ctx.config.optimization.minimizer)) ctx.config.optimization.minimizer.push(new CssMinimizerPlugin({ ...ctx.userConfig.optimizeCSS }));
1076
899
  }
1077
900
  function extractCSS(ctx) {
1078
- const config = ctx.userConfig.extractCSS;
1079
- if (!config) {
1080
- return;
1081
- }
1082
- const filename = fileName(ctx, "css");
1083
- ctx.config.plugins.push(new MiniCssExtractPlugin({
1084
- filename,
1085
- chunkFilename: filename,
1086
- ...config === true ? {} : config
1087
- }));
901
+ const config = ctx.userConfig.extractCSS;
902
+ if (!config) return;
903
+ const filename = fileName(ctx, "css");
904
+ ctx.config.plugins.push(new MiniCssExtractPlugin({
905
+ filename,
906
+ chunkFilename: filename,
907
+ ...config === true ? {} : config
908
+ }));
1088
909
  }
1089
910
  async function loaders(ctx) {
1090
- ctx.config.module.rules.push(await createdStyleRule("css", /\.css$/i, null, ctx));
1091
- ctx.config.module.rules.push(await createdStyleRule("postcss", /\.p(ost)?css$/i, null, ctx));
1092
- const lessLoader = { loader: "less-loader", options: ctx.userConfig.loaders.less };
1093
- ctx.config.module.rules.push(await createdStyleRule("less", /\.less$/i, lessLoader, ctx));
1094
- const sassLoader = { loader: "sass-loader", options: ctx.userConfig.loaders.sass };
1095
- ctx.config.module.rules.push(await createdStyleRule("sass", /\.sass$/i, sassLoader, ctx));
1096
- const scssLoader = { loader: "sass-loader", options: ctx.userConfig.loaders.scss };
1097
- ctx.config.module.rules.push(await createdStyleRule("scss", /\.scss$/i, scssLoader, ctx));
1098
- const stylusLoader = { loader: "stylus-loader", options: ctx.userConfig.loaders.stylus };
1099
- ctx.config.module.rules.push(await createdStyleRule("stylus", /\.styl(us)?$/i, stylusLoader, ctx));
911
+ ctx.config.module.rules.push(await createdStyleRule("css", /\.css$/i, null, ctx));
912
+ ctx.config.module.rules.push(await createdStyleRule("postcss", /\.p(ost)?css$/i, null, ctx));
913
+ const lessLoader = {
914
+ loader: "less-loader",
915
+ options: ctx.userConfig.loaders.less
916
+ };
917
+ ctx.config.module.rules.push(await createdStyleRule("less", /\.less$/i, lessLoader, ctx));
918
+ const sassLoader = {
919
+ loader: "sass-loader",
920
+ options: ctx.userConfig.loaders.sass
921
+ };
922
+ ctx.config.module.rules.push(await createdStyleRule("sass", /\.sass$/i, sassLoader, ctx));
923
+ const scssLoader = {
924
+ loader: "sass-loader",
925
+ options: ctx.userConfig.loaders.scss
926
+ };
927
+ ctx.config.module.rules.push(await createdStyleRule("scss", /\.scss$/i, scssLoader, ctx));
928
+ const stylusLoader = {
929
+ loader: "stylus-loader",
930
+ options: ctx.userConfig.loaders.stylus
931
+ };
932
+ ctx.config.module.rules.push(await createdStyleRule("stylus", /\.styl(us)?$/i, stylusLoader, ctx));
1100
933
  }
1101
934
  async function createdStyleRule(lang, test, processorLoader, ctx) {
1102
- const styleLoaders = [
1103
- await createPostcssLoadersRule(ctx),
1104
- processorLoader
1105
- ].filter(Boolean);
1106
- ctx.userConfig.loaders.css.importLoaders = ctx.userConfig.loaders.cssModules.importLoaders = styleLoaders.length;
1107
- const cssLoaders = createCssLoadersRule(ctx, ctx.userConfig.loaders.css);
1108
- const cssModuleLoaders = createCssLoadersRule(ctx, ctx.userConfig.loaders.cssModules);
1109
- return {
1110
- test,
1111
- oneOf: [
1112
- // This matches <style module>
1113
- {
1114
- resourceQuery: /module/,
1115
- use: cssModuleLoaders.concat(styleLoaders)
1116
- },
1117
- // This matches plain <style> or <style scoped>
1118
- {
1119
- use: cssLoaders.concat(styleLoaders)
1120
- }
1121
- ]
1122
- };
935
+ const styleLoaders = [await createPostcssLoadersRule(ctx), processorLoader].filter(Boolean);
936
+ ctx.userConfig.loaders.css.importLoaders = ctx.userConfig.loaders.cssModules.importLoaders = styleLoaders.length;
937
+ const cssLoaders = createCssLoadersRule(ctx, ctx.userConfig.loaders.css);
938
+ return {
939
+ test,
940
+ oneOf: [{
941
+ resourceQuery: /module/,
942
+ use: createCssLoadersRule(ctx, ctx.userConfig.loaders.cssModules).concat(styleLoaders)
943
+ }, { use: cssLoaders.concat(styleLoaders) }]
944
+ };
1123
945
  }
1124
946
  function createCssLoadersRule(ctx, cssLoaderOptions) {
1125
- const cssLoader = { loader: "css-loader", options: cssLoaderOptions };
1126
- if (ctx.userConfig.extractCSS) {
1127
- if (ctx.isServer) {
1128
- if (cssLoader.options.modules) {
1129
- cssLoader.options.modules.exportOnlyLocals ??= true;
1130
- }
1131
- return [cssLoader];
1132
- }
1133
- return [
1134
- {
1135
- loader: MiniCssExtractPlugin.loader
1136
- },
1137
- cssLoader
1138
- ];
1139
- }
1140
- return [
1141
- // https://github.com/vuejs/vue-style-loader/issues/56
1142
- // {
1143
- // loader: 'vue-style-loader',
1144
- // options: options.webpack.loaders.vueStyle
1145
- // },
1146
- cssLoader
1147
- ];
947
+ const cssLoader = {
948
+ loader: "css-loader",
949
+ options: cssLoaderOptions
950
+ };
951
+ if (ctx.userConfig.extractCSS) {
952
+ if (ctx.isServer) {
953
+ if (cssLoader.options.modules) cssLoader.options.modules.exportOnlyLocals ??= true;
954
+ return [cssLoader];
955
+ }
956
+ return [{ loader: MiniCssExtractPlugin.loader }, cssLoader];
957
+ }
958
+ return [cssLoader];
1148
959
  }
1149
960
  async function createPostcssLoadersRule(ctx) {
1150
- if (!ctx.options.postcss) {
1151
- return;
1152
- }
1153
- const config = await getPostcssConfig(ctx.nuxt);
1154
- if (!config) {
1155
- return;
1156
- }
1157
- return {
1158
- loader: "postcss-loader",
1159
- options: config
1160
- };
961
+ if (!ctx.options.postcss) return;
962
+ const config = await getPostcssConfig(ctx.nuxt);
963
+ if (!config) return;
964
+ return {
965
+ loader: "postcss-loader",
966
+ options: config
967
+ };
1161
968
  }
1162
969
 
1163
- class VueSSRClientPlugin {
1164
- serverDist;
1165
- nuxt;
1166
- constructor(options) {
1167
- this.serverDist = resolve(options.nuxt.options.buildDir, "dist/server");
1168
- this.nuxt = options.nuxt;
1169
- }
1170
- getRelativeModuleId(identifier, context) {
1171
- const id = identifier.replace(/\s\w+$/, "");
1172
- const resourceMatch = id.match(/([^!]*\.vue)(?:\?|$)/);
1173
- return resourceMatch && resourceMatch[1] ? normalize(relative(context, resourceMatch[1])).replace(/^\.\//, "").replace(/\\/g, "/") : id;
1174
- }
1175
- apply(compiler) {
1176
- compiler.hooks.afterEmit.tap("VueSSRClientPlugin", async (compilation) => {
1177
- const stats = compilation.getStats().toJson();
1178
- const context = this.nuxt.options.srcDir;
1179
- const initialFiles = /* @__PURE__ */ new Set();
1180
- for (const { assets } of Object.values(stats.entrypoints)) {
1181
- if (!assets) {
1182
- continue;
1183
- }
1184
- for (const asset of assets) {
1185
- const file = asset.name;
1186
- if ((isJS(file) || isCSS(file)) && !isHotUpdate(file)) {
1187
- initialFiles.add(file);
1188
- }
1189
- }
1190
- }
1191
- const allFiles = /* @__PURE__ */ new Set();
1192
- const asyncFiles = /* @__PURE__ */ new Set();
1193
- const assetsMapping = {};
1194
- for (const { name: file, chunkNames = [] } of stats.assets) {
1195
- if (isHotUpdate(file)) {
1196
- continue;
1197
- }
1198
- allFiles.add(file);
1199
- const isFileJS = isJS(file);
1200
- if (!initialFiles.has(file) && (isFileJS || isCSS(file))) {
1201
- asyncFiles.add(file);
1202
- }
1203
- if (isFileJS) {
1204
- const componentHash = hash(chunkNames.join("|"));
1205
- const map = assetsMapping[componentHash] ||= [];
1206
- map.push(file);
1207
- }
1208
- }
1209
- const webpackManifest = {
1210
- publicPath: stats.publicPath,
1211
- all: [...allFiles],
1212
- initial: [...initialFiles],
1213
- async: [...asyncFiles],
1214
- modules: {
1215
- /* [identifier: string]: Array<index: number> */
1216
- },
1217
- assetsMapping
1218
- };
1219
- const { entrypoints = {}, namedChunkGroups = {} } = stats;
1220
- const fileToIndex = (file) => webpackManifest.all.indexOf(String(file));
1221
- for (const m of stats.modules) {
1222
- if (m.chunks?.length !== 1) {
1223
- continue;
1224
- }
1225
- const [cid] = m.chunks;
1226
- const chunk = stats.chunks.find((c) => c.id === cid);
1227
- if (!chunk || !chunk.files || !cid) {
1228
- continue;
1229
- }
1230
- const relativeId = this.getRelativeModuleId(m.identifier, context);
1231
- const filesSet = /* @__PURE__ */ new Set();
1232
- for (const file of chunk.files) {
1233
- const index = fileToIndex(file);
1234
- if (index !== -1) {
1235
- filesSet.add(index);
1236
- }
1237
- }
1238
- for (const chunkName of chunk.names) {
1239
- if (!entrypoints[chunkName]) {
1240
- const chunkGroup = namedChunkGroups[chunkName];
1241
- if (chunkGroup) {
1242
- for (const asset of chunkGroup.assets) {
1243
- filesSet.add(fileToIndex(asset.name));
1244
- }
1245
- }
1246
- }
1247
- }
1248
- const files = Array.from(filesSet);
1249
- webpackManifest.modules[relativeId] = files;
1250
- if (Array.isArray(m.modules)) {
1251
- for (const concatenatedModule of m.modules) {
1252
- const relativeId2 = this.getRelativeModuleId(concatenatedModule.identifier, context);
1253
- webpackManifest.modules[relativeId2] ||= files;
1254
- }
1255
- }
1256
- if (stats.modules) {
1257
- for (const m2 of stats.modules) {
1258
- if (m2.assets?.length && m2.chunks?.includes(cid)) {
1259
- files.push(...m2.assets.map(fileToIndex));
1260
- }
1261
- }
1262
- }
1263
- }
1264
- const manifest = normalizeWebpackManifest(webpackManifest);
1265
- await this.nuxt.callHook("build:manifest", manifest);
1266
- await mkdir(this.serverDist, { recursive: true });
1267
- const precomputed = precomputeDependencies(manifest);
1268
- await writeFile(join(this.serverDist, `client.manifest.json`), JSON.stringify(manifest, null, 2));
1269
- await writeFile(join(this.serverDist, "client.manifest.mjs"), "export default " + serialize(manifest), "utf8");
1270
- await writeFile(join(this.serverDist, "client.precomputed.mjs"), "export default " + serialize(precomputed), "utf8");
1271
- });
1272
- }
1273
- }
970
+ //#endregion
971
+ //#region ../webpack/src/plugins/vue/client.ts
972
+ /**
973
+ * This file is based on Vue.js (MIT) webpack plugins
974
+ * https://github.com/vuejs/vue/blob/dev/src/server/webpack-plugin/client.js
975
+ */
976
+ var VueSSRClientPlugin = class {
977
+ serverDist;
978
+ nuxt;
979
+ constructor(options) {
980
+ this.serverDist = resolve(options.nuxt.options.buildDir, "dist/server");
981
+ this.nuxt = options.nuxt;
982
+ }
983
+ getRelativeModuleId(identifier, context) {
984
+ const id = identifier.replace(/\s\w+$/, "");
985
+ const resourceMatch = id.match(/([^!]*\.vue)(?:\?|$)/);
986
+ return resourceMatch && resourceMatch[1] ? normalize(relative(context, resourceMatch[1])).replace(/^\.\//, "").replace(/\\/g, "/") : id;
987
+ }
988
+ apply(compiler) {
989
+ compiler.hooks.afterEmit.tap("VueSSRClientPlugin", async (compilation) => {
990
+ const stats = compilation.getStats().toJson();
991
+ const context = this.nuxt.options.srcDir;
992
+ const initialFiles = /* @__PURE__ */ new Set();
993
+ for (const { assets: assets$1 } of Object.values(stats.entrypoints)) {
994
+ if (!assets$1) continue;
995
+ for (const asset of assets$1) {
996
+ const file = asset.name;
997
+ if ((isJS(file) || isCSS(file)) && !isHotUpdate(file)) initialFiles.add(file);
998
+ }
999
+ }
1000
+ const allFiles = /* @__PURE__ */ new Set();
1001
+ const asyncFiles = /* @__PURE__ */ new Set();
1002
+ const assetsMapping = {};
1003
+ for (const { name: file, chunkNames = [] } of stats.assets) {
1004
+ if (isHotUpdate(file)) continue;
1005
+ allFiles.add(file);
1006
+ const isFileJS = isJS(file);
1007
+ if (!initialFiles.has(file) && (isFileJS || isCSS(file))) asyncFiles.add(file);
1008
+ if (isFileJS) {
1009
+ const componentHash = hash(chunkNames.join("|"));
1010
+ (assetsMapping[componentHash] ||= []).push(file);
1011
+ }
1012
+ }
1013
+ const webpackManifest = {
1014
+ publicPath: stats.publicPath,
1015
+ all: [...allFiles],
1016
+ initial: [...initialFiles],
1017
+ async: [...asyncFiles],
1018
+ modules: {},
1019
+ assetsMapping
1020
+ };
1021
+ const { entrypoints = {}, namedChunkGroups = {} } = stats;
1022
+ const fileToIndex = (file) => webpackManifest.all.indexOf(String(file));
1023
+ for (const m of stats.modules) {
1024
+ if (m.chunks?.length !== 1) continue;
1025
+ const [cid] = m.chunks;
1026
+ const chunk = stats.chunks.find((c) => c.id === cid);
1027
+ if (!chunk || !chunk.files || !cid) continue;
1028
+ const relativeId = this.getRelativeModuleId(m.identifier, context);
1029
+ const filesSet = /* @__PURE__ */ new Set();
1030
+ for (const file of chunk.files) {
1031
+ const index = fileToIndex(file);
1032
+ if (index !== -1) filesSet.add(index);
1033
+ }
1034
+ for (const chunkName of chunk.names) if (!entrypoints[chunkName]) {
1035
+ const chunkGroup = namedChunkGroups[chunkName];
1036
+ if (chunkGroup) for (const asset of chunkGroup.assets) filesSet.add(fileToIndex(asset.name));
1037
+ }
1038
+ const files = Array.from(filesSet);
1039
+ webpackManifest.modules[relativeId] = files;
1040
+ if (Array.isArray(m.modules)) for (const concatenatedModule of m.modules) {
1041
+ const relativeId$1 = this.getRelativeModuleId(concatenatedModule.identifier, context);
1042
+ webpackManifest.modules[relativeId$1] ||= files;
1043
+ }
1044
+ if (stats.modules) {
1045
+ for (const m$1 of stats.modules) if (m$1.assets?.length && m$1.chunks?.includes(cid)) files.push(...m$1.assets.map(fileToIndex));
1046
+ }
1047
+ }
1048
+ const manifest = normalizeWebpackManifest(webpackManifest);
1049
+ await this.nuxt.callHook("build:manifest", manifest);
1050
+ await mkdir(this.serverDist, { recursive: true });
1051
+ const precomputed = precomputeDependencies(manifest);
1052
+ await writeFile(join(this.serverDist, `client.manifest.json`), JSON.stringify(manifest, null, 2));
1053
+ await writeFile(join(this.serverDist, "client.manifest.mjs"), "export default " + serialize(manifest), "utf8");
1054
+ await writeFile(join(this.serverDist, "client.precomputed.mjs"), "export default " + serialize(precomputed), "utf8");
1055
+ });
1056
+ }
1057
+ };
1274
1058
 
1059
+ //#endregion
1060
+ //#region ../webpack/src/plugins/vue/server.ts
1275
1061
  const JS_MAP_RE = /\.js\.map$/;
1276
- class VueSSRServerPlugin {
1277
- options;
1278
- constructor(options = {}) {
1279
- this.options = Object.assign({
1280
- filename: null
1281
- }, options);
1282
- }
1283
- apply(compiler) {
1284
- validate(compiler);
1285
- compiler.hooks.make.tap("VueSSRServerPlugin", (compilation) => {
1286
- compilation.hooks.processAssets.tapAsync({
1287
- name: "VueSSRServerPlugin",
1288
- stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
1289
- }, (assets, cb) => {
1290
- const stats = compilation.getStats().toJson();
1291
- const [entryName] = Object.keys(stats.entrypoints);
1292
- const entryInfo = stats.entrypoints[entryName];
1293
- if (!entryInfo) {
1294
- return cb();
1295
- }
1296
- const entryAssets = entryInfo.assets.filter((asset) => isJS(asset.name));
1297
- if (entryAssets.length > 1) {
1298
- throw new Error(
1299
- "Server-side bundle should have one single entry file. Avoid using CommonsChunkPlugin in the server config."
1300
- );
1301
- }
1302
- const [entry] = entryAssets;
1303
- if (!entry || typeof entry.name !== "string") {
1304
- throw new Error(
1305
- `Entry "${entryName}" not found. Did you specify the correct entry option?`
1306
- );
1307
- }
1308
- const bundle = {
1309
- entry: entry.name,
1310
- files: {},
1311
- maps: {}
1312
- };
1313
- for (const asset of stats.assets) {
1314
- if (isJS(asset.name)) {
1315
- const queryPart = extractQueryPartJS(asset.name);
1316
- if (queryPart !== void 0) {
1317
- bundle.files[asset.name] = asset.name.replace(queryPart, "");
1318
- } else {
1319
- bundle.files[asset.name] = asset.name;
1320
- }
1321
- } else if (JS_MAP_RE.test(asset.name)) {
1322
- bundle.maps[asset.name.replace(/\.map$/, "")] = asset.name;
1323
- } else {
1324
- delete assets[asset.name];
1325
- }
1326
- }
1327
- const src = JSON.stringify(bundle, null, 2);
1328
- assets[this.options.filename] = {
1329
- source: () => src,
1330
- size: () => src.length
1331
- };
1332
- const mjsSrc = "export default " + src;
1333
- assets[this.options.filename.replace(".json", ".mjs")] = {
1334
- source: () => mjsSrc,
1335
- map: () => null,
1336
- size: () => mjsSrc.length
1337
- };
1338
- cb();
1339
- });
1340
- });
1341
- }
1342
- }
1062
+ var VueSSRServerPlugin = class {
1063
+ options;
1064
+ constructor(options = {}) {
1065
+ this.options = Object.assign({ filename: null }, options);
1066
+ }
1067
+ apply(compiler) {
1068
+ validate(compiler);
1069
+ compiler.hooks.make.tap("VueSSRServerPlugin", (compilation) => {
1070
+ compilation.hooks.processAssets.tapAsync({
1071
+ name: "VueSSRServerPlugin",
1072
+ stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
1073
+ }, (assets$1, cb) => {
1074
+ const stats = compilation.getStats().toJson();
1075
+ const [entryName] = Object.keys(stats.entrypoints);
1076
+ const entryInfo = stats.entrypoints[entryName];
1077
+ if (!entryInfo) return cb();
1078
+ const entryAssets = entryInfo.assets.filter((asset) => isJS(asset.name));
1079
+ if (entryAssets.length > 1) throw new Error("Server-side bundle should have one single entry file. Avoid using CommonsChunkPlugin in the server config.");
1080
+ const [entry] = entryAssets;
1081
+ if (!entry || typeof entry.name !== "string") throw new Error(`Entry "${entryName}" not found. Did you specify the correct entry option?`);
1082
+ const bundle$1 = {
1083
+ entry: entry.name,
1084
+ files: {},
1085
+ maps: {}
1086
+ };
1087
+ for (const asset of stats.assets) if (isJS(asset.name)) {
1088
+ const queryPart = extractQueryPartJS(asset.name);
1089
+ if (queryPart !== void 0) bundle$1.files[asset.name] = asset.name.replace(queryPart, "");
1090
+ else bundle$1.files[asset.name] = asset.name;
1091
+ } else if (JS_MAP_RE.test(asset.name)) bundle$1.maps[asset.name.replace(/\.map$/, "")] = asset.name;
1092
+ else delete assets$1[asset.name];
1093
+ const src = JSON.stringify(bundle$1, null, 2);
1094
+ assets$1[this.options.filename] = {
1095
+ source: () => src,
1096
+ size: () => src.length
1097
+ };
1098
+ const mjsSrc = "export default " + src;
1099
+ assets$1[this.options.filename.replace(".json", ".mjs")] = {
1100
+ source: () => mjsSrc,
1101
+ map: () => null,
1102
+ size: () => mjsSrc.length
1103
+ };
1104
+ cb();
1105
+ });
1106
+ });
1107
+ }
1108
+ };
1343
1109
 
1110
+ //#endregion
1111
+ //#region ../webpack/src/presets/vue.ts
1344
1112
  function vue(ctx) {
1345
- ctx.config.plugins.push(new (VueLoaderPlugin.default || VueLoaderPlugin)());
1346
- ctx.config.module.rules.push({
1347
- test: /\.vue$/i,
1348
- loader: "vue-loader",
1349
- options: { ...ctx.userConfig.loaders.vue, isServerBuild: ctx.isServer }
1350
- });
1351
- if (ctx.isClient) {
1352
- ctx.config.plugins.push(new VueSSRClientPlugin({ nuxt: ctx.nuxt }));
1353
- } else {
1354
- ctx.config.plugins.push(new VueSSRServerPlugin({
1355
- filename: `${ctx.name}.manifest.json`
1356
- }));
1357
- const loaderPath = resolveModulePath("#vue-module-identifier", { from: import.meta.url });
1358
- ctx.config.module.rules.push({
1359
- test: /\.vue$/i,
1360
- enforce: "post",
1361
- use: [{
1362
- loader: loaderPath,
1363
- options: { srcDir: ctx.nuxt.options.srcDir }
1364
- }]
1365
- });
1366
- }
1367
- ctx.config.plugins.push(new webpack.DefinePlugin({
1368
- "__VUE_OPTIONS_API__": "true",
1369
- "__VUE_PROD_DEVTOOLS__": "false",
1370
- "__VUE_PROD_HYDRATION_MISMATCH_DETAILS__": ctx.nuxt.options.debug && ctx.nuxt.options.debug.hydration
1371
- }));
1113
+ ctx.config.plugins.push(new (VueLoaderPlugin.default || VueLoaderPlugin)());
1114
+ ctx.config.module.rules.push({
1115
+ test: /\.vue$/i,
1116
+ loader: "vue-loader",
1117
+ options: {
1118
+ ...ctx.userConfig.loaders.vue,
1119
+ isServerBuild: ctx.isServer
1120
+ }
1121
+ });
1122
+ if (ctx.isClient) ctx.config.plugins.push(new VueSSRClientPlugin({ nuxt: ctx.nuxt }));
1123
+ else {
1124
+ ctx.config.plugins.push(new VueSSRServerPlugin({ filename: `${ctx.name}.manifest.json` }));
1125
+ const loaderPath = resolveModulePath("#vue-module-identifier", { from: import.meta.url });
1126
+ ctx.config.module.rules.push({
1127
+ test: /\.vue$/i,
1128
+ enforce: "post",
1129
+ use: [{
1130
+ loader: loaderPath,
1131
+ options: { srcDir: ctx.nuxt.options.srcDir }
1132
+ }]
1133
+ });
1134
+ }
1135
+ ctx.config.plugins.push(new webpack.DefinePlugin({
1136
+ "__VUE_OPTIONS_API__": "true",
1137
+ "__VUE_PROD_DEVTOOLS__": "false",
1138
+ "__VUE_PROD_HYDRATION_MISMATCH_DETAILS__": ctx.nuxt.options.debug && ctx.nuxt.options.debug.hydration
1139
+ }));
1372
1140
  }
1373
1141
 
1142
+ //#endregion
1143
+ //#region ../webpack/src/presets/nuxt.ts
1374
1144
  async function nuxt(ctx) {
1375
- await applyPresets(ctx, [
1376
- base,
1377
- assets,
1378
- esbuild,
1379
- pug,
1380
- style,
1381
- vue
1382
- ]);
1145
+ await applyPresets(ctx, [
1146
+ base,
1147
+ assets,
1148
+ esbuild,
1149
+ pug,
1150
+ style,
1151
+ vue
1152
+ ]);
1383
1153
  }
1384
1154
 
1155
+ //#endregion
1156
+ //#region ../webpack/src/configs/client.ts
1385
1157
  async function client(ctx) {
1386
- ctx.name = "client";
1387
- ctx.isClient = true;
1388
- await applyPresets(ctx, [
1389
- nuxt,
1390
- clientPlugins,
1391
- clientOptimization,
1392
- clientDevtool,
1393
- clientPerformance,
1394
- clientHMR,
1395
- clientNodeCompat
1396
- ]);
1158
+ ctx.name = "client";
1159
+ ctx.isClient = true;
1160
+ await applyPresets(ctx, [
1161
+ nuxt,
1162
+ clientPlugins,
1163
+ clientOptimization,
1164
+ clientDevtool,
1165
+ clientPerformance,
1166
+ clientHMR,
1167
+ clientNodeCompat
1168
+ ]);
1397
1169
  }
1398
1170
  function clientDevtool(ctx) {
1399
- if (!ctx.nuxt.options.sourcemap.client) {
1400
- ctx.config.devtool = false;
1401
- return;
1402
- }
1403
- const prefix = ctx.nuxt.options.sourcemap.client === "hidden" ? "hidden-" : "";
1404
- if (!ctx.isDev) {
1405
- ctx.config.devtool = prefix + "source-map";
1406
- return;
1407
- }
1408
- ctx.config.devtool = prefix + "eval-cheap-module-source-map";
1171
+ if (!ctx.nuxt.options.sourcemap.client) {
1172
+ ctx.config.devtool = false;
1173
+ return;
1174
+ }
1175
+ const prefix = ctx.nuxt.options.sourcemap.client === "hidden" ? "hidden-" : "";
1176
+ if (!ctx.isDev) {
1177
+ ctx.config.devtool = prefix + "source-map";
1178
+ return;
1179
+ }
1180
+ ctx.config.devtool = prefix + "eval-cheap-module-source-map";
1409
1181
  }
1410
1182
  function clientPerformance(ctx) {
1411
- ctx.config.performance = {
1412
- maxEntrypointSize: 1e3 * 1024,
1413
- hints: ctx.isDev ? false : "warning",
1414
- ...ctx.config.performance
1415
- };
1183
+ ctx.config.performance = {
1184
+ maxEntrypointSize: 1e3 * 1024,
1185
+ hints: ctx.isDev ? false : "warning",
1186
+ ...ctx.config.performance
1187
+ };
1416
1188
  }
1417
1189
  function clientNodeCompat(ctx) {
1418
- if (!ctx.nuxt.options.experimental.clientNodeCompat) {
1419
- return;
1420
- }
1421
- ctx.config.plugins.push(new webpack.DefinePlugin({ global: "globalThis" }));
1422
- ctx.config.resolve ||= {};
1423
- ctx.config.resolve.fallback = {
1424
- ...defineEnv({
1425
- nodeCompat: true,
1426
- resolve: true
1427
- }).env.alias,
1428
- ...ctx.config.resolve.fallback
1429
- };
1430
- ctx.config.plugins.unshift(new webpack.NormalModuleReplacementPlugin(/node:/, (resource) => {
1431
- resource.request = resource.request.replace(/^node:/, "");
1432
- }));
1190
+ if (!ctx.nuxt.options.experimental.clientNodeCompat) return;
1191
+ ctx.config.plugins.push(new webpack.DefinePlugin({ global: "globalThis" }));
1192
+ ctx.config.resolve ||= {};
1193
+ ctx.config.resolve.fallback = {
1194
+ ...defineEnv({
1195
+ nodeCompat: true,
1196
+ resolve: true
1197
+ }).env.alias,
1198
+ ...ctx.config.resolve.fallback
1199
+ };
1200
+ ctx.config.plugins.unshift(new webpack.NormalModuleReplacementPlugin(/node:/, (resource) => {
1201
+ resource.request = resource.request.replace(/^node:/, "");
1202
+ }));
1433
1203
  }
1434
1204
  function clientHMR(ctx) {
1435
- if (!ctx.isDev) {
1436
- return;
1437
- }
1438
- const clientOptions = ctx.userConfig.hotMiddleware?.client || {};
1439
- const hotMiddlewareClientOptions = {
1440
- reload: true,
1441
- timeout: 3e4,
1442
- path: joinURL(ctx.options.app.baseURL, "__webpack_hmr", ctx.name),
1443
- ...clientOptions,
1444
- ansiColors: JSON.stringify(clientOptions.ansiColors || {}),
1445
- overlayStyles: JSON.stringify(clientOptions.overlayStyles || {}),
1446
- name: ctx.name
1447
- };
1448
- const hotMiddlewareClientOptionsStr = querystring.stringify(hotMiddlewareClientOptions);
1449
- const app = ctx.config.entry.app;
1450
- app.unshift(
1451
- // https://github.com/webpack/webpack-hot-middleware#config
1452
- `webpack-hot-middleware/client?${hotMiddlewareClientOptionsStr}`
1453
- );
1454
- ctx.config.plugins ||= [];
1455
- ctx.config.plugins.push(new webpack.HotModuleReplacementPlugin());
1205
+ if (!ctx.isDev) return;
1206
+ const clientOptions = ctx.userConfig.hotMiddleware?.client || {};
1207
+ const hotMiddlewareClientOptions = {
1208
+ reload: true,
1209
+ timeout: 3e4,
1210
+ path: joinURL(ctx.options.app.baseURL, "__webpack_hmr", ctx.name),
1211
+ ...clientOptions,
1212
+ ansiColors: JSON.stringify(clientOptions.ansiColors || {}),
1213
+ overlayStyles: JSON.stringify(clientOptions.overlayStyles || {}),
1214
+ name: ctx.name
1215
+ };
1216
+ const hotMiddlewareClientOptionsStr = querystring.stringify(hotMiddlewareClientOptions);
1217
+ ctx.config.entry.app.unshift(`webpack-hot-middleware/client?${hotMiddlewareClientOptionsStr}`);
1218
+ ctx.config.plugins ||= [];
1219
+ ctx.config.plugins.push(new webpack.HotModuleReplacementPlugin());
1456
1220
  }
1457
1221
  function clientOptimization(ctx) {
1458
- if (!ctx.nuxt.options.features.inlineStyles) {
1459
- return;
1460
- }
1461
- const globalCSSPaths = /* @__PURE__ */ new Set();
1462
- for (const css of ctx.options.css) {
1463
- if (typeof css === "string") {
1464
- const resolved = resolveAlias(css, ctx.options.alias);
1465
- globalCSSPaths.add(normalize(resolved));
1466
- }
1467
- }
1468
- if (globalCSSPaths.size > 0) {
1469
- ctx.config.optimization ||= {};
1470
- ctx.config.optimization.splitChunks ||= {};
1471
- ctx.config.optimization.splitChunks.cacheGroups ||= {};
1472
- ctx.config.optimization.splitChunks.cacheGroups.nuxtGlobalCSS = {
1473
- name: "nuxt-global-css",
1474
- chunks: "all",
1475
- enforce: true,
1476
- test: (module) => {
1477
- if (module.type !== "css/mini-extract") {
1478
- return false;
1479
- }
1480
- const identifier = normalize(module.identifier());
1481
- for (const globalPath of globalCSSPaths) {
1482
- if (identifier.includes(globalPath)) {
1483
- return true;
1484
- }
1485
- }
1486
- return false;
1487
- }
1488
- };
1489
- }
1222
+ if (!ctx.nuxt.options.features.inlineStyles) return;
1223
+ const globalCSSPaths = /* @__PURE__ */ new Set();
1224
+ for (const css of ctx.options.css) if (typeof css === "string") {
1225
+ const resolved = resolveAlias(css, ctx.options.alias);
1226
+ globalCSSPaths.add(normalize(resolved));
1227
+ }
1228
+ if (globalCSSPaths.size > 0) {
1229
+ ctx.config.optimization ||= {};
1230
+ ctx.config.optimization.splitChunks ||= {};
1231
+ ctx.config.optimization.splitChunks.cacheGroups ||= {};
1232
+ ctx.config.optimization.splitChunks.cacheGroups.nuxtGlobalCSS = {
1233
+ name: "nuxt-global-css",
1234
+ chunks: "all",
1235
+ enforce: true,
1236
+ test: (module) => {
1237
+ if (module.type !== "css/mini-extract") return false;
1238
+ const identifier = normalize(module.identifier());
1239
+ for (const globalPath of globalCSSPaths) if (identifier.includes(globalPath)) return true;
1240
+ return false;
1241
+ }
1242
+ };
1243
+ }
1490
1244
  }
1491
1245
  function clientPlugins(ctx) {
1492
- if (!ctx.isDev && !ctx.nuxt.options.test && ctx.name === "client" && ctx.userConfig.analyze && (ctx.userConfig.analyze === true || ctx.userConfig.analyze.enabled)) {
1493
- const statsDir = resolve(ctx.options.analyzeDir);
1494
- ctx.config.plugins.push(new BundleAnalyzerPlugin({
1495
- analyzerMode: "static",
1496
- defaultSizes: "gzip",
1497
- generateStatsFile: true,
1498
- openAnalyzer: true,
1499
- reportFilename: resolve(statsDir, `${ctx.name}.html`),
1500
- statsFilename: resolve(statsDir, `${ctx.name}.json`),
1501
- ...ctx.userConfig.analyze === true ? {} : ctx.userConfig.analyze
1502
- }));
1503
- }
1504
- if (!ctx.nuxt.options.ssr) {
1505
- if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) {
1506
- ctx.config.plugins.push(new TsCheckerPlugin({
1507
- logger
1508
- }));
1509
- }
1510
- }
1246
+ if (!ctx.isDev && !ctx.nuxt.options.test && ctx.name === "client" && ctx.userConfig.analyze && (ctx.userConfig.analyze === true || ctx.userConfig.analyze.enabled)) {
1247
+ const statsDir = resolve(ctx.options.analyzeDir);
1248
+ ctx.config.plugins.push(new BundleAnalyzerPlugin({
1249
+ analyzerMode: "static",
1250
+ defaultSizes: "gzip",
1251
+ generateStatsFile: true,
1252
+ openAnalyzer: true,
1253
+ reportFilename: resolve(statsDir, `${ctx.name}.html`),
1254
+ statsFilename: resolve(statsDir, `${ctx.name}.json`),
1255
+ ...ctx.userConfig.analyze === true ? {} : ctx.userConfig.analyze
1256
+ }));
1257
+ }
1258
+ if (!ctx.nuxt.options.ssr) {
1259
+ if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) ctx.config.plugins.push(new TsCheckerPlugin({ logger }));
1260
+ }
1511
1261
  }
1512
1262
 
1263
+ //#endregion
1264
+ //#region ../webpack/src/presets/node.ts
1513
1265
  function node(ctx) {
1514
- ctx.config.target = "node";
1515
- ctx.config.node = false;
1516
- ctx.config.experiments.outputModule = true;
1517
- ctx.config.output = {
1518
- ...ctx.config.output,
1519
- chunkFilename: "[name].mjs",
1520
- chunkFormat: "module",
1521
- chunkLoading: "import",
1522
- module: true,
1523
- environment: {
1524
- module: true,
1525
- arrowFunction: true,
1526
- bigIntLiteral: true,
1527
- const: true,
1528
- destructuring: true,
1529
- dynamicImport: true,
1530
- forOf: true
1531
- },
1532
- library: {
1533
- type: "module"
1534
- }
1535
- };
1536
- ctx.config.performance = {
1537
- ...ctx.config.performance,
1538
- hints: false,
1539
- maxEntrypointSize: Number.POSITIVE_INFINITY,
1540
- maxAssetSize: Number.POSITIVE_INFINITY
1541
- };
1266
+ ctx.config.target = "node";
1267
+ ctx.config.node = false;
1268
+ ctx.config.experiments.outputModule = true;
1269
+ ctx.config.output = {
1270
+ ...ctx.config.output,
1271
+ chunkFilename: "[name].mjs",
1272
+ chunkFormat: "module",
1273
+ chunkLoading: "import",
1274
+ module: true,
1275
+ environment: {
1276
+ module: true,
1277
+ arrowFunction: true,
1278
+ bigIntLiteral: true,
1279
+ const: true,
1280
+ destructuring: true,
1281
+ dynamicImport: true,
1282
+ forOf: true
1283
+ },
1284
+ library: { type: "module" }
1285
+ };
1286
+ ctx.config.performance = {
1287
+ ...ctx.config.performance,
1288
+ hints: false,
1289
+ maxEntrypointSize: Number.POSITIVE_INFINITY,
1290
+ maxAssetSize: Number.POSITIVE_INFINITY
1291
+ };
1542
1292
  }
1543
1293
 
1294
+ //#endregion
1295
+ //#region ../webpack/src/configs/server.ts
1544
1296
  const assetPattern = /\.(?:css|s[ca]ss|png|jpe?g|gif|svg|woff2?|eot|ttf|otf|webp|webm|mp4|ogv)(?:\?.*)?$/i;
1545
1297
  const VIRTUAL_RE = /^\0?virtual:(?:nuxt:)?/;
1546
1298
  async function server(ctx) {
1547
- ctx.name = "server";
1548
- ctx.isServer = true;
1549
- await applyPresets(ctx, [
1550
- nuxt,
1551
- node,
1552
- serverStandalone,
1553
- serverPreset,
1554
- serverPlugins
1555
- ]);
1299
+ ctx.name = "server";
1300
+ ctx.isServer = true;
1301
+ await applyPresets(ctx, [
1302
+ nuxt,
1303
+ node,
1304
+ serverStandalone,
1305
+ serverPreset,
1306
+ serverPlugins
1307
+ ]);
1556
1308
  }
1557
1309
  function serverPreset(ctx) {
1558
- ctx.config.output.filename = "server.mjs";
1559
- if (ctx.nuxt.options.sourcemap.server) {
1560
- const prefix = ctx.nuxt.options.sourcemap.server === "hidden" ? "hidden-" : "";
1561
- ctx.config.devtool = prefix + (ctx.isDev ? "cheap-module-source-map" : "source-map");
1562
- } else {
1563
- ctx.config.devtool = false;
1564
- }
1565
- ctx.config.optimization = {
1566
- splitChunks: false,
1567
- minimize: false
1568
- };
1569
- if (ctx.isDev) {
1570
- ctx.config.output.asyncChunks = false;
1571
- }
1310
+ ctx.config.output.filename = "server.mjs";
1311
+ if (ctx.nuxt.options.sourcemap.server) {
1312
+ const prefix = ctx.nuxt.options.sourcemap.server === "hidden" ? "hidden-" : "";
1313
+ ctx.config.devtool = prefix + (ctx.isDev ? "cheap-module-source-map" : "source-map");
1314
+ } else ctx.config.devtool = false;
1315
+ ctx.config.optimization = {
1316
+ splitChunks: false,
1317
+ minimize: false
1318
+ };
1319
+ if (ctx.isDev) ctx.config.output.asyncChunks = false;
1572
1320
  }
1573
1321
  async function serverStandalone(ctx) {
1574
- const inline = [
1575
- "src/",
1576
- "#app",
1577
- "nuxt",
1578
- "nuxt3",
1579
- "nuxt-nightly",
1580
- "!",
1581
- "-!",
1582
- "~",
1583
- "@/",
1584
- "#",
1585
- ...ctx.options.build.transpile
1586
- ];
1587
- const { runtimeDependencies: runtimeNitroDependencies = [] } = await tryImportModule("nitropack/runtime/meta", {
1588
- url: new URL(import.meta.url)
1589
- }) || {};
1590
- const external = /* @__PURE__ */ new Set([
1591
- "nitro/runtime",
1592
- // TODO: remove in v5
1593
- "#internal/nitro",
1594
- "nitropack/runtime",
1595
- "#shared",
1596
- resolve(ctx.nuxt.options.rootDir, ctx.nuxt.options.dir.shared),
1597
- // explicit dependencies we use in our ssr renderer
1598
- "unhead",
1599
- "@unhead/vue",
1600
- "@nuxt/devalue",
1601
- "rou3",
1602
- "unstorage",
1603
- ...runtimeDependencies,
1604
- ...runtimeNitroDependencies
1605
- ]);
1606
- if (!ctx.nuxt.options.dev) {
1607
- external.add("#internal/nuxt/paths");
1608
- external.add("#internal/nuxt/app-config");
1609
- external.add("#app-manifest");
1610
- }
1611
- if (!Array.isArray(ctx.config.externals)) {
1612
- return;
1613
- }
1614
- const conditions = [
1615
- ctx.nuxt.options.dev ? "development" : "production",
1616
- "node",
1617
- "import",
1618
- "require"
1619
- ];
1620
- ctx.config.externals.push(({ request, context }, cb) => {
1621
- if (!request) {
1622
- return cb(void 0, false);
1623
- }
1624
- if (external.has(request)) {
1625
- const resolved = resolveModulePath(request, {
1626
- from: context ? [context, ...ctx.nuxt.options.modulesDir].map((d) => directoryToURL(d)) : ctx.nuxt.options.modulesDir.map((d) => directoryToURL(d)),
1627
- suffixes: ["", "index"],
1628
- conditions,
1629
- try: true
1630
- });
1631
- if (resolved && isAbsolute(resolved)) {
1632
- return cb(void 0, resolved);
1633
- }
1634
- return cb(void 0, true);
1635
- }
1636
- if (request[0] === "." || isAbsolute(request) || inline.find((prefix) => typeof prefix === "string" && request.startsWith(prefix)) || assetPattern.test(request)) {
1637
- return cb(void 0, false);
1638
- }
1639
- if (context && request && !request.startsWith("node:") && (isAbsolute(context) || VIRTUAL_RE.test(context))) {
1640
- try {
1641
- const normalisedRequest = resolveAlias(normalize(request), ctx.nuxt.options.alias);
1642
- const dir = parseNodeModulePath(context).dir || ctx.nuxt.options.rootDir;
1643
- const resolved = resolveModulePath(normalisedRequest, {
1644
- from: [dir, ...ctx.nuxt.options.modulesDir].map((d) => directoryToURL(d)),
1645
- suffixes: ["", "index"],
1646
- conditions,
1647
- try: true
1648
- });
1649
- if (resolved && isAbsolute(resolved)) {
1650
- return cb(void 0, false);
1651
- }
1652
- } catch {
1653
- }
1654
- }
1655
- return cb(void 0, true);
1656
- });
1322
+ const inline = [
1323
+ "src/",
1324
+ "#app",
1325
+ "nuxt",
1326
+ "nuxt3",
1327
+ "nuxt-nightly",
1328
+ "!",
1329
+ "-!",
1330
+ "~",
1331
+ "@/",
1332
+ "#",
1333
+ ...ctx.options.build.transpile
1334
+ ];
1335
+ const { runtimeDependencies: runtimeNitroDependencies = [] } = await tryImportModule("nitropack/runtime/meta", { url: new URL(import.meta.url) }) || {};
1336
+ const external = new Set([
1337
+ "nitro/runtime",
1338
+ "#internal/nitro",
1339
+ "nitropack/runtime",
1340
+ "#shared",
1341
+ resolve(ctx.nuxt.options.rootDir, ctx.nuxt.options.dir.shared),
1342
+ "unhead",
1343
+ "@unhead/vue",
1344
+ "@nuxt/devalue",
1345
+ "rou3",
1346
+ "unstorage",
1347
+ ...runtimeDependencies,
1348
+ ...runtimeNitroDependencies
1349
+ ]);
1350
+ if (!ctx.nuxt.options.dev) {
1351
+ external.add("#internal/nuxt/paths");
1352
+ external.add("#internal/nuxt/app-config");
1353
+ external.add("#app-manifest");
1354
+ }
1355
+ if (!Array.isArray(ctx.config.externals)) return;
1356
+ const conditions = [
1357
+ ctx.nuxt.options.dev ? "development" : "production",
1358
+ "node",
1359
+ "import",
1360
+ "require"
1361
+ ];
1362
+ ctx.config.externals.push(({ request, context }, cb) => {
1363
+ if (!request) return cb(void 0, false);
1364
+ if (external.has(request)) {
1365
+ const resolved = resolveModulePath(request, {
1366
+ from: context ? [context, ...ctx.nuxt.options.modulesDir].map((d) => directoryToURL(d)) : ctx.nuxt.options.modulesDir.map((d) => directoryToURL(d)),
1367
+ suffixes: ["", "index"],
1368
+ conditions,
1369
+ try: true
1370
+ });
1371
+ if (resolved && isAbsolute(resolved)) return cb(void 0, resolved);
1372
+ return cb(void 0, true);
1373
+ }
1374
+ if (request[0] === "." || isAbsolute(request) || inline.find((prefix) => typeof prefix === "string" && request.startsWith(prefix)) || assetPattern.test(request)) return cb(void 0, false);
1375
+ if (context && request && !request.startsWith("node:") && (isAbsolute(context) || VIRTUAL_RE.test(context))) try {
1376
+ const resolved = resolveModulePath(resolveAlias(normalize(request), ctx.nuxt.options.alias), {
1377
+ from: [parseNodeModulePath(context).dir || ctx.nuxt.options.rootDir, ...ctx.nuxt.options.modulesDir].map((d) => directoryToURL(d)),
1378
+ suffixes: ["", "index"],
1379
+ conditions,
1380
+ try: true
1381
+ });
1382
+ if (resolved && isAbsolute(resolved)) return cb(void 0, false);
1383
+ } catch {}
1384
+ return cb(void 0, true);
1385
+ });
1657
1386
  }
1658
1387
  function serverPlugins(ctx) {
1659
- ctx.config.plugins ||= [];
1660
- if (ctx.userConfig.serverURLPolyfill) {
1661
- ctx.config.plugins.push(new webpack.ProvidePlugin({
1662
- URL: [ctx.userConfig.serverURLPolyfill, "URL"],
1663
- URLSearchParams: [ctx.userConfig.serverURLPolyfill, "URLSearchParams"]
1664
- }));
1665
- }
1666
- if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) {
1667
- ctx.config.plugins.push(new TsCheckerPlugin({
1668
- logger
1669
- }));
1670
- }
1388
+ ctx.config.plugins ||= [];
1389
+ if (ctx.userConfig.serverURLPolyfill) ctx.config.plugins.push(new webpack.ProvidePlugin({
1390
+ URL: [ctx.userConfig.serverURLPolyfill, "URL"],
1391
+ URLSearchParams: [ctx.userConfig.serverURLPolyfill, "URLSearchParams"]
1392
+ }));
1393
+ if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) ctx.config.plugins.push(new TsCheckerPlugin({ logger }));
1671
1394
  }
1672
1395
 
1673
- const bundle = async (nuxt) => {
1674
- const webpackConfigs = await Promise.all([client, ...nuxt.options.ssr ? [server] : []].map(async (preset) => {
1675
- const ctx = createWebpackConfigContext(nuxt);
1676
- ctx.userConfig = defu(nuxt.options.webpack[`$${preset.name}`], ctx.userConfig);
1677
- await applyPresets(ctx, preset);
1678
- return ctx.config;
1679
- }));
1680
- if (!nuxt.options.dev) {
1681
- const nitro = useNitro();
1682
- nitro.hooks.hook("rollup:before", (_nitro, config) => {
1683
- const plugins = config.plugins;
1684
- const existingPlugin = plugins.findIndex((i) => i && "name" in i && i.name === "dynamic-require");
1685
- if (existingPlugin >= 0) {
1686
- plugins.splice(existingPlugin, 1);
1687
- }
1688
- });
1689
- }
1690
- await nuxt.callHook(`${builder}:config`, webpackConfigs);
1691
- const mfs = nuxt.options.dev ? createMFS() : null;
1692
- const ssrStylesPlugin = nuxt.options.ssr && !nuxt.options.dev && nuxt.options.features.inlineStyles ? new SSRStylesPlugin(nuxt) : null;
1693
- for (const config of webpackConfigs) {
1694
- config.plugins.push(DynamicBasePlugin.webpack({
1695
- sourcemap: !!nuxt.options.sourcemap[config.name]
1696
- }));
1697
- if (config.name === "client" && nuxt.options.experimental.emitRouteChunkError && nuxt.options.builder !== "@nuxt/rspack-builder") {
1698
- config.plugins.push(new ChunkErrorPlugin());
1699
- }
1700
- if (ssrStylesPlugin) {
1701
- config.plugins.push(ssrStylesPlugin);
1702
- }
1703
- }
1704
- await nuxt.callHook(`${builder}:configResolved`, webpackConfigs);
1705
- const compilers = webpackConfigs.map((config) => {
1706
- const compiler = webpack(config);
1707
- if (nuxt.options.dev && compiler) {
1708
- compiler.outputFileSystem = mfs;
1709
- }
1710
- return compiler;
1711
- });
1712
- nuxt.hook("close", async () => {
1713
- for (const compiler of compilers) {
1714
- await new Promise((resolve) => compiler.close(resolve));
1715
- }
1716
- });
1717
- if (nuxt.options.dev) {
1718
- await Promise.all(compilers.map((c) => compile(c)));
1719
- return;
1720
- }
1721
- for (const c of compilers) {
1722
- await compile(c);
1723
- }
1396
+ //#endregion
1397
+ //#region ../webpack/src/webpack.ts
1398
+ const bundle = async (nuxt$1) => {
1399
+ const webpackConfigs = await Promise.all([client, ...nuxt$1.options.ssr ? [server] : []].map(async (preset) => {
1400
+ const ctx = createWebpackConfigContext(nuxt$1);
1401
+ ctx.userConfig = defu(nuxt$1.options.webpack[`$${preset.name}`], ctx.userConfig);
1402
+ await applyPresets(ctx, preset);
1403
+ return ctx.config;
1404
+ }));
1405
+ /** Remove Nitro rollup plugin for handling dynamic imports from webpack chunks */
1406
+ if (!nuxt$1.options.dev) useNitro().hooks.hook("rollup:before", (_nitro, config) => {
1407
+ const plugins = config.plugins;
1408
+ const existingPlugin = plugins.findIndex((i) => i && "name" in i && i.name === "dynamic-require");
1409
+ if (existingPlugin >= 0) plugins.splice(existingPlugin, 1);
1410
+ });
1411
+ await nuxt$1.callHook(`${builder}:config`, webpackConfigs);
1412
+ const mfs = nuxt$1.options.dev ? createMFS() : null;
1413
+ const ssrStylesPlugin = nuxt$1.options.ssr && !nuxt$1.options.dev && nuxt$1.options.features.inlineStyles ? new SSRStylesPlugin(nuxt$1) : null;
1414
+ for (const config of webpackConfigs) {
1415
+ config.plugins.push(DynamicBasePlugin.webpack({ sourcemap: !!nuxt$1.options.sourcemap[config.name] }));
1416
+ if (config.name === "client" && nuxt$1.options.experimental.emitRouteChunkError && nuxt$1.options.builder !== "@nuxt/rspack-builder") config.plugins.push(new ChunkErrorPlugin());
1417
+ if (ssrStylesPlugin) config.plugins.push(ssrStylesPlugin);
1418
+ }
1419
+ await nuxt$1.callHook(`${builder}:configResolved`, webpackConfigs);
1420
+ const compilers = webpackConfigs.map((config) => {
1421
+ const compiler = webpack(config);
1422
+ if (nuxt$1.options.dev && compiler) compiler.outputFileSystem = mfs;
1423
+ return compiler;
1424
+ });
1425
+ nuxt$1.hook("close", async () => {
1426
+ for (const compiler of compilers) await new Promise((resolve$1) => compiler.close(resolve$1));
1427
+ });
1428
+ if (nuxt$1.options.dev) {
1429
+ await Promise.all(compilers.map((c) => compile(c)));
1430
+ return;
1431
+ }
1432
+ for (const c of compilers) await compile(c);
1724
1433
  };
1725
1434
  async function createDevMiddleware(compiler) {
1726
- const nuxt = useNuxt();
1727
- logger.debug("Creating webpack middleware...");
1728
- const devMiddleware = webpackDevMiddleware(compiler, {
1729
- publicPath: joinURL(nuxt.options.app.baseURL, nuxt.options.app.buildAssetsDir),
1730
- outputFileSystem: compiler.outputFileSystem,
1731
- stats: "none",
1732
- ...nuxt.options.webpack.devMiddleware
1733
- });
1734
- nuxt.hook("close", () => pify(devMiddleware.close.bind(devMiddleware))());
1735
- const { client: _client, ...hotMiddlewareOptions } = nuxt.options.webpack.hotMiddleware || {};
1736
- const hotMiddleware = webpackHotMiddleware(compiler, {
1737
- log: false,
1738
- heartbeat: 1e4,
1739
- path: joinURL(nuxt.options.app.baseURL, "__webpack_hmr", compiler.options.name),
1740
- ...hotMiddlewareOptions
1741
- });
1742
- const devHandler = wdmToH3Handler(devMiddleware, nuxt.options.devServer.cors);
1743
- const hotHandler = fromNodeMiddleware(hotMiddleware);
1744
- await nuxt.callHook("server:devHandler", defineEventHandler(async (event) => {
1745
- const body = await devHandler(event);
1746
- if (body !== void 0) {
1747
- return body;
1748
- }
1749
- await hotHandler(event);
1750
- }));
1751
- return devMiddleware;
1435
+ const nuxt$1 = useNuxt();
1436
+ logger.debug("Creating webpack middleware...");
1437
+ const devMiddleware = webpackDevMiddleware(compiler, {
1438
+ publicPath: joinURL(nuxt$1.options.app.baseURL, nuxt$1.options.app.buildAssetsDir),
1439
+ outputFileSystem: compiler.outputFileSystem,
1440
+ stats: "none",
1441
+ ...nuxt$1.options.webpack.devMiddleware
1442
+ });
1443
+ nuxt$1.hook("close", () => pify(devMiddleware.close.bind(devMiddleware))());
1444
+ const { client: _client, ...hotMiddlewareOptions } = nuxt$1.options.webpack.hotMiddleware || {};
1445
+ const hotMiddleware = webpackHotMiddleware(compiler, {
1446
+ log: false,
1447
+ heartbeat: 1e4,
1448
+ path: joinURL(nuxt$1.options.app.baseURL, "__webpack_hmr", compiler.options.name),
1449
+ ...hotMiddlewareOptions
1450
+ });
1451
+ const devHandler = wdmToH3Handler(devMiddleware, nuxt$1.options.devServer.cors);
1452
+ const hotHandler = fromNodeMiddleware(hotMiddleware);
1453
+ await nuxt$1.callHook("server:devHandler", defineEventHandler(async (event) => {
1454
+ const body = await devHandler(event);
1455
+ if (body !== void 0) return body;
1456
+ await hotHandler(event);
1457
+ }));
1458
+ return devMiddleware;
1752
1459
  }
1753
1460
  function wdmToH3Handler(devMiddleware, corsOptions) {
1754
- return defineEventHandler(async (event) => {
1755
- const isPreflight = handleCors(event, corsOptions);
1756
- if (isPreflight) {
1757
- return null;
1758
- }
1759
- if (getRequestHeader(event, "sec-fetch-mode") === "no-cors" && getRequestHeader(event, "sec-fetch-site") === "cross-site") {
1760
- throw createError({ status: 403 });
1761
- }
1762
- setHeader(event, "Vary", "Origin");
1763
- event.context.webpack = {
1764
- ...event.context.webpack,
1765
- devMiddleware: devMiddleware.context
1766
- };
1767
- const { req, res } = event.node;
1768
- const body = await new Promise((resolve, reject) => {
1769
- res.stream = (stream) => {
1770
- resolve(stream);
1771
- };
1772
- res.send = (data) => {
1773
- resolve(data);
1774
- };
1775
- res.finish = (data) => {
1776
- resolve(data);
1777
- };
1778
- devMiddleware(req, res, (err) => {
1779
- if (err) {
1780
- reject(err);
1781
- } else {
1782
- resolve(void 0);
1783
- }
1784
- });
1785
- });
1786
- return body;
1787
- });
1461
+ return defineEventHandler(async (event) => {
1462
+ if (handleCors(event, corsOptions)) return null;
1463
+ if (getRequestHeader(event, "sec-fetch-mode") === "no-cors" && getRequestHeader(event, "sec-fetch-site") === "cross-site") throw createError({ status: 403 });
1464
+ setHeader(event, "Vary", "Origin");
1465
+ event.context.webpack = {
1466
+ ...event.context.webpack,
1467
+ devMiddleware: devMiddleware.context
1468
+ };
1469
+ const { req, res } = event.node;
1470
+ return await new Promise((resolve$1, reject) => {
1471
+ res.stream = (stream) => {
1472
+ resolve$1(stream);
1473
+ };
1474
+ res.send = (data) => {
1475
+ resolve$1(data);
1476
+ };
1477
+ res.finish = (data) => {
1478
+ resolve$1(data);
1479
+ };
1480
+ devMiddleware(req, res, (err) => {
1481
+ if (err) reject(err);
1482
+ else resolve$1(void 0);
1483
+ });
1484
+ });
1485
+ });
1788
1486
  }
1789
1487
  async function compile(compiler) {
1790
- const nuxt = useNuxt();
1791
- await nuxt.callHook(`${builder}:compile`, { name: compiler.options.name, compiler });
1792
- compiler.hooks.done.tap("load-resources", async (stats2) => {
1793
- await nuxt.callHook(`${builder}:compiled`, { name: compiler.options.name, compiler, stats: stats2 });
1794
- });
1795
- if (nuxt.options.dev) {
1796
- const compilersWatching = [];
1797
- nuxt.hook("close", async () => {
1798
- await Promise.all(compilersWatching.map((watching) => watching && pify(watching.close.bind(watching))()));
1799
- });
1800
- if (compiler.options.name === "client") {
1801
- return new Promise((resolve, reject) => {
1802
- compiler.hooks.done.tap("nuxt-dev", () => {
1803
- resolve(null);
1804
- });
1805
- compiler.hooks.failed.tap("nuxt-errorlog", (err) => {
1806
- reject(err);
1807
- });
1808
- createDevMiddleware(compiler).then((devMiddleware) => {
1809
- if (devMiddleware.context.watching) {
1810
- compilersWatching.push(devMiddleware.context.watching);
1811
- }
1812
- });
1813
- });
1814
- }
1815
- return new Promise((resolve, reject) => {
1816
- const watching = compiler.watch(nuxt.options.watchers.webpack, (err) => {
1817
- if (err) {
1818
- return reject(err);
1819
- }
1820
- resolve(null);
1821
- });
1822
- compilersWatching.push(watching);
1823
- });
1824
- }
1825
- const stats = await new Promise((resolve, reject) => compiler.run((err, stats2) => err ? reject(err) : resolve(stats2)));
1826
- if (stats.hasErrors()) {
1827
- const error = new Error("Nuxt build error");
1828
- error.stack = stats.toString("errors-only");
1829
- throw error;
1830
- }
1488
+ const nuxt$1 = useNuxt();
1489
+ await nuxt$1.callHook(`${builder}:compile`, {
1490
+ name: compiler.options.name,
1491
+ compiler
1492
+ });
1493
+ compiler.hooks.done.tap("load-resources", async (stats$1) => {
1494
+ await nuxt$1.callHook(`${builder}:compiled`, {
1495
+ name: compiler.options.name,
1496
+ compiler,
1497
+ stats: stats$1
1498
+ });
1499
+ });
1500
+ if (nuxt$1.options.dev) {
1501
+ const compilersWatching = [];
1502
+ nuxt$1.hook("close", async () => {
1503
+ await Promise.all(compilersWatching.map((watching) => watching && pify(watching.close.bind(watching))()));
1504
+ });
1505
+ if (compiler.options.name === "client") return new Promise((resolve$1, reject) => {
1506
+ compiler.hooks.done.tap("nuxt-dev", () => {
1507
+ resolve$1(null);
1508
+ });
1509
+ compiler.hooks.failed.tap("nuxt-errorlog", (err) => {
1510
+ reject(err);
1511
+ });
1512
+ createDevMiddleware(compiler).then((devMiddleware) => {
1513
+ if (devMiddleware.context.watching) compilersWatching.push(devMiddleware.context.watching);
1514
+ });
1515
+ });
1516
+ return new Promise((resolve$1, reject) => {
1517
+ const watching = compiler.watch(nuxt$1.options.watchers.webpack, (err) => {
1518
+ if (err) return reject(err);
1519
+ resolve$1(null);
1520
+ });
1521
+ compilersWatching.push(watching);
1522
+ });
1523
+ }
1524
+ const stats = await new Promise((resolve$1, reject) => compiler.run((err, stats$1) => err ? reject(err) : resolve$1(stats$1)));
1525
+ if (stats.hasErrors()) {
1526
+ const error = /* @__PURE__ */ new Error("Nuxt build error");
1527
+ error.stack = stats.toString("errors-only");
1528
+ throw error;
1529
+ }
1831
1530
  }
1832
1531
 
1833
- export { bundle };
1532
+ //#endregion
1533
+ export { bundle };