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