create project

This commit is contained in:
ismailsosic
2022-12-27 12:05:56 +01:00
parent 2a33a2d3de
commit cd2143287c
16035 changed files with 2489703 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import { APP_BUILD_MANIFEST, CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH } from "../../../shared/lib/constants";
import { getEntrypointFiles } from "./build-manifest-plugin";
import getAppRouteFromEntrypoint from "../../../server/get-app-route-from-entrypoint";
const PLUGIN_NAME = "AppBuildManifestPlugin";
export class AppBuildManifestPlugin {
constructor(options){
this.dev = options.dev;
}
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory })=>{
compilation.dependencyFactories.set(webpack.dependencies.ModuleDependency, normalModuleFactory);
compilation.dependencyTemplates.set(webpack.dependencies.ModuleDependency, new webpack.dependencies.NullDependency.Template());
});
compiler.hooks.make.tap(PLUGIN_NAME, (compilation)=>{
compilation.hooks.processAssets.tap({
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, (assets)=>this.createAsset(assets, compilation));
});
}
createAsset(assets, compilation) {
const manifest = {
pages: {}
};
const systemEntrypoints = new Set([
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
]);
const mainFiles = new Set(getEntrypointFiles(compilation.entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_MAIN_APP)));
for (const entrypoint of compilation.entrypoints.values()){
if (!entrypoint.name) {
continue;
}
if (systemEntrypoints.has(entrypoint.name)) {
continue;
}
const pagePath = getAppRouteFromEntrypoint(entrypoint.name);
if (!pagePath) {
continue;
}
const filesForPage = getEntrypointFiles(entrypoint);
manifest.pages[pagePath] = [
...new Set([
...mainFiles,
...filesForPage
])
];
}
const json = JSON.stringify(manifest, null, 2);
assets[APP_BUILD_MANIFEST] = new sources.RawSource(json);
}
}
//# sourceMappingURL=app-build-manifest-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/app-build-manifest-plugin.ts"],"names":["webpack","sources","APP_BUILD_MANIFEST","CLIENT_STATIC_FILES_RUNTIME_AMP","CLIENT_STATIC_FILES_RUNTIME_MAIN","CLIENT_STATIC_FILES_RUNTIME_MAIN_APP","CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH","getEntrypointFiles","getAppRouteFromEntrypoint","PLUGIN_NAME","AppBuildManifestPlugin","constructor","options","dev","apply","compiler","hooks","compilation","tap","normalModuleFactory","dependencyFactories","set","dependencies","ModuleDependency","dependencyTemplates","NullDependency","Template","make","processAssets","name","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS","assets","createAsset","manifest","pages","systemEntrypoints","Set","mainFiles","entrypoints","get","entrypoint","values","has","pagePath","filesForPage","json","JSON","stringify","RawSource"],"mappings":"AAAA,SAASA,OAAO,EAAEC,OAAO,QAAQ,oCAAoC,CAAA;AACrE,SACEC,kBAAkB,EAClBC,+BAA+B,EAC/BC,gCAAgC,EAChCC,oCAAoC,EACpCC,yCAAyC,QACpC,+BAA+B,CAAA;AACtC,SAASC,kBAAkB,QAAQ,yBAAyB,CAAA;AAC5D,OAAOC,yBAAyB,MAAM,+CAA+C,CAAA;AAUrF,MAAMC,WAAW,GAAG,wBAAwB;AAE5C,OAAO,MAAMC,sBAAsB;IAGjCC,YAAYC,OAAgB,CAAE;QAC5B,IAAI,CAACC,GAAG,GAAGD,OAAO,CAACC,GAAG;KACvB;IAED,AAAOC,KAAK,CAACC,QAAa,EAAE;QAC1BA,QAAQ,CAACC,KAAK,CAACC,WAAW,CAACC,GAAG,CAC5BT,WAAW,EACX,CAACQ,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T;YAED,MAAMgB,QAAQ,GAAGrC,yBAAyB,CAACkC,UAAU,CAACb,IAAI,CAAC;YAC3D,IAAI,CAACgB,QAAQ,EAAE;gBACb,SAAQ;aACT;YAED,MAAMC,YAAY,GAAGvC,kBAAkB,CAACmC,UAAU,CAAC;YAEnDP,QAAQ,CAACC,KAAK,CAACS,QAAQ,CAAC,GAAG;mBAAI,IAAIP,GAAG,CAAC;uBAAIC,SAAS;uBAAKO,YAAY;iBAAC,CAAC;aAAC;SACzE;QAED,MAAMC,IAAI,GAAGC,IAAI,CAACC,SAAS,CAACd,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;QAE9CF,MAAM,CAAC/B,kBAAkB,CAAC,GAAG,IAAID,OAAO,CAACiD,SAAS,CAACH,IAAI,CAAC;KACzD;CACF"}

View File

@@ -0,0 +1,178 @@
import devalue from "next/dist/compiled/devalue";
import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import { BUILD_MANIFEST, MIDDLEWARE_BUILD_MANIFEST, CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, CLIENT_STATIC_FILES_RUNTIME_AMP } from "../../../shared/lib/constants";
import getRouteFromEntrypoint from "../../../server/get-route-from-entrypoint";
import { ampFirstEntryNamesMap } from "./next-drop-client-page-plugin";
import { getSortedRoutes } from "../../../shared/lib/router/utils";
import { spans } from "./profiling-plugin";
// This function takes the asset map generated in BuildManifestPlugin and creates a
// reduced version to send to the client.
function generateClientManifest(compiler, compilation, assetMap, rewrites) {
const compilationSpan = spans.get(compilation) || spans.get(compiler);
const genClientManifestSpan = compilationSpan == null ? void 0 : compilationSpan.traceChild("NextJsBuildManifest-generateClientManifest");
return genClientManifestSpan == null ? void 0 : genClientManifestSpan.traceFn(()=>{
const clientManifest = {
// TODO: update manifest type to include rewrites
__rewrites: rewrites
};
const appDependencies = new Set(assetMap.pages["/_app"]);
const sortedPageKeys = getSortedRoutes(Object.keys(assetMap.pages));
sortedPageKeys.forEach((page)=>{
const dependencies = assetMap.pages[page];
if (page === "/_app") return;
// Filter out dependencies in the _app entry, because those will have already
// been loaded by the client prior to a navigation event
const filteredDeps = dependencies.filter((dep)=>!appDependencies.has(dep));
// The manifest can omit the page if it has no requirements
if (filteredDeps.length) {
clientManifest[page] = filteredDeps;
}
});
// provide the sorted pages as an array so we don't rely on the object's keys
// being in order and we don't slow down look-up time for page assets
clientManifest.sortedPages = sortedPageKeys;
return devalue(clientManifest);
});
}
export function getEntrypointFiles(entrypoint) {
return (entrypoint == null ? void 0 : entrypoint.getFiles().filter((file)=>{
// We don't want to include `.hot-update.js` files into the initial page
return /(?<!\.hot-update)\.(js|css)($|\?)/.test(file);
}).map((file)=>file.replace(/\\/g, "/"))) ?? [];
}
const processRoute = (r)=>{
const rewrite = {
...r
};
// omit external rewrite destinations since these aren't
// handled client-side
if (!rewrite.destination.startsWith("/")) {
delete rewrite.destination;
}
return rewrite;
};
// This plugin creates a build-manifest.json for all assets that are being output
// It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production
export default class BuildManifestPlugin {
constructor(options){
this.buildId = options.buildId;
this.isDevFallback = !!options.isDevFallback;
this.rewrites = {
beforeFiles: [],
afterFiles: [],
fallback: []
};
this.appDirEnabled = options.appDirEnabled;
this.rewrites.beforeFiles = options.rewrites.beforeFiles.map(processRoute);
this.rewrites.afterFiles = options.rewrites.afterFiles.map(processRoute);
this.rewrites.fallback = options.rewrites.fallback.map(processRoute);
this.exportRuntime = !!options.exportRuntime;
}
createAssets(compiler, compilation, assets) {
const compilationSpan = spans.get(compilation) || spans.get(compiler);
const createAssetsSpan = compilationSpan == null ? void 0 : compilationSpan.traceChild("NextJsBuildManifest-createassets");
return createAssetsSpan == null ? void 0 : createAssetsSpan.traceFn(()=>{
const entrypoints = compilation.entrypoints;
const assetMap = {
polyfillFiles: [],
devFiles: [],
ampDevFiles: [],
lowPriorityFiles: [],
rootMainFiles: [],
pages: {
"/_app": []
},
ampFirstPages: []
};
const ampFirstEntryNames = ampFirstEntryNamesMap.get(compilation);
if (ampFirstEntryNames) {
for (const entryName of ampFirstEntryNames){
const pagePath = getRouteFromEntrypoint(entryName);
if (!pagePath) {
continue;
}
assetMap.ampFirstPages.push(pagePath);
}
}
const mainFiles = new Set(getEntrypointFiles(entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_MAIN)));
if (this.appDirEnabled) {
assetMap.rootMainFiles = [
...new Set(getEntrypointFiles(entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_MAIN_APP))),
];
}
const compilationAssets = compilation.getAssets();
assetMap.polyfillFiles = compilationAssets.filter((p)=>{
// Ensure only .js files are passed through
if (!p.name.endsWith(".js")) {
return false;
}
return p.info && CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL in p.info;
}).map((v)=>v.name);
assetMap.devFiles = getEntrypointFiles(entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH)).filter((file)=>!mainFiles.has(file));
assetMap.ampDevFiles = getEntrypointFiles(entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_AMP));
const systemEntrypoints = new Set([
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP,
...this.appDirEnabled ? [
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP
] : [],
]);
for (const entrypoint of compilation.entrypoints.values()){
if (systemEntrypoints.has(entrypoint.name)) continue;
const pagePath = getRouteFromEntrypoint(entrypoint.name);
if (!pagePath) {
continue;
}
const filesForPage = getEntrypointFiles(entrypoint);
assetMap.pages[pagePath] = [
...new Set([
...mainFiles,
...filesForPage
])
];
}
if (!this.isDevFallback) {
// Add the runtime build manifest file (generated later in this file)
// as a dependency for the app. If the flag is false, the file won't be
// downloaded by the client.
assetMap.lowPriorityFiles.push(`${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`);
// Add the runtime ssg manifest file as a lazy-loaded file dependency.
// We also stub this file out for development mode (when it is not
// generated).
const srcEmptySsgManifest = `self.__SSG_MANIFEST=new Set;self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`;
const ssgManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_ssgManifest.js`;
assetMap.lowPriorityFiles.push(ssgManifestPath);
assets[ssgManifestPath] = new sources.RawSource(srcEmptySsgManifest);
}
assetMap.pages = Object.keys(assetMap.pages).sort()// eslint-disable-next-line
.reduce((a, c)=>(a[c] = assetMap.pages[c], a), {});
let buildManifestName = BUILD_MANIFEST;
if (this.isDevFallback) {
buildManifestName = `fallback-${BUILD_MANIFEST}`;
}
assets[buildManifestName] = new sources.RawSource(JSON.stringify(assetMap, null, 2));
if (this.exportRuntime) {
assets[`server/${MIDDLEWARE_BUILD_MANIFEST}.js`] = new sources.RawSource(`self.__BUILD_MANIFEST=${JSON.stringify(assetMap)}`);
}
if (!this.isDevFallback) {
const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`;
assets[clientManifestPath] = new sources.RawSource(`self.__BUILD_MANIFEST = ${generateClientManifest(compiler, compilation, assetMap, this.rewrites)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`);
}
return assets;
});
}
apply(compiler) {
compiler.hooks.make.tap("NextJsBuildManifest", (compilation)=>{
compilation.hooks.processAssets.tap({
name: "NextJsBuildManifest",
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, (assets)=>{
this.createAssets(compiler, compilation, assets);
});
});
return;
}
};
//# sourceMappingURL=build-manifest-plugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,52 @@
import { promises as fs } from "fs";
import loaderUtils from "next/dist/compiled/loader-utils3";
import { sources, webpack } from "next/dist/compiled/webpack/webpack";
const PLUGIN_NAME = "CopyFilePlugin";
export class CopyFilePlugin {
constructor({ filePath , cacheKey , name , info }){
this.filePath = filePath;
this.cacheKey = cacheKey;
this.name = name;
this.info = info;
}
apply(compiler) {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation)=>{
const cache = compilation.getCache("CopyFilePlugin");
const hook = compilation.hooks.processAssets;
hook.tapPromise({
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, async ()=>{
if (cache) {
const cachedResult = await cache.getPromise(this.filePath, this.cacheKey);
if (cachedResult) {
const { file , source } = cachedResult;
compilation.emitAsset(file, source, {
...this.info
});
return;
}
}
const content = await fs.readFile(this.filePath, "utf8");
const file = loaderUtils.interpolateName({
resourcePath: this.filePath
}, this.name, {
content,
context: compiler.context
});
const source = new sources.RawSource(content);
if (cache) {
await cache.storePromise(this.filePath, this.cacheKey, {
file,
source
});
}
compilation.emitAsset(file, source, {
...this.info
});
});
});
}
}
//# sourceMappingURL=copy-file-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/copy-file-plugin.ts"],"names":["promises","fs","loaderUtils","sources","webpack","PLUGIN_NAME","CopyFilePlugin","constructor","filePath","cacheKey","name","info","apply","compiler","hooks","thisCompilation","tap","compilation","cache","getCache","hook","processAssets","tapPromise","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS","cachedResult","getPromise","file","source","emitAsset","content","readFile","interpolateName","resourcePath","context","RawSource","storePromise"],"mappings":"AAAA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AACnC,OAAOC,WAAW,MAAM,kCAAkC,CAAA;AAC1D,SAASC,OAAO,EAAEC,OAAO,QAAQ,oCAAoC,CAAA;AAErE,MAAMC,WAAW,GAAG,gBAAgB;AAEpC,OAAO,MAAMC,cAAc;IAMzBC,YAAY,EACVC,QAAQ,CAAA,EACRC,QAAQ,CAAA,EACRC,IAAI,CAAA,E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BAED,MAAMN,MAAM,GAAG,IAAI1B,OAAO,CAACiC,SAAS,CAACL,OAAO,CAAC;gBAE7C,IAAIb,KAAK,EAAE;oBACT,MAAMA,KAAK,CAACmB,YAAY,CAAC,IAAI,CAAC7B,QAAQ,EAAE,IAAI,CAACC,QAAQ,EAAE;wBACrDmB,IAAI;wBACJC,MAAM;qBACP,CAAC;iBACH;gBAEDZ,WAAW,CAACa,SAAS,CAACF,IAAI,EAAEC,MAAM,EAAE;oBAClC,GAAG,IAAI,CAAClB,IAAI;iBACb,CAAC;aACH,CACF;SACF,CAAC;KACH;CACF"}

View File

@@ -0,0 +1,76 @@
import cssnanoSimple from "next/dist/compiled/cssnano-simple";
import postcssScss from "next/dist/compiled/postcss-scss";
import postcss from "postcss";
import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import { spans } from "./profiling-plugin";
// https://github.com/NMFR/optimize-css-assets-webpack-plugin/blob/0a410a9bf28c7b0e81a3470a13748e68ca2f50aa/src/index.js#L20
const CSS_REGEX = /\.css(\?.*)?$/i;
export class CssMinimizerPlugin {
__next_css_remove = true;
constructor(options){
this.options = options;
}
optimizeAsset(file, asset) {
const postcssOptions = {
...this.options.postcssOptions,
to: file,
from: file,
// We don't actually add this parser to support Sass. It can also be used
// for inline comment support. See the README:
// https://github.com/postcss/postcss-scss/blob/master/README.md#2-inline-comments-for-postcss
parser: postcssScss
};
let input;
if (postcssOptions.map && asset.sourceAndMap) {
const { source , map } = asset.sourceAndMap();
input = source;
postcssOptions.map.prev = map ? map : false;
} else {
input = asset.source();
}
return postcss([
cssnanoSimple({}, postcss)
]).process(input, postcssOptions).then((res)=>{
if (res.map) {
return new sources.SourceMapSource(res.css, file, res.map.toJSON());
} else {
return new sources.RawSource(res.css);
}
});
}
apply(compiler) {
compiler.hooks.compilation.tap("CssMinimizerPlugin", (compilation)=>{
const cache = compilation.getCache("CssMinimizerPlugin");
compilation.hooks.processAssets.tapPromise({
name: "CssMinimizerPlugin",
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE
}, async (assets)=>{
const compilationSpan = spans.get(compilation) || spans.get(compiler);
const cssMinimizerSpan = compilationSpan.traceChild("css-minimizer-plugin");
cssMinimizerSpan.setAttribute("webpackVersion", 5);
return cssMinimizerSpan.traceAsyncFn(async ()=>{
const files = Object.keys(assets);
await Promise.all(files.filter((file)=>CSS_REGEX.test(file)).map(async (file)=>{
const assetSpan = cssMinimizerSpan.traceChild("minify-css");
assetSpan.setAttribute("file", file);
return assetSpan.traceAsyncFn(async ()=>{
const asset = assets[file];
const etag = cache.getLazyHashedEtag(asset);
const cachedResult = await cache.getPromise(file, etag);
assetSpan.setAttribute("cache", cachedResult ? "HIT" : "MISS");
if (cachedResult) {
assets[file] = cachedResult;
return;
}
const result = await this.optimizeAsset(file, asset);
await cache.storePromise(file, etag, result);
assets[file] = result;
});
}));
});
});
});
}
}
//# sourceMappingURL=css-minimizer-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/css-minimizer-plugin.ts"],"names":["cssnanoSimple","postcssScss","postcss","webpack","sources","spans","CSS_REGEX","CssMinimizerPlugin","__next_css_remove","constructor","options","optimizeAsset","file","asset","postcssOptions","to","from","parser","input","map","sourceAndMap","source","prev","process","then","res","SourceMapSource","css","toJSON","RawSource","apply","compiler","hooks","compilation","tap","cache","getCache","processAssets","tapPromise","name","stage","Compilation","PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE","assets","compilationSpan","get","cssMinimizerSpan","traceChild","setAttribute","traceAsyncFn","files","Object","keys","Promise","all","filter","test","assetSpan","etag","getLazyHashedEtag","cachedResult","getPromise","result","storePromise"],"mappings":"AAAA,OAAOA,aAAa,MAAM,mCAAmC,CAAA;AAC7D,OAAOC,WAAW,MAAM,iCAAiC,CAAA;AACzD,OAAOC,OAAO,MAAkB,SAAS,CAAA;AACzC,SAASC,OAAO,EAAEC,OAAO,QAAQ,oCAAoC,CAAA;AACrE,SAASC,KAAK,QA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MzB,KAAK,CAAC0B,UAAU,CAACjD,IAAI,EAAE8C,IAAI,CAAC;4BAEvDD,SAAS,CAACT,YAAY,CACpB,OAAO,EACPY,YAAY,GAAG,KAAK,GAAG,MAAM,CAC9B;4BACD,IAAIA,YAAY,EAAE;gCAChBjB,MAAM,CAAC/B,IAAI,CAAC,GAAGgD,YAAY;gCAC3B,OAAM;6BACP;4BAED,MAAME,MAAM,GAAG,MAAM,IAAI,CAACnD,aAAa,CAACC,IAAI,EAAEC,KAAK,CAAC;4BACpD,MAAMsB,KAAK,CAAC4B,YAAY,CAACnD,IAAI,EAAE8C,IAAI,EAAEI,MAAM,CAAC;4BAC5CnB,MAAM,CAAC/B,IAAI,CAAC,GAAGkD,MAAM;yBACtB,CAAC,CAAA;qBACH,CAAC,CACL;iBACF,CAAC,CAAA;aACH,CACF;SACF,CAAC;KACH;CACF"}

View File

@@ -0,0 +1,387 @@
import { webpack } from "next/dist/compiled/webpack/webpack";
import { stringify } from "querystring";
import path from "path";
import { sources } from "next/dist/compiled/webpack/webpack";
import { getInvalidator, entries, EntryTypes } from "../../../server/dev/on-demand-entry-handler";
import { WEBPACK_LAYERS } from "../../../lib/constants";
import { APP_CLIENT_INTERNALS, COMPILER_NAMES, EDGE_RUNTIME_WEBPACK, FLIGHT_SERVER_CSS_MANIFEST } from "../../../shared/lib/constants";
import { ASYNC_CLIENT_MODULES } from "./flight-manifest-plugin";
import { isClientComponentModule, regexCSS } from "../loaders/utils";
import { traverseModules } from "../utils";
import { normalizePathSep } from "../../../shared/lib/page-path/normalize-path-sep";
const PLUGIN_NAME = "ClientEntryPlugin";
export const injectedClientEntries = new Map();
export const serverModuleIds = new Map();
export const edgeServerModuleIds = new Map();
let serverCSSManifest = {};
let edgeServerCSSManifest = {};
export class FlightClientEntryPlugin {
constructor(options){
this.dev = options.dev;
this.appDir = options.appDir;
this.isEdgeServer = options.isEdgeServer;
}
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory })=>{
compilation.dependencyFactories.set(webpack.dependencies.ModuleDependency, normalModuleFactory);
compilation.dependencyTemplates.set(webpack.dependencies.ModuleDependency, new webpack.dependencies.NullDependency.Template());
});
compiler.hooks.finishMake.tapPromise(PLUGIN_NAME, (compilation)=>{
return this.createClientEntries(compiler, compilation);
});
compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation)=>{
traverseModules(compilation, (mod)=>{
// const modId = compilation.chunkGraph.getModuleId(mod) + ''
// The module must has request, and resource so it's not a new entry created with loader.
// Using the client layer module, which doesn't have `rsc` tag in buildInfo.
if (mod.request && mod.resource && !mod.buildInfo.rsc) {
if (compilation.moduleGraph.isAsync(mod)) {
ASYNC_CLIENT_MODULES.add(mod.resource);
}
}
});
const recordModule = (modId, mod)=>{
var ref;
const modResource = ((ref = mod.resourceResolveData) == null ? void 0 : ref.path) || mod.resource;
if (mod.layer !== WEBPACK_LAYERS.client) {
return;
}
// Check mod resource to exclude the empty resource module like virtual module created by next-flight-client-entry-loader
if (typeof modId !== "undefined" && modResource) {
// Note that this isn't that reliable as webpack is still possible to assign
// additional queries to make sure there's no conflict even using the `named`
// module ID strategy.
let ssrNamedModuleId = path.relative(compiler.context, modResource);
if (!ssrNamedModuleId.startsWith(".")) {
// TODO use getModuleId instead
ssrNamedModuleId = `./${normalizePathSep(ssrNamedModuleId)}`;
}
if (this.isEdgeServer) {
edgeServerModuleIds.set(ssrNamedModuleId.replace(/\/next\/dist\/esm\//, "/next/dist/"), modId);
} else {
serverModuleIds.set(ssrNamedModuleId, modId);
}
}
};
traverseModules(compilation, (mod, _chunk, _chunkGroup, modId)=>{
recordModule(String(modId), mod);
});
});
}
async createClientEntries(compiler, compilation) {
const promises = [];
// Loop over all the entry modules.
function forEachEntryModule(callback) {
for (const [name, entry] of compilation.entries.entries()){
var ref;
// Skip for entries under pages/
if (name.startsWith("pages/")) continue;
// Check if the page entry is a server component or not.
const entryDependency = (ref = entry.dependencies) == null ? void 0 : ref[0];
// Ensure only next-app-loader entries are handled.
if (!entryDependency || !entryDependency.request) continue;
const request = entryDependency.request;
if (!request.startsWith("next-edge-ssr-loader?") && !request.startsWith("next-app-loader?")) continue;
let entryModule = compilation.moduleGraph.getResolvedModule(entryDependency);
if (request.startsWith("next-edge-ssr-loader?")) {
entryModule.dependencies.forEach((dependency)=>{
const modRequest = dependency.request;
if (modRequest == null ? void 0 : modRequest.includes("next-app-loader")) {
entryModule = compilation.moduleGraph.getResolvedModule(dependency);
}
});
}
callback({
name,
entryModule
});
}
}
// For each SC server compilation entry, we need to create its corresponding
// client component entry.
forEachEntryModule(({ name , entryModule })=>{
const internalClientComponentEntryImports = new Set();
for (const connection of compilation.moduleGraph.getOutgoingConnections(entryModule)){
// Entry can be any user defined entry files such as layout, page, error, loading, etc.
const entryDependency = connection.dependency;
const entryRequest = connection.dependency.request;
const [clientComponentImports] = this.collectClientComponentsAndCSSForDependency({
entryRequest,
compilation,
dependency: entryDependency
});
const isAbsoluteRequest = path.isAbsolute(entryRequest);
// Next.js internals are put into a separate entry.
if (!isAbsoluteRequest) {
clientComponentImports.forEach((value)=>internalClientComponentEntryImports.add(value));
continue;
}
const relativeRequest = isAbsoluteRequest ? path.relative(compilation.options.context, entryRequest) : entryRequest;
// Replace file suffix as `.js` will be added.
const bundlePath = normalizePathSep(relativeRequest.replace(/\.(js|ts)x?$/, "").replace(/^src[\\/]/, ""));
promises.push(this.injectClientEntryAndSSRModules({
compiler,
compilation,
entryName: name,
clientComponentImports,
bundlePath
}));
}
// Create internal app
promises.push(this.injectClientEntryAndSSRModules({
compiler,
compilation,
entryName: name,
clientComponentImports: [
...internalClientComponentEntryImports
],
bundlePath: APP_CLIENT_INTERNALS
}));
});
// After optimizing all the modules, we collect the CSS that are still used
// by the certain chunk.
compilation.hooks.afterOptimizeModules.tap(PLUGIN_NAME, ()=>{
const cssImportsForChunk = {};
if (this.isEdgeServer) {
edgeServerCSSManifest = {};
} else {
serverCSSManifest = {};
}
let cssManifest = this.isEdgeServer ? edgeServerCSSManifest : serverCSSManifest;
function collectModule(entryName, mod) {
const resource = mod.resource;
const modId = resource;
if (modId) {
if (regexCSS.test(modId)) {
cssImportsForChunk[entryName].push(modId);
}
}
}
compilation.chunkGroups.forEach((chunkGroup)=>{
chunkGroup.chunks.forEach((chunk)=>{
// Here we only track page chunks.
if (!chunk.name) return;
if (!chunk.name.endsWith("/page")) return;
const entryName = path.join(this.appDir, "..", chunk.name);
if (!cssImportsForChunk[entryName]) {
cssImportsForChunk[entryName] = [];
}
const chunkModules = compilation.chunkGraph.getChunkModulesIterable(chunk);
for (const mod of chunkModules){
collectModule(entryName, mod);
const anyModule = mod;
if (anyModule.modules) {
anyModule.modules.forEach((concatenatedMod)=>{
collectModule(entryName, concatenatedMod);
});
}
}
const entryCSSInfo = cssManifest.__entry_css_mods__ || {};
entryCSSInfo[entryName] = cssImportsForChunk[entryName];
Object.assign(cssManifest, {
__entry_css_mods__: entryCSSInfo
});
});
});
forEachEntryModule(({ name , entryModule })=>{
// To collect all CSS imports for a specific entry including the ones
// that are in the client graph, we need to store a map for client boundary
// dependencies.
const clientEntryDependencyMap = {};
const entry = compilation.entries.get(name);
entry.includeDependencies.forEach((dep)=>{
if (dep.request && dep.request.startsWith("next-flight-client-entry-loader?")) {
const mod = compilation.moduleGraph.getResolvedModule(dep);
compilation.moduleGraph.getOutgoingConnections(mod).forEach((connection)=>{
if (connection.dependency) {
clientEntryDependencyMap[connection.dependency.request] = connection.dependency;
}
});
}
});
for (const connection1 of compilation.moduleGraph.getOutgoingConnections(entryModule)){
const entryDependency = connection1.dependency;
const entryRequest = connection1.dependency.request;
const [, cssImports] = this.collectClientComponentsAndCSSForDependency({
entryRequest,
compilation,
dependency: entryDependency,
clientEntryDependencyMap
});
Object.assign(cssManifest, cssImports);
}
});
});
compilation.hooks.processAssets.tap({
name: PLUGIN_NAME,
// Have to be in the optimize stage to run after updating the CSS
// asset hash via extract mini css plugin.
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH
}, (assets)=>{
const manifest = JSON.stringify({
...serverCSSManifest,
...edgeServerCSSManifest,
__entry_css_mods__: {
...serverCSSManifest.__entry_css_mods__,
...edgeServerCSSManifest.__entry_css_mods__
}
}, null, this.dev ? 2 : undefined);
assets[FLIGHT_SERVER_CSS_MANIFEST + ".json"] = new sources.RawSource(manifest);
assets[FLIGHT_SERVER_CSS_MANIFEST + ".js"] = new sources.RawSource("self.__RSC_CSS_MANIFEST=" + manifest);
});
const res = await Promise.all(promises);
// Invalidate in development to trigger recompilation
const invalidator = getInvalidator();
// Check if any of the entry injections need an invalidation
if (invalidator && res.includes(true)) {
invalidator.invalidate([
COMPILER_NAMES.client
]);
}
}
collectClientComponentsAndCSSForDependency({ entryRequest , compilation , dependency , clientEntryDependencyMap }) {
/**
* Keep track of checked modules to avoid infinite loops with recursive imports.
*/ const visitedBySegment = {};
const clientComponentImports = [];
const serverCSSImports = {};
const filterClientComponents = (dependencyToFilter, inClientComponentBoundary)=>{
var ref, ref1;
const mod = compilation.moduleGraph.getResolvedModule(dependencyToFilter);
if (!mod) return;
const rawRequest = mod.rawRequest;
const isCSS = regexCSS.test(rawRequest);
// We have to always use the resolved request here to make sure the
// server and client are using the same module path (required by RSC), as
// the server compiler and client compiler have different resolve configs.
const modRequest = ((ref = mod.resourceResolveData) == null ? void 0 : ref.path) + ((ref1 = mod.resourceResolveData) == null ? void 0 : ref1.query);
// Ensure module is not walked again if it's already been visited
if (!visitedBySegment[entryRequest]) {
visitedBySegment[entryRequest] = new Set();
}
const storeKey = (inClientComponentBoundary ? "0" : "1") + ":" + modRequest;
if (!modRequest || visitedBySegment[entryRequest].has(storeKey)) {
return;
}
visitedBySegment[entryRequest].add(storeKey);
const isClientComponent = isClientComponentModule(mod);
if (isCSS) {
const sideEffectFree = mod.factoryMeta && mod.factoryMeta.sideEffectFree;
if (sideEffectFree) {
const unused = !compilation.moduleGraph.getExportsInfo(mod).isModuleUsed(this.isEdgeServer ? EDGE_RUNTIME_WEBPACK : "webpack-runtime");
if (unused) {
return;
}
}
serverCSSImports[entryRequest] = serverCSSImports[entryRequest] || [];
serverCSSImports[entryRequest].push(modRequest);
}
// Check if request is for css file.
if (!inClientComponentBoundary && isClientComponent || isCSS) {
clientComponentImports.push(modRequest);
// Here we are entering a client boundary, and we need to collect dependencies
// in the client graph too.
if (isClientComponent && clientEntryDependencyMap) {
if (clientEntryDependencyMap[modRequest]) {
filterClientComponents(clientEntryDependencyMap[modRequest], true);
}
}
return;
}
compilation.moduleGraph.getOutgoingConnections(mod).forEach((connection)=>{
filterClientComponents(connection.dependency, inClientComponentBoundary || isClientComponent);
});
};
// Traverse the module graph to find all client components.
filterClientComponents(dependency, false);
return [
clientComponentImports,
serverCSSImports
];
}
async injectClientEntryAndSSRModules({ compiler , compilation , entryName , clientComponentImports , bundlePath }) {
let shouldInvalidate = false;
const loaderOptions = {
modules: clientComponentImports,
server: false
};
// For the client entry, we always use the CJS build of Next.js. If the
// server is using the ESM build (when using the Edge runtime), we need to
// replace them.
const clientLoader = `next-flight-client-entry-loader?${stringify({
modules: this.isEdgeServer ? clientComponentImports.map((importPath)=>importPath.replace("next/dist/esm/", "next/dist/")) : clientComponentImports,
server: false
})}!`;
const clientSSRLoader = `next-flight-client-entry-loader?${stringify({
...loaderOptions,
server: true
})}!`;
// Add for the client compilation
// Inject the entry to the client compiler.
if (this.dev) {
const pageKey = COMPILER_NAMES.client + bundlePath;
if (!entries[pageKey]) {
entries[pageKey] = {
type: EntryTypes.CHILD_ENTRY,
parentEntries: new Set([
entryName
]),
bundlePath,
request: clientLoader,
dispose: false,
lastActiveTime: Date.now()
};
shouldInvalidate = true;
} else {
const entryData = entries[pageKey];
// New version of the client loader
if (entryData.request !== clientLoader) {
entryData.request = clientLoader;
shouldInvalidate = true;
}
if (entryData.type === EntryTypes.CHILD_ENTRY) {
entryData.parentEntries.add(entryName);
}
}
} else {
injectedClientEntries.set(bundlePath, clientLoader);
}
// Inject the entry to the server compiler (__sc_client__).
const clientComponentEntryDep = webpack.EntryPlugin.createDependency(clientSSRLoader, {
name: bundlePath
});
// Add the dependency to the server compiler.
await this.addEntry(compilation, // Reuse compilation context.
compiler.context, clientComponentEntryDep, {
// By using the same entry name
name: entryName,
// Layer should be client for the SSR modules
// This ensures the client components are bundled on client layer
layer: WEBPACK_LAYERS.client
});
return shouldInvalidate;
}
addEntry(compilation, context, dependency, options) /* Promise<module> */ {
return new Promise((resolve, reject)=>{
const entry = compilation.entries.get(options.name);
entry.includeDependencies.push(dependency);
compilation.hooks.addEntry.call(entry, options);
compilation.addModuleTree({
context,
dependency,
contextInfo: {
issuerLayer: options.layer
}
}, (err, module)=>{
if (err) {
compilation.hooks.failedEntry.call(dependency, options, err);
return reject(err);
}
compilation.hooks.succeedEntry.call(dependency, options, module);
return resolve(module);
});
});
}
}
//# sourceMappingURL=flight-client-entry-plugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,215 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import { FLIGHT_MANIFEST } from "../../../shared/lib/constants";
import { relative, sep } from "path";
import { isClientComponentModule, regexCSS } from "../loaders/utils";
import { edgeServerModuleIds, serverModuleIds } from "./flight-client-entry-plugin";
import { traverseModules } from "../utils";
const PLUGIN_NAME = "FlightManifestPlugin";
// Collect modules from server/edge compiler in client layer,
// and detect if it's been used, and mark it as `async: true` for react.
// So that react could unwrap the async module from promise and render module itself.
export const ASYNC_CLIENT_MODULES = new Set();
export class FlightManifestPlugin {
dev = false;
constructor(options){
this.dev = options.dev;
this.appDir = options.appDir;
}
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory })=>{
compilation.dependencyFactories.set(webpack.dependencies.ModuleDependency, normalModuleFactory);
compilation.dependencyTemplates.set(webpack.dependencies.ModuleDependency, new webpack.dependencies.NullDependency.Template());
});
compiler.hooks.make.tap(PLUGIN_NAME, (compilation)=>{
compilation.hooks.processAssets.tap({
name: PLUGIN_NAME,
// Have to be in the optimize stage to run after updating the CSS
// asset hash via extract mini css plugin.
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH
}, (assets)=>this.createAsset(assets, compilation, compiler.context));
});
}
createAsset(assets, compilation, context) {
const manifest = {
__ssr_module_mapping__: {},
__edge_ssr_module_mapping__: {},
__entry_css_files__: {}
};
const dev = this.dev;
const clientRequestsSet = new Set();
// Collect client requests
function collectClientRequest(mod) {
if (mod.resource === "" && mod.buildInfo.rsc) {
const { requests =[] } = mod.buildInfo.rsc;
requests.forEach((r)=>{
clientRequestsSet.add(r);
});
}
}
traverseModules(compilation, (mod)=>collectClientRequest(mod));
compilation.chunkGroups.forEach((chunkGroup)=>{
function recordModule(id, mod, chunkCSS) {
var ref;
const isCSSModule = regexCSS.test(mod.resource) || mod.type === "css/mini-extract" || !!mod.loaders && (dev ? mod.loaders.some((item)=>item.loader.includes("next-style-loader/index.js")) : mod.loaders.some((item)=>item.loader.includes("mini-css-extract-plugin/loader.js")));
const resource = mod.type === "css/mini-extract" ? mod._identifier.slice(mod._identifier.lastIndexOf("!") + 1) : mod.resource;
if (!resource) {
return;
}
const moduleExports = manifest[resource] || {};
const moduleIdMapping = manifest.__ssr_module_mapping__;
const edgeModuleIdMapping = manifest.__edge_ssr_module_mapping__;
// Note that this isn't that reliable as webpack is still possible to assign
// additional queries to make sure there's no conflict even using the `named`
// module ID strategy.
let ssrNamedModuleId = relative(context, ((ref = mod.resourceResolveData) == null ? void 0 : ref.path) || resource);
if (!ssrNamedModuleId.startsWith(".")) ssrNamedModuleId = `./${ssrNamedModuleId.replace(/\\/g, "/")}`;
if (isCSSModule) {
if (!manifest[resource]) {
manifest[resource] = {
default: {
id,
name: "default",
chunks: chunkCSS
}
};
} else {
// It is possible that there are multiple modules with the same resource,
// e.g. extracted by mini-css-extract-plugin. In that case we need to
// merge the chunks.
manifest[resource].default.chunks = [
...new Set([
...manifest[resource].default.chunks,
...chunkCSS
]),
];
}
return;
}
// Only apply following logic to client module requests from client entry,
// or if the module is marked as client module.
if (!clientRequestsSet.has(resource) && !isClientComponentModule(mod)) {
return;
}
const exportsInfo = compilation.moduleGraph.getExportsInfo(mod);
const isAsyncModule = ASYNC_CLIENT_MODULES.has(mod.resource);
const cjsExports = [
...new Set([
...mod.dependencies.map((dep)=>{
// Match CommonJsSelfReferenceDependency
if (dep.type === "cjs self exports reference") {
// @ts-expect-error: TODO: Fix Dependency type
if (dep.base === "module.exports") {
return "default";
}
// `exports.foo = ...`, `exports.default = ...`
// @ts-expect-error: TODO: Fix Dependency type
if (dep.base === "exports") {
// @ts-expect-error: TODO: Fix Dependency type
return dep.names.filter((name)=>name !== "__esModule");
}
}
return null;
}),
]),
];
function getAppPathRequiredChunks() {
return chunkGroup.chunks.map((requiredChunk)=>{
return requiredChunk.id + ":" + (requiredChunk.name || requiredChunk.id) + (dev ? "" : "-" + requiredChunk.hash);
});
}
const moduleExportedKeys = [
"",
"*"
].concat([
...exportsInfo.exports
].filter((exportInfo)=>exportInfo.provided).map((exportInfo)=>exportInfo.name), ...cjsExports).filter((name)=>name !== null);
moduleExportedKeys.forEach((name)=>{
// If the chunk is from `app/` chunkGroup, use it first.
// This make sure not to load the overlapped chunk from `pages/` chunkGroup
if (!moduleExports[name] || chunkGroup.name && /^app[\\/]/.test(chunkGroup.name)) {
const requiredChunks = getAppPathRequiredChunks();
moduleExports[name] = {
id,
name,
chunks: requiredChunks,
// E.g.
// page (server) -> local module (client) -> package (esm)
// The esm package will bubble up to make the entire chain till the client entry as async module.
async: isAsyncModule
};
}
if (serverModuleIds.has(ssrNamedModuleId)) {
moduleIdMapping[id] = moduleIdMapping[id] || {};
moduleIdMapping[id][name] = {
...moduleExports[name],
id: serverModuleIds.get(ssrNamedModuleId)
};
}
if (edgeServerModuleIds.has(ssrNamedModuleId)) {
edgeModuleIdMapping[id] = edgeModuleIdMapping[id] || {};
edgeModuleIdMapping[id][name] = {
...moduleExports[name],
id: edgeServerModuleIds.get(ssrNamedModuleId)
};
}
});
manifest[resource] = moduleExports;
// The client compiler will always use the CJS Next.js build, so here we
// also add the mapping for the ESM build (Edge runtime) to consume.
if (/\/next\/dist\//.test(resource)) {
manifest[resource.replace(/\/next\/dist\//, "/next/dist/esm/")] = moduleExports;
}
manifest.__ssr_module_mapping__ = moduleIdMapping;
manifest.__edge_ssr_module_mapping__ = edgeModuleIdMapping;
}
chunkGroup.chunks.forEach((chunk)=>{
const chunkModules = compilation.chunkGraph.getChunkModulesIterable(chunk);
const chunkCSS = [
...chunk.files
].filter((f)=>!f.startsWith("static/css/pages/") && f.endsWith(".css"));
for (const mod of chunkModules){
const modId = compilation.chunkGraph.getModuleId(mod) + "";
recordModule(modId, mod, chunkCSS);
// If this is a concatenation, register each child to the parent ID.
// TODO: remove any
const anyModule = mod;
if (anyModule.modules) {
anyModule.modules.forEach((concatenatedMod)=>{
recordModule(modId, concatenatedMod, chunkCSS);
});
}
}
});
const entryCSSFiles = manifest.__entry_css_files__ || {};
const addCSSFilesToEntry = (files, entryName)=>{
if (entryName == null ? void 0 : entryName.startsWith("app/")) {
// The `key` here should be the absolute file path but without extension.
// We need to replace the separator in the entry name to match the system separator.
const key = this.appDir + entryName.slice(3).replace(/\//g, sep);
entryCSSFiles[key] = files.concat(entryCSSFiles[key] || []);
}
};
const cssFiles = chunkGroup.getFiles().filter((f)=>f.endsWith(".css"));
if (cssFiles.length) {
// Add to chunk entry and parent chunk groups too.
addCSSFilesToEntry(cssFiles, chunkGroup.name);
chunkGroup.getParents().forEach((parent)=>{
addCSSFilesToEntry(cssFiles, parent.options.name);
});
}
manifest.__entry_css_files__ = entryCSSFiles;
});
const file = "server/" + FLIGHT_MANIFEST;
const json = JSON.stringify(manifest, null, this.dev ? 2 : undefined);
ASYNC_CLIENT_MODULES.clear();
assets[file + ".js"] = new sources.RawSource("self.__RSC_MANIFEST=" + json);
assets[file + ".json"] = new sources.RawSource(json);
}
}
//# sourceMappingURL=flight-manifest-plugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,123 @@
import path from "path";
import { promises as fs } from "fs";
import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import { WEBPACK_LAYERS } from "../../../lib/constants";
const PLUGIN_NAME = "FlightTypesPlugin";
function createTypeGuardFile(fullPath, relativePath, options) {
return `// File: ${fullPath}
import * as entry from '${relativePath}'
type TEntry = typeof entry
check<IEntry, TEntry>(entry)
type PageParams = Record<string, string>
interface PageProps {
params: any
searchParams?: any
}
interface LayoutProps {
children: React.ReactNode
${options.slots ? options.slots.map((slot)=>` ${slot}: React.ReactNode`).join("\n") : ""}
params: any
}
export type PageComponent = (props: PageProps) => React.ReactNode | Promise<React.ReactNode>
export type LayoutComponent = (props: LayoutProps) => React.ReactNode | Promise<React.ReactNode>
interface IEntry {
${options.type === "layout" ? `default: LayoutComponent` : `default: PageComponent`}
config?: {}
generateStaticParams?: (params?: PageParams) => any[] | Promise<any[]>
revalidate?: RevalidateRange<TEntry> | false
dynamic?: 'auto' | 'force-dynamic' | 'error' | 'force-static'
dynamicParams?: boolean
fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache'
preferredRegion?: 'auto' | 'home' | 'edge'
${options.type === "page" ? "runtime?: 'nodejs' | 'experimental-edge' | 'edge'" : ""}
}
// =============
// Utility types
type RevalidateRange<T> = T extends { revalidate: any } ? NonNegative<T['revalidate']> : never
type Impossible<K extends keyof any> = { [P in K]: never }
function check<Base, T extends Base>(_mod: T & Impossible<Exclude<keyof T, keyof Base>>): void {}
// https://github.com/sindresorhus/type-fest
type Numeric = number | bigint
type Zero = 0 | 0n
type Negative<T extends Numeric> = T extends Zero ? never : \`\${T}\` extends \`-\${string}\` ? T : never
type NonNegative<T extends Numeric> = T extends Zero ? T : Negative<T> extends never ? T : '__invalid_negative_number__'
`;
}
async function collectNamedSlots(layoutPath) {
const layoutDir = path.dirname(layoutPath);
const items = await fs.readdir(layoutDir, {
withFileTypes: true
});
const slots = [];
for (const item of items){
if (item.isDirectory() && item.name.startsWith("@")) {
slots.push(item.name.slice(1));
}
}
return slots;
}
export class FlightTypesPlugin {
constructor(options){
this.dir = options.dir;
this.distDir = options.distDir;
this.appDir = options.appDir;
this.dev = options.dev;
this.isEdgeServer = options.isEdgeServer;
}
apply(compiler) {
// From dist root to project root
const distDirRelative = path.relative(this.distDir + "/..", ".");
// From asset root to dist root
const assetDirRelative = this.dev ? ".." : this.isEdgeServer ? ".." : "../..";
const handleModule = async (_mod, assets)=>{
if (_mod.layer !== WEBPACK_LAYERS.server) return;
const mod = _mod;
if (!mod.resource) return;
if (!mod.resource.startsWith(this.appDir + path.sep)) return;
if (!/\.(js|jsx|ts|tsx|mjs)$/.test(mod.resource)) return;
const IS_LAYOUT = /[/\\]layout\.[^./\\]+$/.test(mod.resource);
const IS_PAGE = !IS_LAYOUT && /[/\\]page\.[^.]+$/.test(mod.resource);
const relativePathToApp = path.relative(this.appDir, mod.resource);
const relativePathToRoot = path.relative(this.dir, mod.resource);
const typePath = path.join("types", "app", relativePathToApp.replace(/\.(js|jsx|ts|tsx|mjs)$/, ".ts"));
const relativeImportPath = path.join(distDirRelative, path.relative(typePath, ""), relativePathToRoot.replace(/\.(js|jsx|ts|tsx|mjs)$/, "")).replace(/\\/g, "/");
const assetPath = assetDirRelative + "/" + typePath.replace(/\\/g, "/");
if (IS_LAYOUT) {
const slots = await collectNamedSlots(mod.resource);
assets[assetPath] = new sources.RawSource(createTypeGuardFile(mod.resource, relativeImportPath, {
type: "layout",
slots
}));
} else if (IS_PAGE) {
assets[assetPath] = new sources.RawSource(createTypeGuardFile(mod.resource, relativeImportPath, {
type: "page"
}));
}
};
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
compilation.hooks.processAssets.tapAsync({
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH
}, async (assets, callback)=>{
const promises = [];
for (const entrypoint of compilation.entrypoints.values()){
for (const chunk of entrypoint.chunks){
compilation.chunkGraph.getChunkModules(chunk).forEach((mod)=>{
promises.push(handleModule(mod, assets));
});
}
}
await Promise.all(promises);
callback();
});
});
}
}
//# sourceMappingURL=flight-types-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/flight-types-plugin.ts"],"names":["path","promises","fs","webpack","sources","WEBPACK_LAYERS","PLUGIN_NAME","createTypeGuardFile","fullPath","relativePath","options","slots","map","slot","join","type","collectNamedSlots","layoutPath","layoutDir","dirname","items","readdir","withFileTypes","item","isDirectory","name","startsWith","push","slice","FlightTypesPlugin","constructor","dir","distDir","appDir","dev","isEdgeServer","apply","compiler","distDirRelative","relative","assetDirRelative","handleModule","_mod","assets","layer","server","mod","resource","sep","test","IS_LAYOUT","IS_PAGE","relativePathToApp","relativePathToRoot","typePath","replace","relativeImportPath","assetPath","RawSource","hooks","compilation","tap","processAssets","tapAsync","stage","Compilation","PROCESS_ASSETS_STAGE_OPTIMIZE_HASH","callback","entrypoint","entrypoints","values","chunk","chunks","chunkGraph","getChunkModules","forEach","Promise","all"],"mappings":"AAAA,OAAOA,IAAI,MAAM,MAAM,CAAA;AACvB,SAASC,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AAEnC,SAASC,OAAO,EAAEC,OAAO,QAAQ,oCAAoC,CAAA;AACrE,SAASC,cAAc,QAAQ,wBAAwB,CAAA;AAEvD,MAAMC,WAAW,GAAG,mBAAmB;AAUvC,SAASC,mBAAmB,CAC1BC,QAAgB,EAChBC,YAAoB,EACpBC,OAGC,EACD;IACA,OAAO,CAAC,SAAS,EAAEF,QAAQ,CAAC;wBACN,EAAEC,YAAY,CAAC;;;;;;;;;;;;AAYvC,EACEC,OAAO,CAACC,KAAK,GACTD,OAAO,CAACC,KAAK,CAACC,GAAG,CAAC,CAACC,IAAI,GAAK,CAAC,EAA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,KAAK,CAAC,CAACI,OAAO,CAAC,CAAC7B,GAAG,GAAK;4BAC7D7C,QAAQ,CAAC0B,IAAI,CAACc,YAAY,CAACK,GAAG,EAAEH,MAAM,CAAC,CAAC;yBACzC,CAAC;qBACH;iBACF;gBACD,MAAMiC,OAAO,CAACC,GAAG,CAAC5E,QAAQ,CAAC;gBAC3BkE,QAAQ,EAAE;aACX,CACF;SACF,CAAC;KACH;CACF"}

View File

@@ -0,0 +1,72 @@
import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import getRouteFromEntrypoint from "../../../server/get-route-from-entrypoint";
import { FONT_LOADER_MANIFEST } from "../../../shared/lib/constants";
const PLUGIN_NAME = "FontLoaderManifestPlugin";
// Creates a manifest of all fonts that should be preloaded given a route
export class FontLoaderManifestPlugin {
constructor(options){
this.appDirEnabled = options.appDirEnabled;
this.fontLoaderTargets = options.fontLoaderTargets;
}
apply(compiler) {
compiler.hooks.make.tap(PLUGIN_NAME, (compilation)=>{
let fontLoaderModules;
// Get all font loader modules
if (this.appDirEnabled) {
compilation.hooks.finishModules.tap(PLUGIN_NAME, (modules)=>{
const modulesArr = Array.from(modules);
fontLoaderModules = modulesArr.filter((mod)=>{
return this.fontLoaderTargets.some((fontLoaderTarget)=>{
var ref;
return (ref = mod.userRequest) == null ? void 0 : ref.startsWith(`${fontLoaderTarget}?`);
});
});
});
}
compilation.hooks.processAssets.tap({
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, (assets)=>{
const fontLoaderManifest = {
pages: {},
app: {}
};
if (this.appDirEnabled) {
for (const mod of fontLoaderModules){
var ref;
if (!((ref = mod.buildInfo) == null ? void 0 : ref.assets)) continue;
const modAssets = Object.keys(mod.buildInfo.assets);
const fontFiles = modAssets.filter((file)=>/\.(woff|woff2|eot|ttf|otf)$/.test(file));
// Font files ending with .p.(woff|woff2|eot|ttf|otf) are preloaded
const preloadedFontFiles = fontFiles.filter((file)=>/\.p.(woff|woff2|eot|ttf|otf)$/.test(file));
// Create an entry for the request even if no files should preload. If that's the case a preconnect tag is added.
if (fontFiles.length > 0) {
fontLoaderManifest.app[mod.userRequest] = preloadedFontFiles;
}
}
}
for (const entrypoint of compilation.entrypoints.values()){
const pagePath = getRouteFromEntrypoint(entrypoint.name);
if (!pagePath) {
continue;
}
const fontFiles = entrypoint.chunks.flatMap((chunk)=>[
...chunk.auxiliaryFiles
]).filter((file)=>/\.(woff|woff2|eot|ttf|otf)$/.test(file));
// Font files ending with .p.(woff|woff2|eot|ttf|otf) are preloaded
const preloadedFontFiles = fontFiles.filter((file)=>/\.p.(woff|woff2|eot|ttf|otf)$/.test(file));
// Create an entry for the path even if no files should preload. If that's the case a preconnect tag is added.
if (fontFiles.length > 0) {
fontLoaderManifest.pages[pagePath] = preloadedFontFiles;
}
}
const manifest = JSON.stringify(fontLoaderManifest, null, 2);
assets[`server/${FONT_LOADER_MANIFEST}.js`] = new sources.RawSource(`self.__FONT_LOADER_MANIFEST=${manifest}`);
assets[`server/${FONT_LOADER_MANIFEST}.json`] = new sources.RawSource(manifest);
});
});
return;
}
}
//# sourceMappingURL=font-loader-manifest-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/font-loader-manifest-plugin.ts"],"names":["webpack","sources","getRouteFromEntrypoint","FONT_LOADER_MANIFEST","PLUGIN_NAME","FontLoaderManifestPlugin","constructor","options","appDirEnabled","fontLoaderTargets","apply","compiler","hooks","make","tap","compilation","fontLoaderModules","finishModules","modules","modulesArr","Array","from","filter","mod","some","fontLoaderTarget","userRequest","startsWith","processAssets","name","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS","assets","fontLoaderManifest","pages","app","buildInfo","modAssets","Object","keys","fontFiles","file","test","preloadedFontFiles","length","entrypoint","entrypoints","values","pagePath","chunks","flatMap","chunk","auxiliaryFiles","manifest","JSON","stringify","RawSource"],"mappings":"AAAA,SAASA,OAAO,EAAEC,OAAO,QAAQ,oCAAoC,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AAaH,SAAS,CAACnB,MAAM,CACnD,CAACoB,IAAY,GAAK,gCAAgCC,IAAI,CAACD,IAAI,CAAC,CAC7D;oBAED,8GAA8G;oBAC9G,IAAID,SAAS,CAACI,MAAM,GAAG,CAAC,EAAE;wBACxBX,kBAAkB,CAACC,KAAK,CAACc,QAAQ,CAAC,GAAGL,kBAAkB;qBACxD;iBACF;gBAED,MAAMU,QAAQ,GAAGC,IAAI,CAACC,SAAS,CAACtB,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;gBAC5DD,MAAM,CAAC,CAAC,OAAO,EAAE9B,oBAAoB,CAAC,GAAG,CAAC,CAAC,GAAG,IAAIF,OAAO,CAACwD,SAAS,CACjE,CAAC,4BAA4B,EAAEH,QAAQ,CAAC,CAAC,CAC1C;gBACDrB,MAAM,CAAC,CAAC,OAAO,EAAE9B,oBAAoB,CAAC,KAAK,CAAC,CAAC,GAAG,IAAIF,OAAO,CAACwD,SAAS,CACnEH,QAAQ,CACT;aACF,CACF;SACF,CAAC;QACF,OAAM;KACP;CACF"}

View File

@@ -0,0 +1,168 @@
import { webpack, BasicEvaluatedExpression, sources } from "next/dist/compiled/webpack/webpack";
import { getFontDefinitionFromNetwork, getFontOverrideCss } from "../../../server/font-utils";
import postcss from "postcss";
import minifier from "next/dist/compiled/cssnano-simple";
import { FONT_MANIFEST, OPTIMIZED_FONT_PROVIDERS } from "../../../shared/lib/constants";
import * as Log from "../../output/log";
function minifyCss(css) {
return postcss([
minifier({
excludeAll: true,
discardComments: true,
normalizeWhitespace: {
exclude: false
}
}, postcss),
]).process(css, {
from: undefined
}).then((res)=>res.css);
}
function isNodeCreatingLinkElement(node) {
const callee = node.callee;
if (callee.type !== "Identifier") {
return false;
}
const componentNode = node.arguments[0];
if (componentNode.type !== "Literal") {
return false;
}
// React has pragma: _jsx.
// Next has pragma: __jsx.
return (callee.name === "_jsx" || callee.name === "__jsx") && componentNode.value === "link";
}
export class FontStylesheetGatheringPlugin {
gatheredStylesheets = [];
manifestContent = [];
constructor({ adjustFontFallbacks , adjustFontFallbacksWithSizeAdjust }){
this.adjustFontFallbacks = adjustFontFallbacks;
this.adjustFontFallbacksWithSizeAdjust = adjustFontFallbacksWithSizeAdjust;
}
parserHandler = (factory)=>{
const JS_TYPES = [
"auto",
"esm",
"dynamic"
];
// Do an extra walk per module and add interested visitors to the walk.
for (const type of JS_TYPES){
factory.hooks.parser.for("javascript/" + type).tap(this.constructor.name, (parser)=>{
/**
* Webpack fun facts:
* `parser.hooks.call.for` cannot catch calls for user defined identifiers like `__jsx`
* it can only detect calls for native objects like `window`, `this`, `eval` etc.
* In order to be able to catch calls of variables like `__jsx`, first we need to catch them as
* Identifier and then return `BasicEvaluatedExpression` whose `id` and `type` webpack matches to
* invoke hook for call.
* See: https://github.com/webpack/webpack/blob/webpack-4/lib/Parser.js#L1931-L1932.
*/ parser.hooks.evaluate.for("Identifier").tap(this.constructor.name, (node)=>{
var ref, ref1;
// We will only optimize fonts from first party code.
if (parser == null ? void 0 : (ref = parser.state) == null ? void 0 : (ref1 = ref.module) == null ? void 0 : ref1.resource.includes("node_modules")) {
return;
}
let result;
if (node.name === "_jsx" || node.name === "__jsx") {
result = new BasicEvaluatedExpression();
// @ts-ignore
result.setRange(node.range);
result.setExpression(node);
result.setIdentifier(node.name);
// This was added in webpack 5.
result.getMembers = ()=>[];
}
return result;
});
const jsxNodeHandler = (node)=>{
var ref, ref2;
if (node.arguments.length !== 2) {
// A font link tag has only two arguments rel=stylesheet and href='...'
return;
}
if (!isNodeCreatingLinkElement(node)) {
return;
}
// node.arguments[0] is the name of the tag and [1] are the props.
const arg1 = node.arguments[1];
const propsNode = arg1.type === "ObjectExpression" ? arg1 : undefined;
const props = {};
if (propsNode) {
propsNode.properties.forEach((prop)=>{
if (prop.type !== "Property") {
return;
}
if (prop.key.type === "Identifier" && prop.value.type === "Literal") {
props[prop.key.name] = prop.value.value;
}
});
}
if (!props.rel || props.rel !== "stylesheet" || !props.href || !OPTIMIZED_FONT_PROVIDERS.some(({ url })=>props.href.startsWith(url))) {
return false;
}
this.gatheredStylesheets.push(props.href);
const buildInfo = parser == null ? void 0 : (ref = parser.state) == null ? void 0 : (ref2 = ref.module) == null ? void 0 : ref2.buildInfo;
if (buildInfo) {
buildInfo.valueDependencies.set(FONT_MANIFEST, this.gatheredStylesheets);
}
};
// React JSX transform:
parser.hooks.call.for("_jsx").tap(this.constructor.name, jsxNodeHandler);
// Next.js JSX transform:
parser.hooks.call.for("__jsx").tap(this.constructor.name, jsxNodeHandler);
// New React JSX transform:
parser.hooks.call.for("imported var").tap(this.constructor.name, jsxNodeHandler);
});
}
};
apply(compiler) {
this.compiler = compiler;
compiler.hooks.normalModuleFactory.tap(this.constructor.name, this.parserHandler);
compiler.hooks.make.tapAsync(this.constructor.name, (compilation, cb)=>{
compilation.hooks.finishModules.tapAsync(this.constructor.name, async (modules, modulesFinished)=>{
let fontStylesheets = this.gatheredStylesheets;
const fontUrls = new Set();
modules.forEach((module)=>{
var ref, ref3;
const fontDependencies = module == null ? void 0 : (ref = module.buildInfo) == null ? void 0 : (ref3 = ref.valueDependencies) == null ? void 0 : ref3.get(FONT_MANIFEST);
if (fontDependencies) {
fontDependencies.forEach((v)=>fontUrls.add(v));
}
});
fontStylesheets = Array.from(fontUrls);
const fontDefinitionPromises = fontStylesheets.map((url)=>getFontDefinitionFromNetwork(url));
this.manifestContent = [];
for(let promiseIndex in fontDefinitionPromises){
let css = await fontDefinitionPromises[promiseIndex];
if (this.adjustFontFallbacks) {
css += getFontOverrideCss(fontStylesheets[promiseIndex], css, this.adjustFontFallbacksWithSizeAdjust);
}
if (css) {
try {
const content = await minifyCss(css);
this.manifestContent.push({
url: fontStylesheets[promiseIndex],
content
});
} catch (err) {
Log.warn(`Failed to minify the stylesheet for ${fontStylesheets[promiseIndex]}. Skipped optimizing this font.`);
console.error(err);
}
}
}
// @ts-expect-error invalid assets type
compilation.assets[FONT_MANIFEST] = new sources.RawSource(JSON.stringify(this.manifestContent, null, " "));
modulesFinished();
});
cb();
});
compiler.hooks.make.tap(this.constructor.name, (compilation)=>{
compilation.hooks.processAssets.tap({
name: this.constructor.name,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, (assets)=>{
assets["../" + FONT_MANIFEST] = new sources.RawSource(JSON.stringify(this.manifestContent, null, " "));
});
});
}
}
//# sourceMappingURL=font-stylesheet-gathering-plugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,175 @@
/**
* This webpack resolver is largely based on TypeScript's "paths" handling
* The TypeScript license can be found here:
* https://github.com/microsoft/TypeScript/blob/214df64e287804577afa1fea0184c18c40f7d1ca/LICENSE.txt
*/ import path from "path";
import { debug } from "next/dist/compiled/debug";
const log = debug("next:jsconfig-paths-plugin");
const asterisk = 0x2a;
export function hasZeroOrOneAsteriskCharacter(str) {
let seenAsterisk = false;
for(let i = 0; i < str.length; i++){
if (str.charCodeAt(i) === asterisk) {
if (!seenAsterisk) {
seenAsterisk = true;
} else {
// have already seen asterisk
return false;
}
}
}
return true;
}
/**
* Determines whether a path starts with a relative path component (i.e. `.` or `..`).
*/ export function pathIsRelative(testPath) {
return /^\.\.?($|[\\/])/.test(testPath);
}
export function tryParsePattern(pattern) {
// This should be verified outside of here and a proper error thrown.
const indexOfStar = pattern.indexOf("*");
return indexOfStar === -1 ? undefined : {
prefix: pattern.slice(0, indexOfStar),
suffix: pattern.slice(indexOfStar + 1)
};
}
function isPatternMatch({ prefix , suffix }, candidate) {
return candidate.length >= prefix.length + suffix.length && candidate.startsWith(prefix) && candidate.endsWith(suffix);
}
/** Return the object corresponding to the best pattern to match `candidate`. */ export function findBestPatternMatch(values, getPattern, candidate) {
let matchedValue;
// use length of prefix as betterness criteria
let longestMatchPrefixLength = -1;
for (const v of values){
const pattern = getPattern(v);
if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
longestMatchPrefixLength = pattern.prefix.length;
matchedValue = v;
}
}
return matchedValue;
}
/**
* patternStrings contains both pattern strings (containing "*") and regular strings.
* Return an exact match if possible, or a pattern match, or undefined.
* (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
*/ export function matchPatternOrExact(patternStrings, candidate) {
const patterns = [];
for (const patternString of patternStrings){
if (!hasZeroOrOneAsteriskCharacter(patternString)) continue;
const pattern = tryParsePattern(patternString);
if (pattern) {
patterns.push(pattern);
} else if (patternString === candidate) {
// pattern was matched as is - no need to search further
return patternString;
}
}
return findBestPatternMatch(patterns, (_)=>_, candidate);
}
/**
* Tests whether a value is string
*/ export function isString(text) {
return typeof text === "string";
}
/**
* Given that candidate matches pattern, returns the text matching the '*'.
* E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
*/ export function matchedText(pattern, candidate) {
return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
}
export function patternText({ prefix , suffix }) {
return `${prefix}*${suffix}`;
}
/**
* Calls the iterator function for each entry of the array
* until the first result or error is reached
*/ function forEachBail(array, iterator, callback) {
if (array.length === 0) return callback();
let i = 0;
const next = ()=>{
let loop = undefined;
iterator(array[i++], (err, result)=>{
if (err || result !== undefined || i >= array.length) {
return callback(err, result);
}
if (loop === false) while(next());
loop = true;
});
if (!loop) loop = false;
return loop;
};
while(next());
}
const NODE_MODULES_REGEX = /node_modules/;
/**
* Handles tsconfig.json or jsconfig.js "paths" option for webpack
* Largely based on how the TypeScript compiler handles it:
* https://github.com/microsoft/TypeScript/blob/1a9c8197fffe3dace5f8dca6633d450a88cba66d/src/compiler/moduleNameResolver.ts#L1362
*/ export class JsConfigPathsPlugin {
constructor(paths, resolvedBaseUrl){
this.paths = paths;
this.resolvedBaseUrl = resolvedBaseUrl;
this.jsConfigPlugin = true;
log("tsconfig.json or jsconfig.json paths: %O", paths);
log("resolved baseUrl: %s", resolvedBaseUrl);
}
apply(resolver) {
const target = resolver.ensureHook("resolve");
resolver.getHook("described-resolve").tapAsync("JsConfigPathsPlugin", (request, resolveContext, callback)=>{
const paths = this.paths;
const pathsKeys = Object.keys(paths);
// If no aliases are added bail out
if (pathsKeys.length === 0) {
log("paths are empty, bailing out");
return callback();
}
const moduleName = request.request;
// Exclude node_modules from paths support (speeds up resolving)
if (request.path.match(NODE_MODULES_REGEX)) {
log("skipping request as it is inside node_modules %s", moduleName);
return callback();
}
if (path.posix.isAbsolute(moduleName) || process.platform === "win32" && path.win32.isAbsolute(moduleName)) {
log("skipping request as it is an absolute path %s", moduleName);
return callback();
}
if (pathIsRelative(moduleName)) {
log("skipping request as it is a relative path %s", moduleName);
return callback();
}
// log('starting to resolve request %s', moduleName)
// If the module name does not match any of the patterns in `paths` we hand off resolving to webpack
const matchedPattern = matchPatternOrExact(pathsKeys, moduleName);
if (!matchedPattern) {
log("moduleName did not match any paths pattern %s", moduleName);
return callback();
}
const matchedStar = isString(matchedPattern) ? undefined : matchedText(matchedPattern, moduleName);
const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern);
let triedPaths = [];
forEachBail(paths[matchedPatternText], (subst, pathCallback)=>{
const curPath = matchedStar ? subst.replace("*", matchedStar) : subst;
// Ensure .d.ts is not matched
if (curPath.endsWith(".d.ts")) {
// try next path candidate
return pathCallback();
}
const candidate = path.join(this.resolvedBaseUrl, curPath);
const obj = Object.assign({}, request, {
request: candidate
});
resolver.doResolve(target, obj, `Aliased with tsconfig.json or jsconfig.json ${matchedPatternText} to ${candidate}`, resolveContext, (resolverErr, resolverResult)=>{
if (resolverErr || resolverResult === undefined) {
triedPaths.push(candidate);
// try next path candidate
return pathCallback();
}
return pathCallback(resolverErr, resolverResult);
});
}, callback);
});
}
}
//# sourceMappingURL=jsconfig-paths-plugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,555 @@
import { getNamedMiddlewareRegex } from "../../../shared/lib/router/utils/route-regex";
import { getModuleBuildInfo } from "../loaders/get-module-build-info";
import { getSortedRoutes } from "../../../shared/lib/router/utils";
import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import { isMatch } from "next/dist/compiled/micromatch";
import { EDGE_RUNTIME_WEBPACK, EDGE_UNSUPPORTED_NODE_APIS, MIDDLEWARE_BUILD_MANIFEST, FLIGHT_MANIFEST, MIDDLEWARE_MANIFEST, MIDDLEWARE_REACT_LOADABLE_MANIFEST, NEXT_CLIENT_SSR_ENTRY_SUFFIX, FLIGHT_SERVER_CSS_MANIFEST, SUBRESOURCE_INTEGRITY_MANIFEST, FONT_LOADER_MANIFEST } from "../../../shared/lib/constants";
import { getPageStaticInfo } from "../../analysis/get-page-static-info";
import { traceGlobals } from "../../../trace/shared";
import { EVENT_BUILD_FEATURE_USAGE } from "../../../telemetry/events";
import { normalizeAppPath } from "../../../shared/lib/router/utils/app-paths";
const NAME = "MiddlewarePlugin";
/**
* Checks the value of usingIndirectEval and when it is a set of modules it
* check if any of the modules is actually being used. If the value is
* simply truthy it will return true.
*/ function isUsingIndirectEvalAndUsedByExports(args) {
const { moduleGraph , runtime , module , usingIndirectEval , wp } = args;
if (typeof usingIndirectEval === "boolean") {
return usingIndirectEval;
}
const exportsInfo = moduleGraph.getExportsInfo(module);
for (const exportName of usingIndirectEval){
if (exportsInfo.getUsed(exportName, runtime) !== wp.UsageState.Unused) {
return true;
}
}
return false;
}
function getEntryFiles(entryFiles, meta, opts) {
const files = [];
if (meta.edgeSSR) {
if (meta.edgeSSR.isServerComponent) {
files.push(`server/${FLIGHT_MANIFEST}.js`);
files.push(`server/${FLIGHT_SERVER_CSS_MANIFEST}.js`);
if (opts.sriEnabled) {
files.push(`server/${SUBRESOURCE_INTEGRITY_MANIFEST}.js`);
}
files.push(...entryFiles.filter((file)=>file.startsWith("pages/") && !file.endsWith(".hot-update.js")).map((file)=>"server/" + // TODO-APP: seems this should be removed.
file.replace(".js", NEXT_CLIENT_SSR_ENTRY_SUFFIX + ".js")));
}
files.push(`server/${MIDDLEWARE_BUILD_MANIFEST}.js`, `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`);
if (opts.hasFontLoaders) {
files.push(`server/${FONT_LOADER_MANIFEST}.js`);
}
}
files.push(...entryFiles.filter((file)=>!file.endsWith(".hot-update.js")).map((file)=>"server/" + file));
return files;
}
function getCreateAssets(params) {
const { compilation , metadataByEntry , opts } = params;
return (assets)=>{
const middlewareManifest = {
sortedMiddleware: [],
middleware: {},
functions: {},
version: 2
};
for (const entrypoint of compilation.entrypoints.values()){
var ref, ref1, ref2, ref3, ref4;
if (!entrypoint.name) {
continue;
}
// There should always be metadata for the entrypoint.
const metadata = metadataByEntry.get(entrypoint.name);
const page = (metadata == null ? void 0 : (ref = metadata.edgeMiddleware) == null ? void 0 : ref.page) || (metadata == null ? void 0 : (ref1 = metadata.edgeSSR) == null ? void 0 : ref1.page) || (metadata == null ? void 0 : (ref2 = metadata.edgeApiFunction) == null ? void 0 : ref2.page);
if (!page) {
continue;
}
const { namedRegex } = getNamedMiddlewareRegex(((ref3 = metadata.edgeSSR) == null ? void 0 : ref3.isAppDir) ? normalizeAppPath(page) : page, {
catchAll: !metadata.edgeSSR && !metadata.edgeApiFunction
});
const matchers = (metadata == null ? void 0 : (ref4 = metadata.edgeMiddleware) == null ? void 0 : ref4.matchers) ?? [
{
regexp: namedRegex
},
];
const edgeFunctionDefinition = {
env: Array.from(metadata.env),
files: getEntryFiles(entrypoint.getFiles(), metadata, opts),
name: entrypoint.name,
page: page,
matchers,
wasm: Array.from(metadata.wasmBindings, ([name, filePath])=>({
name,
filePath
})),
assets: Array.from(metadata.assetBindings, ([name, filePath])=>({
name,
filePath
})),
...metadata.regions && {
regions: metadata.regions
}
};
if (metadata.edgeApiFunction || metadata.edgeSSR) {
middlewareManifest.functions[page] = edgeFunctionDefinition;
} else {
middlewareManifest.middleware[page] = edgeFunctionDefinition;
}
}
middlewareManifest.sortedMiddleware = getSortedRoutes(Object.keys(middlewareManifest.middleware));
assets[MIDDLEWARE_MANIFEST] = new sources.RawSource(JSON.stringify(middlewareManifest, null, 2));
};
}
function buildWebpackError({ message , loc , compilation , entryModule , parser }) {
const error = new compilation.compiler.webpack.WebpackError(message);
error.name = NAME;
const module = entryModule ?? (parser == null ? void 0 : parser.state.current);
if (module) {
error.module = module;
}
error.loc = loc;
return error;
}
function isInMiddlewareLayer(parser) {
var ref;
return ((ref = parser.state.module) == null ? void 0 : ref.layer) === "middleware";
}
function isProcessEnvMemberExpression(memberExpression) {
var ref, ref5, ref6;
return ((ref = memberExpression.object) == null ? void 0 : ref.type) === "Identifier" && memberExpression.object.name === "process" && (((ref5 = memberExpression.property) == null ? void 0 : ref5.type) === "Literal" && memberExpression.property.value === "env" || ((ref6 = memberExpression.property) == null ? void 0 : ref6.type) === "Identifier" && memberExpression.property.name === "env");
}
function isNodeJsModule(moduleName) {
return require("module").builtinModules.includes(moduleName);
}
function isDynamicCodeEvaluationAllowed(fileName, edgeFunctionConfig, rootDir) {
const name = fileName.replace(rootDir ?? "", "");
return isMatch(name, (edgeFunctionConfig == null ? void 0 : edgeFunctionConfig.unstable_allowDynamicGlobs) ?? []);
}
function buildUnsupportedApiError({ apiName , loc , ...rest }) {
return buildWebpackError({
message: `A Node.js API is used (${apiName} at line: ${loc.start.line}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`,
loc,
...rest
});
}
function registerUnsupportedApiHooks(parser, compilation) {
for (const expression of EDGE_UNSUPPORTED_NODE_APIS){
const warnForUnsupportedApi = (node)=>{
if (!isInMiddlewareLayer(parser)) {
return;
}
compilation.warnings.push(buildUnsupportedApiError({
compilation,
parser,
apiName: expression,
...node
}));
return true;
};
parser.hooks.call.for(expression).tap(NAME, warnForUnsupportedApi);
parser.hooks.expression.for(expression).tap(NAME, warnForUnsupportedApi);
parser.hooks.callMemberChain.for(expression).tap(NAME, warnForUnsupportedApi);
parser.hooks.expressionMemberChain.for(expression).tap(NAME, warnForUnsupportedApi);
}
const warnForUnsupportedProcessApi = (node, [callee])=>{
if (!isInMiddlewareLayer(parser) || callee === "env") {
return;
}
compilation.warnings.push(buildUnsupportedApiError({
compilation,
parser,
apiName: `process.${callee}`,
...node
}));
return true;
};
parser.hooks.callMemberChain.for("process").tap(NAME, warnForUnsupportedProcessApi);
parser.hooks.expressionMemberChain.for("process").tap(NAME, warnForUnsupportedProcessApi);
}
function getCodeAnalyzer(params) {
return (parser)=>{
const { dev , compiler: { webpack: wp } , compilation , } = params;
const { hooks } = parser;
/**
* For an expression this will check the graph to ensure it is being used
* by exports. Then it will store in the module buildInfo a boolean to
* express that it contains dynamic code and, if it is available, the
* module path that is using it.
*/ const handleExpression = ()=>{
if (!isInMiddlewareLayer(parser)) {
return;
}
wp.optimize.InnerGraph.onUsage(parser.state, (used = true)=>{
const buildInfo = getModuleBuildInfo(parser.state.module);
if (buildInfo.usingIndirectEval === true || used === false) {
return;
}
if (!buildInfo.usingIndirectEval || used === true) {
buildInfo.usingIndirectEval = used;
return;
}
buildInfo.usingIndirectEval = new Set([
...Array.from(buildInfo.usingIndirectEval),
...Array.from(used),
]);
});
};
/**
* This expression handler allows to wrap a dynamic code expression with a
* function call where we can warn about dynamic code not being allowed
* but actually execute the expression.
*/ const handleWrapExpression = (expr)=>{
if (!isInMiddlewareLayer(parser)) {
return;
}
const { ConstDependency } = wp.dependencies;
const dep1 = new ConstDependency("__next_eval__(function() { return ", expr.range[0]);
dep1.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep1);
const dep2 = new ConstDependency("})", expr.range[1]);
dep2.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep2);
handleExpression();
return true;
};
/**
* This expression handler allows to wrap a WebAssembly.compile invocation with a
* function call where we can warn about WASM code generation not being allowed
* but actually execute the expression.
*/ const handleWrapWasmCompileExpression = (expr)=>{
if (!isInMiddlewareLayer(parser)) {
return;
}
const { ConstDependency } = wp.dependencies;
const dep1 = new ConstDependency("__next_webassembly_compile__(function() { return ", expr.range[0]);
dep1.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep1);
const dep2 = new ConstDependency("})", expr.range[1]);
dep2.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep2);
handleExpression();
};
/**
* This expression handler allows to wrap a WebAssembly.instatiate invocation with a
* function call where we can warn about WASM code generation not being allowed
* but actually execute the expression.
*
* Note that we don't update `usingIndirectEval`, i.e. we don't abort a production build
* since we can't determine statically if the first parameter is a module (legit use) or
* a buffer (dynamic code generation).
*/ const handleWrapWasmInstantiateExpression = (expr)=>{
if (!isInMiddlewareLayer(parser)) {
return;
}
if (dev) {
const { ConstDependency } = wp.dependencies;
const dep1 = new ConstDependency("__next_webassembly_instantiate__(function() { return ", expr.range[0]);
dep1.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep1);
const dep2 = new ConstDependency("})", expr.range[1]);
dep2.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep2);
}
};
/**
* Declares an environment variable that is being used in this module
* through this static analysis.
*/ const addUsedEnvVar = (envVarName)=>{
const buildInfo = getModuleBuildInfo(parser.state.module);
if (buildInfo.nextUsedEnvVars === undefined) {
buildInfo.nextUsedEnvVars = new Set();
}
buildInfo.nextUsedEnvVars.add(envVarName);
};
/**
* A handler for calls to `process.env` where we identify the name of the
* ENV variable being assigned and store it in the module info.
*/ const handleCallMemberChain = (_, members)=>{
if (members.length >= 2 && members[0] === "env") {
addUsedEnvVar(members[1]);
if (!isInMiddlewareLayer(parser)) {
return true;
}
}
};
/**
* Handler to store original source location of static and dynamic imports into module's buildInfo.
*/ const handleImport = (node)=>{
var ref;
if (isInMiddlewareLayer(parser) && ((ref = node.source) == null ? void 0 : ref.value) && (node == null ? void 0 : node.loc)) {
var ref7;
const { module , source } = parser.state;
const buildInfo = getModuleBuildInfo(module);
if (!buildInfo.importLocByPath) {
buildInfo.importLocByPath = new Map();
}
const importedModule = (ref7 = node.source.value) == null ? void 0 : ref7.toString();
buildInfo.importLocByPath.set(importedModule, {
sourcePosition: {
...node.loc.start,
source: module.identifier()
},
sourceContent: source.toString()
});
if (!dev && isNodeJsModule(importedModule)) {
compilation.warnings.push(buildWebpackError({
message: `A Node.js module is loaded ('${importedModule}' at line ${node.loc.start.line}) which is not supported in the Edge Runtime.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`,
compilation,
parser,
...node
}));
}
}
};
/**
* A noop handler to skip analyzing some cases.
* Order matters: for it to work, it must be registered first
*/ const skip = ()=>isInMiddlewareLayer(parser) ? true : undefined;
for (const prefix of [
"",
"global."
]){
hooks.expression.for(`${prefix}Function.prototype`).tap(NAME, skip);
hooks.expression.for(`${prefix}Function.bind`).tap(NAME, skip);
hooks.call.for(`${prefix}eval`).tap(NAME, handleWrapExpression);
hooks.call.for(`${prefix}Function`).tap(NAME, handleWrapExpression);
hooks.new.for(`${prefix}Function`).tap(NAME, handleWrapExpression);
hooks.call.for(`${prefix}WebAssembly.compile`).tap(NAME, handleWrapWasmCompileExpression);
hooks.call.for(`${prefix}WebAssembly.instantiate`).tap(NAME, handleWrapWasmInstantiateExpression);
}
hooks.callMemberChain.for("process").tap(NAME, handleCallMemberChain);
hooks.expressionMemberChain.for("process").tap(NAME, handleCallMemberChain);
hooks.importCall.tap(NAME, handleImport);
hooks.import.tap(NAME, handleImport);
/**
* Support static analyzing environment variables through
* destructuring `process.env` or `process["env"]`:
*
* const { MY_ENV, "MY-ENV": myEnv } = process.env
* ^^^^^^ ^^^^^^
*/ hooks.declarator.tap(NAME, (declarator)=>{
var ref, ref8;
if (((ref = declarator.init) == null ? void 0 : ref.type) === "MemberExpression" && isProcessEnvMemberExpression(declarator.init) && ((ref8 = declarator.id) == null ? void 0 : ref8.type) === "ObjectPattern") {
for (const property of declarator.id.properties){
if (property.type === "RestElement") continue;
if (property.key.type === "Literal" && typeof property.key.value === "string") {
addUsedEnvVar(property.key.value);
} else if (property.key.type === "Identifier") {
addUsedEnvVar(property.key.name);
}
}
if (!isInMiddlewareLayer(parser)) {
return true;
}
}
});
if (!dev) {
// do not issue compilation warning on dev: invoking code will provide details
registerUnsupportedApiHooks(parser, compilation);
}
};
}
async function findEntryEdgeFunctionConfig(entryDependency, resolver) {
var ref;
if (entryDependency == null ? void 0 : (ref = entryDependency.request) == null ? void 0 : ref.startsWith("next-")) {
const absolutePagePath = new URL(entryDependency.request, "http://example.org").searchParams.get("absolutePagePath") ?? "";
const pageFilePath = await new Promise((resolve)=>resolver.resolve({}, "/", absolutePagePath, {}, (err, path)=>resolve(err || path)));
if (typeof pageFilePath === "string") {
return {
file: pageFilePath,
config: (await getPageStaticInfo({
nextConfig: {},
pageFilePath,
isDev: false
})).middleware
};
}
}
}
function getExtractMetadata(params) {
const { dev , compilation , metadataByEntry , compiler } = params;
const { webpack: wp } = compiler;
return async ()=>{
metadataByEntry.clear();
const resolver = compilation.resolverFactory.get("normal");
const telemetry = traceGlobals.get("telemetry");
for (const [entryName, entry] of compilation.entries){
var ref;
if (entry.options.runtime !== EDGE_RUNTIME_WEBPACK) {
continue;
}
const entryDependency = (ref = entry.dependencies) == null ? void 0 : ref[0];
const edgeFunctionConfig = await findEntryEdgeFunctionConfig(entryDependency, resolver);
const { rootDir } = getModuleBuildInfo(compilation.moduleGraph.getResolvedModule(entryDependency));
const { moduleGraph } = compilation;
const modules = new Set();
const addEntriesFromDependency = (dependency)=>{
const module = moduleGraph.getModule(dependency);
if (module) {
modules.add(module);
}
};
entry.dependencies.forEach(addEntriesFromDependency);
entry.includeDependencies.forEach(addEntriesFromDependency);
const entryMetadata = {
env: new Set(),
wasmBindings: new Map(),
assetBindings: new Map()
};
let ogImageGenerationCount = 0;
for (const module1 of modules){
var ref9;
const buildInfo = getModuleBuildInfo(module1);
/**
* Check if it uses the image generation feature.
*/ if (!dev) {
const resource = module1.resource;
const hasOGImageGeneration = resource && /[\\/]node_modules[\\/]@vercel[\\/]og[\\/]dist[\\/]index.js$/.test(resource);
if (hasOGImageGeneration) {
ogImageGenerationCount++;
}
}
/**
* When building for production checks if the module is using `eval`
* and in such case produces a compilation error. The module has to
* be in use.
*/ if (!dev && buildInfo.usingIndirectEval && isUsingIndirectEvalAndUsedByExports({
module: module1,
moduleGraph,
runtime: wp.util.runtime.getEntryRuntime(compilation, entryName),
usingIndirectEval: buildInfo.usingIndirectEval,
wp
})) {
var ref10;
const id = module1.identifier();
if (/node_modules[\\/]regenerator-runtime[\\/]runtime\.js/.test(id)) {
continue;
}
if (edgeFunctionConfig == null ? void 0 : (ref10 = edgeFunctionConfig.config) == null ? void 0 : ref10.unstable_allowDynamicGlobs) {
telemetry.record({
eventName: "NEXT_EDGE_ALLOW_DYNAMIC_USED",
payload: {
...edgeFunctionConfig,
file: edgeFunctionConfig.file.replace(rootDir ?? "", ""),
fileWithDynamicCode: module1.userRequest.replace(rootDir ?? "", "")
}
});
}
if (!isDynamicCodeEvaluationAllowed(module1.userRequest, edgeFunctionConfig == null ? void 0 : edgeFunctionConfig.config, rootDir)) {
compilation.errors.push(buildWebpackError({
message: `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime ${typeof buildInfo.usingIndirectEval !== "boolean" ? `\nUsed by ${Array.from(buildInfo.usingIndirectEval).join(", ")}` : ""}\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`,
entryModule: module1,
compilation
}));
}
}
if (edgeFunctionConfig == null ? void 0 : (ref9 = edgeFunctionConfig.config) == null ? void 0 : ref9.regions) {
entryMetadata.regions = edgeFunctionConfig.config.regions;
}
/**
* The entry module has to be either a page or a middleware and hold
* the corresponding metadata.
*/ if (buildInfo == null ? void 0 : buildInfo.nextEdgeSSR) {
entryMetadata.edgeSSR = buildInfo.nextEdgeSSR;
} else if (buildInfo == null ? void 0 : buildInfo.nextEdgeMiddleware) {
entryMetadata.edgeMiddleware = buildInfo.nextEdgeMiddleware;
} else if (buildInfo == null ? void 0 : buildInfo.nextEdgeApiFunction) {
entryMetadata.edgeApiFunction = buildInfo.nextEdgeApiFunction;
}
/**
* If there are env vars found in the module, append them to the set
* of env vars for the entry.
*/ if ((buildInfo == null ? void 0 : buildInfo.nextUsedEnvVars) !== undefined) {
for (const envName of buildInfo.nextUsedEnvVars){
entryMetadata.env.add(envName);
}
}
/**
* If the module is a WASM module we read the binding information and
* append it to the entry wasm bindings.
*/ if (buildInfo == null ? void 0 : buildInfo.nextWasmMiddlewareBinding) {
entryMetadata.wasmBindings.set(buildInfo.nextWasmMiddlewareBinding.name, buildInfo.nextWasmMiddlewareBinding.filePath);
}
if (buildInfo == null ? void 0 : buildInfo.nextAssetMiddlewareBinding) {
entryMetadata.assetBindings.set(buildInfo.nextAssetMiddlewareBinding.name, buildInfo.nextAssetMiddlewareBinding.filePath);
}
/**
* Append to the list of modules to process outgoingConnections from
* the module that is being processed.
*/ for (const conn of moduleGraph.getOutgoingConnections(module1)){
if (conn.module) {
modules.add(conn.module);
}
}
}
telemetry.record({
eventName: EVENT_BUILD_FEATURE_USAGE,
payload: {
featureName: "vercelImageGeneration",
invocationCount: ogImageGenerationCount
}
});
metadataByEntry.set(entryName, entryMetadata);
}
};
}
export default class MiddlewarePlugin {
constructor({ dev , sriEnabled , hasFontLoaders }){
this.dev = dev;
this.sriEnabled = sriEnabled;
this.hasFontLoaders = hasFontLoaders;
}
apply(compiler) {
compiler.hooks.compilation.tap(NAME, (compilation, params)=>{
const { hooks } = params.normalModuleFactory;
/**
* This is the static code analysis phase.
*/ const codeAnalyzer = getCodeAnalyzer({
dev: this.dev,
compiler,
compilation
});
hooks.parser.for("javascript/auto").tap(NAME, codeAnalyzer);
hooks.parser.for("javascript/dynamic").tap(NAME, codeAnalyzer);
hooks.parser.for("javascript/esm").tap(NAME, codeAnalyzer);
/**
* Extract all metadata for the entry points in a Map object.
*/ const metadataByEntry = new Map();
compilation.hooks.finishModules.tapPromise(NAME, getExtractMetadata({
compilation,
compiler,
dev: this.dev,
metadataByEntry
}));
/**
* Emit the middleware manifest.
*/ compilation.hooks.processAssets.tap({
name: "NextJsMiddlewareManifest",
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, getCreateAssets({
compilation,
metadataByEntry,
opts: {
sriEnabled: this.sriEnabled,
hasFontLoaders: this.hasFontLoaders
}
}));
});
}
};
export async function handleWebpackExternalForEdgeRuntime({ request , context , contextInfo , getResolve }) {
if (contextInfo.issuerLayer === "middleware" && isNodeJsModule(request)) {
// allows user to provide and use their polyfills, as we do with buffer.
try {
await getResolve()(context, request);
} catch {
return `root globalThis.__import_unsupported('${request}')`;
}
}
}
//# sourceMappingURL=middleware-plugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
// @ts-ignore: TODO: remove when webpack 5 is stable
import MiniCssExtractPlugin from "next/dist/compiled/mini-css-extract-plugin";
export default class NextMiniCssExtractPlugin extends MiniCssExtractPlugin {
__next_css_remove = true;
};
//# sourceMappingURL=mini-css-extract-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/mini-css-extract-plugin.ts"],"names":["MiniCssExtractPlugin","NextMiniCssExtractPlugin","__next_css_remove"],"mappings":"AAAA,oDAAoD;AACpD,OAAOA,oBAAoB,MAAM,4CAA4C,CAAA;AAE7E,eAAe,MAAMC,wBAAwB,SAASD,oBAAoB;IACxEE,iBAAiB,GAAG,IAAI,CAAA;CACzB,CAAA"}

View File

@@ -0,0 +1,62 @@
import { STRING_LITERAL_DROP_BUNDLE } from "../../../shared/lib/constants";
export const ampFirstEntryNamesMap = new WeakMap();
const PLUGIN_NAME = "DropAmpFirstPagesPlugin";
// Prevents outputting client pages when they are not needed
export class DropClientPage {
ampPages = new Set();
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory })=>{
// Recursively look up the issuer till it ends up at the root
function findEntryModule(mod) {
const queue = new Set([
mod
]);
for (const module of queue){
const incomingConnections = compilation.moduleGraph.getIncomingConnections(module);
for (const incomingConnection of incomingConnections){
if (!incomingConnection.originModule) return module;
queue.add(incomingConnection.originModule);
}
}
return null;
}
function handler(parser) {
function markAsAmpFirst() {
const entryModule = findEntryModule(parser.state.module);
if (!entryModule) {
return;
}
// @ts-ignore buildInfo exists on Module
entryModule.buildInfo.NEXT_ampFirst = true;
}
parser.hooks.preDeclarator.tap(PLUGIN_NAME, (declarator)=>{
var ref;
if ((declarator == null ? void 0 : (ref = declarator.id) == null ? void 0 : ref.name) === STRING_LITERAL_DROP_BUNDLE) {
markAsAmpFirst();
}
});
}
normalModuleFactory.hooks.parser.for("javascript/auto").tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser.for("javascript/esm").tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser.for("javascript/dynamic").tap(PLUGIN_NAME, handler);
if (!ampFirstEntryNamesMap.has(compilation)) {
ampFirstEntryNamesMap.set(compilation, []);
}
const ampFirstEntryNamesItem = ampFirstEntryNamesMap.get(compilation);
compilation.hooks.seal.tap(PLUGIN_NAME, ()=>{
for (const [name, entryData] of compilation.entries){
for (const dependency of entryData.dependencies){
var ref;
const module = compilation.moduleGraph.getModule(dependency);
if (module == null ? void 0 : (ref = module.buildInfo) == null ? void 0 : ref.NEXT_ampFirst) {
ampFirstEntryNamesItem.push(name);
compilation.entries.delete(name);
}
}
}
});
});
}
}
//# sourceMappingURL=next-drop-client-page-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/next-drop-client-page-plugin.ts"],"names":["STRING_LITERAL_DROP_BUNDLE","ampFirstEntryNamesMap","WeakMap","PLUGIN_NAME","DropClientPage","ampPages","Set","apply","compiler","hooks","compilation","tap","normalModuleFactory","findEntryModule","mod","queue","module","incomingConnections","moduleGraph","getIncomingConnections","incomingConnection","originModule","add","handler","parser","markAsAmpFirst","entryModule","state","buildInfo","NEXT_ampFirst","preDeclarator","declarator","id","name","for","has","set","ampFirstEntryNamesItem","get","seal","entryData","entries","dependency","dependencies","getModule","push","delete"],"mappings":"AACA,SAASA,0BAA0B,QAAQ,+BAA+B,CAAA;AAE1E,OAAO,MAAMC,qBAAqB,GAChC,IAAIC,OAAO,EAAE,CAAA;AAEf,MAAMC,WAAW,GAAG,yBAAyB;AAE7C,4DA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,OAAO,CAACK,MAAM,CAACb,IAAI,CAAC;yBACjC;qBACF;iBACF;aACF,CAAC;SACH,CACF;KACF;CACF"}

View File

@@ -0,0 +1,572 @@
import nodePath from "path";
import nodeFs from "fs";
import { spans } from "./profiling-plugin";
import isError from "../../../lib/is-error";
import { nodeFileTrace } from "next/dist/compiled/@vercel/nft";
import { TRACE_OUTPUT_VERSION } from "../../../shared/lib/constants";
import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import { NODE_ESM_RESOLVE_OPTIONS, NODE_RESOLVE_OPTIONS, resolveExternal } from "../../webpack-config";
import { loadBindings } from "../../swc";
import { isMatch } from "next/dist/compiled/micromatch";
const PLUGIN_NAME = "TraceEntryPointsPlugin";
const TRACE_IGNORES = [
"**/*/next/dist/server/next.js",
"**/*/next/dist/bin/next",
];
const NOT_TRACEABLE = [
".wasm",
".png",
".jpg",
".jpeg",
".gif",
".webp",
".avif",
".ico",
".bmp",
".svg",
];
const TURBO_TRACE_DEFAULT_MAX_FILES = 128;
function getModuleFromDependency(compilation, dep) {
return compilation.moduleGraph.getModule(dep);
}
function getFilesMapFromReasons(fileList, reasons, ignoreFn) {
// this uses the reasons tree to collect files specific to a
// certain parent allowing us to not have to trace each parent
// separately
const parentFilesMap = new Map();
function propagateToParents(parents, file, seen = new Set()) {
for (const parent of parents || []){
if (!seen.has(parent)) {
seen.add(parent);
let parentFiles = parentFilesMap.get(parent);
if (!parentFiles) {
parentFiles = new Set();
parentFilesMap.set(parent, parentFiles);
}
if (!(ignoreFn == null ? void 0 : ignoreFn(file, parent))) {
parentFiles.add(file);
}
const parentReason = reasons.get(parent);
if (parentReason == null ? void 0 : parentReason.parents) {
propagateToParents(parentReason.parents, file, seen);
}
}
}
}
for (const file1 of fileList){
const reason = reasons.get(file1);
const isInitial = (reason == null ? void 0 : reason.type.length) === 1 && reason.type.includes("initial");
if (!reason || !reason.parents || isInitial && reason.parents.size === 0) {
continue;
}
propagateToParents(reason.parents, file1);
}
return parentFilesMap;
}
export class TraceEntryPointsPlugin {
chunksToTrace = [];
constructor({ appDir , appDirEnabled , traceIgnores , esmExternals , outputFileTracingRoot , turbotrace }){
this.appDir = appDir;
this.entryTraces = new Map();
this.esmExternals = esmExternals;
this.appDirEnabled = appDirEnabled;
this.traceIgnores = traceIgnores || [];
this.tracingRoot = outputFileTracingRoot || appDir;
this.turbotrace = turbotrace;
}
// Here we output all traced assets and webpack chunks to a
// ${page}.js.nft.json file
async createTraceAssets(compilation, assets, span, readlink, stat) {
const outputPath = compilation.outputOptions.path;
await span.traceChild("create-trace-assets").traceAsyncFn(async ()=>{
const entryFilesMap = new Map();
const chunksToTrace = new Set();
const isTraceable = (file)=>!NOT_TRACEABLE.some((suffix)=>{
return file.endsWith(suffix);
});
for (const entrypoint of compilation.entrypoints.values()){
const entryFiles = new Set();
for (const chunk of entrypoint.getEntrypointChunk().getAllReferencedChunks()){
for (const file of chunk.files){
if (isTraceable(file)) {
const filePath = nodePath.join(outputPath, file);
chunksToTrace.add(filePath);
entryFiles.add(filePath);
}
}
for (const file2 of chunk.auxiliaryFiles){
if (isTraceable(file2)) {
const filePath = nodePath.join(outputPath, file2);
chunksToTrace.add(filePath);
entryFiles.add(filePath);
}
}
}
entryFilesMap.set(entrypoint, entryFiles);
}
// startTrace existed and callable
if (this.turbotrace) {
let binding = await loadBindings();
if (!(binding == null ? void 0 : binding.isWasm) && typeof binding.turbo.startTrace === "function") {
this.chunksToTrace = [
...chunksToTrace
];
return;
}
}
const ignores = [
...TRACE_IGNORES,
...this.traceIgnores
];
const ignoreFn = (path)=>{
return isMatch(path, ignores, {
contains: true,
dot: true
});
};
const result = await nodeFileTrace([
...chunksToTrace
], {
base: this.tracingRoot,
processCwd: this.appDir,
readFile: async (path)=>{
if (chunksToTrace.has(path)) {
var ref;
const source = (ref = assets[nodePath.relative(outputPath, path).replace(/\\/g, "/")]) == null ? void 0 : ref.source == null ? void 0 : ref.source();
if (source) return source;
}
try {
return await new Promise((resolve, reject)=>{
compilation.inputFileSystem.readFile(path, (err, data)=>{
if (err) return reject(err);
resolve(data);
});
});
} catch (e) {
if (isError(e) && (e.code === "ENOENT" || e.code === "EISDIR")) {
return null;
}
throw e;
}
},
readlink,
stat,
ignore: ignoreFn,
mixedModules: true
});
const reasons = result.reasons;
const fileList = result.fileList;
result.esmFileList.forEach((file)=>fileList.add(file));
const parentFilesMap = getFilesMapFromReasons(fileList, reasons);
for (const [entrypoint1, entryFiles] of entryFilesMap){
const traceOutputName = `../${entrypoint1.name}.js.nft.json`;
const traceOutputPath = nodePath.dirname(nodePath.join(outputPath, traceOutputName));
const allEntryFiles = new Set();
entryFiles.forEach((file)=>{
var ref;
(ref = parentFilesMap.get(nodePath.relative(this.tracingRoot, file))) == null ? void 0 : ref.forEach((child)=>{
allEntryFiles.add(nodePath.join(this.tracingRoot, child));
});
});
// don't include the entry itself in the trace
entryFiles.delete(nodePath.join(outputPath, `../${entrypoint1.name}.js`));
assets[traceOutputName] = new sources.RawSource(JSON.stringify({
version: TRACE_OUTPUT_VERSION,
files: [
...new Set([
...entryFiles,
...allEntryFiles,
...this.entryTraces.get(entrypoint1.name) || [],
]),
].map((file)=>{
return nodePath.relative(traceOutputPath, file).replace(/\\/g, "/");
})
}));
}
});
}
tapfinishModules(compilation, traceEntrypointsPluginSpan, doResolve, readlink, stat) {
compilation.hooks.finishModules.tapAsync(PLUGIN_NAME, async (_stats, callback)=>{
const finishModulesSpan = traceEntrypointsPluginSpan.traceChild("finish-modules");
await finishModulesSpan.traceAsyncFn(async ()=>{
// we create entry -> module maps so that we can
// look them up faster instead of having to iterate
// over the compilation modules list
const entryNameMap = new Map();
const entryModMap = new Map();
const additionalEntries = new Map();
const depModMap = new Map();
finishModulesSpan.traceChild("get-entries").traceFn(()=>{
compilation.entries.forEach((entry, name)=>{
const normalizedName = name == null ? void 0 : name.replace(/\\/g, "/");
const isPage = normalizedName.startsWith("pages/");
const isApp = this.appDirEnabled && normalizedName.startsWith("app/");
if (isApp || isPage) {
for (const dep of entry.dependencies){
if (!dep) continue;
const entryMod = getModuleFromDependency(compilation, dep);
// since app entries are wrapped in next-app-loader
// we need to pull the original pagePath for
// referencing during tracing
if (isApp && entryMod.request) {
var ref;
const loaderQueryIdx = entryMod.request.indexOf("?");
const loaderQuery = new URLSearchParams(entryMod.request.substring(loaderQueryIdx));
const resource = ((ref = loaderQuery.get("pagePath")) == null ? void 0 : ref.replace("private-next-app-dir", nodePath.join(this.appDir, "app"))) || "";
entryModMap.set(resource, entryMod);
entryNameMap.set(resource, name);
}
if (entryMod && entryMod.resource) {
const normalizedResource = entryMod.resource.replace(/\\/g, "/");
if (normalizedResource.includes("pages/")) {
entryNameMap.set(entryMod.resource, name);
entryModMap.set(entryMod.resource, entryMod);
} else {
let curMap = additionalEntries.get(name);
if (!curMap) {
curMap = new Map();
additionalEntries.set(name, curMap);
}
depModMap.set(entryMod.resource, entryMod);
curMap.set(entryMod.resource, entryMod);
}
}
}
}
});
});
const readFile = async (path)=>{
const mod = depModMap.get(path) || entryModMap.get(path);
// map the transpiled source when available to avoid
// parse errors in node-file-trace
const source = mod == null ? void 0 : mod.originalSource == null ? void 0 : mod.originalSource();
if (source) {
return source.buffer();
}
// we don't want to analyze non-transpiled
// files here, that is done against webpack output
return "";
};
const entryPaths = Array.from(entryModMap.keys());
const collectDependencies = (mod)=>{
if (!mod || !mod.dependencies) return;
for (const dep of mod.dependencies){
const depMod = getModuleFromDependency(compilation, dep);
if ((depMod == null ? void 0 : depMod.resource) && !depModMap.get(depMod.resource)) {
depModMap.set(depMod.resource, depMod);
collectDependencies(depMod);
}
}
};
const entriesToTrace = [
...entryPaths
];
entryPaths.forEach((entry)=>{
collectDependencies(entryModMap.get(entry));
const entryName = entryNameMap.get(entry);
const curExtraEntries = additionalEntries.get(entryName);
if (curExtraEntries) {
entriesToTrace.push(...curExtraEntries.keys());
}
});
// startTrace existed and callable
if (this.turbotrace) {
let binding = await loadBindings();
if (!(binding == null ? void 0 : binding.isWasm) && typeof binding.turbo.startTrace === "function") {
await finishModulesSpan.traceChild("turbo-trace", {
traceEntryCount: entriesToTrace.length + ""
}).traceAsyncFn(async ()=>{
var ref, ref1;
const contextDirectory = ((ref = this.turbotrace) == null ? void 0 : ref.contextDirectory) ?? this.tracingRoot;
const maxFiles = ((ref1 = this.turbotrace) == null ? void 0 : ref1.maxFiles) ?? TURBO_TRACE_DEFAULT_MAX_FILES;
let chunks = [
...entriesToTrace
];
let restChunks = chunks.length > maxFiles ? chunks.splice(maxFiles) : [];
let filesTracedInEntries = [];
while(chunks.length){
var ref2, ref3, ref4;
filesTracedInEntries = filesTracedInEntries.concat(await binding.turbo.startTrace({
action: "print",
input: chunks,
contextDirectory,
processCwd: ((ref2 = this.turbotrace) == null ? void 0 : ref2.processCwd) ?? this.appDir,
logLevel: (ref3 = this.turbotrace) == null ? void 0 : ref3.logLevel,
showAll: (ref4 = this.turbotrace) == null ? void 0 : ref4.logAll
}));
chunks = restChunks;
if (restChunks.length) {
restChunks = chunks.length > maxFiles ? chunks.splice(maxFiles) : [];
}
}
// only trace the assets under the appDir
// exclude files from node_modules, entries and processed by webpack
const filesTracedFromEntries = filesTracedInEntries.map((f)=>nodePath.join(contextDirectory, f)).filter((f)=>!f.includes("/node_modules/") && f.startsWith(this.appDir) && !entriesToTrace.includes(f) && !depModMap.has(f));
if (!filesTracedFromEntries.length) {
return;
}
// The turbo trace doesn't provide the traced file type and reason at present
// let's write the traced files into the first [entry].nft.json
const [[, entryName]] = Array.from(entryNameMap.entries()).filter(([k])=>k.startsWith(this.appDir));
const outputPath = compilation.outputOptions.path;
const traceOutputPath = nodePath.join(outputPath, `../${entryName}.js.nft.json`);
const traceOutputDir = nodePath.dirname(traceOutputPath);
this.turbotraceOutputPath = traceOutputPath;
this.turbotraceFiles = filesTracedFromEntries.map((file)=>nodePath.relative(traceOutputDir, file));
});
return;
}
}
let fileList;
let reasons;
const ignores = [
...TRACE_IGNORES,
...this.traceIgnores,
"**/node_modules/**",
];
const ignoreFn = (path)=>{
return isMatch(path, ignores, {
contains: true,
dot: true
});
};
await finishModulesSpan.traceChild("node-file-trace", {
traceEntryCount: entriesToTrace.length + ""
}).traceAsyncFn(async ()=>{
const result = await nodeFileTrace(entriesToTrace, {
base: this.tracingRoot,
processCwd: this.appDir,
readFile,
readlink,
stat,
resolve: doResolve ? async (id, parent, job, isCjs)=>{
return doResolve(id, parent, job, !isCjs);
} : undefined,
ignore: ignoreFn,
mixedModules: true
});
// @ts-ignore
fileList = result.fileList;
result.esmFileList.forEach((file)=>fileList.add(file));
reasons = result.reasons;
});
await finishModulesSpan.traceChild("collect-traced-files").traceAsyncFn(()=>{
const parentFilesMap = getFilesMapFromReasons(fileList, reasons, (file)=>{
var ref;
// if a file was imported and a loader handled it
// we don't include it in the trace e.g.
// static image imports, CSS imports
file = nodePath.join(this.tracingRoot, file);
const depMod = depModMap.get(file);
const isAsset = (ref = reasons.get(nodePath.relative(this.tracingRoot, file))) == null ? void 0 : ref.type.includes("asset");
return !isAsset && Array.isArray(depMod == null ? void 0 : depMod.loaders) && depMod.loaders.length > 0;
});
entryPaths.forEach((entry)=>{
var ref;
const entryName = entryNameMap.get(entry);
const normalizedEntry = nodePath.relative(this.tracingRoot, entry);
const curExtraEntries = additionalEntries.get(entryName);
const finalDeps = new Set();
(ref = parentFilesMap.get(normalizedEntry)) == null ? void 0 : ref.forEach((dep)=>{
finalDeps.add(nodePath.join(this.tracingRoot, dep));
});
if (curExtraEntries) {
for (const extraEntry of curExtraEntries.keys()){
var ref5;
const normalizedExtraEntry = nodePath.relative(this.tracingRoot, extraEntry);
finalDeps.add(extraEntry);
(ref5 = parentFilesMap.get(normalizedExtraEntry)) == null ? void 0 : ref5.forEach((dep)=>{
finalDeps.add(nodePath.join(this.tracingRoot, dep));
});
}
}
this.entryTraces.set(entryName, finalDeps);
});
});
}).then(()=>callback(), (err)=>callback(err));
});
}
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
const readlink = async (path)=>{
try {
return await new Promise((resolve, reject)=>{
compilation.inputFileSystem.readlink(path, (err, link)=>{
if (err) return reject(err);
resolve(link);
});
});
} catch (e) {
if (isError(e) && (e.code === "EINVAL" || e.code === "ENOENT" || e.code === "UNKNOWN")) {
return null;
}
throw e;
}
};
const stat = async (path)=>{
try {
return await new Promise((resolve, reject)=>{
compilation.inputFileSystem.stat(path, (err, stats)=>{
if (err) return reject(err);
resolve(stats);
});
});
} catch (e) {
if (isError(e) && (e.code === "ENOENT" || e.code === "ENOTDIR")) {
return null;
}
throw e;
}
};
const compilationSpan = spans.get(compilation) || spans.get(compiler);
const traceEntrypointsPluginSpan = compilationSpan.traceChild("next-trace-entrypoint-plugin");
traceEntrypointsPluginSpan.traceFn(()=>{
compilation.hooks.processAssets.tapAsync({
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE
}, (assets, callback)=>{
this.createTraceAssets(compilation, assets, traceEntrypointsPluginSpan, readlink, stat).then(()=>callback()).catch((err)=>callback(err));
});
let resolver = compilation.resolverFactory.get("normal");
function getPkgName(name) {
const segments = name.split("/");
if (name[0] === "@" && segments.length > 1) return segments.length > 1 ? segments.slice(0, 2).join("/") : null;
return segments.length ? segments[0] : null;
}
const getResolve = (options)=>{
const curResolver = resolver.withOptions(options);
return (parent, request, job)=>{
return new Promise((resolve, reject)=>{
const context = nodePath.dirname(parent);
curResolver.resolve({}, context, request, {
fileDependencies: compilation.fileDependencies,
missingDependencies: compilation.missingDependencies,
contextDependencies: compilation.contextDependencies
}, async (err, result, resContext)=>{
if (err) return reject(err);
if (!result) {
return reject(new Error("module not found"));
}
// webpack resolver doesn't strip loader query info
// from the result so use path instead
if (result.includes("?") || result.includes("!")) {
result = (resContext == null ? void 0 : resContext.path) || result;
}
try {
// we need to collect all parent package.json's used
// as webpack's resolve doesn't expose this and parent
// package.json could be needed for resolving e.g. stylis
// stylis/package.json -> stylis/dist/umd/package.json
if (result.includes("node_modules")) {
let requestPath = result.replace(/\\/g, "/").replace(/\0/g, "");
if (!nodePath.isAbsolute(request) && request.includes("/") && (resContext == null ? void 0 : resContext.descriptionFileRoot)) {
var ref;
requestPath = (resContext.descriptionFileRoot + request.slice(((ref = getPkgName(request)) == null ? void 0 : ref.length) || 0) + nodePath.sep + "package.json").replace(/\\/g, "/").replace(/\0/g, "");
}
const rootSeparatorIndex = requestPath.indexOf("/");
let separatorIndex;
while((separatorIndex = requestPath.lastIndexOf("/")) > rootSeparatorIndex){
requestPath = requestPath.slice(0, separatorIndex);
const curPackageJsonPath = `${requestPath}/package.json`;
if (await job.isFile(curPackageJsonPath)) {
await job.emitFile(await job.realpath(curPackageJsonPath), "resolve", parent);
}
}
}
} catch (_err) {
// we failed to resolve the package.json boundary,
// we don't block emitting the initial asset from this
}
resolve([
result,
options.dependencyType === "esm"
]);
});
});
};
};
const CJS_RESOLVE_OPTIONS = {
...NODE_RESOLVE_OPTIONS,
fullySpecified: undefined,
modules: undefined,
extensions: undefined
};
const BASE_CJS_RESOLVE_OPTIONS = {
...CJS_RESOLVE_OPTIONS,
alias: false
};
const ESM_RESOLVE_OPTIONS = {
...NODE_ESM_RESOLVE_OPTIONS,
fullySpecified: undefined,
modules: undefined,
extensions: undefined
};
const BASE_ESM_RESOLVE_OPTIONS = {
...ESM_RESOLVE_OPTIONS,
alias: false
};
const doResolve = async (request, parent, job, isEsmRequested)=>{
const context = nodePath.dirname(parent);
// When in esm externals mode, and using import, we resolve with
// ESM resolving options.
const { res } = await resolveExternal(this.appDir, this.esmExternals, context, request, isEsmRequested, !!this.appDirEnabled, (options)=>(_, resRequest)=>{
return getResolve(options)(parent, resRequest, job);
}, undefined, undefined, ESM_RESOLVE_OPTIONS, CJS_RESOLVE_OPTIONS, BASE_ESM_RESOLVE_OPTIONS, BASE_CJS_RESOLVE_OPTIONS);
if (!res) {
throw new Error(`failed to resolve ${request} from ${parent}`);
}
return res.replace(/\0/g, "");
};
this.tapfinishModules(compilation, traceEntrypointsPluginSpan, doResolve, readlink, stat);
});
});
if (this.turbotrace) {
compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async (compilation)=>{
const compilationSpan = spans.get(compilation) || spans.get(compiler);
const traceEntrypointsPluginSpan = compilationSpan.traceChild("next-trace-entrypoint-plugin");
const turbotraceAfterEmitSpan = traceEntrypointsPluginSpan.traceChild("after-emit-turbo-trace");
await turbotraceAfterEmitSpan.traceAsyncFn(async ()=>{
let binding = await loadBindings();
if (!(binding == null ? void 0 : binding.isWasm) && typeof binding.turbo.startTrace === "function") {
var ref;
const maxFiles = ((ref = this.turbotrace) == null ? void 0 : ref.maxFiles) ?? TURBO_TRACE_DEFAULT_MAX_FILES;
let chunks = [
...this.chunksToTrace
];
let restChunks = chunks.length > maxFiles ? chunks.splice(maxFiles) : [];
while(chunks.length){
var ref6, ref7, ref8, ref9;
await binding.turbo.startTrace({
action: "annotate",
input: chunks,
contextDirectory: ((ref6 = this.turbotrace) == null ? void 0 : ref6.contextDirectory) ?? this.tracingRoot,
processCwd: ((ref7 = this.turbotrace) == null ? void 0 : ref7.processCwd) ?? this.appDir,
showAll: (ref8 = this.turbotrace) == null ? void 0 : ref8.logAll,
logLevel: (ref9 = this.turbotrace) == null ? void 0 : ref9.logLevel
});
chunks = restChunks;
if (restChunks.length) {
restChunks = chunks.length > maxFiles ? chunks.splice(maxFiles) : [];
}
}
if (this.turbotraceOutputPath && this.turbotraceFiles) {
const existedNftFile = await nodeFs.promises.readFile(this.turbotraceOutputPath, "utf8").then((content)=>JSON.parse(content)).catch(()=>({
version: TRACE_OUTPUT_VERSION,
files: []
}));
console.log(this.turbotraceOutputPath, this.turbotraceFiles);
existedNftFile.files.push(...this.turbotraceFiles);
const filesSet = new Set(existedNftFile.files);
existedNftFile.files = [
...filesSet
];
nodeFs.promises.writeFile(this.turbotraceOutputPath, JSON.stringify(existedNftFile));
}
}
});
});
}
}
}
//# sourceMappingURL=next-trace-entrypoints-plugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,89 @@
import { clearModuleContext } from "../../../server/web/sandbox";
import { realpathSync } from "fs";
import path from "path";
import isError from "../../../lib/is-error";
const originModules = [
require.resolve("../../../server/require"),
require.resolve("../../../server/load-components"),
require.resolve("../../../server/next-server"),
require.resolve("../../../compiled/react-server-dom-webpack/client"),
];
const RUNTIME_NAMES = [
"webpack-runtime",
"webpack-api-runtime"
];
function deleteCache(filePath) {
try {
filePath = realpathSync(filePath);
} catch (e) {
if (isError(e) && e.code !== "ENOENT") throw e;
}
const mod = require.cache[filePath];
if (mod) {
// remove the child reference from the originModules
for (const originModule of originModules){
const parent = require.cache[originModule];
if (parent) {
const idx = parent.children.indexOf(mod);
if (idx >= 0) parent.children.splice(idx, 1);
}
}
// remove parent references from external modules
for (const child of mod.children){
child.parent = null;
}
delete require.cache[filePath];
return true;
}
return false;
}
const PLUGIN_NAME = "NextJsRequireCacheHotReloader";
// This plugin flushes require.cache after emitting the files. Providing 'hot reloading' of server files.
export class NextJsRequireCacheHotReloader {
prevAssets = null;
constructor(opts){
this.hasServerComponents = opts.hasServerComponents;
}
apply(compiler) {
compiler.hooks.assetEmitted.tap(PLUGIN_NAME, (_file, { targetPath , content })=>{
deleteCache(targetPath);
clearModuleContext(targetPath, content.toString("utf-8"));
});
compiler.hooks.afterEmit.tap(PLUGIN_NAME, (compilation)=>{
RUNTIME_NAMES.forEach((name)=>{
const runtimeChunkPath = path.join(compilation.outputOptions.path, `${name}.js`);
deleteCache(runtimeChunkPath);
});
let hasAppPath = false;
// we need to make sure to clear all server entries from cache
// since they can have a stale webpack-runtime cache
// which needs to always be in-sync
const entries = [
...compilation.entries.keys()
].filter((entry)=>{
const isAppPath = entry.toString().startsWith("app/");
hasAppPath = hasAppPath || isAppPath;
return entry.toString().startsWith("pages/") || isAppPath;
});
if (hasAppPath) {
// ensure we reset the cache for sc_server components
// loaded via react-server-dom-webpack
const reactServerDomModId = require.resolve("next/dist/compiled/react-server-dom-webpack/client");
const reactServerDomMod = require.cache[reactServerDomModId];
if (reactServerDomMod) {
for (const child of reactServerDomMod.children){
child.parent = null;
delete require.cache[child.id];
}
}
delete require.cache[reactServerDomModId];
}
entries.forEach((page)=>{
const outputPath = path.join(compilation.outputOptions.path, page + ".js");
deleteCache(outputPath);
});
});
}
}
//# sourceMappingURL=nextjs-require-cache-hot-reloader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/nextjs-require-cache-hot-reloader.ts"],"names":["clearModuleContext","realpathSync","path","isError","originModules","require","resolve","RUNTIME_NAMES","deleteCache","filePath","e","code","mod","cache","originModule","parent","idx","children","indexOf","splice","child","PLUGIN_NAME","NextJsRequireCacheHotReloader","prevAssets","constructor","opts","hasServerComponents","apply","compiler","hooks","assetEmitted","tap","_file","targetPath","content","toString","afterEmit","compilation","forEach","name","runtimeChunkPath","join","outputOptions","hasAppPath","entries","keys","filter","entry","isAppPath","startsWith","reactServerDomModId","reactServerDomMod","id","page","outputPath"],"mappings":"AACA,SAASA,kBAAkB,QAAQ,6BAA6B,CAAA;AAChE,SAASC,YAAY,QAAQ,IAAI,CAAA;AACjC,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,OAAOC,OAAO,MAAM,uBAAuB,CAAA;AAK3C,MAAMC,aAAa,GAAG;IACpBC,OAAO,CAACC,OAAO,CAAC,yBAAyB,CAAC;IAC1CD,OAAO,CAACC,OAAO,CAAC,iCAAiC,CAAC;IAClDD,OAAO,CAACC,OAAO,CAAC,6BAA6B,CAAC;IAC9CD,OAAO,CAACC,OAAO,CAAC,mDAAmD,CAAC;CACrE;AAED,MAAMC,aAAa,GAAG;IAAC,iBAAiB;IAAE,qBAAqB;CAAC;AAEhE,SAASC,WAAW,CAACC,QAAgB,EAAE;IACrC,IAAI;QACFA,QAAQ,GAAGR,YAAY,CAACQ,QAAQ,CAAC;KAClC,CAAC,OAAOC,CAAC,EAAE;QACV,IAAIP,OAAO,CAACO,CAAC,CAAC,IAAIA,CAAC,CAACC,IAAI,KAAK,QAAQ,EAAE,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GpD,IAAI,CAACuC,IAAI,CAC1BJ,WAAW,CAACK,aAAa,CAACxC,IAAI,EAC9BmD,IAAI,GAAG,KAAK,CACb;gBACD7C,WAAW,CAAC8C,UAAU,CAAC;aACxB,CAAC;SACH,CAAC;KACH;CACF"}

View File

@@ -0,0 +1,78 @@
import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import { PAGES_MANIFEST, APP_PATHS_MANIFEST } from "../../../shared/lib/constants";
import getRouteFromEntrypoint from "../../../server/get-route-from-entrypoint";
import { normalizePathSep } from "../../../shared/lib/page-path/normalize-path-sep";
let edgeServerPages = {};
let nodeServerPages = {};
let edgeServerAppPaths = {};
let nodeServerAppPaths = {};
// This plugin creates a pages-manifest.json from page entrypoints.
// This is used for mapping paths like `/` to `.next/server/static/<buildid>/pages/index.js` when doing SSR
// It's also used by next export to provide defaultPathMap
export default class PagesManifestPlugin {
constructor({ dev , isEdgeRuntime , appDirEnabled }){
this.dev = dev;
this.isEdgeRuntime = isEdgeRuntime;
this.appDirEnabled = appDirEnabled;
}
createAssets(compilation, assets) {
const entrypoints = compilation.entrypoints;
const pages = {};
const appPaths = {};
for (const entrypoint of entrypoints.values()){
const pagePath = getRouteFromEntrypoint(entrypoint.name, this.appDirEnabled);
if (!pagePath) {
continue;
}
const files = entrypoint.getFiles().filter((file)=>!file.includes("webpack-runtime") && !file.includes("webpack-api-runtime") && file.endsWith(".js"));
// Skip entries which are empty
if (!files.length) {
continue;
}
// Write filename, replace any backslashes in path (on windows) with forwardslashes for cross-platform consistency.
let file1 = files[files.length - 1];
if (!this.dev) {
if (!this.isEdgeRuntime) {
file1 = file1.slice(3);
}
}
file1 = normalizePathSep(file1);
if (entrypoint.name.startsWith("app/")) {
appPaths[pagePath] = file1;
} else {
pages[pagePath] = file1;
}
}
// This plugin is used by both the Node server and Edge server compilers,
// we need to merge both pages to generate the full manifest.
if (this.isEdgeRuntime) {
edgeServerPages = pages;
edgeServerAppPaths = appPaths;
} else {
nodeServerPages = pages;
nodeServerAppPaths = appPaths;
}
assets[`${!this.dev && !this.isEdgeRuntime ? "../" : ""}` + PAGES_MANIFEST] = new sources.RawSource(JSON.stringify({
...edgeServerPages,
...nodeServerPages
}, null, 2));
if (this.appDirEnabled) {
assets[`${!this.dev && !this.isEdgeRuntime ? "../" : ""}` + APP_PATHS_MANIFEST] = new sources.RawSource(JSON.stringify({
...edgeServerAppPaths,
...nodeServerAppPaths
}, null, 2));
}
}
apply(compiler) {
compiler.hooks.make.tap("NextJsPagesManifest", (compilation)=>{
compilation.hooks.processAssets.tap({
name: "NextJsPagesManifest",
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, (assets)=>{
this.createAssets(compilation, assets);
});
});
}
};
//# sourceMappingURL=pages-manifest-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/pages-manifest-plugin.ts"],"names":["webpack","sources","PAGES_MANIFEST","APP_PATHS_MANIFEST","getRouteFromEntrypoint","normalizePathSep","edgeServerPages","nodeServerPages","edgeServerAppPaths","nodeServerAppPaths","PagesManifestPlugin","constructor","dev","isEdgeRuntime","appDirEnabled","createAssets","compilation","assets","entrypoints","pages","appPaths","entrypoint","values","pagePath","name","files","getFiles","filter","file","includes","endsWith","length","slice","startsWith","RawSource","JSON","stringify","apply","compiler","hooks","make","tap","processAssets","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS"],"mappings":"AAAA,SAASA,OAAO,EAAEC,OAAO,QAAQ,oCAAoC,CAAA;AACrE,SACEC,cAAc,EACdC,kBAAkB,QACb,+BAA+B,CAAA;AACtC,OAAOC,sBAAsB,MAAM,2CAA2C,CAAA;AAC9E,SAASC,gBAAgB,QAAQ,kDAAkD,CAAA;AAInF,IAAIC,eAAe,GAAG,EAAE;AACxB,IAAIC,eAAe,GAAG,EAAE;AACxB,IAAIC,kBAAkB,GAAG,EAAE;AAC3B,IAAIC,kBAAkB,GAAG,EAAE;AAE3B,mEAAmE;AACnE,2GAA2G;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CAACC,8BAA8B;aAC1D,EACD,CAAC5B,MAAW,GAAK;gBACf,IAAI,CAACF,YAAY,CAACC,WAAW,EAAEC,MAAM,CAAC;aACvC,CACF;SACF,CAAC;KACH;CACF,CAAA"}

View File

@@ -0,0 +1,157 @@
import { NormalModule } from "next/dist/compiled/webpack/webpack";
const pluginName = "ProfilingPlugin";
export const spans = new WeakMap();
const moduleSpansByCompilation = new WeakMap();
export const webpackInvalidSpans = new WeakMap();
export class ProfilingPlugin {
constructor({ runWebpackSpan }){
this.runWebpackSpan = runWebpackSpan;
}
apply(compiler) {
this.traceTopLevelHooks(compiler);
this.traceCompilationHooks(compiler);
this.compiler = compiler;
}
traceHookPair(spanName, startHook, stopHook, { parentSpan , attrs , onStart , onStop } = {}) {
let span;
startHook.tap({
name: pluginName,
stage: -Infinity
}, (...params)=>{
const name = typeof spanName === "function" ? spanName() : spanName;
const attributes = attrs ? attrs(...params) : attrs;
span = parentSpan ? parentSpan().traceChild(name, attributes) : this.runWebpackSpan.traceChild(name, attributes);
if (onStart) onStart(span, ...params);
});
stopHook.tap({
name: pluginName,
stage: Infinity
}, ()=>{
// `stopHook` may be triggered when `startHook` has not in cases
// where `stopHook` is used as the terminating event for more
// than one pair of hooks.
if (!span) {
return;
}
if (onStop) onStop();
span.stop();
});
}
traceTopLevelHooks(compiler) {
this.traceHookPair("webpack-compilation", compiler.hooks.compilation, compiler.hooks.afterCompile, {
parentSpan: ()=>webpackInvalidSpans.get(compiler) || this.runWebpackSpan,
attrs: ()=>({
name: compiler.name
}),
onStart: (span, compilation)=>{
spans.set(compilation, span);
spans.set(compiler, span);
moduleSpansByCompilation.set(compilation, new WeakMap());
}
});
if (compiler.options.mode === "development") {
this.traceHookPair(()=>`webpack-invalidated-${compiler.name}`, compiler.hooks.invalid, compiler.hooks.done, {
onStart: (span)=>webpackInvalidSpans.set(compiler, span),
onStop: ()=>webpackInvalidSpans.delete(compiler),
attrs: (fileName)=>({
trigger: fileName || "manual"
})
});
}
}
traceCompilationHooks(compiler) {
this.traceHookPair("emit", compiler.hooks.emit, compiler.hooks.afterEmit, {
parentSpan: ()=>webpackInvalidSpans.get(compiler) || this.runWebpackSpan
});
this.traceHookPair("make", compiler.hooks.make, compiler.hooks.finishMake, {
parentSpan: ()=>webpackInvalidSpans.get(compiler) || this.runWebpackSpan
});
compiler.hooks.compilation.tap(pluginName, (compilation)=>{
compilation.hooks.buildModule.tap(pluginName, (module)=>{
var ref;
const compilationSpan = spans.get(compilation);
if (!compilationSpan) {
return;
}
const moduleType = (()=>{
if (!module.userRequest) {
return "";
}
return module.userRequest.split(".").pop();
})();
const issuerModule = compilation == null ? void 0 : (ref = compilation.moduleGraph) == null ? void 0 : ref.getIssuer(module);
let span;
const moduleSpans = moduleSpansByCompilation.get(compilation);
const spanName = `build-module${moduleType ? `-${moduleType}` : ""}`;
const issuerSpan = issuerModule && (moduleSpans == null ? void 0 : moduleSpans.get(issuerModule));
if (issuerSpan) {
span = issuerSpan.traceChild(spanName);
} else {
span = compilationSpan.traceChild(spanName);
}
span.setAttribute("name", module.userRequest);
moduleSpans.set(module, span);
});
const moduleHooks = NormalModule.getCompilationHooks(compilation);
// @ts-ignore TODO: remove ignore when using webpack 5 types
moduleHooks.readResource.for(undefined).intercept({
register (tapInfo) {
const fn = tapInfo.fn;
tapInfo.fn = (loaderContext, callback)=>{
const moduleSpan = loaderContext.currentTraceSpan.traceChild(`read-resource`);
fn(loaderContext, (err, result)=>{
moduleSpan.stop();
callback(err, result);
});
};
return tapInfo;
}
});
moduleHooks.loader.tap(pluginName, (loaderContext, module)=>{
var ref;
const moduleSpan = (ref = moduleSpansByCompilation.get(compilation)) == null ? void 0 : ref.get(module);
loaderContext.currentTraceSpan = moduleSpan;
});
compilation.hooks.succeedModule.tap(pluginName, (module)=>{
var ref, ref1;
(ref1 = (ref = moduleSpansByCompilation == null ? void 0 : moduleSpansByCompilation.get(compilation)) == null ? void 0 : ref.get(module)) == null ? void 0 : ref1.stop();
});
this.traceHookPair("webpack-compilation-seal", compilation.hooks.seal, compilation.hooks.afterSeal, {
parentSpan: ()=>spans.get(compilation)
});
compilation.hooks.addEntry.tap(pluginName, (entry)=>{
const compilationSpan = spans.get(compilation);
if (!compilationSpan) {
return;
}
const addEntrySpan = compilationSpan.traceChild("add-entry");
addEntrySpan.setAttribute("request", entry.request);
spans.set(entry, addEntrySpan);
});
compilation.hooks.succeedEntry.tap(pluginName, (entry)=>{
var ref;
(ref = spans.get(entry)) == null ? void 0 : ref.stop();
});
this.traceHookPair("webpack-compilation-chunk-graph", compilation.hooks.beforeChunks, compilation.hooks.afterChunks, {
parentSpan: ()=>spans.get(compilation) || spans.get(compiler)
});
this.traceHookPair("webpack-compilation-optimize", compilation.hooks.optimize, compilation.hooks.reviveModules, {
parentSpan: ()=>spans.get(compilation) || spans.get(compiler)
});
this.traceHookPair("webpack-compilation-optimize-modules", compilation.hooks.optimizeModules, compilation.hooks.afterOptimizeModules, {
parentSpan: ()=>spans.get(compilation) || spans.get(compiler)
});
this.traceHookPair("webpack-compilation-optimize-chunks", compilation.hooks.optimizeChunks, compilation.hooks.afterOptimizeChunks, {
parentSpan: ()=>spans.get(compilation) || spans.get(compiler)
});
this.traceHookPair("webpack-compilation-optimize-tree", compilation.hooks.optimizeTree, compilation.hooks.afterOptimizeTree, {
parentSpan: ()=>spans.get(compilation) || spans.get(compiler)
});
this.traceHookPair("webpack-compilation-hash", compilation.hooks.beforeHash, compilation.hooks.afterHash, {
parentSpan: ()=>spans.get(compilation) || spans.get(compiler)
});
});
}
}
//# sourceMappingURL=profiling-plugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,135 @@
/**
COPYRIGHT (c) 2017-present James Kyle <me@thejameskyle.com>
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR
*/ // Implementation of this PR: https://github.com/jamiebuilds/react-loadable/pull/132
// Modified to strip out unneeded results for Next's specific use case
import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import path from "path";
function getModuleId(compilation, module) {
return compilation.chunkGraph.getModuleId(module);
}
function getModuleFromDependency(compilation, dep) {
return compilation.moduleGraph.getModule(dep);
}
function getOriginModuleFromDependency(compilation, dep) {
return compilation.moduleGraph.getParentModule(dep);
}
function getChunkGroupFromBlock(compilation, block) {
return compilation.chunkGraph.getBlockChunkGroup(block);
}
function buildManifest(_compiler, compilation, pagesDir, dev) {
// If there's no pagesDir, output an empty manifest
if (!pagesDir) {
return {};
}
let manifest = {};
// This is allowed:
// import("./module"); <- ImportDependency
// We don't support that:
// import(/* webpackMode: "eager" */ "./module") <- ImportEagerDependency
// import(`./module/${param}`) <- ImportContextDependency
// Find all dependencies blocks which contains a `import()` dependency
const handleBlock = (block)=>{
block.blocks.forEach(handleBlock);
const chunkGroup = getChunkGroupFromBlock(compilation, block);
for (const dependency of block.dependencies){
if (dependency.type.startsWith("import()")) {
// get the referenced module
const module = getModuleFromDependency(compilation, dependency);
if (!module) return;
// get the module containing the import()
const originModule = getOriginModuleFromDependency(compilation, dependency);
const originRequest = originModule == null ? void 0 : originModule.resource;
if (!originRequest) return;
// We construct a "unique" key from origin module and request
// It's not perfect unique, but that will be fine for us.
// We also need to construct the same in the babel plugin.
const key = `${path.relative(pagesDir, originRequest)} -> ${dependency.request}`;
// Capture all files that need to be loaded.
const files = new Set();
if (manifest[key]) {
// In the "rare" case where multiple chunk groups
// are created for the same `import()` or multiple
// import()s reference the same module, we merge
// the files to make sure to not miss files
// This may cause overfetching in edge cases.
for (const file of manifest[key].files){
files.add(file);
}
}
// There might not be a chunk group when all modules
// are already loaded. In this case we only need need
// the module id and no files
if (chunkGroup) {
for (const chunk of chunkGroup.chunks){
chunk.files.forEach((file)=>{
if ((file.endsWith(".js") || file.endsWith(".css")) && file.match(/^static\/(chunks|css)\//)) {
files.add(file);
}
});
}
}
// usually we have to add the parent chunk groups too
// but we assume that all parents are also imported by
// next/dynamic so they are loaded by the same technique
// add the id and files to the manifest
const id = dev ? key : getModuleId(compilation, module);
manifest[key] = {
id,
files: Array.from(files)
};
}
}
};
for (const module1 of compilation.modules){
module1.blocks.forEach(handleBlock);
}
manifest = Object.keys(manifest).sort()// eslint-disable-next-line no-sequences
.reduce((a, c)=>(a[c] = manifest[c], a), {});
return manifest;
}
export class ReactLoadablePlugin {
constructor(opts){
this.filename = opts.filename;
this.pagesDir = opts.pagesDir;
this.runtimeAsset = opts.runtimeAsset;
this.dev = opts.dev;
}
createAssets(compiler, compilation, assets) {
const manifest = buildManifest(compiler, compilation, this.pagesDir, this.dev);
// @ts-ignore: TODO: remove when webpack 5 is stable
assets[this.filename] = new sources.RawSource(JSON.stringify(manifest, null, 2));
if (this.runtimeAsset) {
assets[this.runtimeAsset] = new sources.RawSource(`self.__REACT_LOADABLE_MANIFEST=${JSON.stringify(manifest)}`);
}
return assets;
}
apply(compiler) {
compiler.hooks.make.tap("ReactLoadableManifest", (compilation)=>{
compilation.hooks.processAssets.tap({
name: "ReactLoadableManifest",
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, (assets)=>{
this.createAssets(compiler, compilation, assets);
});
});
}
}
//# sourceMappingURL=react-loadable-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/react-loadable-plugin.ts"],"names":["webpack","sources","path","getModuleId","compilation","module","chunkGraph","getModuleFromDependency","dep","moduleGraph","getModule","getOriginModuleFromDependency","getParentModule","getChunkGroupFromBlock","block","getBlockChunkGroup","buildManifest","_compiler","pagesDir","dev","manifest","handleBlock","blocks","forEach","chunkGroup","dependency","dependencies","type","startsWith","originModule","originRequest","resource","key","relative","request","files","Set","file","add","chunk","chunks","endsWith","match","id","Array","from","modules","Object","keys","sort","reduce","a","c","ReactLoadablePlugin","constructor","opts","filename","runtimeAsset","createAssets","compiler","assets","RawSource","JSON","stringify","apply","hooks","make","tap","processAssets","name","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;EAmBE,CACF,oFAAoF;AACpF,sEAAsE;AAEtE,SAASA,OAAO,EAAEC,OAAO,QAAQ,oCAAoC,CAAA;AAErE,OAAOC,IAAI,MAAM,MAAM,CAAA;AAEvB,SAASC,WAAW,CAACC,WAAgB,EAAEC,MAAW,EAAmB;IACnE,OAAOD,WAAW,CAACE,UAAU,CAACH,WAAW,CAACE,MAAM,CAAC,CAAA;CAClD;AAED,SAASE,uBAAuB,CAC9BH,WAAgB,EAChBI,GAAQ,EACgC;IACxC,OAAOJ,WAAW,CAACK,WAAW,CAACC,SAAS,CAACF,GAAG,CAAC,CAAA;CAC9C;AAED,SAASG,6BAA6B,CACpCP,WAAgB,EAChBI,GAAQ,EACgC;IACxC,OAAOJ,WAAW,CAACK,WAAW,CAACG,eAAe,CAACJ,GAAG,CAAC,CAAA;CACpD;AAED,SAASK,sBAAsB,CAC7BT,WAAgB,EAChBU,KAAU,EAC0B;IACpC,OAAOV,WAAW,CAACE,UAAU,CAACS,kBAAkB,CAACD,KAAK,CAAC,CAAA;CACxD;AAED,SAASE,aAAa,CACpBC,SAA2B,EAC3Bb,WAAgC,EAChCc,QAA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,QAAQ,EAAEvD,WAAW,EAAEwD,MAAM,CAAC;aACjD,CACF;SACF,CAAC;KACH;CACF"}

View File

@@ -0,0 +1,43 @@
import { webpack, sources } from "next/dist/compiled/webpack/webpack";
import crypto from "crypto";
import { SUBRESOURCE_INTEGRITY_MANIFEST } from "../../../shared/lib/constants";
const PLUGIN_NAME = "SubresourceIntegrityPlugin";
export class SubresourceIntegrityPlugin {
constructor(algorithm){
this.algorithm = algorithm;
}
apply(compiler) {
compiler.hooks.make.tap(PLUGIN_NAME, (compilation)=>{
compilation.hooks.afterOptimizeAssets.tap({
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, (assets)=>{
// Collect all the assets.
let files = new Set();
for (const asset of compilation.getAssets()){
files.add(asset.name);
}
// For each file, deduped, calculate the file hash.
const hashes = {};
for (const file of files.values()){
// Get the buffer for the asset.
const asset = assets[file];
if (!asset) {
throw new Error(`could not get asset: ${file}`);
}
// Get the buffer for the asset.
const buffer = asset.buffer();
// Create the hash for the content.
const hash = crypto.createHash(this.algorithm).update(buffer).digest().toString("base64");
hashes[file] = `${this.algorithm}-${hash}`;
}
const json = JSON.stringify(hashes, null, 2);
const file1 = "server/" + SUBRESOURCE_INTEGRITY_MANIFEST;
assets[file1 + ".js"] = new sources.RawSource("self.__SUBRESOURCE_INTEGRITY_MANIFEST=" + json);
assets[file1 + ".json"] = new sources.RawSource(json);
});
});
}
}
//# sourceMappingURL=subresource-integrity-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/subresource-integrity-plugin.ts"],"names":["webpack","sources","crypto","SUBRESOURCE_INTEGRITY_MANIFEST","PLUGIN_NAME","SubresourceIntegrityPlugin","constructor","algorithm","apply","compiler","hooks","make","tap","compilation","afterOptimizeAssets","name","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS","assets","files","Set","asset","getAssets","add","hashes","file","values","Error","buffer","hash","createHash","update","digest","toString","json","JSON","st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AAC,CAC1ByB,MAAM,CAACH,MAAM,CAAC,CACdI,MAAM,EAAE,CACRC,QAAQ,CAAC,QAAQ,CAAC;oBAErBT,MAAM,CAACC,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,CAACnB,SAAS,CAAC,CAAC,EAAEuB,IAAI,CAAC,CAAC;iBAC3C;gBAED,MAAMK,IAAI,GAAGC,IAAI,CAACC,SAAS,CAACZ,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;gBAC5C,MAAMC,KAAI,GAAG,SAAS,GAAGvB,8BAA8B;gBACvDgB,MAAM,CAACO,KAAI,GAAG,KAAK,CAAC,GAAG,IAAIzB,OAAO,CAACqC,SAAS,CAC1C,wCAAwC,GAAGH,IAAI,CAGhD,AAAwC;gBACzChB,MAAM,CAACO,KAAI,GAAG,OAAO,CAAC,GAAG,IAAIzB,OAAO,CAACqC,SAAS,CAC5CH,IAAI,CAGL,AAAwC;aAC1C,CACF;SACF,CAAC;KACH;CACF"}

View File

@@ -0,0 +1,159 @@
import { NormalModule } from "next/dist/compiled/webpack/webpack";
// Map of a feature module to the file it belongs in the next package.
const FEATURE_MODULE_MAP = new Map([
[
"next/image",
"/next/image.js"
],
[
"next/future/image",
"/next/future/image.js"
],
[
"next/legacy/image",
"/next/legacy/image.js"
],
[
"next/script",
"/next/script.js"
],
[
"next/dynamic",
"/next/dynamic.js"
],
]);
const FEATURE_MODULE_REGEXP_MAP = new Map([
[
"@next/font/google",
/\/@next\/font\/google\/target.css?.+$/
],
[
"@next/font/local",
/\/@next\/font\/local\/target.css?.+$/
],
]);
// List of build features used in webpack configuration
const BUILD_FEATURES = [
"swcLoader",
"swcMinify",
"swcRelay",
"swcStyledComponents",
"swcReactRemoveProperties",
"swcExperimentalDecorators",
"swcRemoveConsole",
"swcImportSource",
"swcEmotion",
"swc/target/x86_64-apple-darwin",
"swc/target/x86_64-unknown-linux-gnu",
"swc/target/x86_64-pc-windows-msvc",
"swc/target/i686-pc-windows-msvc",
"swc/target/aarch64-unknown-linux-gnu",
"swc/target/armv7-unknown-linux-gnueabihf",
"swc/target/aarch64-apple-darwin",
"swc/target/aarch64-linux-android",
"swc/target/arm-linux-androideabi",
"swc/target/x86_64-unknown-freebsd",
"swc/target/x86_64-unknown-linux-musl",
"swc/target/aarch64-unknown-linux-musl",
"swc/target/aarch64-pc-windows-msvc",
"turbotrace",
"transpilePackages",
"skipMiddlewareUrlNormalize",
"skipTrailingSlashRedirect",
"modularizeImports",
];
const ELIMINATED_PACKAGES = new Set();
/**
* Determine if there is a feature of interest in the specified 'module'.
*/ function findFeatureInModule(module) {
if (module.type !== "javascript/auto") {
return;
}
const normalizedIdentifier = module.identifier().replace(/\\/g, "/");
for (const [feature, path] of FEATURE_MODULE_MAP){
if (normalizedIdentifier.endsWith(path)) {
return feature;
}
}
for (const [feature1, regexp] of FEATURE_MODULE_REGEXP_MAP){
if (regexp.test(normalizedIdentifier)) {
return feature1;
}
}
}
/**
* Find unique origin modules in the specified 'connections', which possibly
* contains more than one connection for a module due to different types of
* dependency.
*/ function findUniqueOriginModulesInConnections(connections, originModule) {
const originModules = new Set();
for (const connection of connections){
if (!originModules.has(connection.originModule) && connection.originModule !== originModule) {
originModules.add(connection.originModule);
}
}
return originModules;
}
/**
* Plugin that queries the ModuleGraph to look for modules that correspond to
* certain features (e.g. next/image and next/script) and record how many times
* they are imported.
*/ export class TelemetryPlugin {
usageTracker = new Map();
// Build feature usage is on/off and is known before the build starts
constructor(buildFeaturesMap){
for (const featureName of BUILD_FEATURES){
this.usageTracker.set(featureName, {
featureName,
invocationCount: buildFeaturesMap.get(featureName) ? 1 : 0
});
}
for (const featureName1 of FEATURE_MODULE_MAP.keys()){
this.usageTracker.set(featureName1, {
featureName: featureName1,
invocationCount: 0
});
}
for (const featureName2 of FEATURE_MODULE_REGEXP_MAP.keys()){
this.usageTracker.set(featureName2, {
featureName: featureName2,
invocationCount: 0
});
}
}
apply(compiler) {
compiler.hooks.make.tapAsync(TelemetryPlugin.name, async (compilation, callback)=>{
compilation.hooks.finishModules.tapAsync(TelemetryPlugin.name, async (modules, modulesFinish)=>{
for (const module of modules){
const feature = findFeatureInModule(module);
if (!feature) {
continue;
}
const connections = compilation.moduleGraph.getIncomingConnections(module);
const originModules = findUniqueOriginModulesInConnections(connections, module);
this.usageTracker.get(feature).invocationCount = originModules.size;
}
modulesFinish();
});
callback();
});
if (compiler.options.mode === "production" && !compiler.watchMode) {
compiler.hooks.compilation.tap(TelemetryPlugin.name, (compilation)=>{
const moduleHooks = NormalModule.getCompilationHooks(compilation);
moduleHooks.loader.tap(TelemetryPlugin.name, (loaderContext)=>{
loaderContext.eliminatedPackages = ELIMINATED_PACKAGES;
});
});
}
}
usages() {
return [
...this.usageTracker.values()
];
}
packagesUsedInServerSideProps() {
return Array.from(ELIMINATED_PACKAGES);
}
}
//# sourceMappingURL=telemetry-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/plugins/telemetry-plugin.ts"],"names":["NormalModule","FEATURE_MODULE_MAP","Map","FEATURE_MODULE_REGEXP_MAP","BUILD_FEATURES","ELIMINATED_PACKAGES","Set","findFeatureInModule","module","type","normalizedIdentifier","identifier","replace","feature","path","endsWith","regexp","test","findUniqueOriginModulesInConnections","connections","originModule","originModules","connection","has","add","TelemetryPlugin","usageTracker","constructor","buildFeaturesMap","featureName","set","invocationCount","get","keys","apply","compiler","hooks","make","tapAsync","name","compilation","callback","finishModules","modules","modulesFinish","moduleGraph","getIncomingConnections","size","options","mode","watchMode","tap","moduleHooks","getCompilationHooks","loader","loaderContext","eliminatedPackages","usages","values","packagesUsedInServerSideProps","Array","from"],"mappings":"AAAA,SAASA,YAAY,QAAiB,oCAAoC,CAAA;AAgE1E,sEAAsE;AACtE,MAAMC,kBAAkB,GAAiC,IAAIC,GAAG,CAAC;IAC/D;QAAC,YAAY;QAAE,gBAAgB;KAAC;IAChC;QAAC,mBAAmB;QAAE,uBAAuB;KAAC;IAC9C;QAAC,mBAAmB;QAAE,u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;KACvC;CACF"}

View File

@@ -0,0 +1,223 @@
// @ts-nocheck
import * as path from "path";
import { webpack, ModuleFilenameHelpers, sources } from "next/dist/compiled/webpack/webpack";
import pLimit from "next/dist/compiled/p-limit";
import { Worker } from "next/dist/compiled/jest-worker";
import { spans } from "../../profiling-plugin";
function getEcmaVersion(environment) {
// ES 6th
if (environment.arrowFunction || environment.const || environment.destructuring || environment.forOf || environment.module) {
return 2015;
}
// ES 11th
if (environment.bigIntLiteral || environment.dynamicImport) {
return 2020;
}
return 5;
}
function buildError(error, file) {
if (error.line) {
return new Error(`${file} from Terser\n${error.message} [${file}:${error.line},${error.col}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`);
}
if (error.stack) {
return new Error(`${file} from Terser\n${error.message}\n${error.stack}`);
}
return new Error(`${file} from Terser\n${error.message}`);
}
const debugMinify = process.env.NEXT_DEBUG_MINIFY;
export class TerserPlugin {
constructor(options = {}){
const { terserOptions ={} , parallel , swcMinify } = options;
this.options = {
swcMinify,
parallel,
terserOptions
};
}
async optimize(compiler, compilation, assets, optimizeOptions, cache, { SourceMapSource , RawSource }) {
const compilationSpan = spans.get(compilation) || spans.get(compiler);
const terserSpan = compilationSpan.traceChild("terser-webpack-plugin-optimize");
terserSpan.setAttribute("compilationName", compilation.name);
terserSpan.setAttribute("swcMinify", this.options.swcMinify);
return terserSpan.traceAsyncFn(async ()=>{
let numberOfAssetsForMinify = 0;
const assetsList = Object.keys(assets);
const assetsForMinify = await Promise.all(assetsList.filter((name)=>{
if (!ModuleFilenameHelpers.matchObject.bind(// eslint-disable-next-line no-undefined
undefined, {
test: /\.[cm]?js(\?.*)?$/i
})(name)) {
return false;
}
const res = compilation.getAsset(name);
if (!res) {
console.log(name);
return false;
}
// don't minify _middleware as it can break in some cases
// and doesn't provide too much of a benefit as it's server-side
if (name.match(/(edge-runtime-webpack\.js|edge-chunks|middleware\.js$)/)) {
return false;
}
const { info } = res;
// Skip double minimize assets from child compilation
if (info.minimized) {
return false;
}
return true;
}).map(async (name)=>{
const { info , source } = compilation.getAsset(name);
const eTag = cache.getLazyHashedEtag(source);
const output = await cache.getPromise(name, eTag);
if (!output) {
numberOfAssetsForMinify += 1;
}
if (debugMinify && debugMinify === "1") {
console.dir({
name,
source: source.source().toString()
}, {
breakLength: Infinity,
maxStringLength: Infinity
});
}
return {
name,
info,
inputSource: source,
output,
eTag
};
}));
const numberOfWorkers = Math.min(numberOfAssetsForMinify, optimizeOptions.availableNumberOfCores);
let initializedWorker;
// eslint-disable-next-line consistent-return
const getWorker = ()=>{
if (this.options.swcMinify) {
return {
minify: async (options)=>{
const result = await require("../../../../swc").minify(options.input, {
...options.inputSourceMap ? {
sourceMap: {
content: JSON.stringify(options.inputSourceMap)
}
} : {},
compress: true,
mangle: true
});
return result;
}
};
}
if (initializedWorker) {
return initializedWorker;
}
initializedWorker = new Worker(path.join(__dirname, "./minify.js"), {
numWorkers: numberOfWorkers,
enableWorkerThreads: true
});
initializedWorker.getStdout().pipe(process.stdout);
initializedWorker.getStderr().pipe(process.stderr);
return initializedWorker;
};
const limit = pLimit(// When using the SWC minifier the limit will be handled by Node.js
this.options.swcMinify ? Infinity : numberOfAssetsForMinify > 0 ? numberOfWorkers : Infinity);
const scheduledTasks = [];
for (const asset of assetsForMinify){
scheduledTasks.push(limit(async ()=>{
const { name , inputSource , info , eTag } = asset;
let { output } = asset;
const minifySpan = terserSpan.traceChild("minify-js");
minifySpan.setAttribute("name", name);
minifySpan.setAttribute("cache", typeof output === "undefined" ? "MISS" : "HIT");
return minifySpan.traceAsyncFn(async ()=>{
if (!output) {
const { source: sourceFromInputSource , map: inputSourceMap } = inputSource.sourceAndMap();
const input = Buffer.isBuffer(sourceFromInputSource) ? sourceFromInputSource.toString() : sourceFromInputSource;
const options = {
name,
input,
inputSourceMap,
terserOptions: {
...this.options.terserOptions
}
};
if (typeof options.terserOptions.module === "undefined") {
if (typeof info.javascriptModule !== "undefined") {
options.terserOptions.module = info.javascriptModule;
} else if (/\.mjs(\?.*)?$/i.test(name)) {
options.terserOptions.module = true;
} else if (/\.cjs(\?.*)?$/i.test(name)) {
options.terserOptions.module = false;
}
}
try {
output = await getWorker().minify(options);
} catch (error) {
compilation.errors.push(buildError(error, name));
return;
}
if (output.map) {
output.source = new SourceMapSource(output.code, name, output.map, input, /** @type {SourceMapRawSourceMap} */ (inputSourceMap), true);
} else {
output.source = new RawSource(output.code);
}
await cache.storePromise(name, eTag, {
source: output.source
});
}
/** @type {AssetInfo} */ const newInfo = {
minimized: true
};
const { source } = output;
compilation.updateAsset(name, source, newInfo);
});
}));
}
await Promise.all(scheduledTasks);
if (initializedWorker) {
await initializedWorker.end();
}
});
}
/**
* @param {Compiler} compiler
* @returns {void}
*/ apply(compiler) {
var ref;
const { SourceMapSource , RawSource } = (compiler == null ? void 0 : (ref = compiler.webpack) == null ? void 0 : ref.sources) || sources;
const { output } = compiler.options;
if (typeof this.options.terserOptions.ecma === "undefined") {
this.options.terserOptions.ecma = getEcmaVersion(output.environment || {});
}
const pluginName = this.constructor.name;
const availableNumberOfCores = this.options.parallel;
compiler.hooks.thisCompilation.tap(pluginName, (compilation)=>{
const cache = compilation.getCache("TerserWebpackPlugin");
const handleHashForChunk = (hash, chunk)=>{
// increment 'c' to invalidate cache
hash.update("c");
};
const JSModulesHooks = webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
JSModulesHooks.chunkHash.tap(pluginName, (chunk, hash)=>{
if (!chunk.hasRuntime()) return;
return handleHashForChunk(hash, chunk);
});
compilation.hooks.processAssets.tapPromise({
name: pluginName,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE
}, (assets)=>this.optimize(compiler, compilation, assets, {
availableNumberOfCores
}, cache, {
SourceMapSource,
RawSource
}));
compilation.hooks.statsPrinter.tap(pluginName, (stats)=>{
stats.hooks.print.for("asset.info.minimized").tap("terser-webpack-plugin", (minimized, { green , formatFlag })=>// eslint-disable-next-line no-undefined
minimized ? green(formatFlag("minimized")) : undefined);
});
});
}
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,43 @@
// @ts-nocheck
import terser from "next/dist/compiled/terser";
function buildTerserOptions(terserOptions = {}) {
return {
...terserOptions,
mangle: terserOptions.mangle == null ? true : typeof terserOptions.mangle === "boolean" ? terserOptions.mangle : {
...terserOptions.mangle
},
// Ignoring sourceMap from options
// eslint-disable-next-line no-undefined
sourceMap: undefined,
// the `output` option is deprecated
...terserOptions.format ? {
format: {
beautify: false,
...terserOptions.format
}
} : {
output: {
beautify: false,
...terserOptions.output
}
}
};
}
export async function minify(options) {
const { name , input , inputSourceMap , terserOptions } = options;
// Copy terser options
const opts = buildTerserOptions(terserOptions);
// Let terser generate a SourceMap
if (inputSourceMap) {
// @ts-ignore
opts.sourceMap = {
asObject: true
};
}
const result = await terser.minify({
[name]: input
}, opts);
return result;
}
//# sourceMappingURL=minify.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/plugins/terser-webpack-plugin/src/minify.js"],"names":["terser","buildTerserOptions","terserOptions","mangle","sourceMap","undefined","format","beautify","output","minify","options","name","input","inputSourceMap","opts","asObject","result"],"mappings":"AAAA,cAAc;AACd,OAAOA,MAAM,MAAM,2BAA2B,CAAA;AAE9C,SAASC,kBAAkB,CAACC,aAAa,GAAG,EAAE,EAAE;IAC9C,OAAO;QACL,GAAGA,aAAa;QAChBC,MAAM,EACJD,aAAa,CAACC,MAAM,IAAI,IAAI,GACxB,IAAI,GACJ,OAAOD,aAAa,CAACC,MAAM,KAAK,SAAS,GACzCD,aAAa,CAACC,MAAM,GACpB;YAAE,GAAGD,aAAa,CAACC,MAAM;SAAE;QACjC,kCAAkC;QAClC,wCAAwC;QACxCC,SAAS,EAAEC,SAAS;QACpB,oCAAoC;QACpC,GAAIH,aAAa,CAACI,MAAM,GACpB;YAAEA,MAAM,EAAE;gBAAEC,QAAQ,EAAE,KAAK;gBAAE,GAAGL,aAAa,CAACI,MAAM;aAAE;SAAE,GACxD;YAAEE,MAAM,EAAE;gBAAED,QAAQ,EAAE,KAAK;gBAAE,GAAGL,aAAa,CAACM,MAAM;aAAE;SAAE;KAC7D,CAAA;CACF;AAED,OAAO,eAAeC,MAAM,CAACC,OAAO,EAAE;IACpC,MAAM,EAAEC,IAAI,CAAA,EAAEC,KAAK,CAAA,EAAEC,cAAc,CAAA,EAAEX,aAAa,CAAA,EAAE,GAAGQ,OAAO;IAC9D,sBAAsB;IACtB,MAAMI,IAAI,GAAGb,kBAAkB,CAACC,aAAa,CAAC;IAE9C,kCAAkC;IAClC,IAAIW,cAAc,EAAE;QAClB,aAAa;QACbC,IAAI,CAACV,SAAS,GAAG;YAAEW,QAAQ,EAAE,IAAI;SAAE;KACpC;IAED,MAAMC,MAAM,GAAG,MAAMhB,MAAM,CAACS,MAAM,CAAC;QAAE,CAACE,IAAI,CAAC,EAAEC,KAAK;KAAE,EAAEE,IAAI,CAAC;IAC3D,OAAOE,MAAM,CAAA;CACd"}

View File

@@ -0,0 +1,25 @@
import { getModuleBuildError } from "./webpackModuleError";
const NAME = "WellKnownErrorsPlugin";
export class WellKnownErrorsPlugin {
apply(compiler) {
compiler.hooks.compilation.tap(NAME, (compilation)=>{
compilation.hooks.afterSeal.tapPromise(NAME, async ()=>{
var ref;
if ((ref = compilation.errors) == null ? void 0 : ref.length) {
await Promise.all(compilation.errors.map(async (err, i)=>{
try {
const moduleError = await getModuleBuildError(compiler, compilation, err);
if (moduleError !== false) {
compilation.errors[i] = moduleError;
}
} catch (e) {
console.log(e);
}
}));
}
});
});
}
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/plugins/wellknown-errors-plugin/index.ts"],"names":["getModuleBuildError","NAME","WellKnownErrorsPlugin","apply","compiler","hooks","compilation","tap","afterSeal","tapPromise","errors","length","Promise","all","map","err","i","moduleError","e","console","log"],"mappings":"AAEA,SAASA,mBAAmB,QAAQ,sBAAsB,CAAA;AAE1D,MAAMC,IAAI,GAAG,uBAAuB;AACpC,OAAO,MAAMC,qBAAqB;IAChCC,KAAK,CAACC,QAA0B,EAAE;QAChCA,QAAQ,CAACC,KAAK,CAACC,WAAW,CAACC,GAAG,CAACN,IAAI,EAAE,CAACK,WAAW,GAAK;YACpDA,WAAW,CAACD,KAAK,CAACG,SAAS,CAACC,UAAU,CAACR,IAAI,EAAE,UAAY;oBACnDK,GAAkB;gBAAtB,IAAIA,CAAAA,GAAkB,GAAlBA,WAAW,CAACI,MAAM,SAAQ,GAA1BJ,KAAAA,CAA0B,GAA1BA,GAAkB,CAAEK,MAAM,EAAE;oBAC9B,MAAMC,OAAO,CAACC,GAAG,CACfP,WAAW,CAACI,MAAM,CAACI,GAAG,CAAC,OAAOC,GAAG,EAAEC,CAAC,GAAK;wBACvC,IAAI;4BACF,MAAMC,WAAW,GAAG,MAAMjB,mBAAmB,CAC3CI,QAAQ,EACRE,WAAW,EACXS,GAAG,CACJ;4BACD,IAAIE,WAAW,KAAK,KAAK,EAAE;gCACzBX,WAAW,CAACI,MAAM,CAACM,CAAC,CAAC,GAAGC,WAAW;6BACpC;yBACF,CAAC,OAAOC,CAAC,EAAE;4BACVC,OAAO,CAACC,GAAG,CAACF,CAAC,CAAC;yBACf;qBACF,CAAC,CACH;iBACF;aACF,CAAC;SACH,CAAC;KACH;CACF"}

View File

@@ -0,0 +1,22 @@
import Chalk from "next/dist/compiled/chalk";
import { SimpleWebpackError } from "./simpleWebpackError";
const chalk = new Chalk.constructor({
enabled: true
});
export function getBabelError(fileName, err) {
if (err.code !== "BABEL_PARSE_ERROR") {
return false;
}
// https://github.com/babel/babel/blob/34693d6024da3f026534dd8d569f97ac0109602e/packages/babel-core/src/parser/index.js
if (err.loc) {
const lineNumber = Math.max(1, err.loc.line);
const column = Math.max(1, err.loc.column);
let message = err.message// Remove file information, which instead is provided by webpack.
.replace(/^.+?: /, "")// Remove column information from message
.replace(new RegExp(`[^\\S\\r\\n]*\\(${lineNumber}:${column}\\)[^\\S\\r\\n]*`), "");
return new SimpleWebpackError(`${chalk.cyan(fileName)}:${chalk.yellow(lineNumber.toString())}:${chalk.yellow(column.toString())}`, chalk.red.bold("Syntax error").concat(`: ${message}`));
}
return false;
}
//# sourceMappingURL=parseBabel.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/plugins/wellknown-errors-plugin/parseBabel.ts"],"names":["Chalk","SimpleWebpackError","chalk","constructor","enabled","getBabelError","fileName","err","code","loc","lineNumber","Math","max","line","column","message","replace","RegExp","cyan","yellow","toString","red","bold","concat"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAC5C,SAASC,kBAAkB,QAAQ,sBAAsB,CAAA;AAEzD,MAAMC,KAAK,GAAG,IAAIF,KAAK,CAACG,WAAW,CAAC;IAAEC,OAAO,EAAE,IAAI;CAAE,CAAC;AAEtD,OAAO,SAASC,aAAa,CAC3BC,QAAgB,EAChBC,GAGC,EAC2B;IAC5B,IAAIA,GAAG,CAACC,IAAI,KAAK,mBAAmB,EAAE;QACpC,OAAO,KAAK,CAAA;KACb;IAED,uHAAuH;IACvH,IAAID,GAAG,CAACE,GAAG,EAAE;QACX,MAAMC,UAAU,GAAGC,IAAI,CAACC,GAAG,CAAC,CAAC,EAAEL,GAAG,CAACE,GAAG,CAACI,IAAI,CAAC;QAC5C,MAAMC,MAAM,GAAGH,IAAI,CAACC,GAAG,CAAC,CAAC,EAAEL,GAAG,CAACE,GAAG,CAACK,MAAM,CAAC;QAE1C,IAAIC,OAAO,GAAGR,GAAG,CAACQ,OAAO,AACvB,iEAAiE;SAChEC,OAAO,WAAW,EAAE,CAAC,AACtB,yCAAyC;SACxCA,OAAO,CACN,IAAIC,MAAM,CAAC,CAAC,gBAAgB,EAAEP,UAAU,CAAC,CAAC,EAAEI,MAAM,CAAC,gBAAgB,CAAC,CAAC,EACrE,EAAE,CACH;QAEH,OAAO,IAAIb,kBAAkB,CAC3B,CAAC,EAAEC,KAAK,CAACgB,IAAI,CAACZ,QAAQ,CAAC,CAAC,CAAC,EAAEJ,KAAK,CAACiB,MAAM,CACrCT,UAAU,CAACU,QAAQ,EAAE,CACtB,CAAC,CAAC,EAAElB,KAAK,CAACiB,MAAM,CAACL,MAAM,CAACM,QAAQ,EAAE,CAAC,CAAC,CAAC,EACtClB,KAAK,CAACmB,GAAG,CAACC,IAAI,CAAC,cAAc,CAAC,CAACC,MAAM,CAAC,CAAC,EAAE,EAAER,OAAO,CAAC,CAAC,CAAC,CACtD,CAAA;KACF;IAED,OAAO,KAAK,CAAA;CACb"}

View File

@@ -0,0 +1,22 @@
import Chalk from "next/dist/compiled/chalk";
import { SimpleWebpackError } from "./simpleWebpackError";
const chalk = new Chalk.constructor({
enabled: true
});
const regexCssError = /^(?:CssSyntaxError|SyntaxError)\n\n\((\d+):(\d*)\) (.*)$/s;
export function getCssError(fileName, err) {
if (!((err.name === "CssSyntaxError" || err.name === "SyntaxError") && err.stack === false && !(err instanceof SyntaxError))) {
return false;
}
// https://github.com/postcss/postcss-loader/blob/d6931da177ac79707bd758436e476036a55e4f59/src/Error.js
const res = regexCssError.exec(err.message);
if (res) {
const [, _lineNumber, _column, reason] = res;
const lineNumber = Math.max(1, parseInt(_lineNumber, 10));
const column = Math.max(1, parseInt(_column, 10));
return new SimpleWebpackError(`${chalk.cyan(fileName)}:${chalk.yellow(lineNumber.toString())}:${chalk.yellow(column.toString())}`, chalk.red.bold("Syntax error").concat(`: ${reason}`));
}
return false;
}
//# sourceMappingURL=parseCss.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/plugins/wellknown-errors-plugin/parseCss.ts"],"names":["Chalk","SimpleWebpackError","chalk","constructor","enabled","regexCssError","getCssError","fileName","err","name","stack","SyntaxError","res","exec","message","_lineNumber","_column","reason","lineNumber","Math","max","parseInt","column","cyan","yellow","toString","red","bold","concat"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;A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ACrD,CAAA;KACF;IAED,OAAO,KAAK,CAAA;CACb"}

View File

@@ -0,0 +1,33 @@
import { SimpleWebpackError } from "./simpleWebpackError";
export function getNextFontError(err, module) {
try {
const resourceResolveData = module.resourceResolveData;
if (resourceResolveData.descriptionFileData.name !== "@next/font") {
return false;
}
// Parse the query and get the path of the file where the font function was called.
// provided by next-swc next_font_loaders
const file = JSON.parse(resourceResolveData.query.slice(1)).path;
if (err.name === "NextFontError") {
// Known error thrown by @next/font, display the error message
return new SimpleWebpackError(file, `\`@next/font\` error:\n${err.message}`);
} else {
// Unknown error thrown by @next/font
// It might be becuase of incompatible versions of @next/font and next are being used, or it might be a bug
// eslint-disable-next-line import/no-extraneous-dependencies
const nextFontVersion = require("@next/font/package.json").version;
const nextVersion = require("next/package.json").version;
let message = `An error occured in \`@next/font\`.`;
// Using different versions of @next/font and next, add message that it's possibly fixed by updating both
if (nextFontVersion !== nextVersion) {
message += `\n\nYou might be using incompatible version of \`@next/font\` (${nextFontVersion}) and \`next\` (${nextVersion}). Try updating both \`@next/font\` and \`next\`, if the error still persists it may be a bug.`;
}
message += `\n\n${err.stack}`;
return new SimpleWebpackError(file, message);
}
} catch {
return false;
}
}
//# sourceMappingURL=parseNextFontError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/plugins/wellknown-errors-plugin/parseNextFontError.ts"],"names":["SimpleWebpackError","getNextFontError","err","module","resourceResolveData","descriptionFileData","name","file","JSON","parse","query","slice","path","message","nextFontVersion","require","version","nextVersion","stack"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,sBAAsB,CAAA;AAEzD,OAAO,SAASC,gBAAgB,CAC9BC,GAAU,EACVC,MAAW,EACiB;IAC5B,IAAI;QACF,MAAMC,mBAAmB,GAAGD,MAAM,CAACC,mBAAmB;QACtD,IAAIA,mBAAmB,CAACC,mBAAmB,CAACC,IAAI,KAAK,YAAY,EAAE;YACjE,OAAO,KAAK,CAAA;SACb;QAED,mFAAmF;QACnF,yCAAyC;QACzC,MAAMC,IAAI,GAAGC,IAAI,CAACC,KAAK,CAACL,mBAAmB,CAACM,KAAK,CAACC,KAAK,CAAC,CAAC,CAAC,CAAC,CAACC,IAAI;QAEhE,IAAIV,GAAG,CAACI,IAAI,KAAK,eAAe,EAAE;YAChC,8DAA8D;YAC9D,OAAO,IAAIN,kBAAkB,CAC3BO,IAAI,EACJ,CAAC,uBAAuB,EAAEL,GAAG,CAACW,OAAO,CAAC,CAAC,CACxC,CAAA;SACF,MAAM;YACL,qCAAqC;YACrC,2GAA2G;YAE3G,6DAA6D;YAC7D,MAAMC,eAAe,GAAGC,OAAO,CAAC,yBAAyB,CAAC,CAACC,OAAO;YAClE,MAAMC,WAAW,GAAGF,OAAO,CAAC,mBAAmB,CAAC,CAACC,OAAO;YAExD,IAAIH,OAAO,GAAG,CAAC,mCAAmC,CAAC;YAEnD,yGAAyG;YACzG,IAAIC,eAAe,KAAKG,WAAW,EAAE;gBACnCJ,OAAO,IAAI,CAAC,+DAA+D,EAAEC,eAAe,CAAC,gBAAgB,EAAEG,WAAW,CAAC,8FAA8F,CAAC;aAC3N;YAEDJ,OAAO,IAAI,CAAC,IAAI,EAAEX,GAAG,CAACgB,KAAK,CAAC,CAAC;YAE7B,OAAO,IAAIlB,kBAAkB,CAACO,IAAI,EAAEM,OAAO,CAAC,CAAA;SAC7C;KACF,CAAC,OAAM;QACN,OAAO,KAAK,CAAA;KACb;CACF"}

View File

@@ -0,0 +1,101 @@
import Chalk from "next/dist/compiled/chalk";
import { SimpleWebpackError } from "./simpleWebpackError";
import { createOriginalStackFrame } from "next/dist/compiled/@next/react-dev-overlay/dist/middleware";
const chalk = new Chalk.constructor({
enabled: true
});
// Based on https://github.com/webpack/webpack/blob/fcdd04a833943394bbb0a9eeb54a962a24cc7e41/lib/stats/DefaultStatsFactoryPlugin.js#L422-L431
/*
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ function getModuleTrace(input, compilation) {
const visitedModules = new Set();
const moduleTrace = [];
let current = input.module;
while(current){
if (visitedModules.has(current)) break; // circular (technically impossible, but who knows)
visitedModules.add(current);
const origin = compilation.moduleGraph.getIssuer(current);
if (!origin) break;
moduleTrace.push({
origin,
module: current
});
current = origin;
}
return moduleTrace;
}
export async function getNotFoundError(compilation, input, fileName) {
if (input.name !== "ModuleNotFoundError") {
return false;
}
const loc = input.loc ? input.loc : input.dependencies.map((d)=>d.loc).filter(Boolean)[0];
const originalSource = input.module.originalSource();
try {
var ref, ref1;
const result = await createOriginalStackFrame({
line: loc.start.line,
column: loc.start.column,
source: originalSource,
rootDirectory: compilation.options.context,
modulePath: fileName,
frame: {}
});
// If we could not result the original location we still need to show the existing error
if (!result) {
return input;
}
const errorMessage = input.error.message.replace(/ in '.*?'/, "").replace(/Can't resolve '(.*)'/, `Can't resolve '${chalk.green("$1")}'`);
const importTrace = ()=>{
const moduleTrace = getModuleTrace(input, compilation).map(({ origin })=>origin.readableIdentifier(compilation.requestShortener)).filter((name)=>name && !/next-(middleware|client-pages|flight-(client|server|client-entry))-loader\.js/.test(name));
if (moduleTrace.length === 0) return "";
return `\nImport trace for requested module:\n${moduleTrace.join("\n")}\n\n`;
};
const frame = result.originalCodeFrame ?? "";
let message = chalk.red.bold("Module not found") + `: ${errorMessage}` + "\n" + frame + (frame !== "" ? "\n" : "") + importTrace() + "\nhttps://nextjs.org/docs/messages/module-not-found";
return new SimpleWebpackError(`${chalk.cyan(fileName)}:${chalk.yellow(((ref = result.originalStackFrame.lineNumber) == null ? void 0 : ref.toString()) ?? "")}:${chalk.yellow(((ref1 = result.originalStackFrame.column) == null ? void 0 : ref1.toString()) ?? "")}`, message);
} catch (err) {
// Don't fail on failure to resolve sourcemaps
return input;
}
}
export async function getImageError(compilation, input, err) {
if (err.name !== "InvalidImageFormatError") {
return false;
}
const moduleTrace = getModuleTrace(input, compilation);
const { origin , module } = moduleTrace[0] || {};
if (!origin || !module) {
return false;
}
const page = origin.rawRequest.replace(/^private-next-pages/, "./pages");
const importedFile = module.rawRequest;
const source = origin.originalSource().buffer().toString("utf8");
let lineNumber = -1;
source.split("\n").some((line)=>{
lineNumber++;
return line.includes(importedFile);
});
return new SimpleWebpackError(`${chalk.cyan(page)}:${chalk.yellow(lineNumber.toString())}`, chalk.red.bold("Error").concat(`: Image import "${importedFile}" is not a valid image file. The image may be corrupted or an unsupported format.`));
}
//# sourceMappingURL=parseNotFoundError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts"],"names":["Chalk","SimpleWebpackError","createOriginalStackFrame","chalk","constructor","enabled","getModuleTrace","input","compilation","visitedModules","Set","moduleTrace","current","module","has","add","origin","moduleGraph","getIssuer","push","getNotFoundError","fileName","name","loc","dependencies","map","d","filter","Boolean","originalSource","result","line","start","column","source","rootDirectory","options","context","modulePath","frame","errorMessage","error","message","replace","green","importTrace","readableIdentifier","requestShortener","test","length","join","originalCodeFrame","red","bold","cyan","yellow","originalStackFrame","lineNumber","toString","err","getImageError","page","rawRequest","importedFile","buffer","split","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AMgD,IAAI,GAAG7C,MAAM,CAAC8C,UAAU,CAACnB,OAAO,wBAAwB,SAAS,CAAC;IACxE,MAAMoB,YAAY,GAAGlD,MAAM,CAACiD,UAAU;IACtC,MAAM5B,MAAM,GAAGlB,MAAM,CAACa,cAAc,EAAE,CAACmC,MAAM,EAAE,CAACN,QAAQ,CAAC,MAAM,CAAC,AAAU;IAC1E,IAAID,UAAU,GAAG,CAAC,CAAC;IACnBvB,MAAM,CAAC+B,KAAK,CAAC,IAAI,CAAC,CAACC,IAAI,CAAC,CAACnC,IAAI,GAAK;QAChC0B,UAAU,EAAE;QACZ,OAAO1B,IAAI,CAACoC,QAAQ,CAACJ,YAAY,CAAC,CAAA;KACnC,CAAC;IACF,OAAO,IAAI9D,kBAAkB,CAC3B,CAAC,EAAEE,KAAK,CAACmD,IAAI,CAACO,IAAI,CAAC,CAAC,CAAC,EAAE1D,KAAK,CAACoD,MAAM,CAACE,UAAU,CAACC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAC5DvD,KAAK,CAACiD,GAAG,CACNC,IAAI,CAAC,OAAO,CAAC,CACbe,MAAM,CACL,CAAC,gBAAgB,EAAEL,YAAY,CAAC,iFAAiF,CAAC,CACnH,CACJ,CAAA;CACF"}

View File

@@ -0,0 +1,77 @@
import { relative } from "path";
import { SimpleWebpackError } from "./simpleWebpackError";
function formatRSCErrorMessage(message) {
if (message && /NEXT_RSC_ERR_/.test(message)) {
let formattedMessage = message;
let formattedVerboseMessage = "";
// Comes from the "React Server Components" transform in SWC, always
// attach the module trace.
const NEXT_RSC_ERR_REACT_API = /.+NEXT_RSC_ERR_REACT_API: (.*?)\n/s;
const NEXT_RSC_ERR_SERVER_IMPORT = /.+NEXT_RSC_ERR_SERVER_IMPORT: (.*?)\n/s;
const NEXT_RSC_ERR_CLIENT_IMPORT = /.+NEXT_RSC_ERR_CLIENT_IMPORT: (.*?)\n/s;
const NEXT_RSC_ERR_CLIENT_DIRECTIVE = /.+NEXT_RSC_ERR_CLIENT_DIRECTIVE\n/s;
const NEXT_RSC_ERR_CLIENT_DIRECTIVE_PAREN = /.+NEXT_RSC_ERR_CLIENT_DIRECTIVE_PAREN\n/s;
const NEXT_RSC_ERR_INVALID_API = /.+NEXT_RSC_ERR_INVALID_API: (.*?)\n/s;
if (NEXT_RSC_ERR_REACT_API.test(message)) {
formattedMessage = message.replace(NEXT_RSC_ERR_REACT_API, `\n\nYou're importing a component that needs $1. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.\n\n`);
formattedVerboseMessage = '\n\nMaybe one of these should be marked as a client entry with "use client":\n';
} else if (NEXT_RSC_ERR_SERVER_IMPORT.test(message)) {
const matches = message.match(NEXT_RSC_ERR_SERVER_IMPORT);
switch(matches && matches[1]){
case "react-dom/server":
// If importing "react-dom/server", we should show a different error.
formattedMessage = `\n\nYou're importing a component that imports react-dom/server. To fix it, render or return the content directly as a Server Component instead for perf and security.`;
break;
case "next/router":
// If importing "next/router", we should tell them to use "next/navigation".
formattedMessage = `\n\nYou have a Server Component that imports next/router. Use next/navigation instead.`;
break;
default:
formattedMessage = message.replace(NEXT_RSC_ERR_SERVER_IMPORT, `\n\nYou're importing a component that imports $1. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.\n\n`);
}
formattedVerboseMessage = '\n\nMaybe one of these should be marked as a client entry "use client":\n';
} else if (NEXT_RSC_ERR_CLIENT_IMPORT.test(message)) {
formattedMessage = message.replace(NEXT_RSC_ERR_CLIENT_IMPORT, `\n\nYou're importing a component that needs $1. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.\n\n`);
formattedVerboseMessage = '\n\nOne of these is marked as a client entry with "use client":\n';
} else if (NEXT_RSC_ERR_CLIENT_DIRECTIVE.test(message)) {
formattedMessage = message.replace(NEXT_RSC_ERR_CLIENT_DIRECTIVE, `\n\nThe "use client" directive must be placed before other expressions. Move it to the top of the file to resolve this issue.\n\n`);
formattedVerboseMessage = "\n\nImport path:\n";
} else if (NEXT_RSC_ERR_CLIENT_DIRECTIVE_PAREN.test(message)) {
formattedMessage = message.replace(NEXT_RSC_ERR_CLIENT_DIRECTIVE_PAREN, `\n\n"use client" must be a directive, and placed before other expressions. Remove the parentheses and move it to the top of the file to resolve this issue.\n\n`);
formattedVerboseMessage = "\n\nImport path:\n";
} else if (NEXT_RSC_ERR_INVALID_API.test(message)) {
formattedMessage = message.replace(NEXT_RSC_ERR_INVALID_API, `\n\n"$1" is not supported in app/. Read more: https://beta.nextjs.org/docs/data-fetching/fundamentals\n\n`);
formattedVerboseMessage = "\n\nFile path:\n";
}
return [
formattedMessage,
formattedVerboseMessage
];
}
return null;
}
// Check if the error is specifically related to React Server Components.
// If so, we'll format the error message to be more helpful.
export function getRscError(fileName, err, module, compilation, compiler) {
const formattedError = formatRSCErrorMessage(err.message);
if (!formattedError) return false;
// Get the module trace:
// https://cs.github.com/webpack/webpack/blob/9fcaa243573005d6fdece9a3f8d89a0e8b399613/lib/stats/DefaultStatsFactoryPlugin.js#L414
const visitedModules = new Set();
const moduleTrace = [];
let current = module;
while(current){
if (visitedModules.has(current)) break;
visitedModules.add(current);
moduleTrace.push(current);
const origin = compilation.moduleGraph.getIssuer(current);
if (!origin) break;
current = origin;
}
const error = new SimpleWebpackError(fileName, formattedError[0] + formattedError[1] + moduleTrace.map((m)=>m.resource ? " " + relative(compiler.context, m.resource).replace(/\?.+$/, "") : "").filter(Boolean).join("\n"));
// Delete the stack because it's created here.
error.stack = "";
return error;
}
//# sourceMappingURL=parseRSC.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/plugins/wellknown-errors-plugin/parseRSC.ts"],"names":["relative","SimpleWebpackError","formatRSCErrorMessage","message","test","formattedMessage","formattedVerboseMessage","NEXT_RSC_ERR_REACT_API","NEXT_RSC_ERR_SERVER_IMPORT","NEXT_RSC_ERR_CLIENT_IMPORT","NEXT_RSC_ERR_CLIENT_DIRECTIVE","NEXT_RSC_ERR_CLIENT_DIRECTIVE_PAREN","NEXT_RSC_ERR_INVALID_API","replace","matches","match","getRscError","fileName","err","module","compilation","compiler","formattedError","visitedModules","Set","moduleTrace","current","has","add","push","origin","moduleGraph","getIssuer","error","map","m","resource","context","filter","Boolean","join","stack"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,MAAM,CAAA;AAC/B,SAASC,kBAAkB,QAAQ,sBAAsB,CAAA;AAEzD,SAASC,qBAAqB,CAACC,OAAe,EAA2B;IACvE,IAAIA,OAAO,IAAI,gBAAgBC,IAAI,CAACD,OAAO,CAAC,EAAE;QAC5C,IAAIE,gBAAgB,GAAGF,OAAO;QAC9B,IAAIG,uBAAuB,GAAG,EAAE;QAEhC,oEAAoE;QACpE,2BAA2B;QAC3B,MAAMC,sBAAsB,uCAAuC;QACnE,MAAMC,0BAA0B,2CAA2C;QAC3E,MAAMC,0BAA0B,2CAA2C;QAC3E,MAAMC,6BAA6B,uCAAuC;QAC1E,MAAMC,mCAAmC,6CACG;QAC5C,MAAMC,wBAAwB,yCAAyC;QAEvE,IAAIL,sBAAsB,CAACH,IAAI,CAACD,OAAO,CAAC,EAAE;YACxCE,gBAAgB,GAAGF,OAAO,CAACU,OAAO,CAChCN,sBAAsB,EACtB,CAAC,sLAAsL,CAAC,CACzL;YACDD,uBAAuB,GACrB,gFAAgF;SACnF,MAAM,IAAIE,0BAA0B,CAACJ,IAAI,CAACD,OAAO,CAAC,EAAE;YACnD,MAAMW,OAAO,GAAGX,OAAO,CAACY,KAAK,CAACP,0BAA0B,CAAC;YACzD,OAAQM,OAAO,IAAIA,OAAO,CAAC,CAAC,CAAC;gBAC3B,KAAK,kBAAkB;oBACrB,qEAAqE;oBACrET,gBAAgB,GAAG,CAAC,qKAAqK,CAAC;oBAC1L,MAAK;gBACP,KAAK,aAAa;oBAChB,4EAA4E;oBAC5EA,gBAAgB,GAAG,CAAC,sFAAsF,CAAC;oBAC3G,MAAK;gBACP;oBACEA,gBAAgB,GAAGF,OAAO,CAACU,OAAO,CAChCL,0BAA0B,EAC1B,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GAAG,EAAE;IAEtB,IAAIC,OAAO,GAAGP,MAAM;IACpB,MAAOO,OAAO,CAAE;QACd,IAAIH,cAAc,CAACI,GAAG,CAACD,OAAO,CAAC,EAAE,MAAK;QACtCH,cAAc,CAACK,GAAG,CAACF,OAAO,CAAC;QAC3BD,WAAW,CAACI,IAAI,CAACH,OAAO,CAAC;QACzB,MAAMI,MAAM,GAAGV,WAAW,CAACW,WAAW,CAACC,SAAS,CAACN,OAAO,CAAC;QACzD,IAAI,CAACI,MAAM,EAAE,MAAK;QAClBJ,OAAO,GAAGI,MAAM;KACjB;IAED,MAAMG,KAAK,GAAG,IAAIhC,kBAAkB,CAClCgB,QAAQ,EACRK,cAAc,CAAC,CAAC,CAAC,GACfA,cAAc,CAAC,CAAC,CAAC,GACjBG,WAAW,CACRS,GAAG,CAAC,CAACC,CAAC,GACLA,CAAC,CAACC,QAAQ,GACN,IAAI,GAAGpC,QAAQ,CAACqB,QAAQ,CAACgB,OAAO,EAAEF,CAAC,CAACC,QAAQ,CAAC,CAACvB,OAAO,UAAU,EAAE,CAAC,GAClE,EAAE,CACP,CACAyB,MAAM,CAACC,OAAO,CAAC,CACfC,IAAI,CAAC,IAAI,CAAC,CAChB;IAED,8CAA8C;IAC9CP,KAAK,CAACQ,KAAK,GAAG,EAAE;IAEhB,OAAOR,KAAK,CAAA;CACb"}

View File

@@ -0,0 +1,35 @@
import Chalk from "next/dist/compiled/chalk";
import { SimpleWebpackError } from "./simpleWebpackError";
const chalk = new Chalk.constructor({
enabled: true
});
const regexScssError = /SassError: (.+)\n\s+on line (\d+) [\s\S]*?>> (.+)\n\s*(-+)\^$/m;
export function getScssError(fileName, fileContent, err) {
if (err.name !== "SassError") {
return false;
}
const res = regexScssError.exec(err.message);
if (res) {
const [, reason, _lineNumer, backupFrame, columnString] = res;
const lineNumber = Math.max(1, parseInt(_lineNumer, 10));
const column = (columnString == null ? void 0 : columnString.length) ?? 1;
let frame;
if (fileContent) {
try {
const { codeFrameColumns , } = require("next/dist/compiled/babel/code-frame");
frame = codeFrameColumns(fileContent, {
start: {
line: lineNumber,
column
}
}, {
forceColor: true
});
} catch {}
}
return new SimpleWebpackError(`${chalk.cyan(fileName)}:${chalk.yellow(lineNumber.toString())}:${chalk.yellow(column.toString())}`, chalk.red.bold("Syntax error").concat(`: ${reason}\n\n${frame ?? backupFrame}`));
}
return false;
}
//# sourceMappingURL=parseScss.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/plugins/wellknown-errors-plugin/parseScss.ts"],"names":["Chalk","SimpleWebpackError","chalk","constructor","enabled","regexScssError","getScssError","fileName","fileContent","err","name","res","exec","message","reason","_lineNumer","backupFrame","columnString","lineNumber","Math","max","parseInt","column","length","frame","codeFrameColumns","require","start","line","forceColor","cyan","yellow","toString","red","bold","concat"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAC5C,SAASC,kBAAkB,QAAQ,sBAAsB,CAAA;AAEzD,MAAMC,KAAK,GAAG,IAAIF,KAAK,CAACG,WAAW,CAAC;IAAEC,OAAO,EAAE,IAAI;CAAE,CAAC;AACtD,MAAMC,cAAc,mEAC8C;AAElE,OAAO,SAASC,YAAY,CAC1BC,QAAgB,EAChBC,WAA0B,EAC1BC,GAAU,EACkB;IAC5B,IAAIA,GAAG,CAACC,IAAI,KAAK,WAAW,EAAE;QAC5B,OAAO,KAAK,CAAA;KACb;IAED,MAAMC,GAAG,GAAGN,cAAc,CAACO,IAAI,CAACH,GAAG,CAACI,OAAO,CAAC;IAC5C,IAAIF,GAAG,EAAE;QACP,MAAM,GAAGG,MAAM,EAAEC,UAAU,EAAEC,WAAW,EAAEC,YAAY,CAAC,GAAGN,GAAG;QAC7D,MAAMO,UAAU,GAAGC,IAAI,CAACC,GAAG,CAAC,CAAC,EAAEC,QAAQ,CAACN,UAAU,EAAE,EAAE,CAAC,CAAC;QACxD,MAAMO,MAAM,GAAGL,CAAAA,YAAY,QAAQ,GAApBA,KAAAA,CAAoB,GAApBA,YAAY,CAAEM,MAAM,CAAA,IAAI,CAAC;QAExC,IAAIC,KAAK,AAAoB;QAC7B,IAAIhB,WAAW,EAAE;YACf,IAAI;gBACF,MAAM,EACJiB,gBAAgB,CAAA,IACjB,GAAGC,OAAO,CAAC,qCAAqC,CAAC;gBAClDF,KAAK,GAAGC,gBAAgB,CACtBjB,WAAW,EACX;oBAAEmB,KAAK,EAAE;wBAAEC,IAAI,EAAEV,UAAU;wBAAEI,MAAM;qBAAE;iBAAE,EACvC;oBAAEO,UAAU,EAAE,IAAI;iBAAE,CACrB,AAAU;aACZ,CAAC,OAAM,EAAE;SACX;QAED,OAAO,IAAI5B,kBAAkB,CAC3B,CAAC,EAAEC,KAAK,CAAC4B,IAAI,CAACvB,QAAQ,CAAC,CAAC,CAAC,EAAEL,KAAK,CAAC6B,MAAM,CACrCb,UAAU,CAACc,QAAQ,EAAE,CACtB,CAAC,CAAC,EAAE9B,KAAK,CAAC6B,MAAM,CAACT,MAAM,CAACU,QAAQ,EAAE,CAAC,CAAC,CAAC,EACtC9B,KAAK,CAAC+B,GAAG,CACNC,IAAI,CAAC,cAAc,CAAC,CACpBC,MAAM,CAAC,CAAC,EAAE,EAAErB,MAAM,CAAC,IAAI,EAAEU,KAAK,IAAIR,WAAW,CAAC,CAAC,CAAC,CACpD,CAAA;KACF;IAED,OAAO,KAAK,CAAA;CACb"}

View File

@@ -0,0 +1,11 @@
// This class creates a simplified webpack error that formats nicely based on
// webpack's build in serializer.
// https://github.com/webpack/webpack/blob/c9d4ff7b054fc581c96ce0e53432d44f9dd8ca72/lib/Stats.js#L294-L356
export class SimpleWebpackError extends Error {
constructor(file, message){
super(message);
this.file = file;
}
}
//# sourceMappingURL=simpleWebpackError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/plugins/wellknown-errors-plugin/simpleWebpackError.ts"],"names":["SimpleWebpackError","Error","constructor","file","message"],"mappings":"AAEA,6EAA6E;AAC7E,iCAAiC;AACjC,0GAA0G;AAC1G,OAAO,MAAMA,kBAAkB,SAAUC,KAAK;IAG5CC,YAAYC,IAAY,EAAEC,OAAe,CAAE;QACzC,KAAK,CAACA,OAAO,CAAC;QACd,IAAI,CAACD,IAAI,GAAGA,IAAI;KACjB;CACF"}

View File

@@ -0,0 +1,77 @@
import { readFileSync } from "fs";
import * as path from "path";
import { getBabelError } from "./parseBabel";
import { getCssError } from "./parseCss";
import { getScssError } from "./parseScss";
import { getNotFoundError, getImageError } from "./parseNotFoundError";
import isError from "../../../../lib/is-error";
import { getRscError } from "./parseRSC";
import { getNextFontError } from "./parseNextFontError";
function getFileData(compilation, m) {
var ref;
let resolved;
let ctx = ((ref = compilation.compiler) == null ? void 0 : ref.context) ?? null;
if (ctx !== null && typeof m.resource === "string") {
const res = path.relative(ctx, m.resource).replace(/\\/g, path.posix.sep);
resolved = res.startsWith(".") ? res : `.${path.posix.sep}${res}`;
} else {
const requestShortener = compilation.requestShortener;
if (typeof (m == null ? void 0 : m.readableIdentifier) === "function") {
resolved = m.readableIdentifier(requestShortener);
} else {
resolved = m.request ?? m.userRequest;
}
}
if (resolved) {
let content = null;
try {
content = readFileSync(ctx ? path.resolve(ctx, resolved) : resolved, "utf8");
} catch {}
return [
resolved,
content
];
}
return [
"<unknown>",
null
];
}
export async function getModuleBuildError(compiler, compilation, input) {
if (!(typeof input === "object" && ((input == null ? void 0 : input.name) === "ModuleBuildError" || (input == null ? void 0 : input.name) === "ModuleNotFoundError") && Boolean(input.module) && isError(input.error))) {
return false;
}
const err = input.error;
const [sourceFilename, sourceContent] = getFileData(compilation, input.module);
const notFoundError = await getNotFoundError(compilation, input, sourceFilename);
if (notFoundError !== false) {
return notFoundError;
}
const imageError = await getImageError(compilation, input, err);
if (imageError !== false) {
return imageError;
}
const babel = getBabelError(sourceFilename, err);
if (babel !== false) {
return babel;
}
const css = getCssError(sourceFilename, err);
if (css !== false) {
return css;
}
const scss = getScssError(sourceFilename, sourceContent, err);
if (scss !== false) {
return scss;
}
const rsc = getRscError(sourceFilename, err, input.module, compilation, compiler);
if (rsc !== false) {
return rsc;
}
const nextFont = getNextFontError(err, input.module);
if (nextFont !== false) {
return nextFont;
}
return false;
}
//# sourceMappingURL=webpackModuleError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts"],"names":["readFileSync","path","getBabelError","getCssError","getScssError","getNotFoundError","getImageError","isError","getRscError","getNextFontError","getFileData","compilation","m","resolved","ctx","compiler","context","resource","res","relative","replace","posix","sep","startsWith","requestShortener","readableIdentifier","request","userRequest","content","resolve","getModuleBuildError","input","name","Boolean","module","error","err","sourceFilename","sourceContent","notFoundError","imageError","babel","css","scss","rsc","nextFont"],"mappings":"AAAA,SAASA,YAAY,QAAQ,IAAI,CAAA;AACjC,YAAYC,IAAI,MAAM,MAAM,CAAA;AAG5B,SAASC,aAAa,QAAQ,cAAc,CAAA;AAC5C,SAASC,WAAW,QAAQ,YAAY,CAAA;AACxC,SAASC,YAAY,QAAQ,aAAa,CAAA;AAC1C,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,sBAAsB,CAAA;AAEtE,OAAOC,OAAO,MAAM,0BAA0B,CAAA;AAC9C,SAASC,WAAW,QAAQ,YAAY,CAAA;AACxC,SAASC,gBAAgB,QAAQ,sBAAsB,CAAA;AAEvD,SAASC,WAAW,CAClBC,WAAgC,EAChCC,CAAM,EACmB;QAEAD,GAAoB;IAD7C,IAAIE,QAAQ,AAAQ;IACpB,IAAIC,GAAG,GAAkBH,CAAAA,CAAAA,GAAoB,GAApBA,WAAW,CAACI,QAAQ,SAAS,GAA7BJ,KAAAA,CAA6B,GAA7BA,GAAoB,CAAEK,OAAO,CAAA,IAAI,IAAI;IAC9D,IAAIF,GAAG,KAAK,IAAI,IAAI,OAAOF,CAAC,CAACK,QAAQ,KAAK,QAAQ,EAAE;QAClD,MAAMC,GAAG,GAAGjB,IAAI,CAACkB,QAAQ,CAACL,GAAG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