main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
import curry from "next/dist/compiled/lodash.curry";
import { COMPILER_NAMES } from "../../../../shared/lib/constants";
export const base = curry(function base(ctx, config) {
config.mode = ctx.isDevelopment ? "development" : "production";
config.name = ctx.isServer ? ctx.isEdgeRuntime ? COMPILER_NAMES.edgeServer : COMPILER_NAMES.server : COMPILER_NAMES.client;
config.target = !ctx.targetWeb ? "node16.14" // Same version defined in packages/next/package.json#engines
: ctx.isEdgeRuntime ? [
"web",
"es6"
] : [
"web",
"es5"
];
// https://webpack.js.org/configuration/devtool/#development
if (ctx.isDevelopment) {
if (process.env.__NEXT_TEST_MODE && !process.env.__NEXT_TEST_WITH_DEVTOOL) {
config.devtool = false;
} else {
// `eval-source-map` provides full-fidelity source maps for the
// original source, including columns and original variable names.
// This is desirable so the in-browser debugger can correctly pause
// and show scoped variables with their original names.
config.devtool = "eval-source-map";
}
} else {
if (ctx.isEdgeRuntime || ctx.isServer && ctx.serverSourceMaps || // Enable browser sourcemaps:
ctx.productionBrowserSourceMaps && ctx.isClient) {
config.devtool = "source-map";
} else {
config.devtool = false;
}
}
if (!config.module) {
config.module = {
rules: []
};
}
// TODO: add codemod for "Should not import the named export" with JSON files
// config.module.strictExportPresence = !isWebpack5
return config;
});
//# sourceMappingURL=base.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/config/blocks/base.ts"],"names":["curry","COMPILER_NAMES","base","ctx","config","mode","isDevelopment","name","isServer","isEdgeRuntime","edgeServer","server","client","target","targetWeb","process","env","__NEXT_TEST_MODE","__NEXT_TEST_WITH_DEVTOOL","devtool","serverSourceMaps","productionBrowserSourceMaps","isClient","module","rules"],"mappings":"AAAA,OAAOA,WAAW,kCAAiC;AAEnD,SAASC,cAAc,QAAQ,mCAAkC;AAGjE,OAAO,MAAMC,OAAOF,MAAM,SAASE,KACjCC,GAAyB,EACzBC,MAA6B;IAE7BA,OAAOC,IAAI,GAAGF,IAAIG,aAAa,GAAG,gBAAgB;IAClDF,OAAOG,IAAI,GAAGJ,IAAIK,QAAQ,GACtBL,IAAIM,aAAa,GACfR,eAAeS,UAAU,GACzBT,eAAeU,MAAM,GACvBV,eAAeW,MAAM;IAEzBR,OAAOS,MAAM,GAAG,CAACV,IAAIW,SAAS,GAC1B,YAAY,6DAA6D;OACzEX,IAAIM,aAAa,GACjB;QAAC;QAAO;KAAM,GACd;QAAC;QAAO;KAAM;IAElB,4DAA4D;IAC5D,IAAIN,IAAIG,aAAa,EAAE;QACrB,IAAIS,QAAQC,GAAG,CAACC,gBAAgB,IAAI,CAACF,QAAQC,GAAG,CAACE,wBAAwB,EAAE;YACzEd,OAAOe,OAAO,GAAG;QACnB,OAAO;YACL,+DAA+D;YAC/D,kEAAkE;YAClE,mEAAmE;YACnE,uDAAuD;YACvDf,OAAOe,OAAO,GAAG;QACnB;IACF,OAAO;QACL,IACEhB,IAAIM,aAAa,IAChBN,IAAIK,QAAQ,IAAIL,IAAIiB,gBAAgB,IACrC,6BAA6B;QAC5BjB,IAAIkB,2BAA2B,IAAIlB,IAAImB,QAAQ,EAChD;YACAlB,OAAOe,OAAO,GAAG;QACnB,OAAO;YACLf,OAAOe,OAAO,GAAG;QACnB;IACF;IAEA,IAAI,CAACf,OAAOmB,MAAM,EAAE;QAClBnB,OAAOmB,MAAM,GAAG;YAAEC,OAAO,EAAE;QAAC;IAC9B;IAEA,6EAA6E;IAC7E,mDAAmD;IAEnD,OAAOpB;AACT,GAAE"}

View File

@@ -0,0 +1,538 @@
import curry from "next/dist/compiled/lodash.curry";
import { loader, plugin } from "../../helpers";
import { pipe } from "../../utils";
import { getCssModuleLoader, getGlobalCssLoader } from "./loaders";
import { getNextFontLoader } from "./loaders/next-font";
import { getCustomDocumentError, getGlobalImportError, getGlobalModuleImportError, getLocalModuleImportError } from "./messages";
import { getPostCssPlugins } from "./plugins";
import { nonNullable } from "../../../../../lib/non-nullable";
import { WEBPACK_LAYERS } from "../../../../../lib/constants";
// RegExps for all Style Sheet variants
export const regexLikeCss = /\.(css|scss|sass)$/;
// RegExps for Style Sheets
const regexCssGlobal = /(?<!\.module)\.css$/;
const regexCssModules = /\.module\.css$/;
// RegExps for Syntactically Awesome Style Sheets
const regexSassGlobal = /(?<!\.module)\.(scss|sass)$/;
const regexSassModules = /\.module\.(scss|sass)$/;
const APP_LAYER_RULE = {
or: [
WEBPACK_LAYERS.reactServerComponents,
WEBPACK_LAYERS.serverSideRendering,
WEBPACK_LAYERS.appPagesBrowser
]
};
const PAGES_LAYER_RULE = {
not: [
WEBPACK_LAYERS.reactServerComponents,
WEBPACK_LAYERS.serverSideRendering,
WEBPACK_LAYERS.appPagesBrowser
]
};
/**
* Mark a rule as removable if built-in CSS support is disabled
*/ function markRemovable(r) {
Object.defineProperty(r, Symbol.for("__next_css_remove"), {
enumerable: false,
value: true
});
return r;
}
let postcssInstancePromise;
export async function lazyPostCSS(rootDirectory, supportedBrowsers, disablePostcssPresetEnv) {
if (!postcssInstancePromise) {
postcssInstancePromise = (async ()=>{
const postcss = require("postcss");
// @ts-ignore backwards compat
postcss.plugin = function postcssPlugin(name, initializer) {
function creator(...args) {
let transformer = initializer(...args);
transformer.postcssPlugin = name;
// transformer.postcssVersion = new Processor().version
return transformer;
}
let cache;
Object.defineProperty(creator, "postcss", {
get () {
if (!cache) cache = creator();
return cache;
}
});
creator.process = function(css, processOpts, pluginOpts) {
return postcss([
creator(pluginOpts)
]).process(css, processOpts);
};
return creator;
};
// @ts-ignore backwards compat
postcss.vendor = {
/**
* Returns the vendor prefix extracted from an input string.
*
* @example
* postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
* postcss.vendor.prefix('tab-size') //=> ''
*/ prefix: function prefix(prop) {
const match = prop.match(/^(-\w+-)/);
if (match) {
return match[0];
}
return "";
},
/**
* Returns the input string stripped of its vendor prefix.
*
* @example
* postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
*/ unprefixed: function unprefixed(/**
* String with or without vendor prefix.
*/ prop) {
return prop.replace(/^-\w+-/, "");
}
};
const postCssPlugins = await getPostCssPlugins(rootDirectory, supportedBrowsers, disablePostcssPresetEnv);
return {
postcss,
postcssWithPlugins: postcss(postCssPlugins)
};
})();
}
return postcssInstancePromise;
}
export const css = curry(async function css(ctx, config) {
const { prependData: sassPrependData, additionalData: sassAdditionalData, ...sassOptions } = ctx.sassOptions;
const lazyPostCSSInitializer = ()=>lazyPostCSS(ctx.rootDirectory, ctx.supportedBrowsers, ctx.experimental.disablePostcssPresetEnv);
const sassPreprocessors = [
// First, process files with `sass-loader`: this inlines content, and
// compiles away the proprietary syntax.
{
loader: require.resolve("next/dist/compiled/sass-loader"),
options: {
// Source maps are required so that `resolve-url-loader` can locate
// files original to their source directory.
sourceMap: true,
sassOptions: {
// The "fibers" option is not needed for Node.js 16+, but it's causing
// problems for Node.js <= 14 users as you'll have to manually install
// the `fibers` package:
// https://github.com/webpack-contrib/sass-loader#:~:text=We%20automatically%20inject%20the%20fibers%20package
// https://github.com/vercel/next.js/issues/45052
// Since it's optional and not required, we'll disable it by default
// to avoid the confusion.
fibers: false,
...sassOptions
},
additionalData: sassPrependData || sassAdditionalData
}
},
// Then, `sass-loader` will have passed-through CSS imports as-is instead
// of inlining them. Because they were inlined, the paths are no longer
// correct.
// To fix this, we use `resolve-url-loader` to rewrite the CSS
// imports to real file paths.
{
loader: require.resolve("../../../loaders/resolve-url-loader/index"),
options: {
postcss: lazyPostCSSInitializer,
// Source maps are not required here, but we may as well emit
// them.
sourceMap: true
}
}
];
const fns = [];
const googleLoader = require.resolve("next/dist/compiled/@next/font/google/loader");
const localLoader = require.resolve("next/dist/compiled/@next/font/local/loader");
const nextFontLoaders = [
[
require.resolve("next/font/google/target.css"),
googleLoader
],
[
require.resolve("next/font/local/target.css"),
localLoader
],
// TODO: remove this in the next major version
[
/node_modules[\\/]@next[\\/]font[\\/]google[\\/]target.css/,
googleLoader
],
[
/node_modules[\\/]@next[\\/]font[\\/]local[\\/]target.css/,
localLoader
]
];
nextFontLoaders.forEach(([fontLoaderTarget, fontLoaderPath])=>{
// Matches the resolved font loaders noop files to run next-font-loader
fns.push(loader({
oneOf: [
markRemovable({
sideEffects: false,
test: fontLoaderTarget,
use: getNextFontLoader(ctx, lazyPostCSSInitializer, fontLoaderPath)
})
]
}));
});
// CSS cannot be imported in _document. This comes before everything because
// global CSS nor CSS modules work in said file.
fns.push(loader({
oneOf: [
markRemovable({
test: regexLikeCss,
// Use a loose regex so we don't have to crawl the file system to
// find the real file name (if present).
issuer: /pages[\\/]_document\./,
use: {
loader: "error-loader",
options: {
reason: getCustomDocumentError()
}
}
})
]
}));
const shouldIncludeExternalCSSImports = !!ctx.experimental.craCompat || !!ctx.transpilePackages;
// CSS modules & SASS modules support. They are allowed to be imported in anywhere.
fns.push(// CSS Modules should never have side effects. This setting will
// allow unused CSS to be removed from the production build.
// We ensure this by disallowing `:global()` CSS at the top-level
// via the `pure` mode in `css-loader`.
loader({
oneOf: [
// For app dir, we need to match the specific app layer.
ctx.hasAppDir ? markRemovable({
sideEffects: false,
test: regexCssModules,
issuerLayer: APP_LAYER_RULE,
use: [
{
loader: require.resolve("../../../loaders/next-flight-css-loader"),
options: {
cssModules: true
}
},
...getCssModuleLoader({
...ctx,
isAppDir: true
}, lazyPostCSSInitializer)
]
}) : null,
markRemovable({
sideEffects: false,
test: regexCssModules,
issuerLayer: PAGES_LAYER_RULE,
use: getCssModuleLoader({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer)
})
].filter(nonNullable)
}), // Opt-in support for Sass (using .scss or .sass extensions).
// Sass Modules should never have side effects. This setting will
// allow unused Sass to be removed from the production build.
// We ensure this by disallowing `:global()` Sass at the top-level
// via the `pure` mode in `css-loader`.
loader({
oneOf: [
// For app dir, we need to match the specific app layer.
ctx.hasAppDir ? markRemovable({
sideEffects: false,
test: regexSassModules,
issuerLayer: APP_LAYER_RULE,
use: [
{
loader: require.resolve("../../../loaders/next-flight-css-loader"),
options: {
cssModules: true
}
},
...getCssModuleLoader({
...ctx,
isAppDir: true
}, lazyPostCSSInitializer, sassPreprocessors)
]
}) : null,
markRemovable({
sideEffects: false,
test: regexSassModules,
issuerLayer: PAGES_LAYER_RULE,
use: getCssModuleLoader({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer, sassPreprocessors)
})
].filter(nonNullable)
}), // Throw an error for CSS Modules used outside their supported scope
loader({
oneOf: [
markRemovable({
test: [
regexCssModules,
regexSassModules
],
use: {
loader: "error-loader",
options: {
reason: getLocalModuleImportError()
}
}
})
]
}));
// Global CSS and SASS support.
if (ctx.isServer) {
fns.push(loader({
oneOf: [
ctx.hasAppDir && !ctx.isProduction ? markRemovable({
sideEffects: true,
test: [
regexCssGlobal,
regexSassGlobal
],
issuerLayer: APP_LAYER_RULE,
use: {
loader: require.resolve("../../../loaders/next-flight-css-loader"),
options: {
cssModules: false
}
}
}) : null,
markRemovable({
// CSS imports have side effects, even on the server side.
sideEffects: true,
test: [
regexCssGlobal,
regexSassGlobal
],
use: require.resolve("next/dist/compiled/ignore-loader")
})
].filter(nonNullable)
}));
} else {
// External CSS files are allowed to be loaded when any of the following is true:
// - hasAppDir: all CSS files are allowed
// - If the CSS file is located in `node_modules`
// - If the CSS file is located in another package in a monorepo (outside of the current rootDir)
// - If the issuer is pages/_app (matched later)
const allowedPagesGlobalCSSPath = ctx.hasAppDir ? undefined : {
and: [
{
or: [
/node_modules/,
{
not: [
ctx.rootDirectory
]
}
]
}
]
};
const allowedPagesGlobalCSSIssuer = ctx.hasAppDir ? undefined : shouldIncludeExternalCSSImports ? undefined : {
and: [
ctx.rootDirectory
],
not: [
/node_modules/
]
};
fns.push(loader({
oneOf: [
...ctx.hasAppDir ? [
markRemovable({
sideEffects: true,
test: regexCssGlobal,
issuerLayer: APP_LAYER_RULE,
use: [
{
loader: require.resolve("../../../loaders/next-flight-css-loader"),
options: {
cssModules: false
}
},
...getGlobalCssLoader({
...ctx,
isAppDir: true
}, lazyPostCSSInitializer)
]
}),
markRemovable({
sideEffects: true,
test: regexSassGlobal,
issuerLayer: APP_LAYER_RULE,
use: [
{
loader: require.resolve("../../../loaders/next-flight-css-loader"),
options: {
cssModules: false
}
},
...getGlobalCssLoader({
...ctx,
isAppDir: true
}, lazyPostCSSInitializer, sassPreprocessors)
]
})
] : [],
markRemovable({
sideEffects: true,
test: regexCssGlobal,
include: allowedPagesGlobalCSSPath,
issuer: allowedPagesGlobalCSSIssuer,
issuerLayer: PAGES_LAYER_RULE,
use: getGlobalCssLoader({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer)
}),
markRemovable({
sideEffects: true,
test: regexSassGlobal,
include: allowedPagesGlobalCSSPath,
issuer: allowedPagesGlobalCSSIssuer,
issuerLayer: PAGES_LAYER_RULE,
use: getGlobalCssLoader({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer, sassPreprocessors)
})
].filter(nonNullable)
}));
if (ctx.customAppFile) {
fns.push(loader({
oneOf: [
markRemovable({
sideEffects: true,
test: regexCssGlobal,
issuer: {
and: [
ctx.customAppFile
]
},
use: getGlobalCssLoader({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer)
})
]
}), loader({
oneOf: [
markRemovable({
sideEffects: true,
test: regexSassGlobal,
issuer: {
and: [
ctx.customAppFile
]
},
use: getGlobalCssLoader({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer, sassPreprocessors)
})
]
}));
}
}
// Throw an error for Global CSS used inside of `node_modules`
if (!shouldIncludeExternalCSSImports) {
fns.push(loader({
oneOf: [
markRemovable({
test: [
regexCssGlobal,
regexSassGlobal
],
issuer: {
and: [
/node_modules/
]
},
use: {
loader: "error-loader",
options: {
reason: getGlobalModuleImportError()
}
}
})
]
}));
}
// Throw an error for Global CSS used outside of our custom <App> file
fns.push(loader({
oneOf: [
markRemovable({
test: [
regexCssGlobal,
regexSassGlobal
],
issuer: ctx.hasAppDir ? {
// If it's inside the app dir, but not importing from a layout file,
// throw an error.
and: [
ctx.rootDirectory
],
not: [
/layout\.(js|mjs|jsx|ts|tsx)$/
]
} : undefined,
use: {
loader: "error-loader",
options: {
reason: getGlobalImportError()
}
}
})
]
}));
if (ctx.isClient) {
// Automatically transform references to files (i.e. url()) into URLs
// e.g. url(./logo.svg)
fns.push(loader({
oneOf: [
markRemovable({
// This should only be applied to CSS files
issuer: regexLikeCss,
// Exclude extensions that webpack handles by default
exclude: [
/\.(js|mjs|jsx|ts|tsx)$/,
/\.html$/,
/\.json$/,
/\.webpack\[[^\]]+\]$/
],
// `asset/resource` always emits a URL reference, where `asset`
// might inline the asset as a data URI
type: "asset/resource"
})
]
}));
}
// Enable full mini-css-extract-plugin hmr for prod mode pages or app dir
if (ctx.isClient && (ctx.isProduction || ctx.hasAppDir)) {
// Extract CSS as CSS file(s) in the client-side production bundle.
const MiniCssExtractPlugin = require("../../../plugins/mini-css-extract-plugin").default;
fns.push(plugin(// @ts-ignore webpack 5 compat
new MiniCssExtractPlugin({
filename: ctx.isProduction ? "static/css/[contenthash].css" : "static/css/[name].css",
chunkFilename: ctx.isProduction ? "static/css/[contenthash].css" : "static/css/[name].css",
// Next.js guarantees that CSS order "doesn't matter", due to imposed
// restrictions:
// 1. Global CSS can only be defined in a single entrypoint (_app)
// 2. CSS Modules generate scoped class names by default and cannot
// include Global CSS (:global() selector).
//
// While not a perfect guarantee (e.g. liberal use of `:global()`
// selector), this assumption is required to code-split CSS.
//
// If this warning were to trigger, it'd be unactionable by the user,
// but likely not valid -- so we disable it.
ignoreOrder: true
})));
}
const fn = pipe(...fns);
return fn(config);
});
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,37 @@
export function getClientStyleLoader({ hasAppDir, isAppDir, isDevelopment, assetPrefix }) {
const shouldEnableApp = typeof isAppDir === "boolean" ? isAppDir : hasAppDir;
// Keep next-style-loader for development mode in `pages/`
if (isDevelopment && !shouldEnableApp) {
return {
loader: "next-style-loader",
options: {
insert: function(element) {
// By default, style-loader injects CSS into the bottom
// of <head>. This causes ordering problems between dev
// and prod. To fix this, we render a <noscript> tag as
// an anchor for the styles to be placed before. These
// styles will be applied _before_ <style jsx global>.
// These elements should always exist. If they do not,
// this code should fail.
var anchorElement = document.querySelector("#__next_css__DO_NOT_USE__");
var parentNode = anchorElement.parentNode// Normally <head>
;
// Each style tag should be placed right before our
// anchor. By inserting before and not after, we do not
// need to track the last inserted element.
parentNode.insertBefore(element, anchorElement);
}
}
};
}
const MiniCssExtractPlugin = require("../../../../plugins/mini-css-extract-plugin").default;
return {
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: `${assetPrefix}/_next/`,
esModule: false
}
};
}
//# sourceMappingURL=client.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/config/blocks/css/loaders/client.ts"],"names":["getClientStyleLoader","hasAppDir","isAppDir","isDevelopment","assetPrefix","shouldEnableApp","loader","options","insert","element","anchorElement","document","querySelector","parentNode","insertBefore","MiniCssExtractPlugin","require","default","publicPath","esModule"],"mappings":"AAEA,OAAO,SAASA,qBAAqB,EACnCC,SAAS,EACTC,QAAQ,EACRC,aAAa,EACbC,WAAW,EAMZ;IACC,MAAMC,kBAAkB,OAAOH,aAAa,YAAYA,WAAWD;IAEnE,0DAA0D;IAC1D,IAAIE,iBAAiB,CAACE,iBAAiB;QACrC,OAAO;YACLC,QAAQ;YACRC,SAAS;gBACPC,QAAQ,SAAUC,OAAa;oBAC7B,uDAAuD;oBACvD,uDAAuD;oBACvD,uDAAuD;oBACvD,sDAAsD;oBACtD,sDAAsD;oBAEtD,sDAAsD;oBACtD,yBAAyB;oBACzB,IAAIC,gBAAgBC,SAASC,aAAa,CACxC;oBAEF,IAAIC,aAAaH,cAAcG,UAAU,AAAE,kBAAkB;;oBAE7D,mDAAmD;oBACnD,uDAAuD;oBACvD,2CAA2C;oBAC3CA,WAAWC,YAAY,CAACL,SAASC;gBACnC;YACF;QACF;IACF;IAEA,MAAMK,uBACJC,QAAQ,+CAA+CC,OAAO;IAChE,OAAO;QACLX,QAAQS,qBAAqBT,MAAM;QACnCC,SAAS;YACPW,YAAY,CAAC,EAAEd,YAAY,OAAO,CAAC;YACnCe,UAAU;QACZ;IACF;AACF"}

View File

@@ -0,0 +1,11 @@
export function cssFileResolve(url, _resourcePath, urlImports) {
if (url.startsWith("/")) {
return false;
}
if (!urlImports && /^[a-z][a-z0-9+.-]*:/i.test(url)) {
return false;
}
return true;
}
//# sourceMappingURL=file-resolve.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/config/blocks/css/loaders/file-resolve.ts"],"names":["cssFileResolve","url","_resourcePath","urlImports","startsWith","test"],"mappings":"AAAA,OAAO,SAASA,eACdC,GAAW,EACXC,aAAqB,EACrBC,UAAe;IAEf,IAAIF,IAAIG,UAAU,CAAC,MAAM;QACvB,OAAO;IACT;IACA,IAAI,CAACD,cAAc,uBAAuBE,IAAI,CAACJ,MAAM;QACnD,OAAO;IACT;IACA,OAAO;AACT"}

View File

@@ -0,0 +1,22 @@
import loaderUtils from "next/dist/compiled/loader-utils3";
import path from "path";
const regexLikeIndexModule = /(?<!pages[\\/])index\.module\.(scss|sass|css)$/;
export function getCssModuleLocalIdent(context, _, exportName, options) {
const relativePath = path.relative(context.rootContext, context.resourcePath).replace(/\\+/g, "/");
// Generate a more meaningful name (parent folder) when the user names the
// file `index.module.css`.
const fileNameOrFolder = regexLikeIndexModule.test(relativePath) ? "[folder]" : "[name]";
// Generate a hash to make the class name unique.
const hash = loaderUtils.getHashDigest(Buffer.from(`filePath:${relativePath}#className:${exportName}`), "sha1", "base64", 5);
// Have webpack interpolate the `[folder]` or `[name]` to its real value.
return loaderUtils.interpolateName(context, fileNameOrFolder + "_" + exportName + "__" + hash, options).replace(// Webpack name interpolation returns `about.module_root__2oFM9` for
// `.root {}` inside a file named `about.module.css`. Let's simplify
// this.
/\.module_/, "_")// Replace invalid symbols with underscores instead of escaping
// https://mathiasbynens.be/notes/css-escapes#identifiers-strings
.replace(/[^a-zA-Z0-9-_]/g, "_")// "they cannot start with a digit, two hyphens, or a hyphen followed by a digit [sic]"
// https://www.w3.org/TR/CSS21/syndata.html#characters
.replace(/^(\d|--|-\d)/, "__$1");
}
//# sourceMappingURL=getCssModuleLocalIdent.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts"],"names":["loaderUtils","path","regexLikeIndexModule","getCssModuleLocalIdent","context","_","exportName","options","relativePath","relative","rootContext","resourcePath","replace","fileNameOrFolder","test","hash","getHashDigest","Buffer","from","interpolateName"],"mappings":"AAAA,OAAOA,iBAAiB,mCAAkC;AAC1D,OAAOC,UAAU,OAAM;AAGvB,MAAMC,uBAAuB;AAE7B,OAAO,SAASC,uBACdC,OAAkC,EAClCC,CAAM,EACNC,UAAkB,EAClBC,OAAe;IAEf,MAAMC,eAAeP,KAClBQ,QAAQ,CAACL,QAAQM,WAAW,EAAEN,QAAQO,YAAY,EAClDC,OAAO,CAAC,QAAQ;IAEnB,0EAA0E;IAC1E,2BAA2B;IAC3B,MAAMC,mBAAmBX,qBAAqBY,IAAI,CAACN,gBAC/C,aACA;IAEJ,iDAAiD;IACjD,MAAMO,OAAOf,YAAYgB,aAAa,CACpCC,OAAOC,IAAI,CAAC,CAAC,SAAS,EAAEV,aAAa,WAAW,EAAEF,WAAW,CAAC,GAC9D,QACA,UACA;IAGF,yEAAyE;IACzE,OACEN,YACGmB,eAAe,CACdf,SACAS,mBAAmB,MAAMP,aAAa,OAAOS,MAC7CR,SAEDK,OAAO,CACN,oEAAoE;IACpE,oEAAoE;IACpE,QAAQ;IACR,aACA,IAEF,+DAA+D;IAC/D,iEAAiE;KAChEA,OAAO,CAAC,mBAAmB,IAC5B,uFAAuF;IACvF,sDAAsD;KACrDA,OAAO,CAAC,gBAAgB;AAE/B"}

View File

@@ -0,0 +1,40 @@
import { getClientStyleLoader } from "./client";
import { cssFileResolve } from "./file-resolve";
export function getGlobalCssLoader(ctx, postcss, preProcessors = []) {
const loaders = [];
if (ctx.isClient) {
// Add appropriate development more or production mode style
// loader
loaders.push(getClientStyleLoader({
hasAppDir: ctx.hasAppDir,
isAppDir: ctx.isAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix
}));
}
// Resolve CSS `@import`s and `url()`s
loaders.push({
loader: require.resolve("../../../../loaders/css-loader/src"),
options: {
postcss,
importLoaders: 1 + preProcessors.length,
// Next.js controls CSS Modules eligibility:
modules: false,
url: (url, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports)
}
});
// Compile CSS
loaders.push({
loader: require.resolve("../../../../loaders/postcss-loader/src"),
options: {
postcss
}
});
loaders.push(// Webpack loaders run like a stack, so we need to reverse the natural
// order of preprocessors.
...preProcessors.slice().reverse());
return loaders;
}
//# sourceMappingURL=global.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/config/blocks/css/loaders/global.ts"],"names":["getClientStyleLoader","cssFileResolve","getGlobalCssLoader","ctx","postcss","preProcessors","loaders","isClient","push","hasAppDir","isAppDir","isDevelopment","assetPrefix","loader","require","resolve","options","importLoaders","length","modules","url","resourcePath","experimental","urlImports","import","_","slice","reverse"],"mappings":"AAGA,SAASA,oBAAoB,QAAQ,WAAU;AAC/C,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,OAAO,SAASC,mBACdC,GAAyB,EACzBC,OAAY,EACZC,gBAAmD,EAAE;IAErD,MAAMC,UAAoC,EAAE;IAE5C,IAAIH,IAAII,QAAQ,EAAE;QAChB,4DAA4D;QAC5D,SAAS;QACTD,QAAQE,IAAI,CACVR,qBAAqB;YACnBS,WAAWN,IAAIM,SAAS;YACxBC,UAAUP,IAAIO,QAAQ;YACtBC,eAAeR,IAAIQ,aAAa;YAChCC,aAAaT,IAAIS,WAAW;QAC9B;IAEJ;IAEA,sCAAsC;IACtCN,QAAQE,IAAI,CAAC;QACXK,QAAQC,QAAQC,OAAO,CAAC;QACxBC,SAAS;YACPZ;YACAa,eAAe,IAAIZ,cAAca,MAAM;YACvC,4CAA4C;YAC5CC,SAAS;YACTC,KAAK,CAACA,KAAaC,eACjBpB,eAAemB,KAAKC,cAAclB,IAAImB,YAAY,CAACC,UAAU;YAC/DC,QAAQ,CAACJ,KAAaK,GAAQJ,eAC5BpB,eAAemB,KAAKC,cAAclB,IAAImB,YAAY,CAACC,UAAU;QACjE;IACF;IAEA,cAAc;IACdjB,QAAQE,IAAI,CAAC;QACXK,QAAQC,QAAQC,OAAO,CAAC;QACxBC,SAAS;YACPZ;QACF;IACF;IAEAE,QAAQE,IAAI,CACV,sEAAsE;IACtE,0BAA0B;OACvBH,cAAcqB,KAAK,GAAGC,OAAO;IAGlC,OAAOrB;AACT"}

View File

@@ -0,0 +1,4 @@
export * from "./global";
export * from "./modules";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/config/blocks/css/loaders/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAU;AACxB,cAAc,YAAW"}

View File

@@ -0,0 +1,56 @@
import { getClientStyleLoader } from "./client";
import { cssFileResolve } from "./file-resolve";
import { getCssModuleLocalIdent } from "./getCssModuleLocalIdent";
export function getCssModuleLoader(ctx, postcss, preProcessors = []) {
const loaders = [];
if (ctx.isClient) {
// Add appropriate development more or production mode style
// loader
loaders.push(getClientStyleLoader({
hasAppDir: ctx.hasAppDir,
isAppDir: ctx.isAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix
}));
}
// Resolve CSS `@import`s and `url()`s
loaders.push({
loader: require.resolve("../../../../loaders/css-loader/src"),
options: {
postcss,
importLoaders: 1 + preProcessors.length,
// Use CJS mode for backwards compatibility:
esModule: false,
url: (url, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
modules: {
// Do not transform class names (CJS mode backwards compatibility):
exportLocalsConvention: "asIs",
// Server-side (Node.js) rendering support:
exportOnlyLocals: ctx.isServer,
// Disallow global style exports so we can code-split CSS and
// not worry about loading order.
mode: "pure",
// Generate a friendly production-ready name so it's
// reasonably understandable. The same name is used for
// development.
// TODO: Consider making production reduce this to a single
// character?
getLocalIdent: getCssModuleLocalIdent
}
}
});
// Compile CSS
loaders.push({
loader: require.resolve("../../../../loaders/postcss-loader/src"),
options: {
postcss
}
});
loaders.push(// Webpack loaders run like a stack, so we need to reverse the natural
// order of preprocessors.
...preProcessors.slice().reverse());
return loaders;
}
//# sourceMappingURL=modules.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/config/blocks/css/loaders/modules.ts"],"names":["getClientStyleLoader","cssFileResolve","getCssModuleLocalIdent","getCssModuleLoader","ctx","postcss","preProcessors","loaders","isClient","push","hasAppDir","isAppDir","isDevelopment","assetPrefix","loader","require","resolve","options","importLoaders","length","esModule","url","resourcePath","experimental","urlImports","import","_","modules","exportLocalsConvention","exportOnlyLocals","isServer","mode","getLocalIdent","slice","reverse"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,WAAU;AAC/C,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,SAASC,sBAAsB,QAAQ,2BAA0B;AAEjE,OAAO,SAASC,mBACdC,GAAyB,EACzBC,OAAY,EACZC,gBAAmD,EAAE;IAErD,MAAMC,UAAoC,EAAE;IAE5C,IAAIH,IAAII,QAAQ,EAAE;QAChB,4DAA4D;QAC5D,SAAS;QACTD,QAAQE,IAAI,CACVT,qBAAqB;YACnBU,WAAWN,IAAIM,SAAS;YACxBC,UAAUP,IAAIO,QAAQ;YACtBC,eAAeR,IAAIQ,aAAa;YAChCC,aAAaT,IAAIS,WAAW;QAC9B;IAEJ;IAEA,sCAAsC;IACtCN,QAAQE,IAAI,CAAC;QACXK,QAAQC,QAAQC,OAAO,CAAC;QACxBC,SAAS;YACPZ;YACAa,eAAe,IAAIZ,cAAca,MAAM;YACvC,4CAA4C;YAC5CC,UAAU;YACVC,KAAK,CAACA,KAAaC,eACjBrB,eAAeoB,KAAKC,cAAclB,IAAImB,YAAY,CAACC,UAAU;YAC/DC,QAAQ,CAACJ,KAAaK,GAAQJ,eAC5BrB,eAAeoB,KAAKC,cAAclB,IAAImB,YAAY,CAACC,UAAU;YAC/DG,SAAS;gBACP,mEAAmE;gBACnEC,wBAAwB;gBACxB,2CAA2C;gBAC3CC,kBAAkBzB,IAAI0B,QAAQ;gBAC9B,6DAA6D;gBAC7D,iCAAiC;gBACjCC,MAAM;gBACN,oDAAoD;gBACpD,uDAAuD;gBACvD,eAAe;gBACf,2DAA2D;gBAC3D,aAAa;gBACbC,eAAe9B;YACjB;QACF;IACF;IAEA,cAAc;IACdK,QAAQE,IAAI,CAAC;QACXK,QAAQC,QAAQC,OAAO,CAAC;QACxBC,SAAS;YACPZ;QACF;IACF;IAEAE,QAAQE,IAAI,CACV,sEAAsE;IACtE,0BAA0B;OACvBH,cAAc2B,KAAK,GAAGC,OAAO;IAGlC,OAAO3B;AACT"}

View File

@@ -0,0 +1,52 @@
import { getClientStyleLoader } from "./client";
import { cssFileResolve } from "./file-resolve";
export function getNextFontLoader(ctx, postcss, fontLoaderPath) {
const loaders = [];
if (ctx.isClient) {
// Add appropriate development mode or production mode style
// loader
loaders.push(getClientStyleLoader({
hasAppDir: ctx.hasAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix
}));
}
loaders.push({
loader: require.resolve("../../../../loaders/css-loader/src"),
options: {
postcss,
importLoaders: 1,
// Use CJS mode for backwards compatibility:
esModule: false,
url: (url, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
modules: {
// Do not transform class names (CJS mode backwards compatibility):
exportLocalsConvention: "asIs",
// Server-side (Node.js) rendering support:
exportOnlyLocals: ctx.isServer,
// Disallow global style exports so we can code-split CSS and
// not worry about loading order.
mode: "pure",
getLocalIdent: (_context, _localIdentName, exportName, _options, meta)=>{
// hash from next-font-loader
return `__${exportName}_${meta.fontFamilyHash}`;
}
},
fontLoader: true
}
});
loaders.push({
loader: "next-font-loader",
options: {
isDev: ctx.isDevelopment,
isServer: ctx.isServer,
assetPrefix: ctx.assetPrefix,
fontLoaderPath,
postcss
}
});
return loaders;
}
//# sourceMappingURL=next-font.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/config/blocks/css/loaders/next-font.ts"],"names":["getClientStyleLoader","cssFileResolve","getNextFontLoader","ctx","postcss","fontLoaderPath","loaders","isClient","push","hasAppDir","isDevelopment","assetPrefix","loader","require","resolve","options","importLoaders","esModule","url","resourcePath","experimental","urlImports","import","_","modules","exportLocalsConvention","exportOnlyLocals","isServer","mode","getLocalIdent","_context","_localIdentName","exportName","_options","meta","fontFamilyHash","fontLoader","isDev"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,WAAU;AAC/C,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,OAAO,SAASC,kBACdC,GAAyB,EACzBC,OAAY,EACZC,cAAsB;IAEtB,MAAMC,UAAoC,EAAE;IAE5C,IAAIH,IAAII,QAAQ,EAAE;QAChB,4DAA4D;QAC5D,SAAS;QACTD,QAAQE,IAAI,CACVR,qBAAqB;YACnBS,WAAWN,IAAIM,SAAS;YACxBC,eAAeP,IAAIO,aAAa;YAChCC,aAAaR,IAAIQ,WAAW;QAC9B;IAEJ;IAEAL,QAAQE,IAAI,CAAC;QACXI,QAAQC,QAAQC,OAAO,CAAC;QACxBC,SAAS;YACPX;YACAY,eAAe;YACf,4CAA4C;YAC5CC,UAAU;YACVC,KAAK,CAACA,KAAaC,eACjBlB,eAAeiB,KAAKC,cAAchB,IAAIiB,YAAY,CAACC,UAAU;YAC/DC,QAAQ,CAACJ,KAAaK,GAAQJ,eAC5BlB,eAAeiB,KAAKC,cAAchB,IAAIiB,YAAY,CAACC,UAAU;YAC/DG,SAAS;gBACP,mEAAmE;gBACnEC,wBAAwB;gBACxB,2CAA2C;gBAC3CC,kBAAkBvB,IAAIwB,QAAQ;gBAC9B,6DAA6D;gBAC7D,iCAAiC;gBACjCC,MAAM;gBACNC,eAAe,CACbC,UACAC,iBACAC,YACAC,UACAC;oBAEA,6BAA6B;oBAC7B,OAAO,CAAC,EAAE,EAAEF,WAAW,CAAC,EAAEE,KAAKC,cAAc,CAAC,CAAC;gBACjD;YACF;YACAC,YAAY;QACd;IACF;IAEA9B,QAAQE,IAAI,CAAC;QACXI,QAAQ;QACRG,SAAS;YACPsB,OAAOlC,IAAIO,aAAa;YACxBiB,UAAUxB,IAAIwB,QAAQ;YACtBhB,aAAaR,IAAIQ,WAAW;YAC5BN;YACAD;QACF;IACF;IAEA,OAAOE;AACT"}

View File

@@ -0,0 +1,15 @@
import chalk from "next/dist/compiled/chalk";
export function getGlobalImportError() {
return `Global CSS ${chalk.bold("cannot")} be imported from files other than your ${chalk.bold("Custom <App>")}. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to ${chalk.cyan("pages/_app.js")}. Or convert the import to Component-Level CSS (CSS Modules).\nRead more: https://nextjs.org/docs/messages/css-global`;
}
export function getGlobalModuleImportError() {
return `Global CSS ${chalk.bold("cannot")} be imported from within ${chalk.bold("node_modules")}.\nRead more: https://nextjs.org/docs/messages/css-npm`;
}
export function getLocalModuleImportError() {
return `CSS Modules ${chalk.bold("cannot")} be imported from within ${chalk.bold("node_modules")}.\nRead more: https://nextjs.org/docs/messages/css-modules-npm`;
}
export function getCustomDocumentError() {
return `CSS ${chalk.bold("cannot")} be imported within ${chalk.cyan("pages/_document.js")}. Please move global styles to ${chalk.cyan("pages/_app.js")}.`;
}
//# sourceMappingURL=messages.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/config/blocks/css/messages.ts"],"names":["chalk","getGlobalImportError","bold","cyan","getGlobalModuleImportError","getLocalModuleImportError","getCustomDocumentError"],"mappings":"AAAA,OAAOA,WAAW,2BAA0B;AAE5C,OAAO,SAASC;IACd,OAAO,CAAC,WAAW,EAAED,MAAME,IAAI,CAC7B,UACA,wCAAwC,EAAEF,MAAME,IAAI,CACpD,gBACA,qHAAqH,EAAEF,MAAMG,IAAI,CACjI,iBACA,qHAAqH,CAAC;AAC1H;AAEA,OAAO,SAASC;IACd,OAAO,CAAC,WAAW,EAAEJ,MAAME,IAAI,CAC7B,UACA,yBAAyB,EAAEF,MAAME,IAAI,CACrC,gBACA,sDAAsD,CAAC;AAC3D;AAEA,OAAO,SAASG;IACd,OAAO,CAAC,YAAY,EAAEL,MAAME,IAAI,CAC9B,UACA,yBAAyB,EAAEF,MAAME,IAAI,CACrC,gBACA,8DAA8D,CAAC;AACnE;AAEA,OAAO,SAASI;IACd,OAAO,CAAC,IAAI,EAAEN,MAAME,IAAI,CAAC,UAAU,oBAAoB,EAAEF,MAAMG,IAAI,CACjE,sBACA,+BAA+B,EAAEH,MAAMG,IAAI,CAAC,iBAAiB,CAAC,CAAC;AACnE"}

View File

@@ -0,0 +1,152 @@
import chalk from "next/dist/compiled/chalk";
import { findConfig } from "../../../../../lib/find-config";
const genericErrorText = "Malformed PostCSS Configuration";
function getError_NullConfig(pluginName) {
return `${chalk.red.bold("Error")}: Your PostCSS configuration for '${pluginName}' cannot have ${chalk.bold("null")} configuration.\nTo disable '${pluginName}', pass ${chalk.bold("false")}, otherwise, pass ${chalk.bold("true")} or a configuration object.`;
}
function isIgnoredPlugin(pluginPath) {
const ignoredRegex = /(?:^|[\\/])(postcss-modules-values|postcss-modules-scope|postcss-modules-extract-imports|postcss-modules-local-by-default|postcss-modules)(?:[\\/]|$)/i;
const match = ignoredRegex.exec(pluginPath);
if (match == null) {
return false;
}
const plugin = match.pop();
console.warn(`${chalk.yellow.bold("Warning")}: Please remove the ${chalk.underline(plugin)} plugin from your PostCSS configuration. ` + `This plugin is automatically configured by Next.js.\n` + "Read more: https://nextjs.org/docs/messages/postcss-ignored-plugin");
return true;
}
const createLazyPostCssPlugin = (fn)=>{
let result = undefined;
const plugin = (...args)=>{
if (result === undefined) result = fn();
if (result.postcss === true) {
return result(...args);
} else if (result.postcss) {
return result.postcss;
}
return result;
};
plugin.postcss = true;
return plugin;
};
async function loadPlugin(dir, pluginName, options) {
if (options === false || isIgnoredPlugin(pluginName)) {
return false;
}
if (options == null) {
console.error(getError_NullConfig(pluginName));
throw new Error(genericErrorText);
}
const pluginPath = require.resolve(pluginName, {
paths: [
dir
]
});
if (isIgnoredPlugin(pluginPath)) {
return false;
} else if (options === true) {
return createLazyPostCssPlugin(()=>require(pluginPath));
} else {
if (typeof options === "object" && Object.keys(options).length === 0) {
return createLazyPostCssPlugin(()=>require(pluginPath));
}
return createLazyPostCssPlugin(()=>require(pluginPath)(options));
}
}
function getDefaultPlugins(supportedBrowsers, disablePostcssPresetEnv) {
return [
require.resolve("next/dist/compiled/postcss-flexbugs-fixes"),
disablePostcssPresetEnv ? false : [
require.resolve("next/dist/compiled/postcss-preset-env"),
{
browsers: supportedBrowsers ?? [
"defaults"
],
autoprefixer: {
// Disable legacy flexbox support
flexbox: "no-2009"
},
// Enable CSS features that have shipped to the
// web platform, i.e. in 2+ browsers unflagged.
stage: 3,
features: {
"custom-properties": false
}
}
]
].filter(Boolean);
}
export async function getPostCssPlugins(dir, supportedBrowsers, disablePostcssPresetEnv = false) {
let config = await findConfig(dir, "postcss");
if (config == null) {
config = {
plugins: getDefaultPlugins(supportedBrowsers, disablePostcssPresetEnv)
};
}
if (typeof config === "function") {
throw new Error(`Your custom PostCSS configuration may not export a function. Please export a plain object instead.\n` + "Read more: https://nextjs.org/docs/messages/postcss-function");
}
// Warn user about configuration keys which are not respected
const invalidKey = Object.keys(config).find((key)=>key !== "plugins");
if (invalidKey) {
console.warn(`${chalk.yellow.bold("Warning")}: Your PostCSS configuration defines a field which is not supported (\`${invalidKey}\`). ` + `Please remove this configuration value.`);
}
// Enforce the user provided plugins if the configuration file is present
let plugins = config.plugins;
if (plugins == null || typeof plugins !== "object") {
throw new Error(`Your custom PostCSS configuration must export a \`plugins\` key.`);
}
if (!Array.isArray(plugins)) {
// Capture variable so TypeScript is happy
const pc = plugins;
plugins = Object.keys(plugins).reduce((acc, curr)=>{
const p = pc[curr];
if (typeof p === "undefined") {
console.error(getError_NullConfig(curr));
throw new Error(genericErrorText);
}
acc.push([
curr,
p
]);
return acc;
}, []);
}
const parsed = [];
plugins.forEach((plugin)=>{
if (plugin == null) {
console.warn(`${chalk.yellow.bold("Warning")}: A ${chalk.bold("null")} PostCSS plugin was provided. This entry will be ignored.`);
} else if (typeof plugin === "string") {
parsed.push([
plugin,
true
]);
} else if (Array.isArray(plugin)) {
const pluginName = plugin[0];
const pluginConfig = plugin[1];
if (typeof pluginName === "string" && (typeof pluginConfig === "boolean" || typeof pluginConfig === "object" || typeof pluginConfig === "string")) {
parsed.push([
pluginName,
pluginConfig
]);
} else {
if (typeof pluginName !== "string") {
console.error(`${chalk.red.bold("Error")}: A PostCSS Plugin must be provided as a ${chalk.bold("string")}. Instead, we got: '${pluginName}'.\n` + "Read more: https://nextjs.org/docs/messages/postcss-shape");
} else {
console.error(`${chalk.red.bold("Error")}: A PostCSS Plugin was passed as an array but did not provide its configuration ('${pluginName}').\n` + "Read more: https://nextjs.org/docs/messages/postcss-shape");
}
throw new Error(genericErrorText);
}
} else if (typeof plugin === "function") {
console.error(`${chalk.red.bold("Error")}: A PostCSS Plugin was passed as a function using require(), but it must be provided as a ${chalk.bold("string")}.\nRead more: https://nextjs.org/docs/messages/postcss-shape`);
throw new Error(genericErrorText);
} else {
console.error(`${chalk.red.bold("Error")}: An unknown PostCSS plugin was provided (${plugin}).\n` + "Read more: https://nextjs.org/docs/messages/postcss-shape");
throw new Error(genericErrorText);
}
});
const resolved = await Promise.all(parsed.map((p)=>loadPlugin(dir, p[0], p[1])));
const filtered = resolved.filter(Boolean);
return filtered;
}
//# sourceMappingURL=plugins.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/config/blocks/css/plugins.ts"],"names":["chalk","findConfig","genericErrorText","getError_NullConfig","pluginName","red","bold","isIgnoredPlugin","pluginPath","ignoredRegex","match","exec","plugin","pop","console","warn","yellow","underline","createLazyPostCssPlugin","fn","result","undefined","args","postcss","loadPlugin","dir","options","error","Error","require","resolve","paths","Object","keys","length","getDefaultPlugins","supportedBrowsers","disablePostcssPresetEnv","browsers","autoprefixer","flexbox","stage","features","filter","Boolean","getPostCssPlugins","config","plugins","invalidKey","find","key","Array","isArray","pc","reduce","acc","curr","p","push","parsed","forEach","pluginConfig","resolved","Promise","all","map","filtered"],"mappings":"AAAA,OAAOA,WAAW,2BAA0B;AAC5C,SAASC,UAAU,QAAQ,iCAAgC;AAY3D,MAAMC,mBAAmB;AAEzB,SAASC,oBAAoBC,UAAkB;IAC7C,OAAO,CAAC,EAAEJ,MAAMK,GAAG,CAACC,IAAI,CACtB,SACA,kCAAkC,EAAEF,WAAW,cAAc,EAAEJ,MAAMM,IAAI,CACzE,QACA,6BAA6B,EAAEF,WAAW,QAAQ,EAAEJ,MAAMM,IAAI,CAC9D,SACA,kBAAkB,EAAEN,MAAMM,IAAI,CAAC,QAAQ,2BAA2B,CAAC;AACvE;AAEA,SAASC,gBAAgBC,UAAkB;IACzC,MAAMC,eACJ;IACF,MAAMC,QAAQD,aAAaE,IAAI,CAACH;IAChC,IAAIE,SAAS,MAAM;QACjB,OAAO;IACT;IAEA,MAAME,SAASF,MAAMG,GAAG;IACxBC,QAAQC,IAAI,CACV,CAAC,EAAEf,MAAMgB,MAAM,CAACV,IAAI,CAAC,WAAW,oBAAoB,EAAEN,MAAMiB,SAAS,CACnEL,QACA,yCAAyC,CAAC,GAC1C,CAAC,qDAAqD,CAAC,GACvD;IAEJ,OAAO;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AChCL,OAAOM,GAAG,CAAC,CAACR,IAAMjC,WAAWC,KAAKgC,CAAC,CAAC,EAAE,EAAEA,CAAC,CAAC,EAAE;IAE9C,MAAMS,WAA+CJ,SAASnB,MAAM,CAClEC;IAGF,OAAOsB;AACT"}

View File

@@ -0,0 +1,27 @@
import curry from "next/dist/compiled/lodash.curry";
import { nextImageLoaderRegex } from "../../../../webpack-config";
import { loader } from "../../helpers";
import { pipe } from "../../utils";
import { getCustomDocumentImageError } from "./messages";
export const images = curry(async function images(_ctx, config) {
const fns = [
loader({
oneOf: [
{
test: nextImageLoaderRegex,
use: {
loader: "error-loader",
options: {
reason: getCustomDocumentImageError()
}
},
issuer: /pages[\\/]_document\./
}
]
})
];
const fn = pipe(...fns);
return fn(config);
});
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/config/blocks/images/index.ts"],"names":["curry","nextImageLoaderRegex","loader","pipe","getCustomDocumentImageError","images","_ctx","config","fns","oneOf","test","use","options","reason","issuer","fn"],"mappings":"AAAA,OAAOA,WAAW,kCAAiC;AAEnD,SAASC,oBAAoB,QAAQ,6BAA4B;AACjE,SAASC,MAAM,QAAQ,gBAAe;AACtC,SAAgDC,IAAI,QAAQ,cAAa;AACzE,SAASC,2BAA2B,QAAQ,aAAY;AAExD,OAAO,MAAMC,SAASL,MAAM,eAAeK,OACzCC,IAA0B,EAC1BC,MAA6B;IAE7B,MAAMC,MAAyB;QAC7BN,OAAO;YACLO,OAAO;gBACL;oBACEC,MAAMT;oBACNU,KAAK;wBACHT,QAAQ;wBACRU,SAAS;4BACPC,QAAQT;wBACV;oBACF;oBACAU,QAAQ;gBACV;aACD;QACH;KACD;IAED,MAAMC,KAAKZ,QAAQK;IACnB,OAAOO,GAAGR;AACZ,GAAE"}

View File

@@ -0,0 +1,6 @@
import chalk from "next/dist/compiled/chalk";
export function getCustomDocumentImageError() {
return `Images ${chalk.bold("cannot")} be imported within ${chalk.cyan("pages/_document.js")}. Please move image imports that need to be displayed on every page into ${chalk.cyan("pages/_app.js")}.\nRead more: https://nextjs.org/docs/messages/custom-document-image-import`;
}
//# sourceMappingURL=messages.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/config/blocks/images/messages.ts"],"names":["chalk","getCustomDocumentImageError","bold","cyan"],"mappings":"AAAA,OAAOA,WAAW,2BAA0B;AAE5C,OAAO,SAASC;IACd,OAAO,CAAC,OAAO,EAAED,MAAME,IAAI,CAAC,UAAU,oBAAoB,EAAEF,MAAMG,IAAI,CACpE,sBACA,yEAAyE,EAAEH,MAAMG,IAAI,CACrF,iBACA,2EAA2E,CAAC;AAChF"}

View File

@@ -0,0 +1,47 @@
import curry from "next/dist/compiled/lodash.curry";
export const loader = curry(function loader(rule, config) {
var _config_module_rules;
if (!config.module) {
config.module = {
rules: []
};
}
if (rule.oneOf) {
var _config_module_rules1;
const existing = (_config_module_rules1 = config.module.rules) == null ? void 0 : _config_module_rules1.find((arrayRule)=>arrayRule && typeof arrayRule === "object" && arrayRule.oneOf);
if (existing && typeof existing === "object") {
existing.oneOf.push(...rule.oneOf);
return config;
}
}
(_config_module_rules = config.module.rules) == null ? void 0 : _config_module_rules.push(rule);
return config;
});
export const unshiftLoader = curry(function unshiftLoader(rule, config) {
var _config_module_rules;
if (!config.module) {
config.module = {
rules: []
};
}
if (rule.oneOf) {
var _config_module_rules1;
const existing = (_config_module_rules1 = config.module.rules) == null ? void 0 : _config_module_rules1.find((arrayRule)=>arrayRule && typeof arrayRule === "object" && arrayRule.oneOf);
if (existing && typeof existing === "object") {
var _existing_oneOf;
(_existing_oneOf = existing.oneOf) == null ? void 0 : _existing_oneOf.unshift(...rule.oneOf);
return config;
}
}
(_config_module_rules = config.module.rules) == null ? void 0 : _config_module_rules.unshift(rule);
return config;
});
export const plugin = curry(function plugin(p, config) {
if (!config.plugins) {
config.plugins = [];
}
config.plugins.push(p);
return config;
});
//# sourceMappingURL=helpers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/config/helpers.ts"],"names":["curry","loader","rule","config","module","rules","oneOf","existing","find","arrayRule","push","unshiftLoader","unshift","plugin","p","plugins"],"mappings":"AAAA,OAAOA,WAAW,kCAAiC;AAGnD,OAAO,MAAMC,SAASD,MAAM,SAASC,OACnCC,IAAyB,EACzBC,MAA6B;QAiB7BA;IAfA,IAAI,CAACA,OAAOC,MAAM,EAAE;QAClBD,OAAOC,MAAM,GAAG;YAAEC,OAAO,EAAE;QAAC;IAC9B;IAEA,IAAIH,KAAKI,KAAK,EAAE;YACGH;QAAjB,MAAMI,YAAWJ,wBAAAA,OAAOC,MAAM,CAACC,KAAK,qBAAnBF,sBAAqBK,IAAI,CACxC,CAACC,YACCA,aAAa,OAAOA,cAAc,YAAYA,UAAUH,KAAK;QAEjE,IAAIC,YAAY,OAAOA,aAAa,UAAU;YAC5CA,SAASD,KAAK,CAAEI,IAAI,IAAIR,KAAKI,KAAK;YAClC,OAAOH;QACT;IACF;KAEAA,uBAAAA,OAAOC,MAAM,CAACC,KAAK,qBAAnBF,qBAAqBO,IAAI,CAACR;IAC1B,OAAOC;AACT,GAAE;AAEF,OAAO,MAAMQ,gBAAgBX,MAAM,SAASW,cAC1CT,IAAyB,EACzBC,MAA6B;QAiB7BA;IAfA,IAAI,CAACA,OAAOC,MAAM,EAAE;QAClBD,OAAOC,MAAM,GAAG;YAAEC,OAAO,EAAE;QAAC;IAC9B;IAEA,IAAIH,KAAKI,KAAK,EAAE;YACGH;QAAjB,MAAMI,YAAWJ,wBAAAA,OAAOC,MAAM,CAACC,KAAK,qBAAnBF,sBAAqBK,IAAI,CACxC,CAACC,YACCA,aAAa,OAAOA,cAAc,YAAYA,UAAUH,KAAK;QAEjE,IAAIC,YAAY,OAAOA,aAAa,UAAU;gBAC5CA;aAAAA,kBAAAA,SAASD,KAAK,qBAAdC,gBAAgBK,OAAO,IAAIV,KAAKI,KAAK;YACrC,OAAOH;QACT;IACF;KAEAA,uBAAAA,OAAOC,MAAM,CAACC,KAAK,qBAAnBF,qBAAqBS,OAAO,CAACV;IAC7B,OAAOC;AACT,GAAE;AAEF,OAAO,MAAMU,SAASb,MAAM,SAASa,OACnCC,CAAgC,EAChCX,MAA6B;IAE7B,IAAI,CAACA,OAAOY,OAAO,EAAE;QACnBZ,OAAOY,OAAO,GAAG,EAAE;IACrB;IACAZ,OAAOY,OAAO,CAACL,IAAI,CAACI;IACpB,OAAOX;AACT,GAAE"}

View File

@@ -0,0 +1,36 @@
import { base } from "./blocks/base";
import { css } from "./blocks/css";
import { images } from "./blocks/images";
import { pipe } from "./utils";
export async function buildConfiguration(config, { hasAppDir, supportedBrowsers, rootDirectory, customAppFile, isDevelopment, isServer, isEdgeRuntime, targetWeb, assetPrefix, sassOptions, productionBrowserSourceMaps, future, transpilePackages, experimental, disableStaticImages, serverSourceMaps }) {
const ctx = {
hasAppDir,
supportedBrowsers,
rootDirectory,
customAppFile,
isDevelopment,
isProduction: !isDevelopment,
isServer,
isEdgeRuntime,
isClient: !isServer,
targetWeb,
assetPrefix: assetPrefix ? assetPrefix.endsWith("/") ? assetPrefix.slice(0, -1) : assetPrefix : "",
sassOptions,
productionBrowserSourceMaps,
transpilePackages,
future,
experimental,
serverSourceMaps: serverSourceMaps ?? false
};
let fns = [
base(ctx),
css(ctx)
];
if (!disableStaticImages) {
fns.push(images(ctx));
}
const fn = pipe(...fns);
return fn(config);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/config/index.ts"],"names":["base","css","images","pipe","buildConfiguration","config","hasAppDir","supportedBrowsers","rootDirectory","customAppFile","isDevelopment","isServer","isEdgeRuntime","targetWeb","assetPrefix","sassOptions","productionBrowserSourceMaps","future","transpilePackages","experimental","disableStaticImages","serverSourceMaps","ctx","isProduction","isClient","endsWith","slice","fns","push","fn"],"mappings":"AAIA,SAASA,IAAI,QAAQ,gBAAe;AACpC,SAASC,GAAG,QAAQ,eAAc;AAClC,SAASC,MAAM,QAAQ,kBAAiB;AACxC,SAASC,IAAI,QAAQ,UAAS;AAE9B,OAAO,eAAeC,mBACpBC,MAA6B,EAC7B,EACEC,SAAS,EACTC,iBAAiB,EACjBC,aAAa,EACbC,aAAa,EACbC,aAAa,EACbC,QAAQ,EACRC,aAAa,EACbC,SAAS,EACTC,WAAW,EACXC,WAAW,EACXC,2BAA2B,EAC3BC,MAAM,EACNC,iBAAiB,EACjBC,YAAY,EACZC,mBAAmB,EACnBC,gBAAgB,EAkBjB;IAED,MAAMC,MAA4B;QAChChB;QACAC;QACAC;QACAC;QACAC;QACAa,cAAc,CAACb;QACfC;QACAC;QACAY,UAAU,CAACb;QACXE;QACAC,aAAaA,cACTA,YAAYW,QAAQ,CAAC,OACnBX,YAAYY,KAAK,CAAC,GAAG,CAAC,KACtBZ,cACF;QACJC;QACAC;QACAE;QACAD;QACAE;QACAE,kBAAkBA,oBAAoB;IACxC;IAEA,IAAIM,MAAM;QAAC3B,KAAKsB;QAAMrB,IAAIqB;KAAK;IAC/B,IAAI,CAACF,qBAAqB;QACxBO,IAAIC,IAAI,CAAC1B,OAAOoB;IAClB;IACA,MAAMO,KAAK1B,QAAQwB;IACnB,OAAOE,GAAGxB;AACZ"}

View File

@@ -0,0 +1,3 @@
export const pipe = (...fns)=>(param)=>fns.reduce(async (result, next)=>next(await result), param);
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/config/utils.ts"],"names":["pipe","fns","param","reduce","result","next"],"mappings":"AAoCA,OAAO,MAAMA,OACX,CAAI,GAAGC,MACP,CAACC,QACCD,IAAIE,MAAM,CACR,OAAOC,QAAwBC,OAASA,KAAK,MAAMD,SACnDF,OACD"}

View File

@@ -0,0 +1,22 @@
export default class CssSyntaxError extends Error {
constructor(error){
super(error);
const { reason, line, column } = error;
this.name = "CssSyntaxError";
// Based on https://github.com/postcss/postcss/blob/master/lib/css-syntax-error.es6#L132
// We don't need `plugin` and `file` properties.
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
this.message += `(${line}:${column}) `;
}
this.message += `${reason}`;
const code = error.showSourceCode();
if (code) {
this.message += `\n\n${code}\n`;
}
// We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
this.stack = false;
}
}
//# sourceMappingURL=CssSyntaxError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/css-loader/src/CssSyntaxError.ts"],"names":["CssSyntaxError","Error","constructor","error","reason","line","column","name","message","code","showSourceCode","stack"],"mappings":"AAAA,eAAe,MAAMA,uBAAuBC;IAE1CC,YAAYC,KAAU,CAAE;QACtB,KAAK,CAACA;QAEN,MAAM,EAAEC,MAAM,EAAEC,IAAI,EAAEC,MAAM,EAAE,GAAGH;QAEjC,IAAI,CAACI,IAAI,GAAG;QAEZ,wFAAwF;QACxF,gDAAgD;QAChD,IAAI,CAACC,OAAO,GAAG,CAAC,EAAE,IAAI,CAACD,IAAI,CAAC,IAAI,CAAC;QAEjC,IAAI,OAAOF,SAAS,aAAa;YAC/B,IAAI,CAACG,OAAO,IAAI,CAAC,CAAC,EAAEH,KAAK,CAAC,EAAEC,OAAO,EAAE,CAAC;QACxC;QAEA,IAAI,CAACE,OAAO,IAAI,CAAC,EAAEJ,OAAO,CAAC;QAE3B,MAAMK,OAAON,MAAMO,cAAc;QAEjC,IAAID,MAAM;YACR,IAAI,CAACD,OAAO,IAAI,CAAC,IAAI,EAAEC,KAAK,EAAE,CAAC;QACjC;QAEA,wIAAwI;QACxI,IAAI,CAACE,KAAK,GAAG;IACf;AACF"}

View File

@@ -0,0 +1,79 @@
/*
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
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.
*/ const preserveCamelCase = (string, locale)=>{
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for(let i = 0; i < string.length; i++){
const character = string[i];
if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
string = string.slice(0, i) + "-" + string.slice(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
string = string.slice(0, i - 1) + "-" + string.slice(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character;
}
}
return string;
};
const preserveConsecutiveUppercase = (input)=>{
return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, (m1)=>m1.toLowerCase());
};
const postProcess = (input, options)=>{
return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1)=>p1.toLocaleUpperCase(options.locale)).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, (m)=>m.toLocaleUpperCase(options.locale));
};
const camelCase = (input, options)=>{
if (!(typeof input === "string" || Array.isArray(input))) {
throw new TypeError("Expected the input to be `string | string[]`");
}
options = {
pascalCase: false,
preserveConsecutiveUppercase: false,
...options
};
if (Array.isArray(input)) {
input = input.map((x)=>x.trim()).filter((x)=>x.length).join("-");
} else {
input = input.trim();
}
if (input.length === 0) {
return "";
}
if (input.length === 1) {
return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale);
}
const hasUpperCase = input !== input.toLocaleLowerCase(options.locale);
if (hasUpperCase) {
input = preserveCamelCase(input, options.locale);
}
input = input.replace(/^[_.\- ]+/, "");
if (options.preserveConsecutiveUppercase) {
input = preserveConsecutiveUppercase(input);
} else {
input = input.toLocaleLowerCase();
}
if (options.pascalCase) {
input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1);
}
return postProcess(input, options);
};
export default camelCase;
//# sourceMappingURL=camelcase.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/css-loader/src/camelcase.ts"],"names":["preserveCamelCase","string","locale","isLastCharLower","isLastCharUpper","isLastLastCharUpper","i","length","character","test","slice","toLocaleLowerCase","toLocaleUpperCase","preserveConsecutiveUppercase","input","replace","m1","toLowerCase","postProcess","options","_","p1","m","camelCase","Array","isArray","TypeError","pascalCase","map","x","trim","filter","join","hasUpperCase","charAt"],"mappings":"AAAA;;;;;;;;;;AAUA,GAEA,MAAMA,oBAAoB,CAACC,QAAgBC;IACzC,IAAIC,kBAAkB;IACtB,IAAIC,kBAAkB;IACtB,IAAIC,sBAAsB;IAE1B,IAAK,IAAIC,IAAI,GAAGA,IAAIL,OAAOM,MAAM,EAAED,IAAK;QACtC,MAAME,YAAYP,MAAM,CAACK,EAAE;QAE3B,IAAIH,mBAAmB,YAAYM,IAAI,CAACD,YAAY;YAClDP,SAASA,OAAOS,KAAK,CAAC,GAAGJ,KAAK,MAAML,OAAOS,KAAK,CAACJ;YACjDH,kBA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,OAAO;IACT;IAEA,IAAIO,MAAMP,MAAM,KAAK,GAAG;QACtB,OAAOY,QAAQQ,UAAU,GACrBb,MAAMF,iBAAiB,CAACO,QAAQjB,MAAM,IACtCY,MAAMH,iBAAiB,CAACQ,QAAQjB,MAAM;IAC5C;IAEA,MAAM+B,eAAenB,UAAUA,MAAMH,iBAAiB,CAACQ,QAAQjB,MAAM;IAErE,IAAI+B,cAAc;QAChBnB,QAAQd,kBAAkBc,OAAOK,QAAQjB,MAAM;IACjD;IAEAY,QAAQA,MAAMC,OAAO,CAAC,aAAa;IAEnC,IAAII,QAAQN,4BAA4B,EAAE;QACxCC,QAAQD,6BAA6BC;IACvC,OAAO;QACLA,QAAQA,MAAMH,iBAAiB;IACjC;IAEA,IAAIQ,QAAQQ,UAAU,EAAE;QACtBb,QAAQA,MAAMoB,MAAM,CAAC,GAAGtB,iBAAiB,CAACO,QAAQjB,MAAM,IAAIY,MAAMJ,KAAK,CAAC;IAC1E;IAEA,OAAOQ,YAAYJ,OAAOK;AAC5B;AAEA,eAAeI,UAAS"}

View File

@@ -0,0 +1,254 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ import CssSyntaxError from "./CssSyntaxError";
import Warning from "../../postcss-loader/src/Warning";
import { stringifyRequest } from "../../../stringify-request";
const moduleRegExp = /\.module\.\w+$/i;
function getModulesOptions(rawOptions, loaderContext) {
const { resourcePath } = loaderContext;
if (typeof rawOptions.modules === "undefined") {
const isModules = moduleRegExp.test(resourcePath);
if (!isModules) {
return false;
}
} else if (typeof rawOptions.modules === "boolean" && rawOptions.modules === false) {
return false;
}
let modulesOptions = {
compileType: rawOptions.icss ? "icss" : "module",
auto: true,
mode: "local",
exportGlobals: false,
localIdentName: "[hash:base64]",
localIdentContext: loaderContext.rootContext,
localIdentHashPrefix: "",
// eslint-disable-next-line no-undefined
localIdentRegExp: undefined,
namedExport: false,
exportLocalsConvention: "asIs",
exportOnlyLocals: false
};
if (typeof rawOptions.modules === "boolean" || typeof rawOptions.modules === "string") {
modulesOptions.mode = typeof rawOptions.modules === "string" ? rawOptions.modules : "local";
} else {
if (rawOptions.modules) {
if (typeof rawOptions.modules.auto === "boolean") {
const isModules = rawOptions.modules.auto && moduleRegExp.test(resourcePath);
if (!isModules) {
return false;
}
} else if (rawOptions.modules.auto instanceof RegExp) {
const isModules = rawOptions.modules.auto.test(resourcePath);
if (!isModules) {
return false;
}
} else if (typeof rawOptions.modules.auto === "function") {
const isModule = rawOptions.modules.auto(resourcePath);
if (!isModule) {
return false;
}
}
if (rawOptions.modules.namedExport === true && typeof rawOptions.modules.exportLocalsConvention === "undefined") {
modulesOptions.exportLocalsConvention = "camelCaseOnly";
}
}
modulesOptions = {
...modulesOptions,
...rawOptions.modules || {}
};
}
if (typeof modulesOptions.mode === "function") {
modulesOptions.mode = modulesOptions.mode(loaderContext.resourcePath);
}
if (modulesOptions.namedExport === true) {
if (rawOptions.esModule === false) {
throw new Error('The "modules.namedExport" option requires the "esModules" option to be enabled');
}
if (modulesOptions.exportLocalsConvention !== "camelCaseOnly") {
throw new Error('The "modules.namedExport" option requires the "modules.exportLocalsConvention" option to be "camelCaseOnly"');
}
}
return modulesOptions;
}
function normalizeOptions(rawOptions, loaderContext) {
if (rawOptions.icss) {
loaderContext.emitWarning(new Error('The "icss" option is deprecated, use "modules.compileType: "icss"" instead'));
}
const modulesOptions = getModulesOptions(rawOptions, loaderContext);
return {
url: typeof rawOptions.url === "undefined" ? true : rawOptions.url,
import: typeof rawOptions.import === "undefined" ? true : rawOptions.import,
modules: modulesOptions,
// TODO remove in the next major release
icss: typeof rawOptions.icss === "undefined" ? false : rawOptions.icss,
sourceMap: typeof rawOptions.sourceMap === "boolean" ? rawOptions.sourceMap : loaderContext.sourceMap,
importLoaders: typeof rawOptions.importLoaders === "string" ? parseInt(rawOptions.importLoaders, 10) : rawOptions.importLoaders,
esModule: typeof rawOptions.esModule === "undefined" ? true : rawOptions.esModule,
fontLoader: rawOptions.fontLoader
};
}
export default async function loader(content, map, meta) {
const rawOptions = this.getOptions();
const plugins = [];
const callback = this.async();
const loaderSpan = this.currentTraceSpan.traceChild("css-loader");
loaderSpan.traceAsyncFn(async ()=>{
let options;
try {
options = normalizeOptions(rawOptions, this);
} catch (error) {
throw error;
}
const { postcss } = await rawOptions.postcss();
const { shouldUseModulesPlugins, shouldUseImportPlugin, shouldUseURLPlugin, shouldUseIcssPlugin, getPreRequester, getExportCode, getFilter, getImportCode, getModuleCode, getModulesPlugins, normalizeSourceMap, sort } = require("./utils");
const { icssParser, importParser, urlParser } = require("./plugins");
const replacements = [];
// if it's a font loader next-font-loader will have exports that should be exported as is
const exports = options.fontLoader ? meta.exports : [];
if (shouldUseModulesPlugins(options)) {
plugins.push(...getModulesPlugins(options, this, meta));
}
const importPluginImports = [];
const importPluginApi = [];
if (shouldUseImportPlugin(options)) {
const resolver = this.getResolve({
conditionNames: [
"style"
],
extensions: [
".css"
],
mainFields: [
"css",
"style",
"main",
"..."
],
mainFiles: [
"index",
"..."
],
restrictions: [
/\.css$/i
]
});
plugins.push(importParser({
imports: importPluginImports,
api: importPluginApi,
context: this.context,
rootContext: this.rootContext,
filter: getFilter(options.import, this.resourcePath),
resolver,
urlHandler: (url)=>stringifyRequest(this, getPreRequester(this)(options.importLoaders) + url)
}));
}
const urlPluginImports = [];
if (shouldUseURLPlugin(options)) {
const urlResolver = this.getResolve({
conditionNames: [
"asset"
],
mainFields: [
"asset"
],
mainFiles: [],
extensions: []
});
plugins.push(urlParser({
imports: urlPluginImports,
replacements,
context: this.context,
rootContext: this.rootContext,
filter: getFilter(options.url, this.resourcePath),
resolver: urlResolver,
urlHandler: (url)=>stringifyRequest(this, url)
}));
}
const icssPluginImports = [];
const icssPluginApi = [];
if (shouldUseIcssPlugin(options)) {
const icssResolver = this.getResolve({
conditionNames: [
"style"
],
extensions: [],
mainFields: [
"css",
"style",
"main",
"..."
],
mainFiles: [
"index",
"..."
]
});
plugins.push(icssParser({
imports: icssPluginImports,
api: icssPluginApi,
replacements,
exports,
context: this.context,
rootContext: this.rootContext,
resolver: icssResolver,
urlHandler: (url)=>stringifyRequest(this, getPreRequester(this)(options.importLoaders) + url)
}));
}
// Reuse CSS AST (PostCSS AST e.g 'postcss-loader') to avoid reparsing
if (meta) {
const { ast } = meta;
if (ast && ast.type === "postcss") {
// eslint-disable-next-line no-param-reassign
content = ast.root;
loaderSpan.setAttribute("astUsed", "true");
}
}
const { resourcePath } = this;
let result;
try {
result = await postcss(plugins).process(content, {
from: resourcePath,
to: resourcePath,
map: options.sourceMap ? {
prev: map ? normalizeSourceMap(map, resourcePath) : null,
inline: false,
annotation: false
} : false
});
} catch (error) {
if (error.file) {
this.addDependency(error.file);
}
throw error.name === "CssSyntaxError" ? new CssSyntaxError(error) : error;
}
for (const warning of result.warnings()){
this.emitWarning(new Warning(warning));
}
const imports = [
...icssPluginImports.sort(sort),
...importPluginImports.sort(sort),
...urlPluginImports.sort(sort)
];
const api = [
...importPluginApi.sort(sort),
...icssPluginApi.sort(sort)
];
if (options.modules.exportOnlyLocals !== true) {
imports.unshift({
importName: "___CSS_LOADER_API_IMPORT___",
url: stringifyRequest(this, require.resolve("./runtime/api"))
});
}
const importCode = getImportCode(imports, options);
const moduleCode = getModuleCode(result, api, replacements, options, this);
const exportCode = getExportCode(exports, replacements, options);
return `${importCode}${moduleCode}${exportCode}`;
}).then((code)=>{
callback(null, code);
}, (err)=>{
callback(err);
});
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
import importParser from "./postcss-import-parser";
import icssParser from "./postcss-icss-parser";
import urlParser from "./postcss-url-parser";
export { importParser, icssParser, urlParser };
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/loaders/css-loader/src/plugins/index.ts"],"names":["importParser","icssParser","urlParser"],"mappings":"AAAA,OAAOA,kBAAkB,0BAAyB;AAClD,OAAOC,gBAAgB,wBAAuB;AAC9C,OAAOC,eAAe,uBAAsB;AAE5C,SAASF,YAAY,EAAEC,UAAU,EAAEC,SAAS,GAAE"}

View File

@@ -0,0 +1,97 @@
import { extractICSS, replaceValueSymbols, replaceSymbols } from "next/dist/compiled/icss-utils";
import { normalizeUrl, resolveRequests, requestify } from "../utils";
const plugin = (options = {})=>{
return {
postcssPlugin: "postcss-icss-parser",
async OnceExit (root) {
const importReplacements = Object.create(null);
const { icssImports, icssExports } = extractICSS(root);
const imports = new Map();
const tasks = [];
// eslint-disable-next-line guard-for-in
for(const url in icssImports){
const tokens = icssImports[url];
if (Object.keys(tokens).length === 0) {
continue;
}
let normalizedUrl = url;
let prefix = "";
const queryParts = normalizedUrl.split("!");
if (queryParts.length > 1) {
normalizedUrl = queryParts.pop();
prefix = queryParts.join("!");
}
const request = requestify(normalizeUrl(normalizedUrl, true), options.rootContext);
const doResolve = async ()=>{
const { resolver, context } = options;
const resolvedUrl = await resolveRequests(resolver, context, [
...new Set([
normalizedUrl,
request
])
]);
if (!resolvedUrl) {
return;
}
// eslint-disable-next-line consistent-return
return {
url: resolvedUrl,
prefix,
tokens
};
};
tasks.push(doResolve());
}
const results = await Promise.all(tasks);
for(let index = 0; index <= results.length - 1; index++){
const item = results[index];
if (!item) {
continue;
}
const newUrl = item.prefix ? `${item.prefix}!${item.url}` : item.url;
const importKey = newUrl;
let importName = imports.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_ICSS_IMPORT_${imports.size}___`;
imports.set(importKey, importName);
options.imports.push({
type: "icss_import",
importName,
url: options.urlHandler(newUrl),
icss: true,
index
});
options.api.push({
importName,
dedupe: true,
index
});
}
for (const [replacementIndex, token] of Object.keys(item.tokens).entries()){
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${index}_REPLACEMENT_${replacementIndex}___`;
const localName = item.tokens[token];
importReplacements[token] = replacementName;
options.replacements.push({
replacementName,
importName,
localName
});
}
}
if (Object.keys(importReplacements).length > 0) {
replaceSymbols(root, importReplacements);
}
for (const name of Object.keys(icssExports)){
const value = replaceValueSymbols(icssExports[name], importReplacements);
options.exports.push({
name,
value
});
}
}
};
};
plugin.postcss = true;
export default plugin;
//# sourceMappingURL=postcss-icss-parser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/loaders/css-loader/src/plugins/postcss-icss-parser.ts"],"names":["extractICSS","replaceValueSymbols","replaceSymbols","normalizeUrl","resolveRequests","requestify","plugin","options","postcssPlugin","OnceExit","root","importReplacements","Object","create","icssImports","icssExports","imports","Map","tasks","url","tokens","keys","length","normalizedUrl","prefix","queryParts","split","pop","join","request","rootContext","doResolve","resolver","context","resolvedUrl","Set","push","results","Promise","all","index","item","newUrl","importKey","importName","get","size","set","type","urlHandler","icss","api","dedupe","replacementIndex","token","entries","replacementName","localName","replacements","name","value","exports","postcss"],"mappings":"AAAA,SACEA,WAAW,EACXC,mBAAmB,EACnBC,cAAc,QACT,gCAA+B;AAEtC,SAASC,YAAY,EAAEC,eAAe,EAAEC,UAAU,QAAQ,WAAU;AAEpE,MAAMC,SAAS,CAACC,UAAe,CAAC,CAAC;IAC/B,OAAO;QACLC,eAAe;QACf,MAAMC,UAASC,IAAS;YACtB,MAAMC,qBAAqBC,OAAOC,MAAM,CAAC;YACzC,MAAM,EAAEC,WAAW,EAAEC,WAAW,EAAE,GAAGf,YAAYU;YACjD,MAAMM,UAAU,IAAIC;YACpB,MAAMC,QAAQ,EAAE;YAEhB,wCAAwC;YACxC,IAAK,MAAMC,OAAOL,YAAa;gBAC7B,MAAMM,SAASN,WAAW,CAACK,IAAI;gBAE/B,IAAIP,OAAOS,IAAI,CAACD,QAAQE,MAAM,KAAK,GAAG;oBAEpC;gBACF;gBAEA,IAAIC,gBAAgBJ;gBACpB,IAAIK,SAAS;gBAEb,MAAMC,aAAaF,cAAcG,KAAK,CAAC;gBAEvC,IAAID,WAAWH,MAAM,GAAG,GAAG;oBACzBC,gBAAgBE,WAAWE,GAAG;oBAC9BH,SAASC,WAAWG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AAM,IAAI1C,OAAOS,IAAI,CACjDoB,KAAKrB,MAAM,EACXmC,OAAO,GAAI;oBACX,MAAMC,kBAAkB,CAAC,0BAA0B,EAAEhB,MAAM,aAAa,EAAEa,iBAAiB,GAAG,CAAC;oBAC/F,MAAMI,YAAYhB,KAAKrB,MAAM,CAACkC,MAAM;oBAEpC3C,kBAAkB,CAAC2C,MAAM,GAAGE;oBAE5BjD,QAAQmD,YAAY,CAACtB,IAAI,CAAC;wBAAEoB;wBAAiBZ;wBAAYa;oBAAU;gBACrE;YACF;YAEA,IAAI7C,OAAOS,IAAI,CAACV,oBAAoBW,MAAM,GAAG,GAAG;gBAC9CpB,eAAeQ,MAAMC;YACvB;YAEA,KAAK,MAAMgD,QAAQ/C,OAAOS,IAAI,CAACN,aAAc;gBAC3C,MAAM6C,QAAQ3D,oBAAoBc,WAAW,CAAC4C,KAAK,EAAEhD;gBAErDJ,QAAQsD,OAAO,CAACzB,IAAI,CAAC;oBAAEuB;oBAAMC;gBAAM;YACrC;QACF;IACF;AACF;AAEAtD,OAAOwD,OAAO,GAAG;AAEjB,eAAexD,OAAM"}

View File

@@ -0,0 +1,193 @@
import valueParser from "next/dist/compiled/postcss-value-parser";
import { normalizeUrl, resolveRequests, isUrlRequestable, requestify, // @ts-expect-error TODO: this export doesn't exist? Double check.
WEBPACK_IGNORE_COMMENT_REGEXP } from "../utils";
function parseNode(atRule, key) {
// Convert only top-level @import
if (atRule.parent.type !== "root") {
return;
}
if (atRule.raws && atRule.raws.afterName && atRule.raws.afterName.trim().length > 0) {
const lastCommentIndex = atRule.raws.afterName.lastIndexOf("/*");
const matched = atRule.raws.afterName.slice(lastCommentIndex).match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched && matched[2] === "true") {
return;
}
}
const prevNode = atRule.prev();
if (prevNode && prevNode.type === "comment") {
const matched = prevNode.text.match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched && matched[2] === "true") {
return;
}
}
// Nodes do not exists - `@import url('http://') :root {}`
if (atRule.nodes) {
const error = new Error("It looks like you didn't end your @import statement correctly. Child nodes are attached to it.");
error.node = atRule;
throw error;
}
const { nodes: paramsNodes } = valueParser(atRule[key]);
// No nodes - `@import ;`
// Invalid type - `@import foo-bar;`
if (paramsNodes.length === 0 || paramsNodes[0].type !== "string" && paramsNodes[0].type !== "function") {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
let isStringValue;
let url;
if (paramsNodes[0].type === "string") {
isStringValue = true;
url = paramsNodes[0].value;
} else {
// Invalid function - `@import nourl(test.css);`
if (paramsNodes[0].value.toLowerCase() !== "url") {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
isStringValue = paramsNodes[0].nodes.length !== 0 && paramsNodes[0].nodes[0].type === "string";
url = isStringValue ? paramsNodes[0].nodes[0].value : valueParser.stringify(paramsNodes[0].nodes);
}
url = normalizeUrl(url, isStringValue);
const isRequestable = isUrlRequestable(url);
let prefix;
if (isRequestable) {
const queryParts = url.split("!");
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
}
// Empty url - `@import "";` or `@import url();`
if (url.trim().length === 0) {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
const mediaNodes = paramsNodes.slice(1);
let media;
if (mediaNodes.length > 0) {
media = valueParser.stringify(mediaNodes).trim().toLowerCase();
}
// eslint-disable-next-line consistent-return
return {
atRule,
prefix,
url,
media,
isRequestable
};
}
const plugin = (options = {})=>{
return {
postcssPlugin: "postcss-import-parser",
prepare (result) {
const parsedAtRules = [];
return {
AtRule: {
import (atRule) {
let parsedAtRule;
try {
// @ts-expect-error TODO: there is no third argument?
parsedAtRule = parseNode(atRule, "params", result);
} catch (error) {
result.warn(error.message, {
node: error.node
});
}
if (!parsedAtRule) {
return;
}
parsedAtRules.push(parsedAtRule);
}
},
async OnceExit () {
if (parsedAtRules.length === 0) {
return;
}
const resolvedAtRules = await Promise.all(parsedAtRules.map(async (parsedAtRule)=>{
const { atRule, isRequestable, prefix, url, media } = parsedAtRule;
if (options.filter) {
const needKeep = await options.filter(url, media);
if (!needKeep) {
return;
}
}
if (isRequestable) {
const request = requestify(url, options.rootContext);
const { resolver, context } = options;
const resolvedUrl = await resolveRequests(resolver, context, [
...new Set([
request,
url
])
]);
if (!resolvedUrl) {
return;
}
if (resolvedUrl === options.resourcePath) {
atRule.remove();
return;
}
atRule.remove();
// eslint-disable-next-line consistent-return
return {
url: resolvedUrl,
media,
prefix,
isRequestable
};
}
atRule.remove();
// eslint-disable-next-line consistent-return
return {
url,
media,
prefix,
isRequestable
};
}));
const urlToNameMap = new Map();
for(let index = 0; index <= resolvedAtRules.length - 1; index++){
const resolvedAtRule = resolvedAtRules[index];
if (!resolvedAtRule) {
continue;
}
const { url, isRequestable, media } = resolvedAtRule;
if (!isRequestable) {
options.api.push({
url,
media,
index
});
continue;
}
const { prefix } = resolvedAtRule;
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = urlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_AT_RULE_IMPORT_${urlToNameMap.size}___`;
urlToNameMap.set(newUrl, importName);
options.imports.push({
type: "rule_import",
importName,
url: options.urlHandler(newUrl),
index
});
}
options.api.push({
importName,
media,
index
});
}
}
};
}
};
};
plugin.postcss = true;
export default plugin;
//# sourceMappingURL=postcss-import-parser.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,314 @@
import valueParser from "next/dist/compiled/postcss-value-parser";
import { resolveRequests, normalizeUrl, requestify, isUrlRequestable, isDataUrl, // @ts-expect-error TODO: this export doesn't exist? Double check.
WEBPACK_IGNORE_COMMENT_REGEXP } from "../utils";
const isUrlFunc = /url/i;
const isImageSetFunc = /^(?:-webkit-)?image-set$/i;
const needParseDeclaration = /(?:url|(?:-webkit-)?image-set)\(/i;
function getNodeFromUrlFunc(node) {
return node.nodes && node.nodes[0];
}
function getWebpackIgnoreCommentValue(index, nodes, inBetween) {
if (index === 0 && typeof inBetween !== "undefined") {
return inBetween;
}
let prevValueNode = nodes[index - 1];
if (!prevValueNode) {
// eslint-disable-next-line consistent-return
return;
}
if (prevValueNode.type === "space") {
if (!nodes[index - 2]) {
// eslint-disable-next-line consistent-return
return;
}
prevValueNode = nodes[index - 2];
}
if (prevValueNode.type !== "comment") {
// eslint-disable-next-line consistent-return
return;
}
const matched = prevValueNode.value.match(WEBPACK_IGNORE_COMMENT_REGEXP);
return matched && matched[2] === "true";
}
function shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL) {
if (url.length === 0) {
result.warn(`Unable to find uri in '${declaration.toString()}'`, {
node: declaration
});
return false;
}
if (isDataUrl(url) && isSupportDataURLInNewURL) {
try {
decodeURIComponent(url);
} catch (ignoreError) {
return false;
}
return true;
}
if (!isUrlRequestable(url)) {
return false;
}
return true;
}
function parseDeclaration(declaration, key, result, isSupportDataURLInNewURL) {
if (!needParseDeclaration.test(declaration[key])) {
return;
}
const parsed = valueParser(declaration.raws && declaration.raws.value && declaration.raws.value.raw ? declaration.raws.value.raw : declaration[key]);
let inBetween;
if (declaration.raws && declaration.raws.between) {
const lastCommentIndex = declaration.raws.between.lastIndexOf("/*");
const matched = declaration.raws.between.slice(lastCommentIndex).match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched) {
inBetween = matched[2] === "true";
}
}
let isIgnoreOnDeclaration = false;
const prevNode = declaration.prev();
if (prevNode && prevNode.type === "comment") {
const matched = prevNode.text.match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched) {
isIgnoreOnDeclaration = matched[2] === "true";
}
}
let needIgnore;
const parsedURLs = [];
parsed.walk((valueNode, index, valueNodes)=>{
if (valueNode.type !== "function") {
return;
}
if (isUrlFunc.test(valueNode.value)) {
needIgnore = getWebpackIgnoreCommentValue(index, valueNodes, inBetween);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
return;
}
const { nodes } = valueNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
let url = isStringValue ? nodes[0].value : valueParser.stringify(nodes);
url = normalizeUrl(url, isStringValue);
// Do not traverse inside `url`
if (!shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL)) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: getNodeFromUrlFunc(valueNode),
prefix,
url,
needQuotes: false
});
// eslint-disable-next-line consistent-return
return false;
} else if (isImageSetFunc.test(valueNode.value)) {
for (const [innerIndex, nNode] of valueNode.nodes.entries()){
const { type, value } = nNode;
if (type === "function" && isUrlFunc.test(value)) {
needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
continue;
}
const { nodes } = nNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
let url = isStringValue ? nodes[0].value : valueParser.stringify(nodes);
url = normalizeUrl(url, isStringValue);
// Do not traverse inside `url`
if (!shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL)) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: getNodeFromUrlFunc(nNode),
prefix,
url,
needQuotes: false
});
} else if (type === "string") {
needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
continue;
}
let url = normalizeUrl(value, true);
// Do not traverse inside `url`
if (!shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL)) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: nNode,
prefix,
url,
needQuotes: true
});
}
}
// Do not traverse inside `image-set`
// eslint-disable-next-line consistent-return
return false;
}
});
// eslint-disable-next-line consistent-return
return parsedURLs;
}
const plugin = (options = {})=>{
return {
postcssPlugin: "postcss-url-parser",
prepare (result) {
const parsedDeclarations = [];
return {
Declaration (declaration) {
const { isSupportDataURLInNewURL } = options;
const parsedURL = parseDeclaration(declaration, "value", result, isSupportDataURLInNewURL);
if (!parsedURL) {
return;
}
parsedDeclarations.push(...parsedURL);
},
async OnceExit () {
if (parsedDeclarations.length === 0) {
return;
}
const resolvedDeclarations = await Promise.all(parsedDeclarations.map(async (parsedDeclaration)=>{
const { url } = parsedDeclaration;
if (options.filter) {
const needKeep = await options.filter(url);
if (!needKeep) {
// eslint-disable-next-line consistent-return
return;
}
}
if (isDataUrl(url)) {
// eslint-disable-next-line consistent-return
return parsedDeclaration;
}
const splittedUrl = url.split(/(\?)?#/);
const [pathname, query, hashOrQuery] = splittedUrl;
let hash = query ? "?" : "";
hash += hashOrQuery ? `#${hashOrQuery}` : "";
const { needToResolveURL, rootContext } = options;
const request = requestify(pathname, rootContext, // @ts-expect-error TODO: only 2 arguments allowed.
needToResolveURL);
if (!needToResolveURL) {
// eslint-disable-next-line consistent-return
return {
...parsedDeclaration,
url: request,
hash
};
}
const { resolver, context } = options;
const resolvedUrl = await resolveRequests(resolver, context, [
...new Set([
request,
url
])
]);
if (!resolvedUrl) {
// eslint-disable-next-line consistent-return
return;
}
// eslint-disable-next-line consistent-return
return {
...parsedDeclaration,
url: resolvedUrl,
hash
};
}));
const urlToNameMap = new Map();
const urlToReplacementMap = new Map();
let hasUrlImportHelper = false;
for(let index = 0; index <= resolvedDeclarations.length - 1; index++){
const item = resolvedDeclarations[index];
if (!item) {
continue;
}
if (!hasUrlImportHelper) {
options.imports.push({
type: "get_url_import",
importName: "___CSS_LOADER_GET_URL_IMPORT___",
url: options.urlHandler(require.resolve("../runtime/getUrl.js")),
index: -1
});
hasUrlImportHelper = true;
}
const { url, prefix } = item;
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = urlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${urlToNameMap.size}___`;
urlToNameMap.set(newUrl, importName);
options.imports.push({
type: "url",
importName,
url: options.needToResolveURL ? options.urlHandler(newUrl) : JSON.stringify(newUrl),
index
});
}
const { hash, needQuotes } = item;
const replacementKey = JSON.stringify({
newUrl,
hash,
needQuotes
});
let replacementName = urlToReplacementMap.get(replacementKey);
if (!replacementName) {
replacementName = `___CSS_LOADER_URL_REPLACEMENT_${urlToReplacementMap.size}___`;
urlToReplacementMap.set(replacementKey, replacementName);
options.replacements.push({
replacementName,
importName,
hash,
needQuotes
});
}
// eslint-disable-next-line no-param-reassign
item.node.type = "word";
// eslint-disable-next-line no-param-reassign
item.node.value = replacementName;
// eslint-disable-next-line no-param-reassign
item.declaration.value = item.parsed.toString();
}
}
};
}
};
};
plugin.postcss = true;
export default plugin;
//# sourceMappingURL=postcss-url-parser.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,90 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ // css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function(useSourceMap) {
var list = [] // return the list of modules as css string
;
list.toString = function toString() {
return this.map(function(item) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
var content = cssWithMappingToString(item, useSourceMap);
if (item[2]) {
return "@media ".concat(item[2], " {").concat(content, "}");
}
return content;
}).join("");
} // import a list of modules into the list
;
// eslint-disable-next-line func-names
// @ts-expect-error TODO: fix type
list.i = function(modules, mediaQuery, dedupe) {
if (typeof modules === "string") {
// eslint-disable-next-line no-param-reassign
modules = [
[
null,
modules,
""
]
];
}
var alreadyImportedModules = {};
if (dedupe) {
for(var i = 0; i < this.length; i++){
// eslint-disable-next-line prefer-destructuring
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
}
for(var _i = 0; _i < modules.length; _i++){
var item = [].concat(modules[_i]);
if (dedupe && alreadyImportedModules[item[0]]) {
continue;
}
if (mediaQuery) {
if (!item[2]) {
item[2] = mediaQuery;
} else {
item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
}
}
list.push(item);
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || "" // eslint-disable-next-line prefer-destructuring
;
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === "function") {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function(source) {
return "/*# sourceURL=".concat(cssMapping.sourceRoot || "").concat(source, " */");
});
return [
content
].concat(sourceURLs).concat([
sourceMapping
]).join("\n");
}
return [
content
].join("\n");
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
return "/*# ".concat(data, " */");
}
//# sourceMappingURL=api.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/loaders/css-loader/src/runtime/api.ts"],"names":["module","exports","useSourceMap","list","toString","map","item","content","cssWithMappingToString","concat","join","i","modules","mediaQuery","dedupe","alreadyImportedModules","length","id","_i","push","cssMapping","btoa","sourceMapping","toComment","sourceURLs","sources","source","sourceRoot","sourceMap","base64","unescape","encodeURIComponent","JSON","stringify","data"],"mappings":"AAAA;;;AAGA,GACA,4CAA4C;AAC5C,sCAAsC;AACtCA,OAAOC,OAAO,GAAG,SAAUC,YAAiB;IAC1C,IAAIC,OAAc,EAAE,CAAC,2CAA2C;;IAEhEA,KAAKC,QAAQ,GAAG,SAASA;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AACT;AAEA,SAASK,uBAAuBF,IAAS,EAAEJ,YAAiB;IAC1D,IAAIK,UAAUD,IAAI,CAAC,EAAE,IAAI,GAAG,gDAAgD;;IAE5E,IAAIc,aAAad,IAAI,CAAC,EAAE;IAExB,IAAI,CAACc,YAAY;QACf,OAAOb;IACT;IAEA,IAAIL,gBAAgB,OAAOmB,SAAS,YAAY;QAC9C,mEAAmE;QACnE,IAAIC,gBAAgBC,UAAUH;QAC9B,IAAII,aAAaJ,WAAWK,OAAO,CAACpB,GAAG,CAAC,SAAUqB,MAAc;YAC9D,OAAO,iBACJjB,MAAM,CAACW,WAAWO,UAAU,IAAI,IAChClB,MAAM,CAACiB,QAAQ;QACpB;QACA,OAAO;YAACnB;SAAQ,CAACE,MAAM,CAACe,YAAYf,MAAM,CAAC;YAACa;SAAc,EAAEZ,IAAI,CAAC;IACnE;IAEA,OAAO;QAACH;KAAQ,CAACG,IAAI,CAAC;AACxB,EAAE,wCAAwC;AAE1C,SAASa,UAAUK,SAAc;IAC/B,oCAAoC;IACpC,IAAIC,SAASR,KAAKS,SAASC,mBAAmBC,KAAKC,SAAS,CAACL;IAC7D,IAAIM,OACF,+DAA+DzB,MAAM,CACnEoB;IAEJ,OAAO,OAAOpB,MAAM,CAACyB,MAAM;AAC7B"}

View File

@@ -0,0 +1,25 @@
module.exports = function(url, options) {
if (!options) {
// eslint-disable-next-line no-param-reassign
options = {};
} // eslint-disable-next-line no-underscore-dangle, no-param-reassign
url = url && url.__esModule ? url.default : url;
if (typeof url !== "string") {
return url;
} // If url is already wrapped in quotes, remove them
if (/^['"].*['"]$/.test(url)) {
// eslint-disable-next-line no-param-reassign
url = url.slice(1, -1);
}
if (options.hash) {
// eslint-disable-next-line no-param-reassign
url += options.hash;
} // Should url be wrapped?
// See https://drafts.csswg.org/css-values-3/#urls
if (/["'() \t\n]/.test(url) || options.needQuotes) {
return '"'.concat(url.replace(/"/g, '\\"').replace(/\n/g, "\\n"), '"');
}
return url;
};
//# sourceMappingURL=getUrl.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/build/webpack/loaders/css-loader/src/runtime/getUrl.ts"],"names":["module","exports","url","options","__esModule","default","test","slice","hash","needQuotes","concat","replace"],"mappings":"AAAAA,OAAOC,OAAO,GAAG,SAAUC,GAAQ,EAAEC,OAAY;IAC/C,IAAI,CAACA,SAAS;QACZ,6CAA6C;QAC7CA,UAAU,CAAC;IACb,EAAE,mEAAmE;IAErED,MAAMA,OAAOA,IAAIE,UAAU,GAAGF,IAAIG,OAAO,GAAGH;IAE5C,IAAI,OAAOA,QAAQ,UAAU;QAC3B,OAAOA;IACT,EAAE,mDAAmD;IAErD,IAAI,eAAeI,IAAI,CAACJ,MAAM;QAC5B,6CAA6C;QAC7CA,MAAMA,IAAIK,KAAK,CAAC,GAAG,CAAC;IACtB;IAEA,IAAIJ,QAAQK,IAAI,EAAE;QAChB,6CAA6C;QAC7CN,OAAOC,QAAQK,IAAI;IACrB,EAAE,yBAAyB;IAC3B,kDAAkD;IAElD,IAAI,cAAcF,IAAI,CAACJ,QAAQC,QAAQM,UAAU,EAAE;QACjD,OAAO,IAAIC,MAAM,CAACR,IAAIS,OAAO,CAAC,MAAM,OAAOA,OAAO,CAAC,OAAO,QAAQ;IACpE;IAEA,OAAOT;AACT"}

View File

@@ -0,0 +1,368 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ import { fileURLToPath } from "url";
import path from "path";
import { urlToRequest } from "next/dist/compiled/loader-utils3";
import modulesValues from "next/dist/compiled/postcss-modules-values";
import localByDefault from "next/dist/compiled/postcss-modules-local-by-default";
import extractImports from "next/dist/compiled/postcss-modules-extract-imports";
import modulesScope from "next/dist/compiled/postcss-modules-scope";
import camelCase from "./camelcase";
const whitespace = "[\\x20\\t\\r\\n\\f]";
const unescapeRegExp = new RegExp(`\\\\([\\da-f]{1,6}${whitespace}?|(${whitespace})|.)`, "ig");
const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i;
function unescape(str) {
return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace)=>{
const high = `0x${escaped}` - 0x10000;
/* eslint-disable line-comment-position */ // NaN means non-codepoint
// Workaround erroneous numeric interpretation of +"0x"
// eslint-disable-next-line no-self-compare
return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 0x10000) : // eslint-disable-next-line no-bitwise
String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
/* eslint-enable line-comment-position */ });
}
function normalizePath(file) {
return path.sep === "\\" ? file.replace(/\\/g, "/") : file;
}
function fixedEncodeURIComponent(str) {
return str.replace(/[!'()*]/g, (c)=>`%${c.charCodeAt(0).toString(16)}`);
}
function normalizeUrl(url, isStringValue) {
let normalizedUrl = url;
if (isStringValue && /\\(\n|\r\n|\r|\f)/.test(normalizedUrl)) {
normalizedUrl = normalizedUrl.replace(/\\(\n|\r\n|\r|\f)/g, "");
}
if (matchNativeWin32Path.test(url)) {
try {
normalizedUrl = decodeURIComponent(normalizedUrl);
} catch (error) {
// Ignores invalid and broken URLs and try to resolve them as is
}
return normalizedUrl;
}
normalizedUrl = unescape(normalizedUrl);
// eslint-disable-next-line @typescript-eslint/no-use-before-define
if (isDataUrl(url)) {
return fixedEncodeURIComponent(normalizedUrl);
}
try {
normalizedUrl = decodeURI(normalizedUrl);
} catch (error) {
// Ignores invalid and broken URLs and try to resolve them as is
}
return normalizedUrl;
}
function requestify(url, rootContext) {
if (/^file:/i.test(url)) {
return fileURLToPath(url);
}
if (/^[a-z][a-z0-9+.-]*:/i.test(url)) {
return url;
}
return url.charAt(0) === "/" ? urlToRequest(url, rootContext) : urlToRequest(url);
}
function getFilter(filter, resourcePath) {
return (...args)=>{
if (typeof filter === "function") {
return filter(...args, resourcePath);
}
return true;
};
}
function shouldUseImportPlugin(options) {
if (options.modules.exportOnlyLocals) {
return false;
}
if (typeof options.import === "boolean") {
return options.import;
}
return true;
}
function shouldUseURLPlugin(options) {
if (options.modules.exportOnlyLocals) {
return false;
}
if (typeof options.url === "boolean") {
return options.url;
}
return true;
}
function shouldUseModulesPlugins(options) {
return options.modules.compileType === "module";
}
function shouldUseIcssPlugin(options) {
return options.icss === true || Boolean(options.modules);
}
function getModulesPlugins(options, loaderContext, meta) {
const { mode, getLocalIdent, localIdentName, localIdentContext, localIdentHashPrefix, localIdentRegExp } = options.modules;
let plugins = [];
try {
plugins = [
modulesValues,
localByDefault({
mode
}),
extractImports(),
modulesScope({
generateScopedName (exportName) {
return getLocalIdent(loaderContext, localIdentName, exportName, {
context: localIdentContext,
hashPrefix: localIdentHashPrefix,
regExp: localIdentRegExp
}, meta);
},
exportGlobals: options.modules.exportGlobals
})
];
} catch (error) {
loaderContext.emitError(error);
}
return plugins;
}
const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i;
function getURLType(source) {
if (source[0] === "/") {
if (source[1] === "/") {
return "scheme-relative";
}
return "path-absolute";
}
if (IS_NATIVE_WIN32_PATH.test(source)) {
return "path-absolute";
}
return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
}
function normalizeSourceMap(map, resourcePath) {
let newMap = map;
// Some loader emit source map as string
// Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
if (typeof newMap === "string") {
newMap = JSON.parse(newMap);
}
delete newMap.file;
const { sourceRoot } = newMap;
delete newMap.sourceRoot;
if (newMap.sources) {
// Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
// We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
newMap.sources = newMap.sources.map((source)=>{
// Non-standard syntax from `postcss`
if (source.indexOf("<") === 0) {
return source;
}
const sourceType = getURLType(source);
// Do no touch `scheme-relative` and `absolute` URLs
if (sourceType === "path-relative" || sourceType === "path-absolute") {
const absoluteSource = sourceType === "path-relative" && sourceRoot ? path.resolve(sourceRoot, normalizePath(source)) : normalizePath(source);
return path.relative(path.dirname(resourcePath), absoluteSource);
}
return source;
});
}
return newMap;
}
function getPreRequester({ loaders, loaderIndex }) {
const cache = Object.create(null);
return (number)=>{
if (cache[number]) {
return cache[number];
}
if (number === false) {
cache[number] = "";
} else {
const loadersRequest = loaders.slice(loaderIndex, loaderIndex + 1 + (typeof number !== "number" ? 0 : number)).map((x)=>x.request).join("!");
cache[number] = `-!${loadersRequest}!`;
}
return cache[number];
};
}
function getImportCode(imports, options) {
let code = "";
for (const item of imports){
const { importName, url, icss } = item;
if (options.esModule) {
if (icss && options.modules.namedExport) {
code += `import ${options.modules.exportOnlyLocals ? "" : `${importName}, `}* as ${importName}_NAMED___ from ${url};\n`;
} else {
code += `import ${importName} from ${url};\n`;
}
} else {
code += `var ${importName} = require(${url});\n`;
}
}
return code ? `// Imports\n${code}` : "";
}
function normalizeSourceMapForRuntime(map, loaderContext) {
const resultMap = map ? map.toJSON() : null;
if (resultMap) {
delete resultMap.file;
resultMap.sourceRoot = "";
resultMap.sources = resultMap.sources.map((source)=>{
// Non-standard syntax from `postcss`
if (source.indexOf("<") === 0) {
return source;
}
const sourceType = getURLType(source);
if (sourceType !== "path-relative") {
return source;
}
const resourceDirname = path.dirname(loaderContext.resourcePath);
const absoluteSource = path.resolve(resourceDirname, source);
const contextifyPath = normalizePath(path.relative(loaderContext.rootContext, absoluteSource));
return `webpack://${contextifyPath}`;
});
}
return JSON.stringify(resultMap);
}
function getModuleCode(result, api, replacements, options, loaderContext) {
if (options.modules.exportOnlyLocals === true) {
return "";
}
const sourceMapValue = options.sourceMap ? `,${normalizeSourceMapForRuntime(result.map, loaderContext)}` : "";
let code = JSON.stringify(result.css);
let beforeCode = `var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(${options.sourceMap});\n`;
for (const item of api){
const { url, media, dedupe } = item;
beforeCode += url ? `___CSS_LOADER_EXPORT___.push([module.id, ${JSON.stringify(`@import url(${url});`)}${media ? `, ${JSON.stringify(media)}` : ""}]);\n` : `___CSS_LOADER_EXPORT___.i(${item.importName}${media ? `, ${JSON.stringify(media)}` : dedupe ? ', ""' : ""}${dedupe ? ", true" : ""});\n`;
}
for (const item of replacements){
const { replacementName, importName, localName } = item;
if (localName) {
code = code.replace(new RegExp(replacementName, "g"), ()=>options.modules.namedExport ? `" + ${importName}_NAMED___[${JSON.stringify(camelCase(localName))}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
} else {
const { hash, needQuotes } = item;
const getUrlOptions = [
...hash ? [
`hash: ${JSON.stringify(hash)}`
] : [],
...needQuotes ? "needQuotes: true" : []
];
const preparedOptions = getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(", ")} }` : "";
beforeCode += `var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});\n`;
code = code.replace(new RegExp(replacementName, "g"), ()=>`" + ${replacementName} + "`);
}
}
return `${beforeCode}// Module\n___CSS_LOADER_EXPORT___.push([module.id, ${code}, ""${sourceMapValue}]);\n`;
}
function dashesCamelCase(str) {
return str.replace(/-+(\w)/g, (_match, firstLetter)=>firstLetter.toUpperCase());
}
function getExportCode(exports, replacements, options) {
let code = "// Exports\n";
let localsCode = "";
const addExportToLocalsCode = (name, value)=>{
if (options.modules.namedExport) {
localsCode += `export const ${camelCase(name)} = ${JSON.stringify(value)};\n`;
} else {
if (localsCode) {
localsCode += `,\n`;
}
localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
}
};
for (const { name, value } of exports){
switch(options.modules.exportLocalsConvention){
case "camelCase":
{
addExportToLocalsCode(name, value);
const modifiedName = camelCase(name);
if (modifiedName !== name) {
addExportToLocalsCode(modifiedName, value);
}
break;
}
case "camelCaseOnly":
{
addExportToLocalsCode(camelCase(name), value);
break;
}
case "dashes":
{
addExportToLocalsCode(name, value);
const modifiedName = dashesCamelCase(name);
if (modifiedName !== name) {
addExportToLocalsCode(modifiedName, value);
}
break;
}
case "dashesOnly":
{
addExportToLocalsCode(dashesCamelCase(name), value);
break;
}
case "asIs":
default:
addExportToLocalsCode(name, value);
break;
}
}
for (const item of replacements){
const { replacementName, localName } = item;
if (localName) {
const { importName } = item;
localsCode = localsCode.replace(new RegExp(replacementName, "g"), ()=>{
if (options.modules.namedExport) {
return `" + ${importName}_NAMED___[${JSON.stringify(camelCase(localName))}] + "`;
} else if (options.modules.exportOnlyLocals) {
return `" + ${importName}[${JSON.stringify(localName)}] + "`;
}
return `" + ${importName}.locals[${JSON.stringify(localName)}] + "`;
});
} else {
localsCode = localsCode.replace(new RegExp(replacementName, "g"), ()=>`" + ${replacementName} + "`);
}
}
if (options.modules.exportOnlyLocals) {
code += options.modules.namedExport ? localsCode : `${options.esModule ? "export default" : "module.exports ="} {\n${localsCode}\n};\n`;
return code;
}
if (localsCode) {
code += options.modules.namedExport ? localsCode : `___CSS_LOADER_EXPORT___.locals = {\n${localsCode}\n};\n`;
}
code += `${options.esModule ? "export default" : "module.exports ="} ___CSS_LOADER_EXPORT___;\n`;
return code;
}
async function resolveRequests(resolve, context, possibleRequests) {
return resolve(context, possibleRequests[0]).then((result)=>{
return result;
}).catch((error)=>{
const [, ...tailPossibleRequests] = possibleRequests;
if (tailPossibleRequests.length === 0) {
throw error;
}
return resolveRequests(resolve, context, tailPossibleRequests);
});
}
function isUrlRequestable(url) {
// Protocol-relative URLs
if (/^\/\//.test(url)) {
return false;
}
// `file:` protocol
if (/^file:/i.test(url)) {
return true;
}
// Absolute URLs
if (/^[a-z][a-z0-9+.-]*:/i.test(url)) {
return true;
}
// `#` URLs
if (/^#/.test(url)) {
return false;
}
return true;
}
function sort(a, b) {
return a.index - b.index;
}
function isDataUrl(url) {
if (/^data:/i.test(url)) {
return true;
}
return false;
}
export { isDataUrl, shouldUseModulesPlugins, shouldUseImportPlugin, shouldUseURLPlugin, shouldUseIcssPlugin, normalizeUrl, requestify, getFilter, getModulesPlugins, normalizeSourceMap, getPreRequester, getImportCode, getModuleCode, getExportCode, resolveRequests, isUrlRequestable, sort, };
//# sourceMappingURL=utils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
const EmptyLoader = ()=>"export default {}";
export default EmptyLoader;
//# sourceMappingURL=empty-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/empty-loader.ts"],"names":["EmptyLoader"],"mappings":"AAEA,MAAMA,cAAgD,IAAM;AAC5D,eAAeA,YAAW"}

View File

@@ -0,0 +1,17 @@
import chalk from "next/dist/compiled/chalk";
import path from "path";
const ErrorLoader = function() {
var _this__module_issuer, _this__module, _this__compiler;
// @ts-ignore exists
const options = this.getOptions() || {};
const { reason = "An unknown error has occurred" } = options;
// @ts-expect-error
const resource = ((_this__module = this._module) == null ? void 0 : (_this__module_issuer = _this__module.issuer) == null ? void 0 : _this__module_issuer.resource) ?? null;
const context = this.rootContext ?? ((_this__compiler = this._compiler) == null ? void 0 : _this__compiler.context);
const issuer = resource ? context ? path.relative(context, resource) : resource : null;
const err = new Error(reason + (issuer ? `\nLocation: ${chalk.cyan(issuer)}` : ""));
this.emitError(err);
};
export default ErrorLoader;
//# sourceMappingURL=error-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/error-loader.ts"],"names":["chalk","path","ErrorLoader","options","getOptions","reason","resource","_module","issuer","context","rootContext","_compiler","relative","err","Error","cyan","emitError"],"mappings":"AAAA,OAAOA,WAAW,2BAA0B;AAC5C,OAAOC,UAAU,OAAM;AAGvB,MAAMC,cAAgD;QAOnC,sBAAA,eACmB;IAPpC,oBAAoB;IACpB,MAAMC,UAAU,IAAI,CAACC,UAAU,MAAO,CAAC;IAEvC,MAAM,EAAEC,SAAS,+BAA+B,EAAE,GAAGF;IAErD,mBAAmB;IACnB,MAAMG,WAAW,EAAA,gBAAA,IAAI,CAACC,OAAO,sBAAZ,uBAAA,cAAcC,MAAM,qBAApB,qBAAsBF,QAAQ,KAAI;IACnD,MAAMG,UAAU,IAAI,CAACC,WAAW,MAAI,kBAAA,IAAI,CAACC,SAAS,qBAAd,gBAAgBF,OAAO;IAE3D,MAAMD,SAASF,WACXG,UACER,KAAKW,QAAQ,CAACH,SAASH,YACvBA,WACF;IAEJ,MAAMO,MAAM,IAAIC,MACdT,SAAUG,CAAAA,SAAS,CAAC,YAAY,EAAER,MAAMe,IAAI,CAACP,QAAQ,CAAC,GAAG,EAAC;IAE5D,IAAI,CAACQ,SAAS,CAACH;AACjB;AAEA,eAAeX,YAAW"}

View File

@@ -0,0 +1,8 @@
/**
* A getter for module build info that casts to the type it should have.
* We also expose here types to make easier to use it.
*/ export function getModuleBuildInfo(webpackModule) {
return webpackModule.buildInfo;
}
//# sourceMappingURL=get-module-build-info.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/get-module-build-info.ts"],"names":["getModuleBuildInfo","webpackModule","buildInfo"],"mappings":"AAoBA;;;CAGC,GACD,OAAO,SAASA,mBAAmBC,aAA6B;IAC9D,OAAOA,cAAcC,SAAS;AAChC"}

View File

@@ -0,0 +1,92 @@
import path from "path";
import { stringify } from "querystring";
import { STATIC_METADATA_IMAGES } from "../../../../lib/metadata/is-metadata-route";
import { WEBPACK_RESOURCE_QUERIES } from "../../../../lib/constants";
const METADATA_TYPE = "metadata";
// Produce all compositions with filename (icon, apple-icon, etc.) with extensions (png, jpg, etc.)
async function enumMetadataFiles(dir, filename, extensions, { metadataResolver, // When set to true, possible filename without extension could: icon, icon0, ..., icon9
numericSuffix }) {
const collectedFiles = [];
const possibleFileNames = [
filename
].concat(numericSuffix ? Array(10).fill(0).map((_, index)=>filename + index) : []);
for (const name of possibleFileNames){
const resolved = await metadataResolver(dir, name, extensions);
if (resolved) {
collectedFiles.push(resolved);
}
}
return collectedFiles;
}
export async function createStaticMetadataFromRoute(resolvedDir, { segment, metadataResolver, isRootLayoutOrRootPage, pageExtensions, basePath }) {
let hasStaticMetadataFiles = false;
const staticImagesMetadata = {
icon: [],
apple: [],
twitter: [],
openGraph: [],
manifest: undefined
};
async function collectIconModuleIfExists(type) {
if (type === "manifest") {
const staticManifestExtension = [
"webmanifest",
"json"
];
const manifestFile = await enumMetadataFiles(resolvedDir, "manifest", staticManifestExtension.concat(pageExtensions), {
metadataResolver,
numericSuffix: false
});
if (manifestFile.length > 0) {
hasStaticMetadataFiles = true;
const { name, ext } = path.parse(manifestFile[0]);
const extension = staticManifestExtension.includes(ext.slice(1)) ? ext.slice(1) : "webmanifest";
staticImagesMetadata.manifest = JSON.stringify(`/${name}.${extension}`);
}
return;
}
const resolvedMetadataFiles = await enumMetadataFiles(resolvedDir, STATIC_METADATA_IMAGES[type].filename, [
...STATIC_METADATA_IMAGES[type].extensions,
...type === "favicon" ? [] : pageExtensions
], {
metadataResolver,
numericSuffix: true
});
resolvedMetadataFiles.sort((a, b)=>a.localeCompare(b)).forEach((filepath)=>{
const imageModuleImportSource = `next-metadata-image-loader?${stringify({
type,
segment,
basePath,
pageExtensions
})}!${filepath}?${WEBPACK_RESOURCE_QUERIES.metadata}`;
const imageModule = `(async (props) => (await import(/* webpackMode: "eager" */ ${JSON.stringify(imageModuleImportSource)})).default(props))`;
hasStaticMetadataFiles = true;
if (type === "favicon") {
staticImagesMetadata.icon.unshift(imageModule);
} else {
staticImagesMetadata[type].push(imageModule);
}
});
}
// Intentially make these serial to reuse directory access cache.
await collectIconModuleIfExists("icon");
await collectIconModuleIfExists("apple");
await collectIconModuleIfExists("openGraph");
await collectIconModuleIfExists("twitter");
if (isRootLayoutOrRootPage) {
await collectIconModuleIfExists("favicon");
await collectIconModuleIfExists("manifest");
}
return hasStaticMetadataFiles ? staticImagesMetadata : null;
}
export function createMetadataExportsCode(metadata) {
return metadata ? `${METADATA_TYPE}: {
icon: [${metadata.icon.join(",")}],
apple: [${metadata.apple.join(",")}],
openGraph: [${metadata.openGraph.join(",")}],
twitter: [${metadata.twitter.join(",")}],
manifest: ${metadata.manifest ? metadata.manifest : "undefined"}
}` : "";
}
//# sourceMappingURL=discover.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/metadata/discover.ts"],"names":["path","stringify","STATIC_METADATA_IMAGES","WEBPACK_RESOURCE_QUERIES","METADATA_TYPE","enumMetadataFiles","dir","filename","extensions","metadataResolver","numericSuffix","collectedFiles","possibleFileNames","concat","Array","fill","map","_","index","name","resolved","push","createStaticMetadataFromRoute","resolvedDir","segment","isRootLayoutOrRootPage","pageExtensions","basePath","hasStaticMetadataFiles","staticImagesMetadata","icon","apple","twitter","openGraph","manifest","undefined","collectIconModuleIfExists","type","staticManifestExtension","manifestFile","length","ext","parse","extension","includes","slice","JSON","resolvedMetadataFiles","sort","a","b","localeCompare","forEach","filepath","imageModuleImportSource","metadata","imageModule","unshift","createMetadataExportsCode","join"],"mappings":"AAIA,OAAOA,UAAU,OAAM;AACvB,SAASC,SAAS,QAAQ,cAAa;AACvC,SAASC,sBAAsB,QAAQ,6CAA4C;AACnF,SAASC,wBAAwB,QAAQ,4BAA2B;AAGpE,MAAMC,gBAAgB;AAEtB,mGAAmG;AACnG,eAAeC,kBACbC,GAAW,EACXC,QAAgB,EAChBC,UAA6B,EAC7B,EACEC,gBAAgB,EAChB,uFAAuF;AACvFC,aAAa,EAId;IAED,MAAMC,iBAA2B,EAAE;IAEnC,MAAMC,oBAAoB;QAACL;KAAS,CAACM,MAAM,CACzCH,gBACII,MAAM,IACHC,IAAI,CAAC,GACLC,GAAG,CAAC,CAACC,GAAGC,QAAUX,WAAWW,SAChC,EAAE;IAER,KAAK,MAAMC,QAAQP,kBAAmB;QACpC,MAAMQ,WAAW,MAAMX,iBAAiBH,KAAKa,MAAMX;QACnD,IAAIY,UAAU;YACZT,eAAeU,IAAI,CAACD;QACtB;IACF;IAEA,OAAOT;AACT;AAEA,OAAO,eAAeW,8BACpBC,WAAmB,EACnB,EACEC,OAAO,EACPf,gBAAgB,EAChBgB,sBAAsB,EACtBC,cAAc,EACdC,QAAQ,EAOT;IAED,IAAIC,yBAAy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AC;YACrB1B,yBAAyB;YACzB,IAAIS,SAAS,WAAW;gBACtBR,qBAAqBC,IAAI,CAAC2B,OAAO,CAACD;YACpC,OAAO;gBACL3B,oBAAoB,CAACQ,KAAK,CAAChB,IAAI,CAACmC;YAClC;QACF;IACJ;IAEA,iEAAiE;IACjE,MAAMpB,0BAA0B;IAChC,MAAMA,0BAA0B;IAChC,MAAMA,0BAA0B;IAChC,MAAMA,0BAA0B;IAChC,IAAIX,wBAAwB;QAC1B,MAAMW,0BAA0B;QAChC,MAAMA,0BAA0B;IAClC;IAEA,OAAOR,yBAAyBC,uBAAuB;AACzD;AAEA,OAAO,SAAS6B,0BACdH,QAAmE;IAEnE,OAAOA,WACH,CAAC,EAAEnD,cAAc;WACZ,EAAEmD,SAASzB,IAAI,CAAC6B,IAAI,CAAC,KAAK;YACzB,EAAEJ,SAASxB,KAAK,CAAC4B,IAAI,CAAC,KAAK;gBACvB,EAAEJ,SAAStB,SAAS,CAAC0B,IAAI,CAAC,KAAK;cACjC,EAAEJ,SAASvB,OAAO,CAAC2B,IAAI,CAAC,KAAK;cAC7B,EAAEJ,SAASrB,QAAQ,GAAGqB,SAASrB,QAAQ,GAAG,YAAY;GACjE,CAAC,GACE;AACN"}

View File

@@ -0,0 +1,84 @@
import { resolveArray } from "../../../../lib/metadata/generate/utils";
// convert robots data to txt string
export function resolveRobots(data) {
let content = "";
const rules = Array.isArray(data.rules) ? data.rules : [
data.rules
];
for (const rule of rules){
const userAgent = resolveArray(rule.userAgent || [
"*"
]);
for (const agent of userAgent){
content += `User-Agent: ${agent}\n`;
}
if (rule.allow) {
const allow = resolveArray(rule.allow);
for (const item of allow){
content += `Allow: ${item}\n`;
}
}
if (rule.disallow) {
const disallow = resolveArray(rule.disallow);
for (const item of disallow){
content += `Disallow: ${item}\n`;
}
}
if (rule.crawlDelay) {
content += `Crawl-delay: ${rule.crawlDelay}\n`;
}
content += "\n";
}
if (data.host) {
content += `Host: ${data.host}\n`;
}
if (data.sitemap) {
const sitemap = resolveArray(data.sitemap);
// TODO-METADATA: support injecting sitemap url into robots.txt
sitemap.forEach((item)=>{
content += `Sitemap: ${item}\n`;
});
}
return content;
}
// TODO-METADATA: support multi sitemap files
// convert sitemap data to xml string
export function resolveSitemap(data) {
let content = "";
content += '<?xml version="1.0" encoding="UTF-8"?>\n';
content += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n';
for (const item of data){
content += "<url>\n";
content += `<loc>${item.url}</loc>\n`;
if (item.lastModified) {
const serializedDate = item.lastModified instanceof Date ? item.lastModified.toISOString() : item.lastModified;
content += `<lastmod>${serializedDate}</lastmod>\n`;
}
if (item.changeFrequency) {
content += `<changefreq>${item.changeFrequency}</changefreq>\n`;
}
if (typeof item.priority === "number") {
content += `<priority>${item.priority}</priority>\n`;
}
content += "</url>\n";
}
content += "</urlset>\n";
return content;
}
export function resolveManifest(data) {
return JSON.stringify(data);
}
export function resolveRouteData(data, fileType) {
if (fileType === "robots") {
return resolveRobots(data);
}
if (fileType === "sitemap") {
return resolveSitemap(data);
}
if (fileType === "manifest") {
return resolveManifest(data);
}
return "";
}
//# sourceMappingURL=resolve-route-data.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/metadata/resolve-route-data.ts"],"names":["resolveArray","resolveRobots","data","content","rules","Array","isArray","rule","userAgent","agent","allow","item","disallow","crawlDelay","host","sitemap","forEach","resolveSitemap","url","lastModified","serializedDate","Date","toISOString","changeFrequency","priority","resolveManifest","JSON","stringify","resolveRouteData","fileType"],"mappings":"AACA,SAASA,YAAY,QAAQ,0CAAyC;AAEtE,oCAAoC;AACpC,OAAO,SAASC,cAAcC,IAA0B;IACtD,IAAIC,UAAU;IACd,MAAMC,QAAQC,MAAMC,OAAO,CAACJ,KAAKE,KAAK,IAAIF,KAAKE,KAAK,GAAG;QAACF,KAAKE,KAAK;KAAC;IACnE,KAAK,MAAMG,QAAQH,MAAO;QACxB,MAAMI,YAAYR,aAAaO,KAA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BhB,WAAW,CAAC,SAAS,EAAEiB,eAAe,YAAY,CAAC;QACrD;QAEA,IAAIT,KAAKY,eAAe,EAAE;YACxBpB,WAAW,CAAC,YAAY,EAAEQ,KAAKY,eAAe,CAAC,eAAe,CAAC;QACjE;QAEA,IAAI,OAAOZ,KAAKa,QAAQ,KAAK,UAAU;YACrCrB,WAAW,CAAC,UAAU,EAAEQ,KAAKa,QAAQ,CAAC,aAAa,CAAC;QACtD;QAEArB,WAAW;IACb;IAEAA,WAAW;IAEX,OAAOA;AACT;AAEA,OAAO,SAASsB,gBAAgBvB,IAA4B;IAC1D,OAAOwB,KAAKC,SAAS,CAACzB;AACxB;AAEA,OAAO,SAAS0B,iBACd1B,IAA2E,EAC3E2B,QAA2C;IAE3C,IAAIA,aAAa,UAAU;QACzB,OAAO5B,cAAcC;IACvB;IACA,IAAI2B,aAAa,WAAW;QAC1B,OAAOZ,eAAef;IACxB;IACA,IAAI2B,aAAa,YAAY;QAC3B,OAAOJ,gBAAgBvB;IACzB;IACA,OAAO;AACT"}

View File

@@ -0,0 +1,4 @@
// TODO-APP: check if this can be narrowed.
export { };
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/metadata/types.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,WA6Cc"}

View File

@@ -0,0 +1,24 @@
import path from "path";
/**
* This loader is to create special re-exports from a specific file.
* For example, the following loader:
*
* modularize-import-loader?name=Arrow&from=Arrow&as=default&join=./icons/Arrow!lucide-react
*
* will be used to create a re-export of:
*
* export { Arrow as default } from "join(resolve_path('lucide-react'), '/icons/Arrow')"
*
* This works even if there's no export field in the package.json of the package.
*/ export default function transformSource() {
const { name, from, as, join } = this.getOptions();
const { resourcePath } = this;
const fullPath = join ? path.join(path.dirname(resourcePath), join) : resourcePath;
return `
export {
${from === "default" ? "default" : name} as ${as === "default" ? "default" : name}
} from ${JSON.stringify(fullPath)}
`;
}
//# sourceMappingURL=modularize-import-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/modularize-import-loader.ts"],"names":["path","transformSource","name","from","as","join","getOptions","resourcePath","fullPath","dirname","JSON","stringify"],"mappings":"AAAA,OAAOA,UAAU,OAAM;AASvB;;;;;;;;;;;CAWC,GACD,eAAe,SAASC;IACtB,MAAM,EAAEC,IAAI,EAAEC,IAAI,EAAEC,EAAE,EAAEC,IAAI,EAAE,GAC5B,IAAI,CAACC,UAAU;IACjB,MAAM,EAAEC,YAAY,EAAE,GAAG,IAAI;IAC7B,MAAMC,WAAWH,OACbL,KAAKK,IAAI,CAACL,KAAKS,OAAO,CAACF,eAAeF,QACtCE;IAEJ,OAAO,CAAC;;EAER,EAAEJ,SAAS,YAAY,YAAYD,KAAK,IAAI,EAC1CE,OAAO,YAAY,YAAYF,KAChC;OACI,EAAEQ,KAAKC,SAAS,CAACH,UAAU;AAClC,CAAC;AACD"}

View File

@@ -0,0 +1,453 @@
import path from "path";
import { stringify } from "querystring";
import chalk from "next/dist/compiled/chalk";
import { getModuleBuildInfo } from "./get-module-build-info";
import { verifyRootLayout } from "../../../lib/verifyRootLayout";
import * as Log from "../../output/log";
import { APP_DIR_ALIAS, WEBPACK_RESOURCE_QUERIES } from "../../../lib/constants";
import { createMetadataExportsCode, createStaticMetadataFromRoute } from "./metadata/discover";
import { promises as fs } from "fs";
import { isAppRouteRoute } from "../../../lib/is-app-route-route";
import { isMetadataRoute } from "../../../lib/metadata/is-metadata-route";
import { AppPathnameNormalizer } from "../../../server/future/normalizers/built/app/app-pathname-normalizer";
import { AppBundlePathNormalizer } from "../../../server/future/normalizers/built/app/app-bundle-path-normalizer";
import { getFilenameAndExtension } from "./next-metadata-route-loader";
import { isAppBuiltinNotFoundPage } from "../../utils";
import { loadEntrypoint } from "../../load-entrypoint";
import { isGroupSegment } from "../../../shared/lib/segment";
const FILE_TYPES = {
layout: "layout",
template: "template",
error: "error",
loading: "loading",
"not-found": "not-found"
};
const GLOBAL_ERROR_FILE_TYPE = "global-error";
const PAGE_SEGMENT = "page$";
const PARALLEL_CHILDREN_SEGMENT = "children$";
const defaultNotFoundPath = "next/dist/client/components/not-found-error";
async function createAppRouteCode({ name, page, pagePath, resolveAppRoute, pageExtensions, nextConfigOutput }) {
// routePath is the path to the route handler file,
// but could be aliased e.g. private-next-app-dir/favicon.ico
const routePath = pagePath.replace(/[\\/]/, "/");
// This, when used with the resolver will give us the pathname to the built
// route handler file.
let resolvedPagePath = await resolveAppRoute(routePath);
if (!resolvedPagePath) {
throw new Error(`Invariant: could not resolve page path for ${name} at ${routePath}`);
}
// If this is a metadata route, then we need to use the metadata loader for
// the route to ensure that the route is generated.
const filename = path.parse(resolvedPagePath).name;
if (isMetadataRoute(name) && filename !== "route") {
const { ext } = getFilenameAndExtension(resolvedPagePath);
const isDynamic = pageExtensions.includes(ext);
resolvedPagePath = `next-metadata-route-loader?${stringify({
page,
isDynamic: isDynamic ? "1" : "0"
})}!${resolvedPagePath}${`?${WEBPACK_RESOURCE_QUERIES.metadataRoute}`}`;
}
const pathname = new AppPathnameNormalizer().normalize(page);
const bundlePath = new AppBundlePathNormalizer().normalize(page);
return await loadEntrypoint("app-route", {
VAR_USERLAND: resolvedPagePath,
VAR_DEFINITION_PAGE: page,
VAR_DEFINITION_PATHNAME: pathname,
VAR_DEFINITION_FILENAME: filename,
VAR_DEFINITION_BUNDLE_PATH: bundlePath,
VAR_RESOLVED_PAGE_PATH: resolvedPagePath,
VAR_ORIGINAL_PATHNAME: page
}, {
nextConfigOutput: JSON.stringify(nextConfigOutput)
});
}
const normalizeParallelKey = (key)=>key.startsWith("@") ? key.slice(1) : key;
const isDirectory = async (pathname)=>{
try {
const stat = await fs.stat(pathname);
return stat.isDirectory();
} catch (err) {
return false;
}
};
async function createTreeCodeFromPath(pagePath, { page, resolveDir, resolver, resolveParallelSegments, metadataResolver, pageExtensions, basePath }) {
const splittedPath = pagePath.split(/[\\/]/);
const isNotFoundRoute = page === "/_not-found";
const isDefaultNotFound = isAppBuiltinNotFoundPage(pagePath);
const appDirPrefix = isDefaultNotFound ? APP_DIR_ALIAS : splittedPath[0];
const hasRootNotFound = await resolver(`${appDirPrefix}/${FILE_TYPES["not-found"]}`);
const pages = [];
let rootLayout;
let globalError;
async function resolveAdjacentParallelSegments(segmentPath) {
const absoluteSegmentPath = await resolveDir(`${appDirPrefix}${segmentPath}`);
if (!absoluteSegmentPath) {
return [];
}
const segmentIsDirectory = await isDirectory(absoluteSegmentPath);
if (!segmentIsDirectory) {
return [];
}
// We need to resolve all parallel routes in this level.
const files = await fs.opendir(absoluteSegmentPath);
const parallelSegments = [
"children"
];
for await (const dirent of files){
// Make sure name starts with "@" and is a directory.
if (dirent.isDirectory() && dirent.name.charCodeAt(0) === 64) {
parallelSegments.push(dirent.name);
}
}
return parallelSegments;
}
async function createSubtreePropsFromSegmentPath(segments) {
const segmentPath = segments.join("/");
// Existing tree are the children of the current segment
const props = {};
// Root layer could be 1st layer of normal routes
const isRootLayer = segments.length === 0;
const isRootLayoutOrRootPage = segments.length <= 1;
// We need to resolve all parallel routes in this level.
const parallelSegments = [];
if (isRootLayer) {
parallelSegments.push([
"children",
""
]);
} else {
parallelSegments.push(...resolveParallelSegments(segmentPath));
}
let metadata = null;
const routerDirPath = `${appDirPrefix}${segmentPath}`;
// For default not-found, don't traverse the directory to find metadata.
const resolvedRouteDir = isDefaultNotFound ? "" : await resolveDir(routerDirPath);
if (resolvedRouteDir) {
metadata = await createStaticMetadataFromRoute(resolvedRouteDir, {
basePath,
segment: segmentPath,
metadataResolver,
isRootLayoutOrRootPage,
pageExtensions
});
}
for (const [parallelKey, parallelSegment] of parallelSegments){
if (parallelSegment === PAGE_SEGMENT) {
const matchedPagePath = `${appDirPrefix}${segmentPath}${parallelKey === "children" ? "" : `/${parallelKey}`}/page`;
const resolvedPagePath = await resolver(matchedPagePath);
if (resolvedPagePath) pages.push(resolvedPagePath);
// Use '' for segment as it's the page. There can't be a segment called '' so this is the safest way to add it.
props[normalizeParallelKey(parallelKey)] = `['__PAGE__', {}, {
page: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(resolvedPagePath)}), ${JSON.stringify(resolvedPagePath)}],
${createMetadataExportsCode(metadata)}
}]`;
continue;
}
const subSegmentPath = [
...segments
];
if (parallelKey !== "children") {
subSegmentPath.push(parallelKey);
}
const normalizedParallelSegments = Array.isArray(parallelSegment) ? parallelSegment.slice(0, 1) : [
parallelSegment
];
subSegmentPath.push(...normalizedParallelSegments.filter((segment)=>segment !== PAGE_SEGMENT && segment !== PARALLEL_CHILDREN_SEGMENT));
const { treeCode: pageSubtreeCode } = await createSubtreePropsFromSegmentPath(subSegmentPath);
const parallelSegmentPath = subSegmentPath.join("/");
// `page` is not included here as it's added above.
const filePaths = await Promise.all(Object.values(FILE_TYPES).map(async (file)=>{
return [
file,
await resolver(`${appDirPrefix}${// TODO-APP: parallelSegmentPath sometimes ends in `/` but sometimes it doesn't. This should be consistent.
parallelSegmentPath.endsWith("/") ? parallelSegmentPath : parallelSegmentPath + "/"}${file}`)
];
}));
const definedFilePaths = filePaths.filter(([, filePath])=>filePath !== undefined);
// Add default not found error as root not found if not present
const hasNotFoundFile = definedFilePaths.some(([type])=>type === "not-found");
// If the first layer is a group route, we treat it as root layer
const isFirstLayerGroupRoute = segments.length === 1 && subSegmentPath.filter((seg)=>isGroupSegment(seg)).length === 1;
if ((isRootLayer || isFirstLayerGroupRoute) && !hasNotFoundFile) {
// If you already have a root not found, don't insert default not-found to group routes root
if (!(hasRootNotFound && isFirstLayerGroupRoute)) {
definedFilePaths.push([
"not-found",
defaultNotFoundPath
]);
}
}
if (!rootLayout) {
var _definedFilePaths_find;
const layoutPath = (_definedFilePaths_find = definedFilePaths.find(([type])=>type === "layout")) == null ? void 0 : _definedFilePaths_find[1];
rootLayout = layoutPath;
if (isDefaultNotFound && !layoutPath) {
rootLayout = "next/dist/client/components/default-layout";
definedFilePaths.push([
"layout",
rootLayout
]);
}
if (layoutPath) {
globalError = await resolver(`${path.dirname(layoutPath)}/${GLOBAL_ERROR_FILE_TYPE}`);
}
}
let parallelSegmentKey = Array.isArray(parallelSegment) ? parallelSegment[0] : parallelSegment;
parallelSegmentKey = parallelSegmentKey === PARALLEL_CHILDREN_SEGMENT ? "children" : parallelSegmentKey;
const normalizedParallelKey = normalizeParallelKey(parallelKey);
let subtreeCode = pageSubtreeCode;
// If it's root not found page, set not-found boundary as children page
if (isNotFoundRoute && normalizedParallelKey === "children") {
var _definedFilePaths_find1;
const notFoundPath = ((_definedFilePaths_find1 = definedFilePaths.find(([type])=>type === "not-found")) == null ? void 0 : _definedFilePaths_find1[1]) ?? defaultNotFoundPath;
subtreeCode = `{
children: ['__PAGE__', {}, {
page: [
() => import(/* webpackMode: "eager" */ ${JSON.stringify(notFoundPath)}),
${JSON.stringify(notFoundPath)}
]
}]
}`;
}
const componentsCode = `{
${definedFilePaths.map(([file, filePath])=>{
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(filePath)}), ${JSON.stringify(filePath)}],`;
}).join("\n")}
${createMetadataExportsCode(metadata)}
}`;
props[normalizedParallelKey] = `[
'${parallelSegmentKey}',
${subtreeCode},
${componentsCode}
]`;
}
const adjacentParallelSegments = await resolveAdjacentParallelSegments(segmentPath);
for (const adjacentParallelSegment of adjacentParallelSegments){
if (!props[normalizeParallelKey(adjacentParallelSegment)]) {
const actualSegment = adjacentParallelSegment === "children" ? "" : adjacentParallelSegment;
const defaultPath = await resolver(`${appDirPrefix}${segmentPath}/${actualSegment}/default`) ?? "next/dist/client/components/parallel-route-default";
props[normalizeParallelKey(adjacentParallelSegment)] = `[
'__DEFAULT__',
{},
{
defaultPage: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(defaultPath)}), ${JSON.stringify(defaultPath)}],
}
]`;
}
}
return {
treeCode: `{
${Object.entries(props).map(([key, value])=>`${key}: ${value}`).join(",\n")}
}`
};
}
const { treeCode } = await createSubtreePropsFromSegmentPath([]);
return {
treeCode: `${treeCode}.children;`,
pages: `${JSON.stringify(pages)};`,
rootLayout,
globalError
};
}
function createAbsolutePath(appDir, pathToTurnAbsolute) {
return pathToTurnAbsolute// Replace all POSIX path separators with the current OS path separator
.replace(/\//g, path.sep).replace(/^private-next-app-dir/, appDir);
}
const nextAppLoader = async function nextAppLoader() {
const loaderOptions = this.getOptions();
const { name, appDir, appPaths, pagePath, pageExtensions, rootDir, tsconfigPath, isDev, nextConfigOutput, preferredRegion, basePath, middlewareConfig: middlewareConfigBase64 } = loaderOptions;
const buildInfo = getModuleBuildInfo(this._module);
const page = name.replace(/^app/, "");
const middlewareConfig = JSON.parse(Buffer.from(middlewareConfigBase64, "base64").toString());
buildInfo.route = {
page,
absolutePagePath: createAbsolutePath(appDir, pagePath),
preferredRegion,
middlewareConfig
};
const extensions = pageExtensions.map((extension)=>`.${extension}`);
const normalizedAppPaths = typeof appPaths === "string" ? [
appPaths
] : appPaths || [];
const resolveParallelSegments = (pathname)=>{
const matched = {};
let existingChildrenPath;
for (const appPath of normalizedAppPaths){
if (appPath.startsWith(pathname + "/")) {
const rest = appPath.slice(pathname.length + 1).split("/");
// It is the actual page, mark it specially.
if (rest.length === 1 && rest[0] === "page") {
existingChildrenPath = appPath;
matched.children = PAGE_SEGMENT;
continue;
}
const isParallelRoute = rest[0].startsWith("@");
if (isParallelRoute) {
if (rest.length === 2 && rest[1] === "page") {
// matched will be an empty object in case the parallel route is at a path with no existing page
// in which case, we need to mark it as a regular page segment
matched[rest[0]] = Object.keys(matched).length ? [
PAGE_SEGMENT
] : PAGE_SEGMENT;
continue;
}
// we insert a special marker in order to also process layout/etc files at the slot level
matched[rest[0]] = [
PARALLEL_CHILDREN_SEGMENT,
...rest.slice(1)
];
continue;
}
// avoid clobbering existing page segments
// if it's a valid parallel segment, the `children` property will be set appropriately
if (existingChildrenPath && matched.children !== rest[0]) {
throw new Error(`You cannot have two parallel pages that resolve to the same path. Please check ${existingChildrenPath} and ${appPath}. Refer to the route group docs for more information: https://nextjs.org/docs/app/building-your-application/routing/route-groups`);
}
existingChildrenPath = appPath;
matched.children = rest[0];
}
}
return Object.entries(matched);
};
const resolveDir = (pathToResolve)=>{
return createAbsolutePath(appDir, pathToResolve);
};
const resolveAppRoute = (pathToResolve)=>{
return createAbsolutePath(appDir, pathToResolve);
};
// Cached checker to see if a file exists in a given directory.
// This can be more efficient than checking them with `fs.stat` one by one
// because all the thousands of files are likely in a few possible directories.
// Note that it should only be cached for this compilation, not globally.
const filesInDir = new Map();
const fileExistsInDirectory = async (dirname, fileName)=>{
const existingFiles = filesInDir.get(dirname);
if (existingFiles) {
return existingFiles.has(fileName);
}
try {
const files = await fs.readdir(dirname, {
withFileTypes: true
});
const fileNames = new Set();
for (const file of files){
if (file.isFile()) {
fileNames.add(file.name);
}
}
filesInDir.set(dirname, fileNames);
return fileNames.has(fileName);
} catch (err) {
return false;
}
};
const resolver = async (pathname)=>{
const absolutePath = createAbsolutePath(appDir, pathname);
const filenameIndex = absolutePath.lastIndexOf(path.sep);
const dirname = absolutePath.slice(0, filenameIndex);
const filename = absolutePath.slice(filenameIndex + 1);
let result;
for (const ext of extensions){
const absolutePathWithExtension = `${absolutePath}${ext}`;
if (!result && await fileExistsInDirectory(dirname, `${filename}${ext}`)) {
result = absolutePathWithExtension;
}
// Call `addMissingDependency` for all files even if they didn't match,
// because they might be added or removed during development.
this.addMissingDependency(absolutePathWithExtension);
}
return result;
};
const metadataResolver = async (dirname, filename, exts)=>{
const absoluteDir = createAbsolutePath(appDir, dirname);
let result;
for (const ext of exts){
// Compared to `resolver` above the exts do not have the `.` included already, so it's added here.
const filenameWithExt = `${filename}.${ext}`;
const absolutePathWithExtension = `${absoluteDir}${path.sep}${filenameWithExt}`;
if (!result && await fileExistsInDirectory(dirname, filenameWithExt)) {
result = absolutePathWithExtension;
}
// Call `addMissingDependency` for all files even if they didn't match,
// because they might be added or removed during development.
this.addMissingDependency(absolutePathWithExtension);
}
return result;
};
if (isAppRouteRoute(name)) {
return createAppRouteCode({
// TODO: investigate if the local `page` is the same as the loaderOptions.page
page: loaderOptions.page,
name,
pagePath,
resolveAppRoute,
pageExtensions,
nextConfigOutput
});
}
let treeCodeResult = await createTreeCodeFromPath(pagePath, {
page,
resolveDir,
resolver,
metadataResolver,
resolveParallelSegments,
loaderContext: this,
pageExtensions,
basePath
});
if (!treeCodeResult.rootLayout) {
if (!isDev) {
// If we're building and missing a root layout, exit the build
Log.error(`${chalk.bold(pagePath.replace(`${APP_DIR_ALIAS}/`, ""))} doesn't have a root layout. To fix this error, make sure every page has a root layout.`);
process.exit(1);
} else {
// In dev we'll try to create a root layout
const [createdRootLayout, rootLayoutPath] = await verifyRootLayout({
appDir: appDir,
dir: rootDir,
tsconfigPath: tsconfigPath,
pagePath,
pageExtensions
});
if (!createdRootLayout) {
let message = `${chalk.bold(pagePath.replace(`${APP_DIR_ALIAS}/`, ""))} doesn't have a root layout. `;
if (rootLayoutPath) {
var _this__compiler;
message += `We tried to create ${chalk.bold(path.relative(((_this__compiler = this._compiler) == null ? void 0 : _this__compiler.context) ?? "", rootLayoutPath))} for you but something went wrong.`;
} else {
message += "To fix this error, make sure every page has a root layout.";
}
throw new Error(message);
}
// Clear fs cache, get the new result with the created root layout.
filesInDir.clear();
treeCodeResult = await createTreeCodeFromPath(pagePath, {
page,
resolveDir,
resolver,
metadataResolver,
resolveParallelSegments,
loaderContext: this,
pageExtensions,
basePath
});
}
}
const pathname = new AppPathnameNormalizer().normalize(page);
// Prefer to modify next/src/server/app-render/entry-base.ts since this is shared with Turbopack.
// Any changes to this code should be reflected in Turbopack's app_source.rs and/or app-renderer.tsx as well.
return await loadEntrypoint("app-page", {
VAR_DEFINITION_PAGE: page,
VAR_DEFINITION_PATHNAME: pathname,
VAR_MODULE_GLOBAL_ERROR: treeCodeResult.globalError ? treeCodeResult.globalError : "next/dist/client/components/error-boundary",
VAR_ORIGINAL_PATHNAME: page
}, {
tree: treeCodeResult.treeCode,
pages: treeCodeResult.pages,
__next_app_require__: "__webpack_require__",
__next_app_load_chunk__: "() => Promise.resolve()"
});
};
export default nextAppLoader;
//# sourceMappingURL=next-app-loader.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,157 @@
/**
* ## Barrel Optimizations
*
* This loader is used to optimize the imports of "barrel" files that have many
* re-exports. Currently, both Node.js and Webpack have to enter all of these
* submodules even if we only need a few of them.
*
* For example, say a file `foo.js` with the following contents:
*
* export { a } from './a'
* export { b } from './b'
* export { c } from './c'
* ...
*
* If the user imports `a` only, this loader will accept the `names` option to
* be `['a']`. Then, it request the "__barrel_transform__" SWC transform to load
* `foo.js` and receive the following output:
*
* export const __next_private_export_map__ = '[["a","./a","a"],["b","./b","b"],["c","./c","c"],...]'
*
* format: '["<imported identifier>", "<import path>", "<exported name>"]'
* e.g.: import { a as b } from './module-a' => '["b", "./module-a", "a"]'
*
* The export map, generated by SWC, is a JSON that represents the exports of
* that module, their original file, and their original name (since you can do
* `export { a as b }`).
*
* Then, this loader can safely remove all the exports that are not needed and
* re-export the ones from `names`:
*
* export { a } from './a'
*
* That's the basic situation and also the happy path.
*
*
*
* ## Wildcard Exports
*
* For wildcard exports (e.g. `export * from './a'`), it becomes a bit more complicated.
* Say `foo.js` with the following contents:
*
* export * from './a'
* export * from './b'
* export * from './c'
* ...
*
* If the user imports `bar` from it, SWC can never know which files are going to be
* exporting `bar`. So, we have to keep all the wildcard exports and do the same
* process recursively. This loader will return the following output:
*
* export * from '__barrel_optimize__?names=bar&wildcard!=!./a'
* export * from '__barrel_optimize__?names=bar&wildcard!=!./b'
* export * from '__barrel_optimize__?names=bar&wildcard!=!./c'
* ...
*
* The "!=!" tells Webpack to use the same loader to process './a', './b', and './c'.
* After the recursive process, the "inner loaders" will either return an empty string
* or:
*
* export * from './target'
*
* Where `target` is the file that exports `bar`.
*
*
*
* ## Non-Barrel Files
*
* If the file is not a barrel, we can't apply any optimizations. That's because
* we can't easily remove things from the file. For example, say `foo.js` with:
*
* const v = 1
* export function b () {
* return v
* }
*
* If the user imports `b` only, we can't remove the `const v = 1` even though
* the file is side-effect free. In these caes, this loader will simply re-export
* `foo.js`:
*
* export * from './foo'
*
* Besides these cases, this loader also carefully handles the module cache so
* SWC won't analyze the same file twice, and no instance of the same file will
* be accidentally created as different instances.
*/ const NextBarrelLoader = async function() {
this.async();
const { names, wildcard } = this.getOptions();
const source = await new Promise((resolve, reject)=>{
this.loadModule(`__barrel_transform__${wildcard ? "?wildcard" : ""}!=!${this.resourcePath}`, (err, src)=>{
if (err) {
reject(err);
} else {
resolve(src);
}
});
});
const matches = source.match(/^([^]*)export const __next_private_export_map__ = ('[^']+'|"[^"]+")/);
if (!matches) {
// This file isn't a barrel and we can't apply any optimizations. Let's re-export everything.
// Since this loader accepts `names` and the request is keyed with `names`, we can't simply
// return the original source here. That will create these imports with different names as
// different modules instances.
this.callback(null, `export * from ${JSON.stringify(this.resourcePath)}`);
return;
}
const wildcardExports = [
...source.matchAll(/export \* from "([^"]+)"/g)
];
// It needs to keep the prefix for comments and directives like "use client".
const prefix = matches[1];
const exportList = JSON.parse(matches[2].slice(1, -1));
const exportMap = new Map();
for (const [name, path, orig] of exportList){
exportMap.set(name, [
path,
orig
]);
}
let output = prefix;
let missedNames = [];
for (const name of names){
// If the name matches
if (exportMap.has(name)) {
const decl = exportMap.get(name);
// In the wildcard case, if the value is exported from another file, we
// redirect to that file (decl[0]). Otherwise, export from the current
// file itself (this.resourcePath).
if (wildcard && !decl[0]) {
// E.g. the file contains `export const a = 1`
decl[0] = this.resourcePath;
decl[1] = name;
}
if (decl[1] === "*") {
output += `\nexport * as ${name} from ${JSON.stringify(decl[0])}`;
} else if (decl[1] === "default") {
output += `\nexport { default as ${name} } from ${JSON.stringify(decl[0])}`;
} else if (decl[1] === name) {
output += `\nexport { ${name} } from ${JSON.stringify(decl[0])}`;
} else {
output += `\nexport { ${decl[1]} as ${name} } from ${JSON.stringify(decl[0])}`;
}
} else {
missedNames.push(name);
}
}
// These are from wildcard exports.
if (missedNames.length > 0) {
for (const match of wildcardExports){
const path = match[1];
output += `\nexport * from ${JSON.stringify(path.replace("__PLACEHOLDER__", missedNames.join(",") + "&wildcard"))}`;
}
}
this.callback(null, output);
};
export default NextBarrelLoader;
//# sourceMappingURL=next-barrel-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/next-barrel-loader.ts"],"names":["NextBarrelLoader","async","names","wildcard","getOptions","source","Promise","resolve","reject","loadModule","resourcePath","err","src","matches","match","callback","JSON","stringify","wildcardExports","matchAll","prefix","exportList","parse","slice","exportMap","Map","name","path","orig","set","output","missedNames","has","decl","get","push","length","replace","join"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoFC,GAID,MAAMA,mBAAmB;IAMvB,IAAI,CAACC,KAAK;IACV,MAAM,EAAEC,KAAK,EAAEC,QAAQ,EAAE,GAAG,IAAI,CAACC,UAAU;IAE3C,MAAMC,SAAS,MAAM,IAAIC,QAAgB,CAACC,SAASC;QACjD,IAAI,CAACC,UAAU,CACb,CAAC,oBAAoB,EAAEN,WAAW,cAAc,GAAG,GAAG,EACpD,IAAI,CAACO,YAAY,CAClB,CAAC,EACF,CAACC,KAAKC;YACJ,IAAID,KAAK;gBACPH,OAAOG;YACT,OAAO;gBACLJ,QAAQK;YACV;QACF;IAEJ;IAEA,MAAMC,UAAUR,OAAOS,KAAK,CAC1B;IAGF,IAAI,CAACD,SAAS;QACZ,6FAA6F;QAC7F,2FAA2F;QAC3F,0FAA0F;QAC1F,+BAA+B;QAC/B,IAAI,CAACE,QAAQ,CAAC,MAAM,CAAC,cAAc,EAAEC,KAAKC,SAAS,CAAC,IAAI,CAACP,YAAY,EAAE,CAAC;QACxE;IACF;IAEA,MAAMQ,kBAAkB;WAAIb,OAAOc,QAAQ,CAAC;KAA6B;IAEzE,6EAA6E;IAC7E,MAAMC,SAASP,OAAO,CA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ACP,CAAC;YACL;QACF,OAAO;YACLF,YAAYI,IAAI,CAACT;QACnB;IACF;IAEA,mCAAmC;IACnC,IAAIK,YAAYK,MAAM,GAAG,GAAG;QAC1B,KAAK,MAAMtB,SAASI,gBAAiB;YACnC,MAAMS,OAAOb,KAAK,CAAC,EAAE;YAErBgB,UAAU,CAAC,gBAAgB,EAAEd,KAAKC,SAAS,CACzCU,KAAKU,OAAO,CAAC,mBAAmBN,YAAYO,IAAI,CAAC,OAAO,cACxD,CAAC;QACL;IACF;IAEA,IAAI,CAACvB,QAAQ,CAAC,MAAMe;AACtB;AAEA,eAAe9B,iBAAgB"}

View File

@@ -0,0 +1,27 @@
import { stringifyRequest } from "../stringify-request";
// this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
function nextClientPagesLoader() {
const pagesLoaderSpan = this.currentTraceSpan.traceChild("next-client-pages-loader");
return pagesLoaderSpan.traceFn(()=>{
const { absolutePagePath, page } = this.getOptions();
pagesLoaderSpan.setAttribute("absolutePagePath", absolutePagePath);
const stringifiedPageRequest = stringifyRequest(this, absolutePagePath);
const stringifiedPage = JSON.stringify(page);
return `
(window.__NEXT_P = window.__NEXT_P || []).push([
${stringifiedPage},
function () {
return require(${stringifiedPageRequest});
}
]);
if(module.hot) {
module.hot.dispose(function () {
window.__NEXT_P.push([${stringifiedPage}])
});
}
`;
});
}
export default nextClientPagesLoader;
//# sourceMappingURL=next-client-pages-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/next-client-pages-loader.ts"],"names":["stringifyRequest","nextClientPagesLoader","pagesLoaderSpan","currentTraceSpan","traceChild","traceFn","absolutePagePath","page","getOptions","setAttribute","stringifiedPageRequest","stringifiedPage","JSON","stringify"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,uBAAsB;AAOvD,8FAA8F;AAC9F,SAASC;IACP,MAAMC,kBAAkB,IAAI,CAACC,gBAAgB,CAACC,UAAU,CACtD;IAGF,OAAOF,gBAAgBG,OAAO,CAAC;QAC7B,MAAM,EAAEC,gBAAgB,EAAEC,IAAI,EAAE,GAC9B,IAAI,CAACC,UAAU;QAEjBN,gBAAgBO,YAAY,CAAC,oBAAoBH;QAEjD,MAAMI,yBAAyBV,iBAAiB,IAAI,EAAEM;QACtD,MAAMK,kBAAkBC,KAAKC,SAAS,CAACN;QAEvC,OAAO,CAAC;;MAEN,EAAEI,gBAAgB;;uBAED,EAAED,uBAAuB;;;;;8BAKlB,EAAEC,gBAAgB;;;EAG9C,CAAC;IACD;AACF;AAEA,eAAeV,sBAAqB"}

View File

@@ -0,0 +1,34 @@
import { getModuleBuildInfo } from "../get-module-build-info";
import { stringifyRequest } from "../../stringify-request";
import { WEBPACK_RESOURCE_QUERIES } from "../../../../lib/constants";
const EdgeAppRouteLoader = function() {
const { page, absolutePagePath, preferredRegion, appDirLoader: appDirLoaderBase64 = "", middlewareConfig: middlewareConfigBase64 = "" } = this.getOptions();
const appDirLoader = Buffer.from(appDirLoaderBase64, "base64").toString();
const middlewareConfig = JSON.parse(Buffer.from(middlewareConfigBase64, "base64").toString());
// Ensure we only run this loader for as a module.
if (!this._module) throw new Error("This loader is only usable as a module");
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextEdgeSSR = {
isServerComponent: false,
page: page,
isAppDir: true
};
buildInfo.route = {
page,
absolutePagePath,
preferredRegion,
middlewareConfig
};
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
const modulePath = `${appDirLoader}${stringifiedPagePath.substring(1, stringifiedPagePath.length - 1)}?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}`;
return `
import { EdgeRouteModuleWrapper } from 'next/dist/esm/server/web/edge-route-module-wrapper'
import * as module from ${JSON.stringify(modulePath)}
export const ComponentMod = module
export default EdgeRouteModuleWrapper.wrap(module.routeModule)`;
};
export default EdgeAppRouteLoader;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-edge-app-route-loader/index.ts"],"names":["getModuleBuildInfo","stringifyRequest","WEBPACK_RESOURCE_QUERIES","EdgeAppRouteLoader","page","absolutePagePath","preferredRegion","appDirLoader","appDirLoaderBase64","middlewareConfig","middlewareConfigBase64","getOptions","Buffer","from","toString","JSON","parse","_module","Error","buildInfo","nextEdgeSSR","isServerComponent","isAppDir","route","stringifiedPagePath","modulePath","substring","length","edgeSSREntry","stringify"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,2BAA0B;AAC7D,SAASC,gBAAgB,QAAQ,0BAAyB;AAG1D,SAASC,wBAAwB,QAAQ,4BAA2B;AAYpE,MAAMC,qBACJ;IACE,MAAM,EACJC,IAAI,EACJC,gBAAgB,EAChBC,eAAe,EACfC,cAAcC,qBAAqB,EAAE,EACrCC,kBAAkBC,yBAAyB,EAAE,EAC9C,GAAG,IAAI,CAACC,UAAU;IAEnB,MAAMJ,eAAeK,OAAOC,IAAI,CAACL,oBAAoB,UAAUM,QAAQ;IACvE,MAAML,mBAAqCM,KAAKC,KAAK,CACnDJ,OAAOC,IAAI,CAACH,wBAAwB,UAAUI,QAAQ;IAGxD,kDAAkD;IAClD,IAAI,CAAC,IAAI,CAACG,OAAO,EAAE,MAAM,IAAIC,MAAM;IAEnC,MAAMC,YAAYnB,mBAAmB,IAAI,CAACiB,OAAO;IAEjDE,UAAUC,WAAW,GAAG;QACtBC,mBAAmB;QACnBjB,MAAMA;QACNkB,UAAU;IACZ;IACAH,UAAUI,KAAK,GAAG;QAChBnB;QACAC;QACAC;QACAG;IACF;IAEA,MAAMe,sBAAsBvB,iBAAiB,IAAI,EAAEI;IACnD,MAAMoB,aAAa,CAAC,EAAElB,aAAa,EAAEiB,oBAAoBE,SAAS,CAChE,GACAF,oBAAoBG,MAAM,GAAG,GAC7B,CAAC,EAAEzB,yBAAyB0B,YAAY,CAAC,CAAC;IAE5C,OAAO,CAAC;;4BAEgB,EAAEb,KAAKc,SAAS,CAACJ,YAAY;;;;kEAIS,CAAC;AACjE;AAEF,eAAetB,mBAAkB"}

View File

@@ -0,0 +1,41 @@
import { getModuleBuildInfo } from "./get-module-build-info";
import { stringifyRequest } from "../stringify-request";
const nextEdgeFunctionLoader = function nextEdgeFunctionLoader() {
const { absolutePagePath, page, rootDir, preferredRegion, middlewareConfig: middlewareConfigBase64 } = this.getOptions();
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
const buildInfo = getModuleBuildInfo(this._module);
const middlewareConfig = JSON.parse(Buffer.from(middlewareConfigBase64, "base64").toString());
buildInfo.route = {
page: page || "/",
absolutePagePath,
preferredRegion,
middlewareConfig
};
buildInfo.nextEdgeApiFunction = {
page: page || "/"
};
buildInfo.rootDir = rootDir;
return `
import 'next/dist/esm/server/web/globals'
import { adapter } from 'next/dist/esm/server/web/adapter'
import { IncrementalCache } from 'next/dist/esm/server/lib/incremental-cache'
import handler from ${stringifiedPagePath}
if (typeof handler !== 'function') {
throw new Error('The Edge Function "pages${page}" must export a \`default\` function');
}
export default function (opts) {
return adapter({
...opts,
IncrementalCache,
page: ${JSON.stringify(page)},
handler,
})
}
`;
};
export default nextEdgeFunctionLoader;
//# sourceMappingURL=next-edge-function-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/next-edge-function-loader.ts"],"names":["getModuleBuildInfo","stringifyRequest","nextEdgeFunctionLoader","absolutePagePath","page","rootDir","preferredRegion","middlewareConfig","middlewareConfigBase64","getOptions","stringifiedPagePath","buildInfo","_module","JSON","parse","Buffer","from","toString","route","nextEdgeApiFunction","stringify"],"mappings":"AACA,SAASA,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,gBAAgB,QAAQ,uBAAsB;AAWvD,MAAMC,yBACJ,SAASA;IACP,MAAM,EACJC,gBAAgB,EAChBC,IAAI,EACJC,OAAO,EACPC,eAAe,EACfC,kBAAkBC,sBAAsB,EACzC,GAA8B,IAAI,CAACC,UAAU;IAC9C,MAAMC,sBAAsBT,iBAAiB,IAAI,EAAEE;IACnD,MAAMQ,YAAYX,mBAAmB,IAAI,CAACY,OAAO;IACjD,MAAML,mBAAqCM,KAAKC,KAAK,CACnDC,OAAOC,IAAI,CAACR,wBAAwB,UAAUS,QAAQ;IAExDN,UAAUO,KAAK,GAAG;QAChBd,MAAMA,QAAQ;QACdD;QACAG;QACAC;IACF;IACAI,UAAUQ,mBAAmB,GAAG;QAC9Bf,MAAMA,QAAQ;IAChB;IACAO,UAAUN,OAAO,GAAGA;IAEpB,OAAO,CAAC;;;;;4BAKgB,EAAEK,oBAAoB;;;mDAGC,EAAEN,KAAK;;;;;;;oBAOtC,EAAES,KAAKO,SAAS,CAAChB,MAAM;;;;IAIvC,CAAC;AACH;AAEF,eAAeF,uBAAsB"}

View File

@@ -0,0 +1,166 @@
import { getModuleBuildInfo } from "../get-module-build-info";
import { WEBPACK_RESOURCE_QUERIES } from "../../../../lib/constants";
import { stringifyRequest } from "../../stringify-request";
import { RouteKind } from "../../../../server/future/route-kind";
import { normalizePagePath } from "../../../../shared/lib/page-path/normalize-page-path";
/*
For pages SSR'd at the edge, we bundle them with the ESM version of Next in order to
benefit from the better tree-shaking and thus, smaller bundle sizes.
The absolute paths for _app, _error and _document, used in this loader, link to the regular CJS modules.
They are generated in `createPagesMapping` where we don't have access to `isEdgeRuntime`,
so we have to do it here. It's not that bad because it keeps all references to ESM modules magic in this place.
*/ function swapDistFolderWithEsmDistFolder(path) {
return path.replace("next/dist/pages", "next/dist/esm/pages");
}
function getRouteModuleOptions(page) {
const options = {
definition: {
kind: RouteKind.PAGES,
page: normalizePagePath(page),
pathname: page,
// The following aren't used in production.
bundlePath: "",
filename: ""
}
};
return options;
}
const edgeSSRLoader = function edgeSSRLoader() {
const { dev, page, buildId, absolutePagePath, absoluteAppPath, absoluteDocumentPath, absolute500Path, absoluteErrorPath, isServerComponent, stringifiedConfig: stringifiedConfigBase64, appDirLoader: appDirLoaderBase64, pagesType, sriEnabled, incrementalCacheHandlerPath, preferredRegion, middlewareConfig: middlewareConfigBase64, serverActionsBodySizeLimit } = this.getOptions();
const middlewareConfig = JSON.parse(Buffer.from(middlewareConfigBase64, "base64").toString());
const stringifiedConfig = Buffer.from(stringifiedConfigBase64 || "", "base64").toString();
const appDirLoader = Buffer.from(appDirLoaderBase64 || "", "base64").toString();
const isAppDir = pagesType === "app";
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextEdgeSSR = {
// @ts-expect-error === 'true' is correct because loader options are serialized as searchParams. Type needs to be fixed somehow.
isServerComponent: isServerComponent === "true",
page: page,
isAppDir
};
buildInfo.route = {
page,
absolutePagePath,
preferredRegion,
middlewareConfig
};
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
const stringifiedAppPath = stringifyRequest(this, swapDistFolderWithEsmDistFolder(absoluteAppPath));
const stringifiedErrorPath = stringifyRequest(this, swapDistFolderWithEsmDistFolder(absoluteErrorPath));
const stringifiedDocumentPath = stringifyRequest(this, swapDistFolderWithEsmDistFolder(absoluteDocumentPath));
const stringified500Path = absolute500Path ? stringifyRequest(this, absolute500Path) : null;
const pageModPath = `${appDirLoader}${stringifiedPagePath.substring(1, stringifiedPagePath.length - 1)}${isAppDir ? `?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}` : ""}`;
const transformed = `
import 'next/dist/esm/server/web/globals'
import { adapter } from 'next/dist/esm/server/web/adapter'
import { getRender } from 'next/dist/esm/build/webpack/loaders/next-edge-ssr-loader/render'
import { IncrementalCache } from 'next/dist/esm/server/lib/incremental-cache'
const pagesType = ${JSON.stringify(pagesType)}
${isAppDir ? `
import { renderToHTMLOrFlight as renderToHTML } from 'next/dist/esm/server/app-render/app-render'
import * as pageMod from ${JSON.stringify(pageModPath)}
const Document = null
const appMod = null
const errorMod = null
const error500Mod = null
` : `
import Document from ${stringifiedDocumentPath}
import * as appMod from ${stringifiedAppPath}
import * as userlandPage from ${stringifiedPagePath}
import * as userlandErrorPage from ${stringifiedErrorPath}
${stringified500Path ? `import * as userland500Page from ${stringified500Path}` : ""}
// TODO: re-enable this once we've refactored to use implicit matches
// const renderToHTML = undefined
import { renderToHTML } from 'next/dist/esm/server/render'
import RouteModule from "next/dist/esm/server/future/route-modules/pages/module"
const pageMod = {
...userlandPage,
routeModule: new RouteModule({
...${JSON.stringify(getRouteModuleOptions(page))},
components: {
App: appMod.default,
Document,
},
userland: userlandPage,
}),
}
const errorMod = {
...userlandErrorPage,
routeModule: new RouteModule({
...${JSON.stringify(getRouteModuleOptions("/_error"))},
components: {
App: appMod.default,
Document,
},
userland: userlandErrorPage,
}),
}
const error500Mod = ${stringified500Path ? `{
...userland500Page,
routeModule: new RouteModule({
...${JSON.stringify(getRouteModuleOptions("/500"))},
components: {
App: appMod.default,
Document,
},
userland: userland500Page,
}),
}` : "null"}`}
${incrementalCacheHandlerPath ? `import incrementalCacheHandler from ${JSON.stringify(incrementalCacheHandlerPath)}` : "const incrementalCacheHandler = null"}
const maybeJSONParse = (str) => str ? JSON.parse(str) : undefined
const buildManifest = self.__BUILD_MANIFEST
const prerenderManifest = maybeJSONParse(self.__PRERENDER_MANIFEST)
const reactLoadableManifest = maybeJSONParse(self.__REACT_LOADABLE_MANIFEST)
const rscManifest = self.__RSC_MANIFEST?.[${JSON.stringify(page)}]
const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)
const subresourceIntegrityManifest = ${sriEnabled ? "maybeJSONParse(self.__SUBRESOURCE_INTEGRITY_MANIFEST)" : "undefined"}
const nextFontManifest = maybeJSONParse(self.__NEXT_FONT_MANIFEST)
const render = getRender({
pagesType,
dev: ${dev},
page: ${JSON.stringify(page)},
appMod,
pageMod,
errorMod,
error500Mod,
Document,
buildManifest,
isAppPath: ${!!isAppDir},
prerenderManifest,
renderToHTML,
reactLoadableManifest,
clientReferenceManifest: ${isServerComponent} ? rscManifest : null,
serverActionsManifest: ${isServerComponent} ? rscServerManifest : null,
serverActionsBodySizeLimit: ${isServerComponent} ? ${typeof serverActionsBodySizeLimit === "undefined" ? "undefined" : JSON.stringify(serverActionsBodySizeLimit)} : undefined,
subresourceIntegrityManifest,
config: ${stringifiedConfig},
buildId: ${JSON.stringify(buildId)},
nextFontManifest,
incrementalCacheHandler,
})
export const ComponentMod = pageMod
export default function(opts) {
return adapter({
...opts,
IncrementalCache,
handler: render
})
}`;
return transformed;
};
export default edgeSSRLoader;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-edge-ssr-loader/index.ts"],"names":["getModuleBuildInfo","WEBPACK_RESOURCE_QUERIES","stringifyRequest","RouteKind","normalizePagePath","swapDistFolderWithEsmDistFolder","path","replace","getRouteModuleOptions","page","options","definition","kind","PAGES","pathname","bundlePath","filename","edgeSSRLoader","dev","buildId","absolutePagePath","absoluteAppPath","absoluteDocumentPath","absolute500Path","absoluteErrorPath","isServerComponent","stringifiedConfig","stringifiedConfigBase64","appDirLoader","appDirLoaderBase64","pagesType","sriEnabled","incrementalCacheHandlerPath","preferredRegion","middlewareConfig","middlewareConfigBase64","serverActionsBodySizeLimit","getOptions","JSON","parse","Buffer","from","toString","isAppDir","buildInfo","_module","nextEdgeSSR","route","stringifiedPagePath","stringifiedAppPath","stringifiedErrorPath","stringifiedDocumentPath","stringified500Path","pageModPath","substring","length","edgeSSREntry","transformed","stringify"],"mappings":"AAKA,SAASA,kBAAkB,QAAQ,2BAA0B;AAC7D,SAASC,wBAAwB,QAAQ,4BAA2B;AACpE,SAASC,gBAAgB,QAAQ,0BAAyB;AAC1D,SAASC,SAAS,QAAQ,uCAAsC;AAChE,SAASC,iBAAiB,QAAQ,uDAAsD;AAsBxF;;;;;;;AAOA,GACA,SAASC,gCAAgCC,IAAY;IACnD,OAAOA,KAAKC,OAAO,CAAC,mBAAmB;AACzC;AAEA,SAASC,sBAAsBC,IAAY;IACzC,MAAMC,UAAoE;QACxEC,YAAY;YACVC,MAAMT,UAAUU,KAAK;YACrBJ,MAAML,kBAAkBK;YACxBK,UAAUL;YACV,2CAA2C;YAC3CM,YAAY;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../../../server/web-server";
import { WebNextRequest, WebNextResponse } from "../../../../server/base-http/web";
import { SERVER_RUNTIME } from "../../../../lib/constants";
import { normalizeAppPath } from "../../../../shared/lib/router/utils/app-paths";
export function getRender({ dev, page, appMod, pageMod, errorMod, error500Mod, pagesType, Document, buildManifest, prerenderManifest, reactLoadableManifest, renderToHTML, clientReferenceManifest, subresourceIntegrityManifest, serverActionsManifest, serverActionsBodySizeLimit, config, buildId, nextFontManifest, incrementalCacheHandler }) {
const isAppPath = pagesType === "app";
const baseLoadComponentResult = {
dev,
buildManifest,
reactLoadableManifest,
subresourceIntegrityManifest,
Document,
App: appMod == null ? void 0 : appMod.default,
clientReferenceManifest
};
const server = new WebServer({
dev,
conf: config,
minimalMode: true,
webServerConfig: {
page,
pathname: isAppPath ? normalizeAppPath(page) : page,
pagesType,
prerenderManifest,
extendRenderOpts: {
buildId,
runtime: SERVER_RUNTIME.experimentalEdge,
supportsDynamicHTML: true,
disableOptimizedLoading: true,
serverActionsManifest,
serverActionsBodySizeLimit,
nextFontManifest
},
renderToHTML,
incrementalCacheHandler,
loadComponent: async (inputPage)=>{
if (inputPage === page) {
return {
...baseLoadComponentResult,
Component: pageMod.default,
pageConfig: pageMod.config || {},
getStaticProps: pageMod.getStaticProps,
getServerSideProps: pageMod.getServerSideProps,
getStaticPaths: pageMod.getStaticPaths,
ComponentMod: pageMod,
isAppPath: !!pageMod.__next_app__,
page: inputPage,
routeModule: pageMod.routeModule
};
}
// If there is a custom 500 page, we need to handle it separately.
if (inputPage === "/500" && error500Mod) {
return {
...baseLoadComponentResult,
Component: error500Mod.default,
pageConfig: error500Mod.config || {},
getStaticProps: error500Mod.getStaticProps,
getServerSideProps: error500Mod.getServerSideProps,
getStaticPaths: error500Mod.getStaticPaths,
ComponentMod: error500Mod,
page: inputPage,
routeModule: error500Mod.routeModule
};
}
if (inputPage === "/_error") {
return {
...baseLoadComponentResult,
Component: errorMod.default,
pageConfig: errorMod.config || {},
getStaticProps: errorMod.getStaticProps,
getServerSideProps: errorMod.getServerSideProps,
getStaticPaths: errorMod.getStaticPaths,
ComponentMod: errorMod,
page: inputPage,
routeModule: errorMod.routeModule
};
}
return null;
}
}
});
const handler = server.getRequestHandler();
return async function render(request) {
const extendedReq = new WebNextRequest(request);
const extendedRes = new WebNextResponse();
handler(extendedReq, extendedRes);
return await extendedRes.toResponse();
};
}
//# sourceMappingURL=render.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-edge-ssr-loader/render.ts"],"names":["WebServer","WebNextRequest","WebNextResponse","SERVER_RUNTIME","normalizeAppPath","getRender","dev","page","appMod","pageMod","errorMod","error500Mod","pagesType","Document","buildManifest","prerenderManifest","reactLoadableManifest","renderToHTML","clientReferenceManifest","subresourceIntegrityManifest","serverActionsManifest","serverActionsBodySizeLimit","config","buildId","nextFontManifest","incrementalCacheHandler","isAppPath","baseLoadComponentResult","App","default","server","conf","minimalMode","webServerConfig","pathname","extendRenderOpts","runtime","experimentalEdge","supportsDynamicHTML","disableOptimizedLoading","loadComponent","inputPage","Component","pageConfig","getStaticProps","getServerSideProps","getStaticPaths","ComponentMod","__next_app__","routeModule","handler","getRequestHandler","render","request","extendedReq","extendedRes","toResponse"],"mappings":"AAQA,OAAOA,eAAe,gCAA+B;AACrD,SACEC,cAAc,EACdC,eAAe,QACV,mCAAkC;AACzC,SAASC,cAAc,QAAQ,4BAA2B;AAE1D,SAASC,gBAAgB,QAAQ,gDAA+C;AAGhF,OAAO,SAASC,UAAU,EACxBC,GAAG,EACHC,IAAI,EACJC,MAAM,EACNC,OAAO,EACPC,QAAQ,EACRC,WAAW,EACXC,SAAS,EACTC,QAAQ,EACRC,aAAa,EACbC,iBAAiB,EACjBC,qBAAqB,EACrBC,YAAY,EACZC,uBAAuB,EACvBC,4BAA4B,EAC5BC,qBAAqB,EACrBC,0BAA0B,EAC1BC,MAAM,EACNC,OAAO,EACPC,gBAAgB,EAChBC,uBAAuB,EAuBxB;IACC,MAAMC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AC3Bc,YAAYjC,SAASY,MAAM,IAAI,CAAC;wBAChCsB,gBAAgBlC,SAASkC,cAAc;wBACvCC,oBAAoBnC,SAASmC,kBAAkB;wBAC/CC,gBAAgBpC,SAASoC,cAAc;wBACvCC,cAAcrC;wBACdH,MAAMkC;wBACNQ,aAAavC,SAASuC,WAAW;oBACnC;gBACF;gBAEA,OAAO;YACT;QACF;IACF;IAEA,MAAMC,UAAUpB,OAAOqB,iBAAiB;IAExC,OAAO,eAAeC,OAAOC,OAAgB;QAC3C,MAAMC,cAAc,IAAIrD,eAAeoD;QACvC,MAAME,cAAc,IAAIrD;QAExBgD,QAAQI,aAAaC;QAErB,OAAO,MAAMA,YAAYC,UAAU;IACrC;AACF"}

View File

@@ -0,0 +1,37 @@
import { generateActionId } from "./utils";
function nextFlightActionEntryLoader() {
const { actions } = this.getOptions();
const actionList = JSON.parse(actions);
const individualActions = actionList.map(([path, names])=>{
return names.map((name)=>{
const id = generateActionId(path, name);
return [
id,
path,
name
];
});
}).flat();
return `
const actions = {
${individualActions.map(([id, path, name])=>{
return `'${id}': () => import(/* webpackMode: "eager" */ ${JSON.stringify(path)}).then(mod => mod[${JSON.stringify(name)}]),`;
}).join("\n")}
}
async function endpoint(id, ...args) {
const action = await actions[id]()
return action.apply(null, args)
}
// Using CJS to avoid this to be tree-shaken away due to unused exports.
module.exports = {
${individualActions.map(([id])=>{
return ` '${id}': endpoint.bind(null, '${id}'),`;
}).join("\n")}
}
`;
}
export default nextFlightActionEntryLoader;
//# sourceMappingURL=next-flight-action-entry-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/next-flight-action-entry-loader.ts"],"names":["generateActionId","nextFlightActionEntryLoader","actions","getOptions","actionList","JSON","parse","individualActions","map","path","names","name","id","flat","stringify","join"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,UAAS;AAM1C,SAASC;IACP,MAAM,EAAEC,OAAO,EAAE,GAAuC,IAAI,CAACC,UAAU;IAEvE,MAAMC,aAAaC,KAAKC,KAAK,CAACJ;IAC9B,MAAMK,oBAAoBH,WACvBI,GAAG,CAAC,CAAC,CAACC,MAAMC,MAAM;QACjB,OAAOA,MAAMF,GAAG,CAAC,CAACG;YAChB,MAAMC,KAAKZ,iBAAiBS,MAAME;YAClC,OAAO;gBAACC;gBAAIH;gBAAME;aAAK;QACzB;IACF,GACCE,IAAI;IAEP,OAAO,CAAC;;AAEV,EAAEN,kBACCC,GAAG,CAAC,CAAC,CAACI,IAAIH,MAAME,KAAK;QACpB,OAAO,CAAC,CAAC,EAAEC,GAAG,2CAA2C,EAAEP,KAAKS,SAAS,CACvEL,MACA,kBAAkB,EAAEJ,KAAKS,SAAS,CAACH,MAAM,GAAG,CAAC;IACjD,GACCI,IAAI,CAAC,MAAM;;;;;;;;;;AAUd,EAAER,kBACCC,GAAG,CAAC,CAAC,CAACI,GAAG;QACR,OAAO,CAAC,GAAG,EAAEA,GAAG,wBAAwB,EAAEA,GAAG,GAAG,CAAC;IACnD,GACCG,IAAI,CAAC,MAAM;;AAEd,CAAC;AACD;AAEA,eAAed,4BAA2B"}

View File

@@ -0,0 +1,22 @@
import { RSC_MODULE_TYPES } from "../../../shared/lib/constants";
import { getModuleBuildInfo } from "./get-module-build-info";
import { regexCSS } from "./utils";
export default function transformSource() {
let { modules, server } = this.getOptions();
const isServer = server === "true";
if (!Array.isArray(modules)) {
modules = modules ? [
modules
] : [];
}
const requests = modules;
const code = requests// Filter out CSS files in the SSR compilation
.filter((request)=>isServer ? !regexCSS.test(request) : true).map((request)=>`import(/* webpackMode: "eager" */ ${JSON.stringify(request)})`).join(";\n");
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.rsc = {
type: RSC_MODULE_TYPES.client
};
return code;
}
//# sourceMappingURL=next-flight-client-entry-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/next-flight-client-entry-loader.ts"],"names":["RSC_MODULE_TYPES","getModuleBuildInfo","regexCSS","transformSource","modules","server","getOptions","isServer","Array","isArray","requests","code","filter","request","test","map","JSON","stringify","join","buildInfo","_module","rsc","type","client"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,gCAA+B;AAChE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,QAAQ,QAAQ,UAAS;AAWlC,eAAe,SAASC;IACtB,IAAI,EAAEC,OAAO,EAAEC,MAAM,EAAE,GACrB,IAAI,CAACC,UAAU;IACjB,MAAMC,WAAWF,WAAW;IAE5B,IAAI,CAACG,MAAMC,OAAO,CAACL,UAAU;QAC3BA,UAAUA,UAAU;YAACA;SAAQ,GAAG,EAAE;IACpC;IAEA,MAAMM,WAAWN;IACjB,MAAMO,OAAOD,QACX,8CAA8C;KAC7CE,MAAM,CAAC,CAACC,UAAaN,WAAW,CAACL,SAASY,IAAI,CAACD,WAAW,MAC1DE,GAAG,CACF,CAACF,UACC,CAAC,kCAAkC,EAAEG,KAAKC,SAAS,CAACJ,SAAS,CAAC,CAAC,EAElEK,IAAI,CAAC;IAER,MAAMC,YAAYlB,mBAAmB,IAAI,CAACmB,OAAO;IAEjDD,UAAUE,GAAG,GAAG;QACdC,MAAMtB,iBAAiBuB,MAAM;IAC/B;IAEA,OAAOZ;AACT"}

View File

@@ -0,0 +1,27 @@
import { getRSCModuleInformation } from "../../analysis/get-page-static-info";
import { getModuleBuildInfo } from "./get-module-build-info";
export default function transformSource(source, sourceMap) {
// Avoid buffer to be consumed
if (typeof source !== "string") {
throw new Error("Expected source to have been transformed to a string.");
}
// Assign the RSC meta information to buildInfo.
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.rsc = getRSCModuleInformation(source, false);
// This is a server action entry module in the client layer. We need to attach
// noop exports of `callServer` wrappers for each action.
if (buildInfo.rsc.actions) {
source = `
import { callServer } from 'next/dist/client/app-call-server'
function __build_action__(action, args) {
return callServer(action.$$id, args)
}
${source}
`;
}
return this.callback(null, source, sourceMap);
}
//# sourceMappingURL=next-flight-client-module-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/next-flight-client-module-loader.ts"],"names":["getRSCModuleInformation","getModuleBuildInfo","transformSource","source","sourceMap","Error","buildInfo","_module","rsc","actions","callback"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,sCAAqC;AAC7E,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,eAAe,SAASC,gBAEtBC,MAAc,EACdC,SAAc;IAEd,8BAA8B;IAC9B,IAAI,OAAOD,WAAW,UAAU;QAC9B,MAAM,IAAIE,MAAM;IAClB;IAEA,gDAAgD;IAChD,MAAMC,YAAYL,mBAAmB,IAAI,CAACM,OAAO;IACjDD,UAAUE,GAAG,GAAGR,wBAAwBG,QAAQ;IAEhD,8EAA8E;IAC9E,yDAAyD;IACzD,IAAIG,UAAUE,GAAG,CAACC,OAAO,EAAE;QACzBN,SAAS,CAAC;;;;;;;AAOd,EAAEA,OAAO;AACT,CAAC;IACC;IAEA,OAAO,IAAI,CAACO,QAAQ,CAAC,MAAMP,QAAQC;AACrC"}

View File

@@ -0,0 +1,37 @@
/**
* For server-side CSS imports, we need to ignore the actual module content but
* still trigger the hot-reloading diff mechanism. So here we put the content
* inside a comment.
*/ import crypto from "crypto";
const NextServerCSSLoader = function(content) {
this.cacheable && this.cacheable();
const options = this.getOptions();
let isCSSModule = options.cssModules;
// Only add the checksum during development.
if (process.env.NODE_ENV !== "production") {
// This check is only for backwards compatibility.
// TODO: Remove this in the next major version (next 14)
if (isCSSModule === undefined) {
this.emitWarning(new Error("No 'cssModules' option was found for the next-flight-css-loader plugin."));
isCSSModule = this.resourcePath.match(/\.module\.(css|sass|scss)$/) !== null;
}
const checksum = crypto.createHash("sha1").update(typeof content === "string" ? Buffer.from(content) : content).digest().toString("hex").substring(0, 12);
if (isCSSModule) {
return `\
${content}
module.exports.__checksum = ${JSON.stringify(checksum)}
`;
}
// Server CSS imports are always available for HMR, so we attach
// `module.hot.accept()` to the generated module.
const hmrCode = "if (module.hot) { module.hot.accept() }";
return `\
export default ${JSON.stringify(checksum)}
${hmrCode}
`;
}
return content;
};
export default NextServerCSSLoader;
//# sourceMappingURL=next-flight-css-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/webpack/loaders/next-flight-css-loader.ts"],"names":["crypto","NextServerCSSLoader","content","cacheable","options","getOptions","isCSSModule","cssModules","process","env","NODE_ENV","undefined","emitWarning","Error","resourcePath","match","checksum","createHash","update","Buffer","from","digest","toString","substring","JSON","stringify","hmrCode"],"mappings":"AAAA;;;;CAIC,GAED,OAAOA,YAAY,SAAQ;AAO3B,MAAMC,sBACJ,SAAUC,OAAO;IACf,IAAI,CAACC,SAAS,IAAI,IAAI,CAACA,SAAS;IAChC,MAAMC,UAAU,IAAI,CAACC,UAAU;IAC/B,IAAIC,cAAcF,QAAQG,UAAU;IAEpC,4CAA4C;IAC5C,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;QACzC,kDAAkD;QAClD,wDAAwD;QACxD,IAAIJ,gBAAgBK,WAAW;YAC7B,IAAI,CAACC,WAAW,CACd,IAAIC,MACF;YAGJP,cACE,IAAI,CAACQ,YAAY,CAACC,KAAK,CAAC,kCAAkC;QAC9D;QACA,MAAMC,WAAWhB,OACdiB,UAAU,CAAC,QACXC,MAAM,CAAC,OAAOhB,YAAY,WAAWiB,OAAOC,IAAI,CAAClB,WAAWA,SAC5DmB,MAAM,GACNC,QAAQ,CAAC,OACTC,SAAS,CAAC,GAAG;QAEhB,IAAIjB,aAAa;YACf,OAAO,CAAC;AAChB,EAAEJ,QAAQ;4BACkB,EAAEsB,KAAKC,SAAS,CAACT,UAAU;AACvD,CAAC;QACK;QAEA,gEAAgE;QAChE,iDAAiD;QACjD,MAAMU,UAAU;QAEhB,OAAO,CAAC;eACC,EAAEF,KAAKC,SAAS,CAACT,UAAU;AAC1C,EAAEU,QAAQ;AACV,CAAC;IACG;IAEA,OAAOxB;AACT;AAEF,eAAeD,oBAAmB"}

View File

@@ -0,0 +1,15 @@
// This file must be bundled in the app's client layer, it shouldn't be directly
// imported by the server.
import { callServer } from "next/dist/client/app-call-server";
// A noop wrapper to let the Flight client create the server reference.
// See also: https://github.com/facebook/react/pull/26632
export function createServerReference(id) {
// Since we're using the Edge build of Flight client for SSR [1], here we need to
// also use the same Edge build to create the reference. For the client bundle,
// we use the default and let Webpack to resolve it to the correct version.
// 1: https://github.com/vercel/next.js/blob/16eb80b0b0be13f04a6407943664b5efd8f3d7d0/packages/next/src/server/app-render/use-flight-response.tsx#L24-L26
const { createServerReference: createServerReferenceImpl } = !!process.env.NEXT_RUNTIME ? require("react-server-dom-webpack/client.edge") : require("react-server-dom-webpack/client");
return createServerReferenceImpl(id, callServer);
}
//# sourceMappingURL=action-client-wrapper.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-flight-loader/action-client-wrapper.ts"],"names":["callServer","createServerReference","id","createServerReferenceImpl","process","env","NEXT_RUNTIME","require"],"mappings":"AAAA,gFAAgF;AAChF,0BAA0B;AAE1B,SAASA,UAAU,QAAQ,mCAAkC;AAE7D,uEAAuE;AACvE,yDAAyD;AACzD,OAAO,SAASC,sBAAsBC,EAAU;IAC9C,iFAAiF;IACjF,+EAA+E;IAC/E,2EAA2E;IAC3E,yJAAyJ;IACzJ,MAAM,EAAED,uBAAuBE,yBAAyB,EAAE,GACxD,CAAC,CAACC,QAAQC,GAAG,CAACC,YAAY,GAEtBC,QAAQ,0CAERA,QAAQ;IAGd,OAAOJ,0BAA0BD,IAAIF;AACvC"}

View File

@@ -0,0 +1,43 @@
const SERVER_REFERENCE_TAG = Symbol.for("react.server.reference");
export function createActionProxy(id, bound, action, originalAction) {
function bindImpl(_, ...boundArgs) {
const currentAction = this;
const newAction = async function(...args) {
if (originalAction) {
return originalAction(newAction.$$bound.concat(args));
} else {
// In this case we're calling the user-defined action directly.
return currentAction(...newAction.$$bound, ...args);
}
};
for (const key of [
"$$typeof",
"$$id",
"$$FORM_ACTION"
]){
// @ts-ignore
newAction[key] = currentAction[key];
}
// Rebind args
newAction.$$bound = (currentAction.$$bound || []).concat(boundArgs);
// Assign bind method
newAction.bind = bindImpl.bind(newAction);
return newAction;
}
Object.defineProperties(action, {
$$typeof: {
value: SERVER_REFERENCE_TAG
},
$$id: {
value: id
},
$$bound: {
value: bound
},
bind: {
value: bindImpl
}
});
}
//# sourceMappingURL=action-proxy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-flight-loader/action-proxy.ts"],"names":["SERVER_REFERENCE_TAG","Symbol","for","createActionProxy","id","bound","action","originalAction","bindImpl","_","boundArgs","currentAction","newAction","args","$$bound","concat","key","bind","Object","defineProperties","$$typeof","value","$$id"],"mappings":"AAAA,MAAMA,uBAAuBC,OAAOC,GAAG,CAAC;AAExC,OAAO,SAASC,kBACdC,EAAU,EACVC,KAAmB,EACnBC,MAAW,EACXC,cAAoB;IAEpB,SAASC,SAAoBC,CAAM,EAAE,GAAGC,SAAgB;QACtD,MAAMC,gBAAgB,IAAI;QAE1B,MAAMC,YAAY,eAAgB,GAAGC,IAAW;YAC9C,IAAIN,gBAAgB;gBAClB,OAAOA,eAAeK,UAAUE,OAAO,CAACC,MAAM,CAACF;YACjD,OAAO;gBACL,+DAA+D;gBAC/D,OAAOF,iBAAiBC,UAAUE,OAAO,KAAKD;YAChD;QACF;QAEA,KAAK,MAAMG,OAAO;YAAC;YAAY;YAAQ;SAAgB,CAAE;YACvD,aAAa;YACbJ,SAAS,CAACI,IAAI,GAAGL,aAAa,CAACK,IAAI;QACrC;QAEA,cAAc;QACdJ,UAAUE,OAAO,GAAG,AAACH,CAAAA,cAAcG,OAAO,IAAI,EAAE,AAAD,EAAGC,MAAM,CAACL;QAEzD,qBAAqB;QACrBE,UAAUK,IAAI,GAAGT,SAASS,IAAI,CAACL;QAE/B,OAAOA;IACT;IAEAM,OAAOC,gBAAgB,CAACb,QAAQ;QAC9Bc,UAAU;YACRC,OAAOrB;QACT;QACAsB,MAAM;YACJD,OAAOjB;QACT;QACAU,SAAS;YACPO,OAAOhB;QACT;QACAY,MAAM;YACJI,OAAOb;QACT;IACF;AACF"}

View File

@@ -0,0 +1,13 @@
// This function ensures that all the exported values are valid server actions,
// during the runtime. By definition all actions are required to be async
// functions, but here we can only check that they are functions.
export function ensureServerEntryExports(actions) {
for(let i = 0; i < actions.length; i++){
const action = actions[i];
if (typeof action !== "function") {
throw new Error(`A "use server" file can only export async functions, found ${typeof action}.`);
}
}
}
//# sourceMappingURL=action-validate.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-flight-loader/action-validate.ts"],"names":["ensureServerEntryExports","actions","i","length","action","Error"],"mappings":"AAAA,+EAA+E;AAC/E,yEAAyE;AACzE,iEAAiE;AACjE,OAAO,SAASA,yBAAyBC,OAAc;IACrD,IAAK,IAAIC,IAAI,GAAGA,IAAID,QAAQE,MAAM,EAAED,IAAK;QACvC,MAAME,SAASH,OAAO,CAACC,EAAE;QACzB,IAAI,OAAOE,WAAW,YAAY;YAChC,MAAM,IAAIC,MACR,CAAC,2DAA2D,EAAE,OAAOD,OAAO,CAAC,CAAC;QAElF;IACF;AACF"}

View File

@@ -0,0 +1,82 @@
import { RSC_MOD_REF_PROXY_ALIAS } from "../../../../lib/constants";
import { RSC_MODULE_TYPES } from "../../../../shared/lib/constants";
import { warnOnce } from "../../../../shared/lib/utils/warn-once";
import { getRSCModuleInformation } from "../../../analysis/get-page-static-info";
import { getModuleBuildInfo } from "../get-module-build-info";
const noopHeadPath = require.resolve("next/dist/client/components/noop-head");
// For edge runtime it will be aliased to esm version by webpack
const MODULE_PROXY_PATH = "next/dist/build/webpack/loaders/next-flight-loader/module-proxy";
export default function transformSource(source, sourceMap) {
var _buildInfo_rsc, _buildInfo_rsc1;
// Avoid buffer to be consumed
if (typeof source !== "string") {
throw new Error("Expected source to have been transformed to a string.");
}
// Assign the RSC meta information to buildInfo.
// Exclude next internal files which are not marked as client files
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.rsc = getRSCModuleInformation(source, true);
// A client boundary.
if (((_buildInfo_rsc = buildInfo.rsc) == null ? void 0 : _buildInfo_rsc.type) === RSC_MODULE_TYPES.client) {
var _this__module_parser, _this__module;
const sourceType = (_this__module = this._module) == null ? void 0 : (_this__module_parser = _this__module.parser) == null ? void 0 : _this__module_parser.sourceType;
const detectedClientEntryType = buildInfo.rsc.clientEntryType;
const clientRefs = buildInfo.rsc.clientRefs;
// It's tricky to detect the type of a client boundary, but we should always
// use the `module` type when we can, to support `export *` and `export from`
// syntax in other modules that import this client boundary.
let assumedSourceType = sourceType;
if (assumedSourceType === "auto" && detectedClientEntryType === "auto") {
if (clientRefs.length === 0 || clientRefs.length === 1 && clientRefs[0] === "") {
// If there's zero export detected in the client boundary, and it's the
// `auto` type, we can safely assume it's a CJS module because it doesn't
// have ESM exports.
assumedSourceType = "commonjs";
} else if (!clientRefs.includes("*")) {
// Otherwise, we assume it's an ESM module.
assumedSourceType = "module";
}
}
if (assumedSourceType === "module") {
if (clientRefs.includes("*")) {
this.callback(new Error(`It's currently unsupported to use "export *" in a client boundary. Please use named exports instead.`));
return;
}
let esmSource = `\
import { createProxy } from "${MODULE_PROXY_PATH}"
const proxy = createProxy(String.raw\`${this.resourcePath}\`)
// Accessing the __esModule property and exporting $$typeof are required here.
// The __esModule getter forces the proxy target to create the default export
// and the $$typeof value is for rendering logic to determine if the module
// is a client boundary.
const { __esModule, $$typeof } = proxy;
const __default__ = proxy.default;
`;
let cnt = 0;
for (const ref of clientRefs){
if (ref === "") {
esmSource += `\nexports[''] = proxy[''];`;
} else if (ref === "default") {
esmSource += `
export { __esModule, $$typeof };
export default __default__;`;
} else {
esmSource += `
const e${cnt} = proxy["${ref}"];
export { e${cnt++} as ${ref} };`;
}
}
this.callback(null, esmSource, sourceMap);
return;
}
}
if (((_buildInfo_rsc1 = buildInfo.rsc) == null ? void 0 : _buildInfo_rsc1.type) !== RSC_MODULE_TYPES.client) {
if (noopHeadPath === this.resourcePath) {
warnOnce(`Warning: You're using \`next/head\` inside the \`app\` directory, please migrate to the Metadata API. See https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#step-3-migrating-nexthead for more details.`);
}
}
this.callback(null, source.replace(RSC_MOD_REF_PROXY_ALIAS, MODULE_PROXY_PATH), sourceMap);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-flight-loader/index.ts"],"names":["RSC_MOD_REF_PROXY_ALIAS","RSC_MODULE_TYPES","warnOnce","getRSCModuleInformation","getModuleBuildInfo","noopHeadPath","require","resolve","MODULE_PROXY_PATH","transformSource","source","sourceMap","buildInfo","Error","_module","rsc","type","client","sourceType","parser","detectedClientEntryType","clientEntryType","clientRefs","assumedSourceType","length","includes","callback","esmSource","resourcePath","cnt","ref","replace"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,4BAA2B;AACnE,SAASC,gBAAgB,QAAQ,mCAAkC;AACnE,SAASC,QAAQ,QAAQ,yCAAwC;AACjE,SAASC,uBAAuB,QAAQ,yCAAwC;AAChF,SAASC,kBAAkB,QAAQ,2BAA0B;AAE7D,MAAMC,eAAeC,QAAQC,OAAO,CAAC;AACrC,gEAAgE;AAChE,MAAMC,oBACJ;AAEF,eAAe,SAASC,gBAEtBC,MAAc,EACdC,SAAc;QAaVC,gBAiEAA;IA5EJ,8BAA8B;IAC9B,IAAI,OAAOF,WAAW,UAAU;QAC9B,MAAM,IAAIG,MAAM;IAClB;IAEA,gDAAgD;IAChD,mEAAmE;IACnE,MAAMD,YAAYR,mBAAmB,IAAI,CAACU,OAAO;IACjDF,UAAUG,GAAG,GAAGZ,wBAAwBO,QAAQ;IAEhD,qBAAqB;IACrB,IAAIE,EAAAA,iBAAAA,UAAUG,GAAG,qBAAbH,eAAeI,IAAI,MAAKf,iBAAiBgB,MAAM,EAAE;YAChC,sBAAA;QAAnB,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BAAbH,gBAAeI,IAAI,MAAKf,iBAAiBgB,MAAM,EAAE;QACnD,IAAIZ,iBAAiB,IAAI,CAACuB,YAAY,EAAE;YACtC1B,SACE,CAAC,0OAA0O,CAAC;QAEhP;IACF;IAEA,IAAI,CAACwB,QAAQ,CACX,MACAhB,OAAOqB,OAAO,CAAC/B,yBAAyBQ,oBACxCG;AAEJ"}

View File

@@ -0,0 +1,5 @@
/* eslint-disable import/no-extraneous-dependencies */ import { createClientModuleProxy } from "react-server-dom-webpack/server.edge";
// Re-assign to make it typed.
export const createProxy = createClientModuleProxy;
//# sourceMappingURL=module-proxy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-flight-loader/module-proxy.ts"],"names":["createClientModuleProxy","createProxy"],"mappings":"AAAA,oDAAoD,GACpD,SAASA,uBAAuB,QAAQ,uCAAsC;AAE9E,8BAA8B;AAC9B,OAAO,MAAMC,cAAyCD,wBAAuB"}

View File

@@ -0,0 +1,105 @@
import path from "path";
import chalk from "next/dist/compiled/chalk";
import loaderUtils from "next/dist/compiled/loader-utils3";
import postcssNextFontPlugin from "./postcss-next-font";
import { promisify } from "util";
export default async function nextFontLoader() {
const nextFontLoaderSpan = this.currentTraceSpan.traceChild("next-font-loader");
return nextFontLoaderSpan.traceAsyncFn(async ()=>{
const callback = this.async();
/**
* The next-swc plugin next-transform-font turns font function calls into CSS imports.
* At the end of the import, it adds the call arguments and some additional data as a resourceQuery.
* e.g:
* const inter = Inter({ subset: ['latin'] })
* ->
* import inter from 'next/font/google/target.css?{"import":"Inter","subsets":["latin"]}'
*
* Here we parse the resourceQuery to get the font function name, call arguments, and the path to the file that called the font function.
*/ const { path: relativeFilePathFromRoot, import: functionName, arguments: data, variableName } = JSON.parse(this.resourceQuery.slice(1));
// Throw error if @next/font is used in _document.js
if (/pages[\\/]_document\./.test(relativeFilePathFromRoot)) {
const err = new Error(`${chalk.bold("Cannot")} be used within ${chalk.cyan("pages/_document.js")}.`);
err.name = "NextFontError";
callback(err);
return;
}
const { isDev, isServer, assetPrefix, fontLoaderPath, postcss: getPostcss } = this.getOptions();
if (assetPrefix && !/^\/|https?:\/\//.test(assetPrefix)) {
const err = new Error("assetPrefix must start with a leading slash or be an absolute URL(http:// or https://)");
err.name = "NextFontError";
callback(err);
return;
}
/**
* Emit font files to .next/static/media as [hash].[ext].
*
* If the font should be preloaded, add .p to the filename: [hash].p.[ext]
* NextFontManifestPlugin adds these files to the next/font manifest.
*
* If the font is using a size-adjust fallback font, add -s to the filename: [hash]-s.[ext]
* NextFontManifestPlugin uses this to see if fallback fonts are being used.
* This is used to collect stats on fallback fonts usage by the Google Aurora team.
*/ const emitFontFile = (content, ext, preload, isUsingSizeAdjust)=>{
const opts = {
context: this.rootContext,
content
};
const interpolatedName = loaderUtils.interpolateName(this, `static/media/[hash]${isUsingSizeAdjust ? "-s" : ""}${preload ? ".p" : ""}.${ext}`, opts);
const outputPath = `${assetPrefix}/_next/${interpolatedName}`;
// Only the client emits the font file
if (!isServer) {
this.emitFile(interpolatedName, content, null);
}
// But both the server and client must get the resulting path
return outputPath;
};
try {
// Import the font loader function from either next/font/local or next/font/google
// The font loader function emits font files and returns @font-faces and fallback font metrics
const fontLoader = require(fontLoaderPath).default;
let { css, fallbackFonts, adjustFontFallback, weight, style, variable } = await nextFontLoaderSpan.traceChild("font-loader").traceAsyncFn(()=>fontLoader({
functionName,
variableName,
data,
emitFontFile,
resolve: (src)=>promisify(this.resolve)(path.dirname(path.join(this.rootContext, relativeFilePathFromRoot)), src.startsWith(".") ? src : `./${src}`),
isDev,
isServer,
loaderContext: this
}));
const { postcss } = await getPostcss();
// Exports will be exported as is from css-loader instead of a CSS module export
const exports = [];
// Generate a hash from the CSS content. Used to generate classnames and font families
const fontFamilyHash = loaderUtils.getHashDigest(Buffer.from(css), "sha1", "hex", 6);
// Add CSS classes, exports and make the font-family locally scoped by turning it unguessable
const result = await nextFontLoaderSpan.traceChild("postcss").traceAsyncFn(()=>postcss(postcssNextFontPlugin({
exports,
fontFamilyHash,
fallbackFonts,
weight,
style,
adjustFontFallback,
variable
})).process(css, {
from: undefined
}));
const ast = {
type: "postcss",
version: result.processor.version,
root: result.root
};
// Return the resulting CSS and send the postcss ast, font exports and the hash to the css-loader in the meta argument.
callback(null, result.css, null, {
exports,
ast,
fontFamilyHash
});
} catch (err) {
callback(err);
}
});
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-font-loader/index.ts"],"names":["path","chalk","loaderUtils","postcssNextFontPlugin","promisify","nextFontLoader","nextFontLoaderSpan","currentTraceSpan","traceChild","traceAsyncFn","callback","async","relativeFilePathFromRoot","import","functionName","arguments","data","variableName","JSON","parse","resourceQuery","slice","test","err","Error","bold","cyan","name","isDev","isServer","assetPrefix","fontLoaderPath","postcss","getPostcss","getOptions","emitFontFile","content","ext","preload","isUsingSizeAdjust","opts","context","rootContext","interpolatedName","interpolateName","outputPath","emitFile","fontLoader","require","default","css","fallbackFonts","adjustFontFallback","weight","style","variable","resolve","src","dirname","join","startsWith","loaderContext","exports","fontFamilyHash","getHashDigest","Buffer","from","result","process","undefined","ast","type","version","processor","root"],"mappings":"AAEA,OAAOA,UAAU,OAAM;AACvB,OAAOC,WAAW,2BAA0B;AAC5C,OAAOC,iBAAiB,mCAAkC;AAC1D,OAAOC,2BAA2B,sBAAqB;AACvD,SAASC,SAAS,QAAQ,OAAM;AAEhC,eAAe,eAAeC;IAC5B,MAAMC,qBACJ,IAAI,CAACC,gBAAgB,CAACC,UAAU,CAAC;IACnC,OAAOF,mBAAmBG,YAAY,CAAC;QACrC,MAAMC,WAAW,IAAI,CAACC,KAAK;QAE3B;;;;;;;;;KASC,GACD,MAAM,EACJX,MAAMY,wBAAwB,EAC9BC,QAAQC,YAAY,EACpBC,WAAWC,IAAI,EACfC,YAAY,EACb,GAAGC,KAAKC,KAAK,CAAC,IAAI,CAACC,aAAa,CAACC,KAAK,CAAC;Q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ACAD;oBACAmB;oBACAqB,SAAS,CAACC,MACRrD,UAAU,IAAI,CAACoD,OAAO,EACpBxD,KAAK0D,OAAO,CACV1D,KAAK2D,IAAI,CAAC,IAAI,CAACjB,WAAW,EAAE9B,4BAE9B6C,IAAIG,UAAU,CAAC,OAAOH,MAAM,CAAC,EAAE,EAAEA,IAAI,CAAC;oBAE1C7B;oBACAC;oBACAgC,eAAe,IAAI;gBACrB;YAGJ,MAAM,EAAE7B,OAAO,EAAE,GAAG,MAAMC;YAE1B,gFAAgF;YAChF,MAAM6B,UAAuC,EAAE;YAE/C,sFAAsF;YACtF,MAAMC,iBAAiB7D,YAAY8D,aAAa,CAC9CC,OAAOC,IAAI,CAAChB,MACZ,QACA,OACA;YAGF,6FAA6F;YAC7F,MAAMiB,SAAS,MAAM7D,mBAClBE,UAAU,CAAC,WACXC,YAAY,CAAC,IACZuB,QACE7B,sBAAsB;oBACpB2D;oBACAC;oBACAZ;oBACAE;oBACAC;oBACAF;oBACAG;gBACF,IACAa,OAAO,CAAClB,KAAK;oBACbgB,MAAMG;gBACR;YAGJ,MAAMC,MAAM;gBACVC,MAAM;gBACNC,SAASL,OAAOM,SAAS,CAACD,OAAO;gBACjCE,MAAMP,OAAOO,IAAI;YACnB;YAEA,uHAAuH;YACvHhE,SAAS,MAAMyD,OAAOjB,GAAG,EAAE,MAAM;gBAC/BY;gBACAQ;gBACAP;YACF;QACF,EAAE,OAAOxC,KAAU;YACjBb,SAASa;QACX;IACF;AACF"}

Some files were not shown because too many files have changed in this diff Show More