fixed version control heatmap and activity

This commit is contained in:
will
2026-04-02 20:38:56 +01:00
parent 1da5da43e1
commit 250a7030bf
1777 changed files with 170575 additions and 83 deletions

View File

@@ -0,0 +1,200 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
NoSuchDeclarationError: null,
UnsupportedValueError: null,
extractExportedConstValue: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
NoSuchDeclarationError: function() {
return NoSuchDeclarationError;
},
UnsupportedValueError: function() {
return UnsupportedValueError;
},
extractExportedConstValue: function() {
return extractExportedConstValue;
}
});
class NoSuchDeclarationError extends Error {
}
function isExportDeclaration(node) {
return node.type === "ExportDeclaration";
}
function isVariableDeclaration(node) {
return node.type === "VariableDeclaration";
}
function isIdentifier(node) {
return node.type === "Identifier";
}
function isBooleanLiteral(node) {
return node.type === "BooleanLiteral";
}
function isNullLiteral(node) {
return node.type === "NullLiteral";
}
function isStringLiteral(node) {
return node.type === "StringLiteral";
}
function isNumericLiteral(node) {
return node.type === "NumericLiteral";
}
function isArrayExpression(node) {
return node.type === "ArrayExpression";
}
function isObjectExpression(node) {
return node.type === "ObjectExpression";
}
function isKeyValueProperty(node) {
return node.type === "KeyValueProperty";
}
function isRegExpLiteral(node) {
return node.type === "RegExpLiteral";
}
function isTemplateLiteral(node) {
return node.type === "TemplateLiteral";
}
class UnsupportedValueError extends Error {
constructor(message, paths){
super(message);
// Generating "path" that looks like "config.runtime[0].value"
let codePath;
if (paths) {
codePath = "";
for (const path of paths){
if (path[0] === "[") {
// "array" + "[0]"
codePath += path;
} else {
if (codePath === "") {
codePath = path;
} else {
// "object" + ".key"
codePath += `.${path}`;
}
}
}
}
this.path = codePath;
}
}
function extractValue(node, path) {
if (isNullLiteral(node)) {
return null;
} else if (isBooleanLiteral(node)) {
// e.g. true / false
return node.value;
} else if (isStringLiteral(node)) {
// e.g. "abc"
return node.value;
} else if (isNumericLiteral(node)) {
// e.g. 123
return node.value;
} else if (isRegExpLiteral(node)) {
// e.g. /abc/i
return new RegExp(node.pattern, node.flags);
} else if (isIdentifier(node)) {
switch(node.value){
case "undefined":
return undefined;
default:
throw new UnsupportedValueError(`Unknown identifier "${node.value}"`, path);
}
} else if (isArrayExpression(node)) {
// e.g. [1, 2, 3]
const arr = [];
for(let i = 0, len = node.elements.length; i < len; i++){
const elem = node.elements[i];
if (elem) {
if (elem.spread) {
// e.g. [ ...a ]
throw new UnsupportedValueError("Unsupported spread operator in the Array Expression", path);
}
arr.push(extractValue(elem.expression, path && [
...path,
`[${i}]`
]));
} else {
// e.g. [1, , 2]
// ^^
arr.push(undefined);
}
}
return arr;
} else if (isObjectExpression(node)) {
// e.g. { a: 1, b: 2 }
const obj = {};
for (const prop of node.properties){
if (!isKeyValueProperty(prop)) {
// e.g. { ...a }
throw new UnsupportedValueError("Unsupported spread operator in the Object Expression", path);
}
let key;
if (isIdentifier(prop.key)) {
// e.g. { a: 1, b: 2 }
key = prop.key.value;
} else if (isStringLiteral(prop.key)) {
// e.g. { "a": 1, "b": 2 }
key = prop.key.value;
} else {
throw new UnsupportedValueError(`Unsupported key type "${prop.key.type}" in the Object Expression`, path);
}
obj[key] = extractValue(prop.value, path && [
...path,
key
]);
}
return obj;
} else if (isTemplateLiteral(node)) {
// e.g. `abc`
if (node.expressions.length !== 0) {
// TODO: should we add support for `${'e'}d${'g'}'e'`?
throw new UnsupportedValueError("Unsupported template literal with expressions", path);
}
// When TemplateLiteral has 0 expressions, the length of quasis is always 1.
// Because when parsing TemplateLiteral, the parser yields the first quasi,
// then the first expression, then the next quasi, then the next expression, etc.,
// until the last quasi.
// Thus if there is no expression, the parser ends at the frst and also last quasis
//
// A "cooked" interpretation where backslashes have special meaning, while a
// "raw" interpretation where backslashes do not have special meaning
// https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw
const [{ cooked, raw }] = node.quasis;
return cooked ?? raw;
} else {
throw new UnsupportedValueError(`Unsupported node type "${node.type}"`, path);
}
}
function extractExportedConstValue(module1, exportedName) {
for (const moduleItem of module1.body){
if (!isExportDeclaration(moduleItem)) {
continue;
}
const declaration = moduleItem.declaration;
if (!isVariableDeclaration(declaration)) {
continue;
}
if (declaration.kind !== "const") {
continue;
}
for (const decl of declaration.declarations){
if (isIdentifier(decl.id) && decl.id.value === exportedName && decl.init) {
return extractValue(decl.init, [
exportedName
]);
}
}
}
throw new NoSuchDeclarationError();
}
//# sourceMappingURL=extract-const-value.js.map

View File

@@ -0,0 +1,494 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getMiddlewareMatchers: null,
getPageStaticInfo: null,
getRSCModuleInformation: null,
isDynamicMetadataRoute: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getMiddlewareMatchers: function() {
return getMiddlewareMatchers;
},
getPageStaticInfo: function() {
return getPageStaticInfo;
},
getRSCModuleInformation: function() {
return getRSCModuleInformation;
},
isDynamicMetadataRoute: function() {
return isDynamicMetadataRoute;
}
});
const _fs = require("fs");
const _lrucache = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lru-cache"));
const _picomatch = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/picomatch"));
const _extractconstvalue = require("./extract-const-value");
const _parsemodule = require("./parse-module");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../output/log"));
const _constants = require("../../lib/constants");
const _loadcustomroutes = require("../../lib/load-custom-routes");
const _trytoparsepath = require("../../lib/try-to-parse-path");
const _isapiroute = require("../../lib/is-api-route");
const _isedgeruntime = require("../../lib/is-edge-runtime");
const _constants1 = require("../../shared/lib/constants");
const _pagetypes = require("../../lib/page-types");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
// TODO: migrate preferredRegion here
// Don't forget to update the next-types-plugin file as well
const AUTHORIZED_EXTRA_ROUTER_PROPS = [
"maxDuration"
];
const CLIENT_MODULE_LABEL = /\/\* __next_internal_client_entry_do_not_use__ ([^ ]*) (cjs|auto) \*\//;
const ACTION_MODULE_LABEL = /\/\* __next_internal_action_entry_do_not_use__ (\{[^}]+\}) \*\//;
const CLIENT_DIRECTIVE = "use client";
const SERVER_ACTION_DIRECTIVE = "use server";
function getRSCModuleInformation(source, isReactServerLayer) {
var _clientInfoMatch_;
const actionsJson = source.match(ACTION_MODULE_LABEL);
const actions = actionsJson ? Object.values(JSON.parse(actionsJson[1])) : undefined;
const clientInfoMatch = source.match(CLIENT_MODULE_LABEL);
const isClientRef = !!clientInfoMatch;
if (!isReactServerLayer) {
return {
type: _constants1.RSC_MODULE_TYPES.client,
actions,
isClientRef
};
}
const clientRefs = clientInfoMatch == null ? void 0 : (_clientInfoMatch_ = clientInfoMatch[1]) == null ? void 0 : _clientInfoMatch_.split(",");
const clientEntryType = clientInfoMatch == null ? void 0 : clientInfoMatch[2];
const type = clientRefs ? _constants1.RSC_MODULE_TYPES.client : _constants1.RSC_MODULE_TYPES.server;
return {
type,
actions,
clientRefs,
clientEntryType,
isClientRef
};
}
const warnedInvalidValueMap = {
runtime: new Map(),
preferredRegion: new Map()
};
function warnInvalidValue(pageFilePath, key, message) {
if (warnedInvalidValueMap[key].has(pageFilePath)) return;
_log.warn(`Next.js can't recognize the exported \`${key}\` field in "${pageFilePath}" as ${message}.` + "\n" + "The default runtime will be used instead.");
warnedInvalidValueMap[key].set(pageFilePath, true);
}
/**
* Receives a parsed AST from SWC and checks if it belongs to a module that
* requires a runtime to be specified. Those are:
* - Modules with `export function getStaticProps | getServerSideProps`
* - Modules with `export { getStaticProps | getServerSideProps } <from ...>`
* - Modules with `export const runtime = ...`
*/ function checkExports(swcAST, pageFilePath) {
const exportsSet = new Set([
"getStaticProps",
"getServerSideProps",
"generateImageMetadata",
"generateSitemaps",
"generateStaticParams"
]);
if (Array.isArray(swcAST == null ? void 0 : swcAST.body)) {
try {
let runtime;
let preferredRegion;
let ssr = false;
let ssg = false;
let generateImageMetadata = false;
let generateSitemaps = false;
let generateStaticParams = false;
let extraProperties = new Set();
let directives = new Set();
let hasLeadingNonDirectiveNode = false;
for (const node of swcAST.body){
var _node_declaration, _node_declaration1, _node_declaration_identifier, _node_declaration2;
// There should be no non-string literals nodes before directives
if (node.type === "ExpressionStatement" && node.expression.type === "StringLiteral") {
if (!hasLeadingNonDirectiveNode) {
const directive = node.expression.value;
if (CLIENT_DIRECTIVE === directive) {
directives.add("client");
}
if (SERVER_ACTION_DIRECTIVE === directive) {
directives.add("server");
}
}
} else {
hasLeadingNonDirectiveNode = true;
}
if (node.type === "ExportDeclaration" && ((_node_declaration = node.declaration) == null ? void 0 : _node_declaration.type) === "VariableDeclaration") {
var _node_declaration3;
for (const declaration of (_node_declaration3 = node.declaration) == null ? void 0 : _node_declaration3.declarations){
if (declaration.id.value === "runtime") {
runtime = declaration.init.value;
} else if (declaration.id.value === "preferredRegion") {
if (declaration.init.type === "ArrayExpression") {
const elements = [];
for (const element of declaration.init.elements){
const { expression } = element;
if (expression.type !== "StringLiteral") {
continue;
}
elements.push(expression.value);
}
preferredRegion = elements;
} else {
preferredRegion = declaration.init.value;
}
} else {
extraProperties.add(declaration.id.value);
}
}
}
if (node.type === "ExportDeclaration" && ((_node_declaration1 = node.declaration) == null ? void 0 : _node_declaration1.type) === "FunctionDeclaration" && exportsSet.has((_node_declaration_identifier = node.declaration.identifier) == null ? void 0 : _node_declaration_identifier.value)) {
const id = node.declaration.identifier.value;
ssg = id === "getStaticProps";
ssr = id === "getServerSideProps";
generateImageMetadata = id === "generateImageMetadata";
generateSitemaps = id === "generateSitemaps";
generateStaticParams = id === "generateStaticParams";
}
if (node.type === "ExportDeclaration" && ((_node_declaration2 = node.declaration) == null ? void 0 : _node_declaration2.type) === "VariableDeclaration") {
var _node_declaration_declarations_, _node_declaration4;
const id = (_node_declaration4 = node.declaration) == null ? void 0 : (_node_declaration_declarations_ = _node_declaration4.declarations[0]) == null ? void 0 : _node_declaration_declarations_.id.value;
if (exportsSet.has(id)) {
ssg = id === "getStaticProps";
ssr = id === "getServerSideProps";
generateImageMetadata = id === "generateImageMetadata";
generateSitemaps = id === "generateSitemaps";
generateStaticParams = id === "generateStaticParams";
}
}
if (node.type === "ExportNamedDeclaration") {
const values = node.specifiers.map((specifier)=>{
var _specifier_orig, _specifier_orig1;
return specifier.type === "ExportSpecifier" && ((_specifier_orig = specifier.orig) == null ? void 0 : _specifier_orig.type) === "Identifier" && ((_specifier_orig1 = specifier.orig) == null ? void 0 : _specifier_orig1.value);
});
for (const value of values){
if (!ssg && value === "getStaticProps") ssg = true;
if (!ssr && value === "getServerSideProps") ssr = true;
if (!generateImageMetadata && value === "generateImageMetadata") generateImageMetadata = true;
if (!generateSitemaps && value === "generateSitemaps") generateSitemaps = true;
if (!generateStaticParams && value === "generateStaticParams") generateStaticParams = true;
if (!runtime && value === "runtime") warnInvalidValue(pageFilePath, "runtime", "it was not assigned to a string literal");
if (!preferredRegion && value === "preferredRegion") warnInvalidValue(pageFilePath, "preferredRegion", "it was not assigned to a string literal or an array of string literals");
}
}
}
return {
ssr,
ssg,
runtime,
preferredRegion,
generateImageMetadata,
generateSitemaps,
generateStaticParams,
extraProperties,
directives
};
} catch (err) {}
}
return {
ssg: false,
ssr: false,
runtime: undefined,
preferredRegion: undefined,
generateImageMetadata: false,
generateSitemaps: false,
generateStaticParams: false,
extraProperties: undefined,
directives: undefined
};
}
async function tryToReadFile(filePath, shouldThrow) {
try {
return await _fs.promises.readFile(filePath, {
encoding: "utf8"
});
} catch (error) {
if (shouldThrow) {
error.message = `Next.js ERROR: Failed to read file ${filePath}:\n${error.message}`;
throw error;
}
}
}
function getMiddlewareMatchers(matcherOrMatchers, nextConfig) {
let matchers = [];
if (Array.isArray(matcherOrMatchers)) {
matchers = matcherOrMatchers;
} else {
matchers.push(matcherOrMatchers);
}
const { i18n } = nextConfig;
const originalSourceMap = new Map();
let routes = matchers.map((m)=>{
let middleware = typeof m === "string" ? {
source: m
} : m;
if (middleware) {
originalSourceMap.set(middleware, middleware.source);
}
return middleware;
});
// check before we process the routes and after to ensure
// they are still valid
(0, _loadcustomroutes.checkCustomRoutes)(routes, "middleware");
routes = routes.map((r)=>{
let { source } = r;
const isRoot = source === "/";
if ((i18n == null ? void 0 : i18n.locales) && r.locale !== false) {
source = `/:nextInternalLocale((?!_next/)[^/.]{1,})${isRoot ? "" : source}`;
}
source = `/:nextData(_next/data/[^/]{1,})?${source}${isRoot ? `(${nextConfig.i18n ? "|\\.json|" : ""}/?index|/?index\\.json)?` : "(.json)?"}`;
if (nextConfig.basePath) {
source = `${nextConfig.basePath}${source}`;
}
r.source = source;
return r;
});
(0, _loadcustomroutes.checkCustomRoutes)(routes, "middleware");
return routes.map((r)=>{
const { source, ...rest } = r;
const parsedPage = (0, _trytoparsepath.tryToParsePath)(source);
if (parsedPage.error || !parsedPage.regexStr) {
throw new Error(`Invalid source: ${source}`);
}
const originalSource = originalSourceMap.get(r);
return {
...rest,
regexp: parsedPage.regexStr,
originalSource: originalSource || source
};
});
}
function getMiddlewareConfig(pageFilePath, config, nextConfig) {
const result = {};
if (config.matcher) {
result.matchers = getMiddlewareMatchers(config.matcher, nextConfig);
}
if (typeof config.regions === "string" || Array.isArray(config.regions)) {
result.regions = config.regions;
} else if (typeof config.regions !== "undefined") {
_log.warn(`The \`regions\` config was ignored: config must be empty, a string or an array of strings. (${pageFilePath})`);
}
if (config.unstable_allowDynamic) {
result.unstable_allowDynamicGlobs = Array.isArray(config.unstable_allowDynamic) ? config.unstable_allowDynamic : [
config.unstable_allowDynamic
];
for (const glob of result.unstable_allowDynamicGlobs ?? []){
try {
(0, _picomatch.default)(glob);
} catch (err) {
throw new Error(`${pageFilePath} exported 'config.unstable_allowDynamic' contains invalid pattern '${glob}': ${err.message}`);
}
}
}
return result;
}
const apiRouteWarnings = new _lrucache.default({
max: 250
});
function warnAboutExperimentalEdge(apiRoute) {
if (process.env.NODE_ENV === "production" && process.env.NEXT_PRIVATE_BUILD_WORKER === "1") {
return;
}
if (apiRouteWarnings.has(apiRoute)) {
return;
}
_log.warn(apiRoute ? `${apiRoute} provided runtime 'experimental-edge'. It can be updated to 'edge' instead.` : `You are using an experimental edge runtime, the API might change.`);
apiRouteWarnings.set(apiRoute, 1);
}
const warnedUnsupportedValueMap = new _lrucache.default({
max: 250
});
function warnAboutUnsupportedValue(pageFilePath, page, error) {
if (warnedUnsupportedValueMap.has(pageFilePath)) {
return;
}
_log.warn(`Next.js can't recognize the exported \`config\` field in ` + (page ? `route "${page}"` : `"${pageFilePath}"`) + ":\n" + error.message + (error.path ? ` at "${error.path}"` : "") + ".\n" + "The default config will be used instead.\n" + "Read More - https://nextjs.org/docs/messages/invalid-page-config");
warnedUnsupportedValueMap.set(pageFilePath, true);
}
async function isDynamicMetadataRoute(pageFilePath) {
const fileContent = await tryToReadFile(pageFilePath, true) || "";
if (/generateImageMetadata|generateSitemaps/.test(fileContent)) {
const swcAST = await (0, _parsemodule.parseModule)(pageFilePath, fileContent);
const exportsInfo = checkExports(swcAST, pageFilePath);
return !!(exportsInfo.generateImageMetadata || exportsInfo.generateSitemaps);
}
return false;
}
async function getPageStaticInfo(params) {
const { isDev, pageFilePath, nextConfig, page, pageType } = params;
const fileContent = await tryToReadFile(pageFilePath, !isDev) || "";
if (/(?<!(_jsx|jsx-))runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const/.test(fileContent)) {
const swcAST = await (0, _parsemodule.parseModule)(pageFilePath, fileContent);
const { ssg, ssr, runtime, preferredRegion, generateStaticParams, extraProperties, directives } = checkExports(swcAST, pageFilePath);
const rscInfo = getRSCModuleInformation(fileContent, true);
const rsc = rscInfo.type;
// default / failsafe value for config
let config// TODO: type this as unknown
;
try {
config = (0, _extractconstvalue.extractExportedConstValue)(swcAST, "config");
} catch (e) {
if (e instanceof _extractconstvalue.UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e);
}
// `export config` doesn't exist, or other unknown error thrown by swc, silence them
}
const extraConfig = {};
if (extraProperties && pageType === _pagetypes.PAGE_TYPES.APP) {
for (const prop of extraProperties){
if (!AUTHORIZED_EXTRA_ROUTER_PROPS.includes(prop)) continue;
try {
extraConfig[prop] = (0, _extractconstvalue.extractExportedConstValue)(swcAST, prop);
} catch (e) {
if (e instanceof _extractconstvalue.UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e);
}
}
}
} else if (pageType === _pagetypes.PAGE_TYPES.PAGES) {
for(const key in config){
if (!AUTHORIZED_EXTRA_ROUTER_PROPS.includes(key)) continue;
extraConfig[key] = config[key];
}
}
if (pageType === _pagetypes.PAGE_TYPES.APP) {
if (config) {
let message = `Page config in ${pageFilePath} is deprecated. Replace \`export const config=…\` with the following:`;
if (config.runtime) {
message += `\n - \`export const runtime = ${JSON.stringify(config.runtime)}\``;
}
if (config.regions) {
message += `\n - \`export const preferredRegion = ${JSON.stringify(config.regions)}\``;
}
message += `\nVisit https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config for more information.`;
if (isDev) {
_log.warnOnce(message);
} else {
throw new Error(message);
}
config = {};
}
}
if (!config) config = {};
// We use `export const config = { runtime: '...' }` to specify the page runtime for pages/.
// In the new app directory, we prefer to use `export const runtime = '...'`
// and deprecate the old way. To prevent breaking changes for `pages`, we use the exported config
// as the fallback value.
let resolvedRuntime;
if (pageType === _pagetypes.PAGE_TYPES.APP) {
resolvedRuntime = runtime;
} else {
resolvedRuntime = runtime || config.runtime;
}
if (typeof resolvedRuntime !== "undefined" && resolvedRuntime !== _constants.SERVER_RUNTIME.nodejs && !(0, _isedgeruntime.isEdgeRuntime)(resolvedRuntime)) {
const options = Object.values(_constants.SERVER_RUNTIME).join(", ");
const message = typeof resolvedRuntime !== "string" ? `The \`runtime\` config must be a string. Please leave it empty or choose one of: ${options}` : `Provided runtime "${resolvedRuntime}" is not supported. Please leave it empty or choose one of: ${options}`;
if (isDev) {
_log.error(message);
} else {
throw new Error(message);
}
}
const requiresServerRuntime = ssr || ssg || pageType === _pagetypes.PAGE_TYPES.APP;
const isAnAPIRoute = (0, _isapiroute.isAPIRoute)(page == null ? void 0 : page.replace(/^(?:\/src)?\/pages\//, "/"));
resolvedRuntime = (0, _isedgeruntime.isEdgeRuntime)(resolvedRuntime) || requiresServerRuntime ? resolvedRuntime : undefined;
if (resolvedRuntime === _constants.SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdge(isAnAPIRoute ? page : null);
}
if (resolvedRuntime === _constants.SERVER_RUNTIME.edge && pageType === _pagetypes.PAGE_TYPES.PAGES && page && !isAnAPIRoute) {
const message = `Page ${page} provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.`;
if (isDev) {
_log.error(message);
} else {
throw new Error(message);
}
}
const middlewareConfig = getMiddlewareConfig(page ?? "middleware/edge API route", config, nextConfig);
if (pageType === _pagetypes.PAGE_TYPES.APP && (directives == null ? void 0 : directives.has("client")) && generateStaticParams) {
throw new Error(`Page "${page}" cannot use both "use client" and export function "generateStaticParams()".`);
}
return {
ssr,
ssg,
rsc,
generateStaticParams,
amp: config.amp || false,
...middlewareConfig && {
middleware: middlewareConfig
},
...resolvedRuntime && {
runtime: resolvedRuntime
},
preferredRegion,
extraConfig
};
}
return {
ssr: false,
ssg: false,
rsc: _constants1.RSC_MODULE_TYPES.server,
generateStaticParams: false,
amp: false,
runtime: undefined
};
}
//# sourceMappingURL=get-page-static-info.js.map

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "parseModule", {
enumerable: true,
get: function() {
return parseModule;
}
});
const _lrucache = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lru-cache"));
const _withpromisecache = require("../../lib/with-promise-cache");
const _crypto = require("crypto");
const _swc = require("../swc");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const parseModule = (0, _withpromisecache.withPromiseCache)(new _lrucache.default({
max: 500
}), async (filename, content)=>(0, _swc.parse)(content, {
isModule: "unknown",
filename
}).catch(()=>null), (_, content)=>(0, _crypto.createHash)("sha1").update(content).digest("hex"));
//# sourceMappingURL=parse-module.js.map

View File

@@ -0,0 +1,335 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return getConfig;
}
});
const _fs = require("fs");
const _json5 = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/json5"));
const _core = require("next/dist/compiled/babel/core");
const _corelibconfig = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/babel/core-lib-config"));
const _util = require("./util");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../output/log"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const nextDistPath = /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/;
const fileExtensionRegex = /\.([a-z]+)$/;
function getCacheCharacteristics(loaderOptions, source, filename) {
var _fileExtensionRegex_exec;
const { isServer, pagesDir } = loaderOptions;
const isPageFile = filename.startsWith(pagesDir);
const isNextDist = nextDistPath.test(filename);
const hasModuleExports = source.indexOf("module.exports") !== -1;
const fileExt = ((_fileExtensionRegex_exec = fileExtensionRegex.exec(filename)) == null ? void 0 : _fileExtensionRegex_exec[1]) || "unknown";
return {
isServer,
isPageFile,
isNextDist,
hasModuleExports,
fileExt
};
}
/**
* Return an array of Babel plugins, conditioned upon loader options and
* source file characteristics.
*/ function getPlugins(loaderOptions, cacheCharacteristics) {
const { isServer, isPageFile, isNextDist, hasModuleExports } = cacheCharacteristics;
const { hasReactRefresh, development } = loaderOptions;
const applyCommonJsItem = hasModuleExports ? (0, _core.createConfigItem)(require("../plugins/commonjs"), {
type: "plugin"
}) : null;
const reactRefreshItem = hasReactRefresh ? (0, _core.createConfigItem)([
require("next/dist/compiled/react-refresh/babel"),
{
skipEnvCheck: true
}
], {
type: "plugin"
}) : null;
const pageConfigItem = !isServer && isPageFile ? (0, _core.createConfigItem)([
require("../plugins/next-page-config")
], {
type: "plugin"
}) : null;
const disallowExportAllItem = !isServer && isPageFile ? (0, _core.createConfigItem)([
require("../plugins/next-page-disallow-re-export-all-exports")
], {
type: "plugin"
}) : null;
const transformDefineItem = (0, _core.createConfigItem)([
require.resolve("next/dist/compiled/babel/plugin-transform-define"),
{
"process.env.NODE_ENV": development ? "development" : "production",
"typeof window": isServer ? "undefined" : "object",
"process.browser": isServer ? false : true
},
"next-js-transform-define-instance"
], {
type: "plugin"
});
const nextSsgItem = !isServer && isPageFile ? (0, _core.createConfigItem)([
require.resolve("../plugins/next-ssg-transform")
], {
type: "plugin"
}) : null;
const commonJsItem = isNextDist ? (0, _core.createConfigItem)(require("next/dist/compiled/babel/plugin-transform-modules-commonjs"), {
type: "plugin"
}) : null;
const nextFontUnsupported = (0, _core.createConfigItem)([
require("../plugins/next-font-unsupported")
], {
type: "plugin"
});
return [
reactRefreshItem,
pageConfigItem,
disallowExportAllItem,
applyCommonJsItem,
transformDefineItem,
nextSsgItem,
commonJsItem,
nextFontUnsupported
].filter(Boolean);
}
const isJsonFile = /\.(json|babelrc)$/;
const isJsFile = /\.js$/;
/**
* While this function does block execution while reading from disk, it
* should not introduce any issues. The function is only invoked when
* generating a fresh config, and only a small handful of configs should
* be generated during compilation.
*/ function getCustomBabelConfig(configFilePath) {
if (isJsonFile.exec(configFilePath)) {
const babelConfigRaw = (0, _fs.readFileSync)(configFilePath, "utf8");
return _json5.default.parse(babelConfigRaw);
} else if (isJsFile.exec(configFilePath)) {
return require(configFilePath);
}
throw new Error("The Next.js Babel loader does not support .mjs or .cjs config files.");
}
let babelConfigWarned = false;
/**
* Check if custom babel configuration from user only contains options that
* can be migrated into latest Next.js features supported by SWC.
*
* This raises soft warning messages only, not making any errors yet.
*/ function checkCustomBabelConfigDeprecation(config) {
if (!config || Object.keys(config).length === 0) {
return;
}
const { plugins, presets, ...otherOptions } = config;
if (Object.keys(otherOptions ?? {}).length > 0) {
return;
}
if (babelConfigWarned) {
return;
}
babelConfigWarned = true;
const isPresetReadyToDeprecate = !presets || presets.length === 0 || presets.length === 1 && presets[0] === "next/babel";
const pluginReasons = [];
const unsupportedPlugins = [];
if (Array.isArray(plugins)) {
for (const plugin of plugins){
const pluginName = Array.isArray(plugin) ? plugin[0] : plugin;
// [NOTE]: We cannot detect if the user uses babel-plugin-macro based transform plugins,
// such as `styled-components/macro` in here.
switch(pluginName){
case "styled-components":
case "babel-plugin-styled-components":
pluginReasons.push(`\t- 'styled-components' can be enabled via 'compiler.styledComponents' in 'next.config.js'`);
break;
case "@emotion/babel-plugin":
pluginReasons.push(`\t- '@emotion/babel-plugin' can be enabled via 'compiler.emotion' in 'next.config.js'`);
break;
case "babel-plugin-relay":
pluginReasons.push(`\t- 'babel-plugin-relay' can be enabled via 'compiler.relay' in 'next.config.js'`);
break;
case "react-remove-properties":
pluginReasons.push(`\t- 'react-remove-properties' can be enabled via 'compiler.reactRemoveProperties' in 'next.config.js'`);
break;
case "transform-remove-console":
pluginReasons.push(`\t- 'transform-remove-console' can be enabled via 'compiler.removeConsole' in 'next.config.js'`);
break;
default:
unsupportedPlugins.push(pluginName);
break;
}
}
}
if (isPresetReadyToDeprecate && unsupportedPlugins.length === 0) {
_log.warn(`It looks like there is a custom Babel configuration that can be removed${pluginReasons.length > 0 ? ":" : "."}`);
if (pluginReasons.length > 0) {
_log.warn(`Next.js supports the following features natively: `);
_log.warn(pluginReasons.join(""));
_log.warn(`For more details configuration options, please refer https://nextjs.org/docs/architecture/nextjs-compiler#supported-features`);
}
}
}
/**
* Generate a new, flat Babel config, ready to be handed to Babel-traverse.
* This config should have no unresolved overrides, presets, etc.
*/ function getFreshConfig(cacheCharacteristics, loaderOptions, target, filename, inputSourceMap) {
let { isServer, pagesDir, development, hasJsxRuntime, configFile, srcDir } = loaderOptions;
let customConfig = configFile ? getCustomBabelConfig(configFile) : undefined;
checkCustomBabelConfigDeprecation(customConfig);
let options = {
babelrc: false,
cloneInputAst: false,
filename,
inputSourceMap: inputSourceMap || undefined,
// Set the default sourcemap behavior based on Webpack's mapping flag,
// but allow users to override if they want.
sourceMaps: loaderOptions.sourceMaps === undefined ? this.sourceMap : loaderOptions.sourceMaps,
// Ensure that Webpack will get a full absolute path in the sourcemap
// so that it can properly map the module back to its internal cached
// modules.
sourceFileName: filename,
plugins: [
...getPlugins(loaderOptions, cacheCharacteristics),
...(customConfig == null ? void 0 : customConfig.plugins) || []
],
// target can be provided in babelrc
target: isServer ? undefined : customConfig == null ? void 0 : customConfig.target,
// env can be provided in babelrc
env: customConfig == null ? void 0 : customConfig.env,
presets: (()=>{
// If presets is defined the user will have next/babel in their babelrc
if (customConfig == null ? void 0 : customConfig.presets) {
return customConfig.presets;
}
// If presets is not defined the user will likely have "env" in their babelrc
if (customConfig) {
return undefined;
}
// If no custom config is provided the default is to use next/babel
return [
"next/babel"
];
})(),
overrides: loaderOptions.overrides,
caller: {
name: "next-babel-turbo-loader",
supportsStaticESM: true,
supportsDynamicImport: true,
// Provide plugins with insight into webpack target.
// https://github.com/babel/babel-loader/issues/787
target: target,
// Webpack 5 supports TLA behind a flag. We enable it by default
// for Babel, and then webpack will throw an error if the experimental
// flag isn't enabled.
supportsTopLevelAwait: true,
isServer,
srcDir,
pagesDir,
isDev: development,
hasJsxRuntime,
...loaderOptions.caller
}
};
// Babel does strict checks on the config so undefined is not allowed
if (typeof options.target === "undefined") {
delete options.target;
}
Object.defineProperty(options.caller, "onWarning", {
enumerable: false,
writable: false,
value: (reason)=>{
if (!(reason instanceof Error)) {
reason = new Error(reason);
}
this.emitWarning(reason);
}
});
const loadedOptions = (0, _core.loadOptions)(options);
const config = (0, _util.consumeIterator)((0, _corelibconfig.default)(loadedOptions));
return config;
}
/**
* Each key returned here corresponds with a Babel config that can be shared.
* The conditions of permissible sharing between files is dependent on specific
* file attributes and Next.js compiler states: `CharacteristicsGermaneToCaching`.
*/ function getCacheKey(cacheCharacteristics) {
const { isServer, isPageFile, isNextDist, hasModuleExports, fileExt } = cacheCharacteristics;
const flags = 0 | (isServer ? 1 : 0) | (isPageFile ? 2 : 0) | (isNextDist ? 4 : 0) | (hasModuleExports ? 8 : 0);
return fileExt + flags;
}
const configCache = new Map();
const configFiles = new Set();
function getConfig({ source, target, loaderOptions, filename, inputSourceMap }) {
const cacheCharacteristics = getCacheCharacteristics(loaderOptions, source, filename);
if (loaderOptions.configFile) {
// Ensures webpack invalidates the cache for this loader when the config file changes
this.addDependency(loaderOptions.configFile);
}
const cacheKey = getCacheKey(cacheCharacteristics);
if (configCache.has(cacheKey)) {
const cachedConfig = configCache.get(cacheKey);
return {
...cachedConfig,
options: {
...cachedConfig.options,
cwd: loaderOptions.cwd,
root: loaderOptions.cwd,
filename,
sourceFileName: filename
}
};
}
if (loaderOptions.configFile && !configFiles.has(loaderOptions.configFile)) {
configFiles.add(loaderOptions.configFile);
_log.info(`Using external babel configuration from ${loaderOptions.configFile}`);
}
const freshConfig = getFreshConfig.call(this, cacheCharacteristics, loaderOptions, target, filename, inputSourceMap);
configCache.set(cacheKey, freshConfig);
return freshConfig;
}
//# sourceMappingURL=get-config.js.map

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return _default;
}
});
const _transform = /*#__PURE__*/ _interop_require_default(require("./transform"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function nextBabelLoader(parentTrace, inputSource, inputSourceMap) {
const filename = this.resourcePath;
const target = this.target;
const loaderOptions = parentTrace.traceChild("get-options")// @ts-ignore TODO: remove ignore once webpack 5 types are used
.traceFn(()=>this.getOptions());
const loaderSpanInner = parentTrace.traceChild("next-babel-turbo-transform");
const { code: transformedSource, map: outputSourceMap } = loaderSpanInner.traceFn(()=>_transform.default.call(this, inputSource, inputSourceMap, loaderOptions, filename, target, loaderSpanInner));
return [
transformedSource,
outputSourceMap
];
}
const nextBabelLoaderOuter = function nextBabelLoaderOuter(inputSource, inputSourceMap) {
const callback = this.async();
const loaderSpan = this.currentTraceSpan.traceChild("next-babel-turbo-loader");
loaderSpan.traceAsyncFn(()=>nextBabelLoader.call(this, loaderSpan, inputSource, inputSourceMap)).then(([transformedSource, outputSourceMap])=>callback == null ? void 0 : callback(null, transformedSource, outputSourceMap || inputSourceMap), (err)=>{
callback == null ? void 0 : callback(err);
});
};
const _default = nextBabelLoaderOuter;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,97 @@
/*
* Partially adapted from @babel/core (MIT license).
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return transform;
}
});
const _traverse = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/babel/traverse"));
const _generator = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/babel/generator"));
const _corelibnormalizefile = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/babel/core-lib-normalize-file"));
const _corelibnormalizeopts = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/babel/core-lib-normalize-opts"));
const _corelibblockhoistplugin = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/babel/core-lib-block-hoist-plugin"));
const _corelibpluginpass = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/babel/core-lib-plugin-pass"));
const _getconfig = /*#__PURE__*/ _interop_require_default(require("./get-config"));
const _util = require("./util");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function getTraversalParams(file, pluginPairs) {
const passPairs = [];
const passes = [];
const visitors = [];
for (const plugin of pluginPairs.concat((0, _corelibblockhoistplugin.default)())){
const pass = new _corelibpluginpass.default(file, plugin.key, plugin.options);
passPairs.push([
plugin,
pass
]);
passes.push(pass);
visitors.push(plugin.visitor);
}
return {
passPairs,
passes,
visitors
};
}
function invokePluginPre(file, passPairs) {
for (const [{ pre }, pass] of passPairs){
if (pre) {
pre.call(pass, file);
}
}
}
function invokePluginPost(file, passPairs) {
for (const [{ post }, pass] of passPairs){
if (post) {
post.call(pass, file);
}
}
}
function transformAstPass(file, pluginPairs, parentSpan) {
const { passPairs, passes, visitors } = getTraversalParams(file, pluginPairs);
invokePluginPre(file, passPairs);
const visitor = _traverse.default.visitors.merge(visitors, passes, // @ts-ignore - the exported types are incorrect here
file.opts.wrapPluginVisitorMethod);
parentSpan.traceChild("babel-turbo-traverse").traceFn(()=>(0, _traverse.default)(file.ast, visitor, file.scope));
invokePluginPost(file, passPairs);
}
function transformAst(file, babelConfig, parentSpan) {
for (const pluginPairs of babelConfig.passes){
transformAstPass(file, pluginPairs, parentSpan);
}
}
function transform(source, inputSourceMap, loaderOptions, filename, target, parentSpan) {
const getConfigSpan = parentSpan.traceChild("babel-turbo-get-config");
const babelConfig = _getconfig.default.call(this, {
source,
loaderOptions,
inputSourceMap,
target,
filename
});
getConfigSpan.stop();
const normalizeSpan = parentSpan.traceChild("babel-turbo-normalize-file");
const file = (0, _util.consumeIterator)((0, _corelibnormalizefile.default)(babelConfig.passes, (0, _corelibnormalizeopts.default)(babelConfig), source));
normalizeSpan.stop();
const transformSpan = parentSpan.traceChild("babel-turbo-transform");
transformAst(file, babelConfig, transformSpan);
transformSpan.stop();
const generateSpan = parentSpan.traceChild("babel-turbo-generate");
const { code, map } = (0, _generator.default)(file.ast, file.opts.generatorOpts, file.code);
generateSpan.stop();
return {
code,
map
};
}
//# sourceMappingURL=transform.js.map

View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "consumeIterator", {
enumerable: true,
get: function() {
return consumeIterator;
}
});
function consumeIterator(iter) {
while(true){
const { value, done } = iter.next();
if (done) {
return value;
}
}
}
//# sourceMappingURL=util.js.map

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, // Handle module.exports in user code
"default", {
enumerable: true,
get: function() {
return CommonJSModulePlugin;
}
});
const _plugintransformmodulescommonjs = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/babel/plugin-transform-modules-commonjs"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function CommonJSModulePlugin(...args) {
const commonjs = (0, _plugintransformmodulescommonjs.default)(...args);
return {
visitor: {
Program: {
exit (path, state) {
let foundModuleExports = false;
path.traverse({
MemberExpression (expressionPath) {
if (expressionPath.node.object.name !== "module") return;
if (expressionPath.node.property.name !== "exports") return;
foundModuleExports = true;
}
});
if (!foundModuleExports) {
return;
}
commonjs.visitor.Program.exit.call(this, path, state);
}
}
}
};
}
//# sourceMappingURL=commonjs.js.map

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return NextPageDisallowReExportAllExports;
}
});
function NextPageDisallowReExportAllExports() {
return {
visitor: {
ImportDeclaration (path) {
if ([
"@next/font/local",
"@next/font/google",
"next/font/local",
"next/font/google"
].includes(path.node.source.value)) {
var _path_node_loc, _path_node_loc1;
const err = new SyntaxError(`"next/font" requires SWC although Babel is being used due to a custom babel config being present.\nRead more: https://nextjs.org/docs/messages/babel-font-loader-conflict`);
err.code = "BABEL_PARSE_ERROR";
err.loc = ((_path_node_loc = path.node.loc) == null ? void 0 : _path_node_loc.start) ?? ((_path_node_loc1 = path.node.loc) == null ? void 0 : _path_node_loc1.end) ?? path.node.loc;
throw err;
}
}
}
};
}
//# sourceMappingURL=next-font-unsupported.js.map

View File

@@ -0,0 +1,116 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, // config to parsing pageConfig for client bundles
"default", {
enumerable: true,
get: function() {
return nextPageConfig;
}
});
const _core = require("next/dist/compiled/babel/core");
const _constants = require("../../../shared/lib/constants");
const CONFIG_KEY = "config";
// replace program path with just a variable with the drop identifier
function replaceBundle(path, t) {
path.parentPath.replaceWith(t.program([
t.variableDeclaration("const", [
t.variableDeclarator(t.identifier(_constants.STRING_LITERAL_DROP_BUNDLE), t.stringLiteral(`${_constants.STRING_LITERAL_DROP_BUNDLE} ${Date.now()}`))
])
], []));
}
function errorMessage(state, details) {
const pageName = (state.filename || "").split(state.cwd || "").pop() || "unknown";
return `Invalid page config export found. ${details} in file ${pageName}. See: https://nextjs.org/docs/messages/invalid-page-config`;
}
function nextPageConfig({ types: t }) {
return {
visitor: {
Program: {
enter (path, state) {
path.traverse({
ExportDeclaration (exportPath, exportState) {
var _exportPath_node_specifiers;
if (_core.types.isExportNamedDeclaration(exportPath.node) && ((_exportPath_node_specifiers = exportPath.node.specifiers) == null ? void 0 : _exportPath_node_specifiers.some((specifier)=>{
return (t.isIdentifier(specifier.exported) ? specifier.exported.name : specifier.exported.value) === CONFIG_KEY;
})) && _core.types.isStringLiteral(exportPath.node.source)) {
throw new Error(errorMessage(exportState, "Expected object but got export from"));
}
},
ExportNamedDeclaration (exportPath, exportState) {
var _exportPath_node_declaration, _exportPath_scope_getBinding;
if (exportState.bundleDropped || !exportPath.node.declaration && exportPath.node.specifiers.length === 0) {
return;
}
const config = {};
const declarations = [
...((_exportPath_node_declaration = exportPath.node.declaration) == null ? void 0 : _exportPath_node_declaration.declarations) || [],
(_exportPath_scope_getBinding = exportPath.scope.getBinding(CONFIG_KEY)) == null ? void 0 : _exportPath_scope_getBinding.path.node
].filter(Boolean);
for (const specifier of exportPath.node.specifiers){
if ((t.isIdentifier(specifier.exported) ? specifier.exported.name : specifier.exported.value) === CONFIG_KEY) {
// export {} from 'somewhere'
if (_core.types.isStringLiteral(exportPath.node.source)) {
throw new Error(errorMessage(exportState, `Expected object but got import`));
// import hello from 'world'
// export { hello as config }
} else if (_core.types.isIdentifier(specifier.local)) {
var _exportPath_scope_getBinding1;
if (_core.types.isImportSpecifier((_exportPath_scope_getBinding1 = exportPath.scope.getBinding(specifier.local.name)) == null ? void 0 : _exportPath_scope_getBinding1.path.node)) {
throw new Error(errorMessage(exportState, `Expected object but got import`));
}
}
}
}
for (const declaration of declarations){
if (!_core.types.isIdentifier(declaration.id, {
name: CONFIG_KEY
})) {
continue;
}
let { init } = declaration;
if (_core.types.isTSAsExpression(init)) {
init = init.expression;
}
if (!_core.types.isObjectExpression(init)) {
const got = init ? init.type : "undefined";
throw new Error(errorMessage(exportState, `Expected object but got ${got}`));
}
for (const prop of init.properties){
if (_core.types.isSpreadElement(prop)) {
throw new Error(errorMessage(exportState, `Property spread is not allowed`));
}
const { name } = prop.key;
if (_core.types.isIdentifier(prop.key, {
name: "amp"
})) {
if (!_core.types.isObjectProperty(prop)) {
throw new Error(errorMessage(exportState, `Invalid property "${name}"`));
}
if (!_core.types.isBooleanLiteral(prop.value) && !_core.types.isStringLiteral(prop.value)) {
throw new Error(errorMessage(exportState, `Invalid value for "${name}"`));
}
config.amp = prop.value.value;
}
}
}
if (config.amp === true) {
var _exportState_file_opts, _exportState_file;
if (!((_exportState_file = exportState.file) == null ? void 0 : (_exportState_file_opts = _exportState_file.opts) == null ? void 0 : _exportState_file_opts.caller.isDev)) {
// don't replace bundle in development so HMR can track
// dependencies and trigger reload when they are changed
replaceBundle(exportPath, t);
}
exportState.bundleDropped = true;
return;
}
}
}, state);
}
}
}
};
}
//# sourceMappingURL=next-page-config.js.map

View File

@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return NextPageDisallowReExportAllExports;
}
});
function NextPageDisallowReExportAllExports() {
return {
visitor: {
ExportAllDeclaration (path) {
var _path_node_loc, _path_node_loc1;
const err = new SyntaxError(`Using \`export * from '...'\` in a page is disallowed. Please use \`export { default } from '...'\` instead.\n` + `Read more: https://nextjs.org/docs/messages/export-all-in-page`);
err.code = "BABEL_PARSE_ERROR";
err.loc = ((_path_node_loc = path.node.loc) == null ? void 0 : _path_node_loc.start) ?? ((_path_node_loc1 = path.node.loc) == null ? void 0 : _path_node_loc1.end) ?? path.node.loc;
throw err;
}
}
};
}
//# sourceMappingURL=next-page-disallow-re-export-all-exports.js.map

View File

@@ -0,0 +1,328 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
EXPORT_NAME_GET_SERVER_PROPS: null,
EXPORT_NAME_GET_STATIC_PATHS: null,
EXPORT_NAME_GET_STATIC_PROPS: null,
default: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
EXPORT_NAME_GET_SERVER_PROPS: function() {
return EXPORT_NAME_GET_SERVER_PROPS;
},
EXPORT_NAME_GET_STATIC_PATHS: function() {
return EXPORT_NAME_GET_STATIC_PATHS;
},
EXPORT_NAME_GET_STATIC_PROPS: function() {
return EXPORT_NAME_GET_STATIC_PROPS;
},
default: function() {
return nextTransformSsg;
}
});
const _constants = require("../../../lib/constants");
const _constants1 = require("../../../shared/lib/constants");
const EXPORT_NAME_GET_STATIC_PROPS = "getStaticProps";
const EXPORT_NAME_GET_STATIC_PATHS = "getStaticPaths";
const EXPORT_NAME_GET_SERVER_PROPS = "getServerSideProps";
const ssgExports = new Set([
EXPORT_NAME_GET_STATIC_PROPS,
EXPORT_NAME_GET_STATIC_PATHS,
EXPORT_NAME_GET_SERVER_PROPS,
// legacy methods added so build doesn't fail from importing
// server-side only methods
`unstable_getStaticProps`,
`unstable_getStaticPaths`,
`unstable_getServerProps`,
`unstable_getServerSideProps`
]);
function decorateSsgExport(t, path, state) {
const gsspName = state.isPrerender ? _constants1.STATIC_PROPS_ID : _constants1.SERVER_PROPS_ID;
const gsspId = t.identifier(gsspName);
const addGsspExport = (exportPath)=>{
if (state.done) {
return;
}
state.done = true;
const [pageCompPath] = exportPath.replaceWithMultiple([
t.exportNamedDeclaration(t.variableDeclaration(// We use 'var' instead of 'let' or 'const' for ES5 support. Since
// this runs in `Program#exit`, no ES2015 transforms (preset env)
// will be ran against this code.
"var", [
t.variableDeclarator(gsspId, t.booleanLiteral(true))
]), [
t.exportSpecifier(gsspId, gsspId)
]),
exportPath.node
]);
exportPath.scope.registerDeclaration(pageCompPath);
};
path.traverse({
ExportDefaultDeclaration (exportDefaultPath) {
addGsspExport(exportDefaultPath);
},
ExportNamedDeclaration (exportNamedPath) {
addGsspExport(exportNamedPath);
}
});
}
const isDataIdentifier = (name, state)=>{
if (ssgExports.has(name)) {
if (name === EXPORT_NAME_GET_SERVER_PROPS) {
if (state.isPrerender) {
throw new Error(_constants.SERVER_PROPS_SSG_CONFLICT);
}
state.isServerProps = true;
} else {
if (state.isServerProps) {
throw new Error(_constants.SERVER_PROPS_SSG_CONFLICT);
}
state.isPrerender = true;
}
return true;
}
return false;
};
function nextTransformSsg({ types: t }) {
function getIdentifier(path) {
const parentPath = path.parentPath;
if (parentPath.type === "VariableDeclarator") {
const pp = parentPath;
const name = pp.get("id");
return name.node.type === "Identifier" ? name : null;
}
if (parentPath.type === "AssignmentExpression") {
const pp = parentPath;
const name = pp.get("left");
return name.node.type === "Identifier" ? name : null;
}
if (path.node.type === "ArrowFunctionExpression") {
return null;
}
return path.node.id && path.node.id.type === "Identifier" ? path.get("id") : null;
}
function isIdentifierReferenced(ident) {
const b = ident.scope.getBinding(ident.node.name);
if (b == null ? void 0 : b.referenced) {
// Functions can reference themselves, so we need to check if there's a
// binding outside the function scope or not.
if (b.path.type === "FunctionDeclaration") {
return !b.constantViolations.concat(b.referencePaths)// Check that every reference is contained within the function:
.every((ref)=>ref.findParent((p)=>p === b.path));
}
return true;
}
return false;
}
function markFunction(path, state) {
const ident = getIdentifier(path);
if ((ident == null ? void 0 : ident.node) && isIdentifierReferenced(ident)) {
state.refs.add(ident);
}
}
function markImport(path, state) {
const local = path.get("local");
if (isIdentifierReferenced(local)) {
state.refs.add(local);
}
}
return {
visitor: {
Program: {
enter (path, state) {
state.refs = new Set();
state.isPrerender = false;
state.isServerProps = false;
state.done = false;
path.traverse({
VariableDeclarator (variablePath, variableState) {
if (variablePath.node.id.type === "Identifier") {
const local = variablePath.get("id");
if (isIdentifierReferenced(local)) {
variableState.refs.add(local);
}
} else if (variablePath.node.id.type === "ObjectPattern") {
const pattern = variablePath.get("id");
const properties = pattern.get("properties");
properties.forEach((p)=>{
const local = p.get(p.node.type === "ObjectProperty" ? "value" : p.node.type === "RestElement" ? "argument" : function() {
throw new Error("invariant");
}());
if (isIdentifierReferenced(local)) {
variableState.refs.add(local);
}
});
} else if (variablePath.node.id.type === "ArrayPattern") {
const pattern = variablePath.get("id");
const elements = pattern.get("elements");
elements.forEach((e)=>{
var _e_node, _e_node1;
let local;
if (((_e_node = e.node) == null ? void 0 : _e_node.type) === "Identifier") {
local = e;
} else if (((_e_node1 = e.node) == null ? void 0 : _e_node1.type) === "RestElement") {
local = e.get("argument");
} else {
return;
}
if (isIdentifierReferenced(local)) {
variableState.refs.add(local);
}
});
}
},
FunctionDeclaration: markFunction,
FunctionExpression: markFunction,
ArrowFunctionExpression: markFunction,
ImportSpecifier: markImport,
ImportDefaultSpecifier: markImport,
ImportNamespaceSpecifier: markImport,
ExportNamedDeclaration (exportNamedPath, exportNamedState) {
const specifiers = exportNamedPath.get("specifiers");
if (specifiers.length) {
specifiers.forEach((s)=>{
if (isDataIdentifier(t.isIdentifier(s.node.exported) ? s.node.exported.name : s.node.exported.value, exportNamedState)) {
s.remove();
}
});
if (exportNamedPath.node.specifiers.length < 1) {
exportNamedPath.remove();
}
return;
}
const decl = exportNamedPath.get("declaration");
if (decl == null || decl.node == null) {
return;
}
switch(decl.node.type){
case "FunctionDeclaration":
{
const name = decl.node.id.name;
if (isDataIdentifier(name, exportNamedState)) {
exportNamedPath.remove();
}
break;
}
case "VariableDeclaration":
{
const inner = decl.get("declarations");
inner.forEach((d)=>{
if (d.node.id.type !== "Identifier") {
return;
}
const name = d.node.id.name;
if (isDataIdentifier(name, exportNamedState)) {
d.remove();
}
});
break;
}
default:
{
break;
}
}
}
}, state);
if (!state.isPrerender && !state.isServerProps) {
return;
}
const refs = state.refs;
let count;
function sweepFunction(sweepPath) {
const ident = getIdentifier(sweepPath);
if ((ident == null ? void 0 : ident.node) && refs.has(ident) && !isIdentifierReferenced(ident)) {
++count;
if (t.isAssignmentExpression(sweepPath.parentPath.node) || t.isVariableDeclarator(sweepPath.parentPath.node)) {
sweepPath.parentPath.remove();
} else {
sweepPath.remove();
}
}
}
function sweepImport(sweepPath) {
const local = sweepPath.get("local");
if (refs.has(local) && !isIdentifierReferenced(local)) {
++count;
sweepPath.remove();
if (sweepPath.parent.specifiers.length === 0) {
sweepPath.parentPath.remove();
}
}
}
do {
path.scope.crawl();
count = 0;
path.traverse({
// eslint-disable-next-line no-loop-func
VariableDeclarator (variablePath) {
if (variablePath.node.id.type === "Identifier") {
const local = variablePath.get("id");
if (refs.has(local) && !isIdentifierReferenced(local)) {
++count;
variablePath.remove();
}
} else if (variablePath.node.id.type === "ObjectPattern") {
const pattern = variablePath.get("id");
const beforeCount = count;
const properties = pattern.get("properties");
properties.forEach((p)=>{
const local = p.get(p.node.type === "ObjectProperty" ? "value" : p.node.type === "RestElement" ? "argument" : function() {
throw new Error("invariant");
}());
if (refs.has(local) && !isIdentifierReferenced(local)) {
++count;
p.remove();
}
});
if (beforeCount !== count && pattern.get("properties").length < 1) {
variablePath.remove();
}
} else if (variablePath.node.id.type === "ArrayPattern") {
const pattern = variablePath.get("id");
const beforeCount = count;
const elements = pattern.get("elements");
elements.forEach((e)=>{
var _e_node, _e_node1;
let local;
if (((_e_node = e.node) == null ? void 0 : _e_node.type) === "Identifier") {
local = e;
} else if (((_e_node1 = e.node) == null ? void 0 : _e_node1.type) === "RestElement") {
local = e.get("argument");
} else {
return;
}
if (refs.has(local) && !isIdentifierReferenced(local)) {
++count;
e.remove();
}
});
if (beforeCount !== count && pattern.get("elements").length < 1) {
variablePath.remove();
}
}
},
FunctionDeclaration: sweepFunction,
FunctionExpression: sweepFunction,
ArrowFunctionExpression: sweepFunction,
ImportSpecifier: sweepImport,
ImportDefaultSpecifier: sweepImport,
ImportNamespaceSpecifier: sweepImport
});
}while (count);
decorateSsgExport(t, path, state);
}
}
}
};
}
//# sourceMappingURL=next-ssg-transform.js.map

View File

@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
NextBuildContext: null,
getPluginState: null,
getProxiedPluginState: null,
resumePluginState: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
NextBuildContext: function() {
return NextBuildContext;
},
getPluginState: function() {
return getPluginState;
},
getProxiedPluginState: function() {
return getProxiedPluginState;
},
resumePluginState: function() {
return resumePluginState;
}
});
// A layer for storing data that is used by plugins to communicate with each
// other between different steps of the build process. This is only internal
// to Next.js and will not be a part of the final build output.
// These states don't need to be deeply merged.
let pluginState = {};
function resumePluginState(resumedState) {
Object.assign(pluginState, resumedState);
}
function getProxiedPluginState(initialState) {
return new Proxy(pluginState, {
get (target, key) {
if (typeof target[key] === "undefined") {
return target[key] = initialState[key];
}
return target[key];
},
set (target, key, value) {
target[key] = value;
return true;
}
});
}
function getPluginState() {
return pluginState;
}
const NextBuildContext = {};
//# sourceMappingURL=build-context.js.map

View File

@@ -0,0 +1,281 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createAppRouterApiAliases: null,
createNextApiEsmAliases: null,
createRSCAliases: null,
createServerOnlyClientOnlyAliases: null,
createWebpackAliases: null,
getOptimizedModuleAliases: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createAppRouterApiAliases: function() {
return createAppRouterApiAliases;
},
createNextApiEsmAliases: function() {
return createNextApiEsmAliases;
},
createRSCAliases: function() {
return createRSCAliases;
},
createServerOnlyClientOnlyAliases: function() {
return createServerOnlyClientOnlyAliases;
},
createWebpackAliases: function() {
return createWebpackAliases;
},
getOptimizedModuleAliases: function() {
return getOptimizedModuleAliases;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _constants = require("../lib/constants");
const _requirehook = require("../server/require-hook");
const _webpackconfig = require("./webpack-config");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function createWebpackAliases({ distDir, isClient, isEdgeServer, isNodeServer, dev, config, pagesDir, appDir, dir, reactProductionProfiling, hasRewrites }) {
const pageExtensions = config.pageExtensions;
const clientResolveRewrites = require.resolve("../shared/lib/router/utils/resolve-rewrites");
const customAppAliases = {};
const customDocumentAliases = {};
// tell webpack where to look for _app and _document
// using aliases to allow falling back to the default
// version when removed or not present
if (dev) {
const nextDistPath = "next/dist/" + (isEdgeServer ? "esm/" : "");
customAppAliases[`${_constants.PAGES_DIR_ALIAS}/_app`] = [
...pagesDir ? pageExtensions.reduce((prev, ext)=>{
prev.push(_path.default.join(pagesDir, `_app.${ext}`));
return prev;
}, []) : [],
`${nextDistPath}pages/_app.js`
];
customAppAliases[`${_constants.PAGES_DIR_ALIAS}/_error`] = [
...pagesDir ? pageExtensions.reduce((prev, ext)=>{
prev.push(_path.default.join(pagesDir, `_error.${ext}`));
return prev;
}, []) : [],
`${nextDistPath}pages/_error.js`
];
customDocumentAliases[`${_constants.PAGES_DIR_ALIAS}/_document`] = [
...pagesDir ? pageExtensions.reduce((prev, ext)=>{
prev.push(_path.default.join(pagesDir, `_document.${ext}`));
return prev;
}, []) : [],
`${nextDistPath}pages/_document.js`
];
}
return {
"@vercel/og$": "next/dist/server/og/image-response",
// Alias next/dist imports to next/dist/esm assets,
// let this alias hit before `next` alias.
...isEdgeServer ? {
"next/dist/api": "next/dist/esm/api",
"next/dist/build": "next/dist/esm/build",
"next/dist/client": "next/dist/esm/client",
"next/dist/shared": "next/dist/esm/shared",
"next/dist/pages": "next/dist/esm/pages",
"next/dist/lib": "next/dist/esm/lib",
"next/dist/server": "next/dist/esm/server",
...createNextApiEsmAliases()
} : undefined,
// For RSC server bundle
...!(0, _webpackconfig.hasExternalOtelApiPackage)() && {
"@opentelemetry/api": "next/dist/compiled/@opentelemetry/api"
},
...config.images.loaderFile ? {
"next/dist/shared/lib/image-loader": config.images.loaderFile,
...isEdgeServer && {
"next/dist/esm/shared/lib/image-loader": config.images.loaderFile
}
} : undefined,
next: _webpackconfig.NEXT_PROJECT_ROOT,
"styled-jsx/style$": _requirehook.defaultOverrides["styled-jsx/style"],
"styled-jsx$": _requirehook.defaultOverrides["styled-jsx"],
...customAppAliases,
...customDocumentAliases,
...pagesDir ? {
[_constants.PAGES_DIR_ALIAS]: pagesDir
} : {},
...appDir ? {
[_constants.APP_DIR_ALIAS]: appDir
} : {},
[_constants.ROOT_DIR_ALIAS]: dir,
[_constants.DOT_NEXT_ALIAS]: distDir,
...isClient || isEdgeServer ? getOptimizedModuleAliases() : {},
...reactProductionProfiling ? getReactProfilingInProduction() : {},
// For Node server, we need to re-alias the package imports to prefer to
// resolve to the ESM export.
...isNodeServer ? getBarrelOptimizationAliases(config.experimental.optimizePackageImports || []) : {},
[_constants.RSC_ACTION_VALIDATE_ALIAS]: "next/dist/build/webpack/loaders/next-flight-loader/action-validate",
[_constants.RSC_ACTION_CLIENT_WRAPPER_ALIAS]: "next/dist/build/webpack/loaders/next-flight-loader/action-client-wrapper",
[_constants.RSC_ACTION_PROXY_ALIAS]: "next/dist/build/webpack/loaders/next-flight-loader/server-reference",
[_constants.RSC_ACTION_ENCRYPTION_ALIAS]: "next/dist/server/app-render/encryption",
...isClient || isEdgeServer ? {
[clientResolveRewrites]: hasRewrites ? clientResolveRewrites : false
} : {},
"@swc/helpers/_": _path.default.join(_path.default.dirname(require.resolve("@swc/helpers/package.json")), "_"),
setimmediate: "next/dist/compiled/setimmediate"
};
}
function createServerOnlyClientOnlyAliases(isServer) {
return isServer ? {
"server-only$": "next/dist/compiled/server-only/empty",
"client-only$": "next/dist/compiled/client-only/error",
"next/dist/compiled/server-only$": "next/dist/compiled/server-only/empty",
"next/dist/compiled/client-only$": "next/dist/compiled/client-only/error"
} : {
"server-only$": "next/dist/compiled/server-only/index",
"client-only$": "next/dist/compiled/client-only/index",
"next/dist/compiled/client-only$": "next/dist/compiled/client-only/index",
"next/dist/compiled/server-only": "next/dist/compiled/server-only/index"
};
}
function createNextApiEsmAliases() {
const mapping = {
head: "next/dist/api/head",
image: "next/dist/api/image",
constants: "next/dist/api/constants",
router: "next/dist/api/router",
dynamic: "next/dist/api/dynamic",
script: "next/dist/api/script",
link: "next/dist/api/link",
navigation: "next/dist/api/navigation",
headers: "next/dist/api/headers",
og: "next/dist/api/og",
server: "next/dist/api/server",
// pages api
document: "next/dist/api/document",
app: "next/dist/api/app"
};
const aliasMap = {};
// Handle fully specified imports like `next/image.js`
for (const [key, value] of Object.entries(mapping)){
const nextApiFilePath = _path.default.join(_webpackconfig.NEXT_PROJECT_ROOT, key);
aliasMap[nextApiFilePath + ".js"] = value;
}
return aliasMap;
}
function createAppRouterApiAliases(isServerOnlyLayer) {
const mapping = {
head: "next/dist/client/components/noop-head",
dynamic: "next/dist/api/app-dynamic"
};
if (isServerOnlyLayer) {
mapping["navigation"] = "next/dist/api/navigation.react-server";
}
const aliasMap = {};
for (const [key, value] of Object.entries(mapping)){
const nextApiFilePath = _path.default.join(_webpackconfig.NEXT_PROJECT_ROOT, key);
aliasMap[nextApiFilePath + ".js"] = value;
}
return aliasMap;
}
function createRSCAliases(bundledReactChannel, { layer, isEdgeServer, reactProductionProfiling }) {
let alias = {
react$: `next/dist/compiled/react${bundledReactChannel}`,
"react-dom$": `next/dist/compiled/react-dom${bundledReactChannel}`,
"react/jsx-runtime$": `next/dist/compiled/react${bundledReactChannel}/jsx-runtime`,
"react/jsx-dev-runtime$": `next/dist/compiled/react${bundledReactChannel}/jsx-dev-runtime`,
"react-dom/client$": `next/dist/compiled/react-dom${bundledReactChannel}/client`,
"react-dom/server$": `next/dist/compiled/react-dom${bundledReactChannel}/server`,
"react-dom/static$": `next/dist/compiled/react-dom-experimental/static`,
"react-dom/static.edge$": `next/dist/compiled/react-dom-experimental/static.edge`,
"react-dom/static.browser$": `next/dist/compiled/react-dom-experimental/static.browser`,
// optimizations to ignore the legacy build of react-dom/server in `server.browser` build
"react-dom/server.edge$": `next/dist/build/webpack/alias/react-dom-server-edge${bundledReactChannel}.js`,
"react-dom/server.browser$": `next/dist/build/webpack/alias/react-dom-server-browser${bundledReactChannel}.js`,
// react-server-dom-webpack alias
"react-server-dom-webpack/client$": `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client`,
"react-server-dom-webpack/client.edge$": `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client.edge`,
"react-server-dom-webpack/server.edge$": `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/server.edge`,
"react-server-dom-webpack/server.node$": `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/server.node`
};
if (!isEdgeServer) {
if (layer === _constants.WEBPACK_LAYERS.serverSideRendering) {
alias = Object.assign(alias, {
"react/jsx-runtime$": `next/dist/server/future/route-modules/app-page/vendored/${layer}/react-jsx-runtime`,
"react/jsx-dev-runtime$": `next/dist/server/future/route-modules/app-page/vendored/${layer}/react-jsx-dev-runtime`,
react$: `next/dist/server/future/route-modules/app-page/vendored/${layer}/react`,
"react-dom$": `next/dist/server/future/route-modules/app-page/vendored/${layer}/react-dom`,
"react-server-dom-webpack/client.edge$": `next/dist/server/future/route-modules/app-page/vendored/${layer}/react-server-dom-webpack-client-edge`
});
} else if (layer === _constants.WEBPACK_LAYERS.reactServerComponents) {
alias = Object.assign(alias, {
"react/jsx-runtime$": `next/dist/server/future/route-modules/app-page/vendored/${layer}/react-jsx-runtime`,
"react/jsx-dev-runtime$": `next/dist/server/future/route-modules/app-page/vendored/${layer}/react-jsx-dev-runtime`,
react$: `next/dist/server/future/route-modules/app-page/vendored/${layer}/react`,
"react-dom$": `next/dist/server/future/route-modules/app-page/vendored/${layer}/react-dom`,
"react-server-dom-webpack/server.edge$": `next/dist/server/future/route-modules/app-page/vendored/${layer}/react-server-dom-webpack-server-edge`,
"react-server-dom-webpack/server.node$": `next/dist/server/future/route-modules/app-page/vendored/${layer}/react-server-dom-webpack-server-node`
});
}
}
if (isEdgeServer) {
if (layer === _constants.WEBPACK_LAYERS.reactServerComponents) {
alias["react$"] = `next/dist/compiled/react${bundledReactChannel}/react.react-server`;
alias["react-dom$"] = `next/dist/compiled/react-dom${bundledReactChannel}/react-dom.react-server`;
} else {
// x-ref: https://github.com/facebook/react/pull/25436
alias["react-dom$"] = `next/dist/compiled/react-dom${bundledReactChannel}/server-rendering-stub`;
}
}
if (reactProductionProfiling) {
alias["react-dom$"] = `next/dist/compiled/react-dom${bundledReactChannel}/profiling`;
}
alias["@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client.ts"] = `next/dist/client/dev/noop-turbopack-hmr`;
return alias;
}
function getOptimizedModuleAliases() {
return {
unfetch: require.resolve("next/dist/build/polyfills/fetch/index.js"),
"isomorphic-unfetch": require.resolve("next/dist/build/polyfills/fetch/index.js"),
"whatwg-fetch": require.resolve("next/dist/build/polyfills/fetch/whatwg-fetch.js"),
"object-assign": require.resolve("next/dist/build/polyfills/object-assign.js"),
"object.assign/auto": require.resolve("next/dist/build/polyfills/object.assign/auto.js"),
"object.assign/implementation": require.resolve("next/dist/build/polyfills/object.assign/implementation.js"),
"object.assign/polyfill": require.resolve("next/dist/build/polyfills/object.assign/polyfill.js"),
"object.assign/shim": require.resolve("next/dist/build/polyfills/object.assign/shim.js"),
url: require.resolve("next/dist/compiled/native-url")
};
}
// Alias these modules to be resolved with "module" if possible.
function getBarrelOptimizationAliases(packages) {
const aliases = {};
const mainFields = [
"module",
"main"
];
for (const pkg of packages){
try {
const descriptionFileData = require(`${pkg}/package.json`);
const descriptionFilePath = require.resolve(`${pkg}/package.json`);
for (const field of mainFields){
if (descriptionFileData.hasOwnProperty(field)) {
aliases[pkg + "$"] = _path.default.join(_path.default.dirname(descriptionFilePath), descriptionFileData[field]);
break;
}
}
} catch {}
}
return aliases;
}
function getReactProfilingInProduction() {
return {
"react-dom$": "react-dom/profiling"
};
}
//# sourceMappingURL=create-compiler-aliases.js.map

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getDeploymentIdQueryOrEmptyString", {
enumerable: true,
get: function() {
return getDeploymentIdQueryOrEmptyString;
}
});
function getDeploymentIdQueryOrEmptyString() {
if (process.env.NEXT_DEPLOYMENT_ID) {
return `?dpl=${process.env.NEXT_DEPLOYMENT_ID}`;
}
return "";
}
//# sourceMappingURL=deployment-id.js.map

View File

@@ -0,0 +1,625 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createEntrypoints: null,
createPagesMapping: null,
finalizeEntrypoint: null,
getAppEntry: null,
getClientEntry: null,
getEdgeServerEntry: null,
getInstrumentationEntry: null,
getPageFilePath: null,
getPageFromPath: null,
getStaticInfoIncludingLayouts: null,
runDependingOnPageType: null,
sortByPageExts: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createEntrypoints: function() {
return createEntrypoints;
},
createPagesMapping: function() {
return createPagesMapping;
},
finalizeEntrypoint: function() {
return finalizeEntrypoint;
},
getAppEntry: function() {
return getAppEntry;
},
getClientEntry: function() {
return getClientEntry;
},
getEdgeServerEntry: function() {
return getEdgeServerEntry;
},
getInstrumentationEntry: function() {
return getInstrumentationEntry;
},
getPageFilePath: function() {
return getPageFilePath;
},
getPageFromPath: function() {
return getPageFromPath;
},
getStaticInfoIncludingLayouts: function() {
return getStaticInfoIncludingLayouts;
},
runDependingOnPageType: function() {
return runDependingOnPageType;
},
sortByPageExts: function() {
return sortByPageExts;
}
});
const _path = require("path");
const _querystring = require("querystring");
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
const _constants = require("../lib/constants");
const _isapiroute = require("../lib/is-api-route");
const _isedgeruntime = require("../lib/is-edge-runtime");
const _constants1 = require("../shared/lib/constants");
const _utils = require("./utils");
const _getpagestaticinfo = require("./analysis/get-page-static-info");
const _normalizepathsep = require("../shared/lib/page-path/normalize-path-sep");
const _normalizepagepath = require("../shared/lib/page-path/normalize-page-path");
const _apppaths = require("../shared/lib/router/utils/app-paths");
const _nextmiddlewareloader = require("./webpack/loaders/next-middleware-loader");
const _isapprouteroute = require("../lib/is-app-route-route");
const _getmetadataroute = require("../lib/metadata/get-metadata-route");
const _nextrouteloader = require("./webpack/loaders/next-route-loader");
const _isinternalcomponent = require("../lib/is-internal-component");
const _ismetadataroute = require("../lib/metadata/is-metadata-route");
const _routekind = require("../server/future/route-kind");
const _utils1 = require("./webpack/loaders/utils");
const _normalizecatchallroutes = require("./normalize-catchall-routes");
const _pagetypes = require("../lib/page-types");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function sortByPageExts(pageExtensions) {
return (a, b)=>{
// prioritize entries according to pageExtensions order
// for consistency as fs order can differ across systems
// NOTE: this is reversed so preferred comes last and
// overrides prior
const aExt = (0, _path.extname)(a);
const bExt = (0, _path.extname)(b);
const aNoExt = a.substring(0, a.length - aExt.length);
const bNoExt = a.substring(0, b.length - bExt.length);
if (aNoExt !== bNoExt) return 0;
// find extension index (skip '.' as pageExtensions doesn't have it)
const aExtIndex = pageExtensions.indexOf(aExt.substring(1));
const bExtIndex = pageExtensions.indexOf(bExt.substring(1));
return bExtIndex - aExtIndex;
};
}
async function getStaticInfoIncludingLayouts({ isInsideAppDir, pageExtensions, pageFilePath, appDir, config, isDev, page }) {
const pageStaticInfo = await (0, _getpagestaticinfo.getPageStaticInfo)({
nextConfig: config,
pageFilePath,
isDev,
page,
pageType: isInsideAppDir ? _pagetypes.PAGE_TYPES.APP : _pagetypes.PAGE_TYPES.PAGES
});
const staticInfo = isInsideAppDir ? {
// TODO-APP: Remove the rsc key altogether. It's no longer required.
rsc: "server"
} : pageStaticInfo;
if (isInsideAppDir && appDir) {
const layoutFiles = [];
const potentialLayoutFiles = pageExtensions.map((ext)=>"layout." + ext);
let dir = (0, _path.dirname)(pageFilePath);
// Uses startsWith to not include directories further up.
while(dir.startsWith(appDir)){
for (const potentialLayoutFile of potentialLayoutFiles){
const layoutFile = (0, _path.join)(dir, potentialLayoutFile);
if (!_fs.default.existsSync(layoutFile)) {
continue;
}
layoutFiles.unshift(layoutFile);
}
// Walk up the directory tree
dir = (0, _path.join)(dir, "..");
}
for (const layoutFile of layoutFiles){
const layoutStaticInfo = await (0, _getpagestaticinfo.getPageStaticInfo)({
nextConfig: config,
pageFilePath: layoutFile,
isDev,
page,
pageType: isInsideAppDir ? _pagetypes.PAGE_TYPES.APP : _pagetypes.PAGE_TYPES.PAGES
});
// Only runtime is relevant here.
if (layoutStaticInfo.runtime) {
staticInfo.runtime = layoutStaticInfo.runtime;
}
if (layoutStaticInfo.preferredRegion) {
staticInfo.preferredRegion = layoutStaticInfo.preferredRegion;
}
}
if (pageStaticInfo.runtime) {
staticInfo.runtime = pageStaticInfo.runtime;
}
if (pageStaticInfo.preferredRegion) {
staticInfo.preferredRegion = pageStaticInfo.preferredRegion;
}
// if it's static metadata route, don't inherit runtime from layout
const relativePath = pageFilePath.replace(appDir, "");
if ((0, _ismetadataroute.isStaticMetadataRouteFile)(relativePath)) {
delete staticInfo.runtime;
delete staticInfo.preferredRegion;
}
}
return staticInfo;
}
function getPageFromPath(pagePath, pageExtensions) {
let page = (0, _normalizepathsep.normalizePathSep)(pagePath.replace(new RegExp(`\\.+(${pageExtensions.join("|")})$`), ""));
page = page.replace(/\/index$/, "");
return page === "" ? "/" : page;
}
function getPageFilePath({ absolutePagePath, pagesDir, appDir, rootDir }) {
if (absolutePagePath.startsWith(_constants.PAGES_DIR_ALIAS) && pagesDir) {
return absolutePagePath.replace(_constants.PAGES_DIR_ALIAS, pagesDir);
}
if (absolutePagePath.startsWith(_constants.APP_DIR_ALIAS) && appDir) {
return absolutePagePath.replace(_constants.APP_DIR_ALIAS, appDir);
}
if (absolutePagePath.startsWith(_constants.ROOT_DIR_ALIAS)) {
return absolutePagePath.replace(_constants.ROOT_DIR_ALIAS, rootDir);
}
return require.resolve(absolutePagePath);
}
function createPagesMapping({ isDev, pageExtensions, pagePaths, pagesType, pagesDir }) {
const isAppRoute = pagesType === "app";
const pages = pagePaths.reduce((result, pagePath)=>{
// Do not process .d.ts files as routes
if (pagePath.endsWith(".d.ts") && pageExtensions.includes("ts")) {
return result;
}
let pageKey = getPageFromPath(pagePath, pageExtensions);
if (isAppRoute) {
pageKey = pageKey.replace(/%5F/g, "_");
if (pageKey === "/not-found") {
pageKey = _constants1.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY;
}
}
const normalizedPath = (0, _normalizepathsep.normalizePathSep)((0, _path.join)(pagesType === "pages" ? _constants.PAGES_DIR_ALIAS : pagesType === "app" ? _constants.APP_DIR_ALIAS : _constants.ROOT_DIR_ALIAS, pagePath));
const route = pagesType === "app" ? (0, _getmetadataroute.normalizeMetadataRoute)(pageKey) : pageKey;
result[route] = normalizedPath;
return result;
}, {});
switch(pagesType){
case _pagetypes.PAGE_TYPES.ROOT:
{
return pages;
}
case _pagetypes.PAGE_TYPES.APP:
{
const hasAppPages = Object.keys(pages).some((page)=>page.endsWith("/page"));
return {
// If there's any app pages existed, add a default not-found page.
// If there's any custom not-found page existed, it will override the default one.
...hasAppPages && {
[_constants1.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY]: "next/dist/client/components/not-found-error"
},
...pages
};
}
case _pagetypes.PAGE_TYPES.PAGES:
{
if (isDev) {
delete pages["/_app"];
delete pages["/_error"];
delete pages["/_document"];
}
// In development we always alias these to allow Webpack to fallback to
// the correct source file so that HMR can work properly when a file is
// added or removed.
const root = isDev && pagesDir ? _constants.PAGES_DIR_ALIAS : "next/dist/pages";
return {
"/_app": `${root}/_app`,
"/_error": `${root}/_error`,
"/_document": `${root}/_document`,
...pages
};
}
default:
{
return {};
}
}
}
function getEdgeServerEntry(opts) {
var _opts_config_experimental_sri;
if (opts.pagesType === "app" && (0, _isapprouteroute.isAppRouteRoute)(opts.page) && opts.appDirLoader) {
const loaderParams = {
absolutePagePath: opts.absolutePagePath,
page: opts.page,
appDirLoader: Buffer.from(opts.appDirLoader || "").toString("base64"),
nextConfigOutput: opts.config.output,
preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(JSON.stringify(opts.middlewareConfig || {})).toString("base64")
};
return {
import: `next-edge-app-route-loader?${(0, _querystring.stringify)(loaderParams)}!`,
layer: _constants.WEBPACK_LAYERS.reactServerComponents
};
}
if ((0, _utils.isMiddlewareFile)(opts.page)) {
var _opts_middleware;
const loaderParams = {
absolutePagePath: opts.absolutePagePath,
page: opts.page,
rootDir: opts.rootDir,
matchers: ((_opts_middleware = opts.middleware) == null ? void 0 : _opts_middleware.matchers) ? (0, _nextmiddlewareloader.encodeMatchers)(opts.middleware.matchers) : "",
preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(JSON.stringify(opts.middlewareConfig || {})).toString("base64")
};
return `next-middleware-loader?${(0, _querystring.stringify)(loaderParams)}!`;
}
if ((0, _isapiroute.isAPIRoute)(opts.page)) {
const loaderParams = {
absolutePagePath: opts.absolutePagePath,
page: opts.page,
rootDir: opts.rootDir,
preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(JSON.stringify(opts.middlewareConfig || {})).toString("base64")
};
return `next-edge-function-loader?${(0, _querystring.stringify)(loaderParams)}!`;
}
const loaderParams = {
absolute500Path: opts.pages["/500"] || "",
absoluteAppPath: opts.pages["/_app"],
absoluteDocumentPath: opts.pages["/_document"],
absoluteErrorPath: opts.pages["/_error"],
absolutePagePath: opts.absolutePagePath,
buildId: opts.buildId,
dev: opts.isDev,
isServerComponent: opts.isServerComponent,
page: opts.page,
stringifiedConfig: Buffer.from(JSON.stringify(opts.config)).toString("base64"),
pagesType: opts.pagesType,
appDirLoader: Buffer.from(opts.appDirLoader || "").toString("base64"),
sriEnabled: !opts.isDev && !!((_opts_config_experimental_sri = opts.config.experimental.sri) == null ? void 0 : _opts_config_experimental_sri.algorithm),
cacheHandler: opts.config.cacheHandler,
preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(JSON.stringify(opts.middlewareConfig || {})).toString("base64"),
serverActions: opts.config.experimental.serverActions
};
return {
import: `next-edge-ssr-loader?${JSON.stringify(loaderParams)}!`,
// The Edge bundle includes the server in its entrypoint, so it has to
// be in the SSR layer — we later convert the page request to the RSC layer
// via a webpack rule.
layer: opts.appDirLoader ? _constants.WEBPACK_LAYERS.serverSideRendering : undefined
};
}
function getInstrumentationEntry(opts) {
// the '../' is needed to make sure the file is not chunked
const filename = `${opts.isEdgeServer ? "edge-" : opts.isDev ? "" : "../"}${_constants.INSTRUMENTATION_HOOK_FILENAME}.js`;
return {
import: opts.absolutePagePath,
filename,
layer: _constants.WEBPACK_LAYERS.instrument
};
}
function getAppEntry(opts) {
return {
import: `next-app-loader?${(0, _querystring.stringify)(opts)}!`,
layer: _constants.WEBPACK_LAYERS.reactServerComponents
};
}
function getClientEntry(opts) {
const loaderOptions = {
absolutePagePath: opts.absolutePagePath,
page: opts.page
};
const pageLoader = `next-client-pages-loader?${(0, _querystring.stringify)(loaderOptions)}!`;
// Make sure next/router is a dependency of _app or else chunk splitting
// might cause the router to not be able to load causing hydration
// to fail
return opts.page === "/_app" ? [
pageLoader,
require.resolve("../client/router")
] : pageLoader;
}
function runDependingOnPageType(params) {
if (params.pageType === _pagetypes.PAGE_TYPES.ROOT && (0, _utils.isInstrumentationHookFile)(params.page)) {
params.onServer();
params.onEdgeServer();
return;
}
if ((0, _utils.isMiddlewareFile)(params.page)) {
params.onEdgeServer();
return;
}
if ((0, _isapiroute.isAPIRoute)(params.page)) {
if ((0, _isedgeruntime.isEdgeRuntime)(params.pageRuntime)) {
params.onEdgeServer();
return;
}
params.onServer();
return;
}
if (params.page === "/_document") {
params.onServer();
return;
}
if (params.page === "/_app" || params.page === "/_error" || params.page === "/404" || params.page === "/500") {
params.onClient();
params.onServer();
return;
}
if ((0, _isedgeruntime.isEdgeRuntime)(params.pageRuntime)) {
params.onClient();
params.onEdgeServer();
return;
}
params.onClient();
params.onServer();
return;
}
async function createEntrypoints(params) {
const { config, pages, pagesDir, isDev, rootDir, rootPaths, appDir, appPaths, pageExtensions } = params;
const edgeServer = {};
const server = {};
const client = {};
let middlewareMatchers = undefined;
let appPathsPerRoute = {};
if (appDir && appPaths) {
for(const pathname in appPaths){
const normalizedPath = (0, _apppaths.normalizeAppPath)(pathname);
const actualPath = appPaths[pathname];
if (!appPathsPerRoute[normalizedPath]) {
appPathsPerRoute[normalizedPath] = [];
}
appPathsPerRoute[normalizedPath].push(// TODO-APP: refactor to pass the page path from createPagesMapping instead.
getPageFromPath(actualPath, pageExtensions).replace(_constants.APP_DIR_ALIAS, ""));
}
// TODO: find a better place to do this
(0, _normalizecatchallroutes.normalizeCatchAllRoutes)(appPathsPerRoute);
// Make sure to sort parallel routes to make the result deterministic.
appPathsPerRoute = Object.fromEntries(Object.entries(appPathsPerRoute).map(([k, v])=>[
k,
v.sort()
]));
}
const getEntryHandler = (mappings, pagesType)=>async (page)=>{
const bundleFile = (0, _normalizepagepath.normalizePagePath)(page);
const clientBundlePath = _path.posix.join(pagesType, bundleFile);
const serverBundlePath = pagesType === _pagetypes.PAGE_TYPES.PAGES ? _path.posix.join("pages", bundleFile) : pagesType === _pagetypes.PAGE_TYPES.APP ? _path.posix.join("app", bundleFile) : bundleFile.slice(1);
const absolutePagePath = mappings[page];
// Handle paths that have aliases
const pageFilePath = getPageFilePath({
absolutePagePath,
pagesDir,
appDir,
rootDir
});
const isInsideAppDir = !!appDir && (absolutePagePath.startsWith(_constants.APP_DIR_ALIAS) || absolutePagePath.startsWith(appDir));
const staticInfo = await getStaticInfoIncludingLayouts({
isInsideAppDir,
pageExtensions,
pageFilePath,
appDir,
config,
isDev,
page
});
// TODO(timneutkens): remove this
const isServerComponent = isInsideAppDir && staticInfo.rsc !== _constants1.RSC_MODULE_TYPES.client;
if ((0, _utils.isMiddlewareFile)(page)) {
var _staticInfo_middleware;
middlewareMatchers = ((_staticInfo_middleware = staticInfo.middleware) == null ? void 0 : _staticInfo_middleware.matchers) ?? [
{
regexp: ".*",
originalSource: "/:path*"
}
];
}
const isInstrumentation = (0, _utils.isInstrumentationHookFile)(page) && pagesType === _pagetypes.PAGE_TYPES.ROOT;
runDependingOnPageType({
page,
pageRuntime: staticInfo.runtime,
pageType: pagesType,
onClient: ()=>{
if (isServerComponent || isInsideAppDir) {
// We skip the initial entries for server component pages and let the
// server compiler inject them instead.
} else {
client[clientBundlePath] = getClientEntry({
absolutePagePath,
page
});
}
},
onServer: ()=>{
if (pagesType === "app" && appDir) {
const matchedAppPaths = appPathsPerRoute[(0, _apppaths.normalizeAppPath)(page)];
server[serverBundlePath] = getAppEntry({
page,
name: serverBundlePath,
pagePath: absolutePagePath,
appDir,
appPaths: matchedAppPaths,
pageExtensions,
basePath: config.basePath,
assetPrefix: config.assetPrefix,
nextConfigOutput: config.output,
nextConfigExperimentalUseEarlyImport: config.experimental.useEarlyImport,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: (0, _utils1.encodeToBase64)(staticInfo.middleware || {})
});
} else if (isInstrumentation) {
server[serverBundlePath.replace("src/", "")] = getInstrumentationEntry({
absolutePagePath,
isEdgeServer: false,
isDev: false
});
} else if ((0, _isapiroute.isAPIRoute)(page)) {
server[serverBundlePath] = [
(0, _nextrouteloader.getRouteLoaderEntry)({
kind: _routekind.RouteKind.PAGES_API,
page,
absolutePagePath,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: staticInfo.middleware || {}
})
];
} else if (!(0, _utils.isMiddlewareFile)(page) && !(0, _isinternalcomponent.isInternalComponent)(absolutePagePath) && !(0, _isinternalcomponent.isNonRoutePagesPage)(page)) {
server[serverBundlePath] = [
(0, _nextrouteloader.getRouteLoaderEntry)({
kind: _routekind.RouteKind.PAGES,
page,
pages,
absolutePagePath,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: staticInfo.middleware ?? {}
})
];
} else {
server[serverBundlePath] = [
absolutePagePath
];
}
},
onEdgeServer: ()=>{
let appDirLoader = "";
if (isInstrumentation) {
edgeServer[serverBundlePath.replace("src/", "")] = getInstrumentationEntry({
absolutePagePath,
isEdgeServer: true,
isDev: false
});
} else {
if (pagesType === "app") {
const matchedAppPaths = appPathsPerRoute[(0, _apppaths.normalizeAppPath)(page)];
appDirLoader = getAppEntry({
name: serverBundlePath,
page,
pagePath: absolutePagePath,
appDir: appDir,
appPaths: matchedAppPaths,
pageExtensions,
basePath: config.basePath,
assetPrefix: config.assetPrefix,
nextConfigOutput: config.output,
// This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead.
// Still passing it here for consistency.
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from(JSON.stringify(staticInfo.middleware || {})).toString("base64")
}).import;
}
edgeServer[serverBundlePath] = getEdgeServerEntry({
...params,
rootDir,
absolutePagePath: absolutePagePath,
bundlePath: clientBundlePath,
isDev: false,
isServerComponent,
page,
middleware: staticInfo == null ? void 0 : staticInfo.middleware,
pagesType,
appDirLoader,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: staticInfo.middleware
});
}
}
});
};
const promises = [];
if (appPaths) {
const entryHandler = getEntryHandler(appPaths, _pagetypes.PAGE_TYPES.APP);
promises.push(Promise.all(Object.keys(appPaths).map(entryHandler)));
}
if (rootPaths) {
promises.push(Promise.all(Object.keys(rootPaths).map(getEntryHandler(rootPaths, _pagetypes.PAGE_TYPES.ROOT))));
}
promises.push(Promise.all(Object.keys(pages).map(getEntryHandler(pages, _pagetypes.PAGE_TYPES.PAGES))));
await Promise.all(promises);
return {
client,
server,
edgeServer,
middlewareMatchers
};
}
function finalizeEntrypoint({ name, compilerType, value, isServerComponent, hasAppDir }) {
const entry = typeof value !== "object" || Array.isArray(value) ? {
import: value
} : value;
const isApi = name.startsWith("pages/api/");
const isInstrumentation = (0, _utils.isInstrumentationHookFilename)(name);
switch(compilerType){
case _constants1.COMPILER_NAMES.server:
{
const layer = isApi ? _constants.WEBPACK_LAYERS.api : isInstrumentation ? _constants.WEBPACK_LAYERS.instrument : isServerComponent ? _constants.WEBPACK_LAYERS.reactServerComponents : undefined;
return {
publicPath: isApi ? "" : undefined,
runtime: isApi ? "webpack-api-runtime" : "webpack-runtime",
layer,
...entry
};
}
case _constants1.COMPILER_NAMES.edgeServer:
{
return {
layer: (0, _utils.isMiddlewareFilename)(name) || isApi || isInstrumentation ? _constants.WEBPACK_LAYERS.middleware : undefined,
library: {
name: [
"_ENTRIES",
`middleware_[name]`
],
type: "assign"
},
runtime: _constants1.EDGE_RUNTIME_WEBPACK,
asyncChunks: false,
...entry
};
}
case _constants1.COMPILER_NAMES.client:
{
const isAppLayer = hasAppDir && (name === _constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN_APP || name === _constants1.APP_CLIENT_INTERNALS || name.startsWith("app/"));
if (// Client special cases
name !== _constants1.CLIENT_STATIC_FILES_RUNTIME_POLYFILLS && name !== _constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN && name !== _constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN_APP && name !== _constants1.CLIENT_STATIC_FILES_RUNTIME_AMP && name !== _constants1.CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH) {
if (isAppLayer) {
return {
dependOn: _constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
layer: _constants.WEBPACK_LAYERS.appPagesBrowser,
...entry
};
}
return {
dependOn: name.startsWith("pages/") && name !== "pages/_app" ? "pages/_app" : _constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN,
...entry
};
}
if (isAppLayer) {
return {
layer: _constants.WEBPACK_LAYERS.appPagesBrowser,
...entry
};
}
return entry;
}
default:
{
// Should never happen.
throw new Error("Invalid compiler type");
}
}
}
//# sourceMappingURL=entries.js.map

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getBabelConfigFile", {
enumerable: true,
get: function() {
return getBabelConfigFile;
}
});
const _path = require("path");
const _fs = require("fs");
const BABEL_CONFIG_FILES = [
".babelrc",
".babelrc.json",
".babelrc.js",
".babelrc.mjs",
".babelrc.cjs",
"babel.config.js",
"babel.config.json",
"babel.config.mjs",
"babel.config.cjs"
];
function getBabelConfigFile(dir) {
for (const filename of BABEL_CONFIG_FILES){
const configFilePath = (0, _path.join)(dir, filename);
const exists = (0, _fs.existsSync)(configFilePath);
if (!exists) {
continue;
}
return configFilePath;
}
}
//# sourceMappingURL=get-babel-config-file.js.map

View File

@@ -0,0 +1,300 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
isResourceInPackages: null,
makeExternalHandler: null,
resolveExternal: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
isResourceInPackages: function() {
return isResourceInPackages;
},
makeExternalHandler: function() {
return makeExternalHandler;
},
resolveExternal: function() {
return resolveExternal;
}
});
const _constants = require("../lib/constants");
const _requirehook = require("../server/require-hook");
const _constants1 = require("../shared/lib/constants");
const _path = /*#__PURE__*/ _interop_require_default(require("../shared/lib/isomorphic/path"));
const _webpackconfig = require("./webpack-config");
const _utils = require("./utils");
const _normalizepathsep = require("../shared/lib/page-path/normalize-path-sep");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const reactPackagesRegex = /^(react|react-dom|react-server-dom-webpack)($|\/)/;
const pathSeparators = "[/\\\\]";
const optionalEsmPart = `((${pathSeparators}esm)?${pathSeparators})`;
const externalFileEnd = "(\\.external(\\.js)?)$";
const nextDist = `next${pathSeparators}dist`;
const externalPattern = new RegExp(`${nextDist}${optionalEsmPart}.*${externalFileEnd}`);
const nodeModulesRegex = /node_modules[/\\].*\.[mc]?js$/;
function containsImportInPackages(request, packages) {
return packages.some((pkg)=>request === pkg || request.startsWith(pkg + "/"));
}
function isResourceInPackages(resource, packageNames, packageDirMapping) {
if (!packageNames) return false;
return packageNames.some((p)=>packageDirMapping && packageDirMapping.has(p) ? resource.startsWith(packageDirMapping.get(p) + _path.default.sep) : resource.includes(_path.default.sep + _path.default.join("node_modules", p.replace(/\//g, _path.default.sep)) + _path.default.sep));
}
async function resolveExternal(dir, esmExternalsConfig, context, request, isEsmRequested, optOutBundlingPackages, getResolve, isLocalCallback, baseResolveCheck = true, esmResolveOptions = _webpackconfig.NODE_ESM_RESOLVE_OPTIONS, nodeResolveOptions = _webpackconfig.NODE_RESOLVE_OPTIONS, baseEsmResolveOptions = _webpackconfig.NODE_BASE_ESM_RESOLVE_OPTIONS, baseResolveOptions = _webpackconfig.NODE_BASE_RESOLVE_OPTIONS) {
const esmExternals = !!esmExternalsConfig;
const looseEsmExternals = esmExternalsConfig === "loose";
let res = null;
let isEsm = false;
const preferEsmOptions = esmExternals && isEsmRequested && // For package that marked as externals that should be not bundled,
// we don't resolve them as ESM since it could be resolved as async module,
// such as `import(external package)` in the bundle, valued as a `Promise`.
!containsImportInPackages(request, optOutBundlingPackages) ? [
true,
false
] : [
false
];
for (const preferEsm of preferEsmOptions){
const resolve = getResolve(preferEsm ? esmResolveOptions : nodeResolveOptions);
// Resolve the import with the webpack provided context, this
// ensures we're resolving the correct version when multiple
// exist.
try {
[res, isEsm] = await resolve(context, request);
} catch (err) {
res = null;
}
if (!res) {
continue;
}
// ESM externals can only be imported (and not required).
// Make an exception in loose mode.
if (!isEsmRequested && isEsm && !looseEsmExternals) {
continue;
}
if (isLocalCallback) {
return {
localRes: isLocalCallback(res)
};
}
// Bundled Node.js code is relocated without its node_modules tree.
// This means we need to make sure its request resolves to the same
// package that'll be available at runtime. If it's not identical,
// we need to bundle the code (even if it _should_ be external).
if (baseResolveCheck) {
let baseRes;
let baseIsEsm;
try {
const baseResolve = getResolve(isEsm ? baseEsmResolveOptions : baseResolveOptions);
[baseRes, baseIsEsm] = await baseResolve(dir, request);
} catch (err) {
baseRes = null;
baseIsEsm = false;
}
// Same as above: if the package, when required from the root,
// would be different from what the real resolution would use, we
// cannot externalize it.
// if request is pointing to a symlink it could point to the the same file,
// the resolver will resolve symlinks so this is handled
if (baseRes !== res || isEsm !== baseIsEsm) {
res = null;
continue;
}
}
break;
}
return {
res,
isEsm
};
}
function makeExternalHandler({ config, optOutBundlingPackages, optOutBundlingPackageRegex, dir }) {
var _config_experimental;
let resolvedExternalPackageDirs;
const looseEsmExternals = ((_config_experimental = config.experimental) == null ? void 0 : _config_experimental.esmExternals) === "loose";
return async function handleExternals(context, request, dependencyType, layer, getResolve) {
// We need to externalize internal requests for files intended to
// not be bundled.
const isLocal = request.startsWith(".") || // Always check for unix-style path, as webpack sometimes
// normalizes as posix.
_path.default.posix.isAbsolute(request) || // When on Windows, we also want to check for Windows-specific
// absolute paths.
process.platform === "win32" && _path.default.win32.isAbsolute(request);
// make sure import "next" shows a warning when imported
// in pages/components
if (request === "next") {
return `commonjs next/dist/lib/import-next-warning`;
}
const isAppLayer = (0, _utils.isWebpackAppLayer)(layer);
// Relative requires don't need custom resolution, because they
// are relative to requests we've already resolved here.
// Absolute requires (require('/foo')) are extremely uncommon, but
// also have no need for customization as they're already resolved.
if (!isLocal) {
if (/^(?:next$)/.test(request)) {
return `commonjs ${request}`;
}
if (reactPackagesRegex.test(request) && !isAppLayer) {
return `commonjs ${request}`;
}
const notExternalModules = /^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|legacy\/image|constants|dynamic|script|navigation|headers|router)$)|string-hash|private-next-rsc-action-validate|private-next-rsc-action-client-wrapper|private-next-rsc-server-reference$)/;
if (notExternalModules.test(request)) {
return;
}
}
// @swc/helpers should not be external as it would
// require hoisting the package which we can't rely on
if (request.includes("@swc/helpers")) {
return;
}
// BARREL_OPTIMIZATION_PREFIX is a special marker that tells Next.js to
// optimize the import by removing unused exports. This has to be compiled.
if (request.startsWith(_constants1.BARREL_OPTIMIZATION_PREFIX)) {
return;
}
// When in esm externals mode, and using import, we resolve with
// ESM resolving options.
// Also disable esm request when appDir is enabled
const isEsmRequested = dependencyType === "esm";
// Don't bundle @vercel/og nodejs bundle for nodejs runtime.
// TODO-APP: bundle route.js with different layer that externals common node_module deps.
// Make sure @vercel/og is loaded as ESM for Node.js runtime
if ((0, _utils.isWebpackServerOnlyLayer)(layer) && request === "next/dist/compiled/@vercel/og/index.node.js") {
return `module ${request}`;
}
// Specific Next.js imports that should remain external
// TODO-APP: Investigate if we can remove this.
if (request.startsWith("next/dist/")) {
// Non external that needs to be transpiled
// Image loader needs to be transpiled
if (/^next[\\/]dist[\\/]shared[\\/]lib[\\/]image-loader/.test(request)) {
return;
}
if (/^next[\\/]dist[\\/]compiled[\\/]next-server/.test(request)) {
return `commonjs ${request}`;
}
if (/^next[\\/]dist[\\/]shared[\\/](?!lib[\\/]router[\\/]router)/.test(request) || /^next[\\/]dist[\\/]compiled[\\/].*\.c?js$/.test(request)) {
return `commonjs ${request}`;
}
if (/^next[\\/]dist[\\/]esm[\\/]shared[\\/](?!lib[\\/]router[\\/]router)/.test(request) || /^next[\\/]dist[\\/]compiled[\\/].*\.mjs$/.test(request)) {
return `module ${request}`;
}
return resolveNextExternal(request);
}
// Early return if the request needs to be bundled, such as in the client layer.
// Treat react packages and next internals as external for SSR layer,
// also map react to builtin ones with require-hook.
// Otherwise keep continue the process to resolve the externals.
if (layer === _constants.WEBPACK_LAYERS.serverSideRendering) {
const isRelative = request.startsWith(".");
const fullRequest = isRelative ? (0, _normalizepathsep.normalizePathSep)(_path.default.join(context, request)) : request;
// Check if it's opt out bundling package first
if (containsImportInPackages(fullRequest, optOutBundlingPackages)) {
return fullRequest;
}
return resolveNextExternal(fullRequest);
}
// TODO-APP: Let's avoid this resolve call as much as possible, and eventually get rid of it.
const resolveResult = await resolveExternal(dir, config.experimental.esmExternals, context, request, isEsmRequested, optOutBundlingPackages, getResolve, isLocal ? resolveNextExternal : undefined);
if ("localRes" in resolveResult) {
return resolveResult.localRes;
}
// Forcedly resolve the styled-jsx installed by next.js,
// since `resolveExternal` cannot find the styled-jsx dep with pnpm
if (request === "styled-jsx/style") {
resolveResult.res = _requirehook.defaultOverrides["styled-jsx/style"];
}
const { res, isEsm } = resolveResult;
// If the request cannot be resolved we need to have
// webpack "bundle" it so it surfaces the not found error.
if (!res) {
return;
}
// ESM externals can only be imported (and not required).
// Make an exception in loose mode.
if (!isEsmRequested && isEsm && !looseEsmExternals && !isLocal) {
throw new Error(`ESM packages (${request}) need to be imported. Use 'import' to reference the package instead. https://nextjs.org/docs/messages/import-esm-externals`);
}
const externalType = isEsm ? "module" : "commonjs";
// Default pages have to be transpiled
if (// This is the @babel/plugin-transform-runtime "helpers: true" option
/node_modules[/\\]@babel[/\\]runtime[/\\]/.test(res)) {
return;
}
// Webpack itself has to be compiled because it doesn't always use module relative paths
if (/node_modules[/\\]webpack/.test(res) || /node_modules[/\\]css-loader/.test(res)) {
return;
}
// If a package should be transpiled by Next.js, we skip making it external.
// It doesn't matter what the extension is, as we'll transpile it anyway.
if (config.transpilePackages && !resolvedExternalPackageDirs) {
resolvedExternalPackageDirs = new Map();
// We need to resolve all the external package dirs initially.
for (const pkg of config.transpilePackages){
const pkgRes = await resolveExternal(dir, config.experimental.esmExternals, context, pkg + "/package.json", isEsmRequested, optOutBundlingPackages, getResolve, isLocal ? resolveNextExternal : undefined);
if (pkgRes.res) {
resolvedExternalPackageDirs.set(pkg, _path.default.dirname(pkgRes.res));
}
}
}
const resolvedBundlingOptOutRes = resolveBundlingOptOutPackages({
resolvedRes: res,
optOutBundlingPackageRegex,
config,
resolvedExternalPackageDirs,
isEsm,
isAppLayer,
layer,
externalType,
request
});
if (resolvedBundlingOptOutRes) {
return resolvedBundlingOptOutRes;
}
// if here, we default to bundling the file
return;
};
}
function resolveBundlingOptOutPackages({ resolvedRes, optOutBundlingPackageRegex, config, resolvedExternalPackageDirs, isEsm, isAppLayer, layer, externalType, request }) {
const shouldBeBundled = isResourceInPackages(resolvedRes, config.transpilePackages, resolvedExternalPackageDirs) || isEsm && isAppLayer || !isAppLayer && config.experimental.bundlePagesExternals;
if (nodeModulesRegex.test(resolvedRes)) {
const isOptOutBundling = optOutBundlingPackageRegex.test(resolvedRes);
if ((0, _utils.isWebpackServerOnlyLayer)(layer)) {
if (isOptOutBundling) {
return `${externalType} ${request}` // Externalize if opted out
;
}
} else if (!shouldBeBundled || isOptOutBundling) {
return `${externalType} ${request}` // Externalize if not bundled or opted out
;
}
}
}
/**
* @param localRes the full path to the file
* @returns the externalized path
* @description returns an externalized path if the file is a Next.js file and ends with either `.shared-runtime.js` or `.external.js`
* This is used to ensure that files used across the rendering runtime(s) and the user code are one and the same. The logic in this function
* will rewrite the require to the correct bundle location depending on the layer at which the file is being used.
*/ function resolveNextExternal(localRes) {
const isExternal = externalPattern.test(localRes);
// if the file ends with .external, we need to make it a commonjs require in all cases
// this is used mainly to share the async local storage across the routing, rendering and user layers.
if (isExternal) {
// it's important we return the path that starts with `next/dist/` here instead of the absolute path
// otherwise NFT will get tripped up
return `commonjs ${(0, _normalizepathsep.normalizePathSep)(localRes.replace(/.*?next[/\\]dist/, "next/dist"))}`;
}
}
//# sourceMappingURL=handle-externals.js.map

View File

@@ -0,0 +1,128 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "loadEntrypoint", {
enumerable: true,
get: function() {
return loadEntrypoint;
}
});
const _promises = /*#__PURE__*/ _interop_require_default(require("fs/promises"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
// NOTE: this should be updated if this loader file is moved.
const PACKAGE_ROOT = _path.default.normalize(_path.default.join(__dirname, "../../.."));
const TEMPLATE_FOLDER = _path.default.join(__dirname, "templates");
const TEMPLATES_ESM_FOLDER = _path.default.normalize(_path.default.join(__dirname, "../../dist/esm/build/templates"));
async function loadEntrypoint(entrypoint, replacements, injections, imports) {
const filepath = _path.default.resolve(_path.default.join(TEMPLATES_ESM_FOLDER, `${entrypoint}.js`));
let file = await _promises.default.readFile(filepath, "utf8");
// Update the relative imports to be absolute. This will update any relative
// imports to be relative to the root of the `next` package.
let count = 0;
file = file.replaceAll(/from "(\..*)"|import "(\..*)"/g, function(_, fromRequest, importRequest) {
count++;
const relative = _path.default.relative(PACKAGE_ROOT, _path.default.resolve(TEMPLATE_FOLDER, fromRequest ?? importRequest))// Ensure that we use linux style path separators for node.
.replace(/\\/g, "/");
// Verify that the relative import is relative to the `next` package. This
// will catch cases where the constants at the top of the file were not
// updated after the file was moved.
if (!relative.startsWith("next/")) {
throw new Error(`Invariant: Expected relative import to start with "next/", found "${relative}"`);
}
return fromRequest ? `from ${JSON.stringify(relative)}` : `import ${JSON.stringify(relative)}`;
});
// Verify that at least one import was replaced. It's the case today where
// every template file has at least one import to update, so this ensures that
// we don't accidentally remove the import replacement code or use the wrong
// template file.
if (count === 0) {
throw new Error("Invariant: Expected to replace at least one import");
}
const replaced = new Set();
// Replace all the template variables with the actual values. If a template
// variable is missing, throw an error.
file = file.replaceAll(new RegExp(`${Object.keys(replacements).map((k)=>`"${k}"`).join("|")}`, "g"), (match)=>{
const key = JSON.parse(match);
if (!(key in replacements)) {
throw new Error(`Invariant: Unexpected template variable ${key}`);
}
replaced.add(key);
return JSON.stringify(replacements[key]);
});
// Check to see if there's any remaining template variables.
let matches = file.match(/VAR_[A-Z_]+/g);
if (matches) {
throw new Error(`Invariant: Expected to replace all template variables, found ${matches.join(", ")}`);
}
// Check to see if any template variable was provided but not used.
if (replaced.size !== Object.keys(replacements).length) {
// Find the difference between the provided replacements and the replaced
// template variables. This will let us notify the user of any template
// variables that were not used but were provided.
const difference = Object.keys(replacements).filter((key)=>!replaced.has(key));
throw new Error(`Invariant: Expected to replace all template variables, missing ${difference.join(", ")} in template`);
}
// Replace the injections.
const injected = new Set();
if (injections) {
// Track all the injections to ensure that we're not missing any.
file = file.replaceAll(new RegExp(`// INJECT:(${Object.keys(injections).join("|")})`, "g"), (_, key)=>{
if (!(key in injections)) {
throw new Error(`Invariant: Unexpected injection ${key}`);
}
injected.add(key);
return `const ${key} = ${injections[key]}`;
});
}
// Check to see if there's any remaining injections.
matches = file.match(/\/\/ INJECT:[A-Za-z0-9_]+/g);
if (matches) {
throw new Error(`Invariant: Expected to inject all injections, found ${matches.join(", ")}`);
}
// Check to see if any injection was provided but not used.
if (injected.size !== Object.keys(injections ?? {}).length) {
// Find the difference between the provided injections and the injected
// injections. This will let us notify the user of any injections that were
// not used but were provided.
const difference = Object.keys(injections ?? {}).filter((key)=>!injected.has(key));
throw new Error(`Invariant: Expected to inject all injections, missing ${difference.join(", ")} in template`);
}
// Replace the optional imports.
const importsAdded = new Set();
if (imports) {
// Track all the imports to ensure that we're not missing any.
file = file.replaceAll(new RegExp(`// OPTIONAL_IMPORT:(\\* as )?(${Object.keys(imports).join("|")})`, "g"), (_, asNamespace = "", key)=>{
if (!(key in imports)) {
throw new Error(`Invariant: Unexpected optional import ${key}`);
}
importsAdded.add(key);
if (imports[key]) {
return `import ${asNamespace}${key} from ${JSON.stringify(imports[key])}`;
} else {
return `const ${key} = null`;
}
});
}
// Check to see if there's any remaining imports.
matches = file.match(/\/\/ OPTIONAL_IMPORT:(\* as )?[A-Za-z0-9_]+/g);
if (matches) {
throw new Error(`Invariant: Expected to inject all imports, found ${matches.join(", ")}`);
}
// Check to see if any import was provided but not used.
if (importsAdded.size !== Object.keys(imports ?? {}).length) {
// Find the difference between the provided imports and the injected
// imports. This will let us notify the user of any imports that were
// not used but were provided.
const difference = Object.keys(imports ?? {}).filter((key)=>!importsAdded.has(key));
throw new Error(`Invariant: Expected to inject all imports, missing ${difference.join(", ")} in template`);
}
return file;
}
//# sourceMappingURL=load-entrypoint.js.map

View File

@@ -0,0 +1,144 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return loadJsConfig;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _fs = /*#__PURE__*/ _interop_require_wildcard(require("fs"));
const _log = /*#__PURE__*/ _interop_require_wildcard(require("./output/log"));
const _getTypeScriptConfiguration = require("../lib/typescript/getTypeScriptConfiguration");
const _iserror = /*#__PURE__*/ _interop_require_default(require("../lib/is-error"));
const _hasnecessarydependencies = require("../lib/has-necessary-dependencies");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
let TSCONFIG_WARNED = false;
function parseJsonFile(filePath) {
const JSON5 = require("next/dist/compiled/json5");
const contents = (0, _fs.readFileSync)(filePath, "utf8");
// Special case an empty file
if (contents.trim() === "") {
return {};
}
try {
return JSON5.parse(contents);
} catch (err) {
if (!(0, _iserror.default)(err)) throw err;
const { codeFrameColumns } = require("next/dist/compiled/babel/code-frame");
const codeFrame = codeFrameColumns(String(contents), {
start: {
line: err.lineNumber || 0,
column: err.columnNumber || 0
}
}, {
message: err.message,
highlightCode: true
});
throw new Error(`Failed to parse "${filePath}":\n${codeFrame}`);
}
}
async function loadJsConfig(dir, config) {
var _jsConfig_compilerOptions;
let typeScriptPath;
try {
const deps = await (0, _hasnecessarydependencies.hasNecessaryDependencies)(dir, [
{
pkg: "typescript",
file: "typescript/lib/typescript.js",
exportsRestrict: true
}
]);
typeScriptPath = deps.resolved.get("typescript");
} catch {}
const tsConfigPath = _path.default.join(dir, config.typescript.tsconfigPath);
const useTypeScript = Boolean(typeScriptPath && _fs.default.existsSync(tsConfigPath));
let implicitBaseurl;
let jsConfig;
// jsconfig is a subset of tsconfig
if (useTypeScript) {
if (config.typescript.tsconfigPath !== "tsconfig.json" && TSCONFIG_WARNED === false) {
TSCONFIG_WARNED = true;
_log.info(`Using tsconfig file: ${config.typescript.tsconfigPath}`);
}
const ts = await Promise.resolve(require(typeScriptPath));
const tsConfig = await (0, _getTypeScriptConfiguration.getTypeScriptConfiguration)(ts, tsConfigPath, true);
jsConfig = {
compilerOptions: tsConfig.options
};
implicitBaseurl = _path.default.dirname(tsConfigPath);
}
const jsConfigPath = _path.default.join(dir, "jsconfig.json");
if (!useTypeScript && _fs.default.existsSync(jsConfigPath)) {
jsConfig = parseJsonFile(jsConfigPath);
implicitBaseurl = _path.default.dirname(jsConfigPath);
}
let resolvedBaseUrl;
if (jsConfig == null ? void 0 : (_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.baseUrl) {
resolvedBaseUrl = {
baseUrl: _path.default.resolve(dir, jsConfig.compilerOptions.baseUrl),
isImplicit: false
};
} else {
if (implicitBaseurl) {
resolvedBaseUrl = {
baseUrl: implicitBaseurl,
isImplicit: true
};
}
}
return {
useTypeScript,
jsConfig,
resolvedBaseUrl
};
}
//# sourceMappingURL=load-jsconfig.js.map

View File

@@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "normalizeCatchAllRoutes", {
enumerable: true,
get: function() {
return normalizeCatchAllRoutes;
}
});
const _interceptionroutes = require("../server/future/helpers/interception-routes");
const _apppathnamenormalizer = require("../server/future/normalizers/built/app/app-pathname-normalizer");
function normalizeCatchAllRoutes(appPaths, normalizer = new _apppathnamenormalizer.AppPathnameNormalizer()) {
const catchAllRoutes = [
...new Set(Object.values(appPaths).flat().filter(isCatchAllRoute)// Sorting is important because we want to match the most specific path.
.sort((a, b)=>b.split("/").length - a.split("/").length))
];
// interception routes should only be matched by a single entrypoint
// we don't want to push a catch-all route to an interception route
// because it would mean the interception would be handled by the wrong page component
const filteredAppPaths = Object.keys(appPaths).filter((route)=>!(0, _interceptionroutes.isInterceptionRouteAppPath)(route));
for (const appPath of filteredAppPaths){
for (const catchAllRoute of catchAllRoutes){
const normalizedCatchAllRoute = normalizer.normalize(catchAllRoute);
const normalizedCatchAllRouteBasePath = normalizedCatchAllRoute.slice(0, normalizedCatchAllRoute.search(catchAllRouteRegex));
if (// check if the appPath could match the catch-all
appPath.startsWith(normalizedCatchAllRouteBasePath) && // check if there's not already a slot value that could match the catch-all
!appPaths[appPath].some((path)=>hasMatchedSlots(path, catchAllRoute))) {
// optional catch-all routes are not currently supported, but leaving this logic in place
// for when they are eventually supported.
if (isOptionalCatchAll(catchAllRoute)) {
// optional catch-all routes should match both the root segment and any segment after it
// for example, `/[[...slug]]` should match `/` and `/foo` and `/foo/bar`
appPaths[appPath].push(catchAllRoute);
} else if (isCatchAll(catchAllRoute)) {
// regular catch-all (single bracket) should only match segments after it
// for example, `/[...slug]` should match `/foo` and `/foo/bar` but not `/`
if (normalizedCatchAllRouteBasePath !== appPath) {
appPaths[appPath].push(catchAllRoute);
}
}
}
}
}
}
function hasMatchedSlots(path1, path2) {
const slots1 = path1.split("/").filter(isMatchableSlot);
const slots2 = path2.split("/").filter(isMatchableSlot);
// if the catch-all route does not have the same number of slots as the app path, it can't match
if (slots1.length !== slots2.length) return false;
// compare the slots in both paths. For there to be a match, each slot must be the same
for(let i = 0; i < slots1.length; i++){
if (slots1[i] !== slots2[i]) return false;
}
return true;
}
/**
* Returns true for slots that should be considered when checking for match compatability.
* Excludes children slots because these are similar to having a segment-level `page`
* which would cause a slot length mismatch when comparing it to a catch-all route.
*/ function isMatchableSlot(segment) {
return segment.startsWith("@") && segment !== "@children";
}
const catchAllRouteRegex = /\[?\[\.\.\./;
function isCatchAllRoute(pathname) {
// Optional catch-all slots are not currently supported, and as such they are not considered when checking for match compatability.
return !isOptionalCatchAll(pathname) && isCatchAll(pathname);
}
function isOptionalCatchAll(pathname) {
return pathname.includes("[[...");
}
function isCatchAll(pathname) {
return pathname.includes("[...");
}
//# sourceMappingURL=normalize-catchall-routes.js.map

View File

@@ -0,0 +1,295 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ampValidation: null,
formatAmpMessages: null,
reportTrigger: null,
startedDevelopmentServer: null,
watchCompilers: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ampValidation: function() {
return ampValidation;
},
formatAmpMessages: function() {
return formatAmpMessages;
},
reportTrigger: function() {
return reportTrigger;
},
startedDevelopmentServer: function() {
return startedDevelopmentServer;
},
watchCompilers: function() {
return watchCompilers;
}
});
const _picocolors = require("../../lib/picocolors");
const _stripansi = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/strip-ansi"));
const _texttable = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/text-table"));
const _unistore = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/unistore"));
const _formatwebpackmessages = /*#__PURE__*/ _interop_require_default(require("../../client/components/react-dev-overlay/internal/helpers/format-webpack-messages"));
const _store = require("./store");
const _constants = require("../../shared/lib/constants");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function startedDevelopmentServer(appUrl, bindAddr) {
_store.store.setState({
appUrl,
bindAddr
});
}
function formatAmpMessages(amp) {
let output = (0, _picocolors.bold)("Amp Validation") + "\n\n";
let messages = [];
const chalkError = (0, _picocolors.red)("error");
function ampError(page, error) {
messages.push([
page,
chalkError,
error.message,
error.specUrl || ""
]);
}
const chalkWarn = (0, _picocolors.yellow)("warn");
function ampWarn(page, warn) {
messages.push([
page,
chalkWarn,
warn.message,
warn.specUrl || ""
]);
}
for(const page in amp){
let { errors, warnings } = amp[page];
const devOnlyFilter = (err)=>err.code !== "DEV_MODE_ONLY";
errors = errors.filter(devOnlyFilter);
warnings = warnings.filter(devOnlyFilter);
if (!(errors.length || warnings.length)) {
continue;
}
if (errors.length) {
ampError(page, errors[0]);
for(let index = 1; index < errors.length; ++index){
ampError("", errors[index]);
}
}
if (warnings.length) {
ampWarn(errors.length ? "" : page, warnings[0]);
for(let index = 1; index < warnings.length; ++index){
ampWarn("", warnings[index]);
}
}
messages.push([
"",
"",
"",
""
]);
}
if (!messages.length) {
return "";
}
output += (0, _texttable.default)(messages, {
align: [
"l",
"l",
"l",
"l"
],
stringLength (str) {
return (0, _stripansi.default)(str).length;
}
});
return output;
}
const buildStore = (0, _unistore.default)({
// @ts-expect-error initial value
client: {},
// @ts-expect-error initial value
server: {},
// @ts-expect-error initial value
edgeServer: {}
});
let buildWasDone = false;
let clientWasLoading = true;
let serverWasLoading = true;
let edgeServerWasLoading = false;
buildStore.subscribe((state)=>{
const { amp, client, server, edgeServer, trigger, url } = state;
const { appUrl } = _store.store.getState();
if (client.loading || server.loading || (edgeServer == null ? void 0 : edgeServer.loading)) {
_store.store.setState({
bootstrap: false,
appUrl: appUrl,
// If it takes more than 3 seconds to compile, mark it as loading status
loading: true,
trigger,
url
}, true);
clientWasLoading = !buildWasDone && clientWasLoading || client.loading;
serverWasLoading = !buildWasDone && serverWasLoading || server.loading;
edgeServerWasLoading = !buildWasDone && edgeServerWasLoading || edgeServer.loading;
buildWasDone = false;
return;
}
buildWasDone = true;
let partialState = {
bootstrap: false,
appUrl: appUrl,
loading: false,
typeChecking: false,
totalModulesCount: (clientWasLoading ? client.totalModulesCount : 0) + (serverWasLoading ? server.totalModulesCount : 0) + (edgeServerWasLoading ? (edgeServer == null ? void 0 : edgeServer.totalModulesCount) || 0 : 0),
hasEdgeServer: !!edgeServer
};
if (client.errors && clientWasLoading) {
// Show only client errors
_store.store.setState({
...partialState,
errors: client.errors,
warnings: null
}, true);
} else if (server.errors && serverWasLoading) {
_store.store.setState({
...partialState,
errors: server.errors,
warnings: null
}, true);
} else if (edgeServer.errors && edgeServerWasLoading) {
_store.store.setState({
...partialState,
errors: edgeServer.errors,
warnings: null
}, true);
} else {
// Show warnings from all of them
const warnings = [
...client.warnings || [],
...server.warnings || [],
...edgeServer.warnings || []
].concat(formatAmpMessages(amp) || []);
_store.store.setState({
...partialState,
errors: null,
warnings: warnings.length === 0 ? null : warnings
}, true);
}
});
function ampValidation(page, errors, warnings) {
const { amp } = buildStore.getState();
if (!(errors.length || warnings.length)) {
buildStore.setState({
amp: Object.keys(amp).filter((k)=>k !== page).sort()// eslint-disable-next-line no-sequences
.reduce((a, c)=>(a[c] = amp[c], a), {})
});
return;
}
const newAmp = {
...amp,
[page]: {
errors,
warnings
}
};
buildStore.setState({
amp: Object.keys(newAmp).sort()// eslint-disable-next-line no-sequences
.reduce((a, c)=>(a[c] = newAmp[c], a), {})
});
}
function watchCompilers(client, server, edgeServer) {
buildStore.setState({
client: {
loading: true
},
server: {
loading: true
},
edgeServer: {
loading: true
},
trigger: "initial",
url: undefined
});
function tapCompiler(key, compiler, onEvent) {
compiler.hooks.invalid.tap(`NextJsInvalid-${key}`, ()=>{
onEvent({
loading: true
});
});
compiler.hooks.done.tap(`NextJsDone-${key}`, (stats)=>{
buildStore.setState({
amp: {}
});
const { errors, warnings } = (0, _formatwebpackmessages.default)(stats.toJson({
preset: "errors-warnings",
moduleTrace: true
}));
const hasErrors = !!(errors == null ? void 0 : errors.length);
const hasWarnings = !!(warnings == null ? void 0 : warnings.length);
onEvent({
loading: false,
totalModulesCount: stats.compilation.modules.size,
errors: hasErrors ? errors : null,
warnings: hasWarnings ? warnings : null
});
});
}
tapCompiler(_constants.COMPILER_NAMES.client, client, (status)=>{
if (!status.loading && !buildStore.getState().server.loading && !buildStore.getState().edgeServer.loading && status.totalModulesCount > 0) {
buildStore.setState({
client: status,
trigger: undefined,
url: undefined
});
} else {
buildStore.setState({
client: status
});
}
});
tapCompiler(_constants.COMPILER_NAMES.server, server, (status)=>{
if (!status.loading && !buildStore.getState().client.loading && !buildStore.getState().edgeServer.loading && status.totalModulesCount > 0) {
buildStore.setState({
server: status,
trigger: undefined,
url: undefined
});
} else {
buildStore.setState({
server: status
});
}
});
tapCompiler(_constants.COMPILER_NAMES.edgeServer, edgeServer, (status)=>{
if (!status.loading && !buildStore.getState().client.loading && !buildStore.getState().server.loading && status.totalModulesCount > 0) {
buildStore.setState({
edgeServer: status,
trigger: undefined,
url: undefined
});
} else {
buildStore.setState({
edgeServer: status
});
}
});
}
function reportTrigger(trigger, url) {
buildStore.setState({
trigger,
url
});
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,115 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
bootstrap: null,
error: null,
event: null,
info: null,
prefixes: null,
ready: null,
trace: null,
wait: null,
warn: null,
warnOnce: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
bootstrap: function() {
return bootstrap;
},
error: function() {
return error;
},
event: function() {
return event;
},
info: function() {
return info;
},
prefixes: function() {
return prefixes;
},
ready: function() {
return ready;
},
trace: function() {
return trace;
},
wait: function() {
return wait;
},
warn: function() {
return warn;
},
warnOnce: function() {
return warnOnce;
}
});
const _picocolors = require("../../lib/picocolors");
const prefixes = {
wait: (0, _picocolors.white)((0, _picocolors.bold)("○")),
error: (0, _picocolors.red)((0, _picocolors.bold)("")),
warn: (0, _picocolors.yellow)((0, _picocolors.bold)("⚠")),
ready: "▲",
info: (0, _picocolors.white)((0, _picocolors.bold)(" ")),
event: (0, _picocolors.green)((0, _picocolors.bold)("✓")),
trace: (0, _picocolors.magenta)((0, _picocolors.bold)("\xbb"))
};
const LOGGING_METHOD = {
log: "log",
warn: "warn",
error: "error"
};
function prefixedLog(prefixType, ...message) {
if ((message[0] === "" || message[0] === undefined) && message.length === 1) {
message.shift();
}
const consoleMethod = prefixType in LOGGING_METHOD ? LOGGING_METHOD[prefixType] : "log";
const prefix = prefixes[prefixType];
// If there's no message, don't print the prefix but a new line
if (message.length === 0) {
console[consoleMethod]("");
} else {
console[consoleMethod](" " + prefix, ...message);
}
}
function bootstrap(...message) {
console.log(" ", ...message);
}
function wait(...message) {
prefixedLog("wait", ...message);
}
function error(...message) {
prefixedLog("error", ...message);
}
function warn(...message) {
prefixedLog("warn", ...message);
}
function ready(...message) {
prefixedLog("ready", ...message);
}
function info(...message) {
prefixedLog("info", ...message);
}
function event(...message) {
prefixedLog("event", ...message);
}
function trace(...message) {
prefixedLog("trace", ...message);
}
const warnOnceMessages = new Set();
function warnOnce(...message) {
if (!warnOnceMessages.has(message[0])) {
warnOnceMessages.add(message.join(" "));
warn(...message);
}
}
//# sourceMappingURL=log.js.map

View File

@@ -0,0 +1,214 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
formatTrigger: null,
store: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
formatTrigger: function() {
return formatTrigger;
},
store: function() {
return store;
}
});
const _unistore = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/unistore"));
const _stripansi = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/strip-ansi"));
const _trace = require("../../trace");
const _swc = require("../swc");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("./log"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const MAX_LOG_SKIP_DURATION = 500 // 500ms
;
const internalSegments = [
"[[...__metadata_id__]]",
"[__metadata_id__]"
];
function formatTrigger(trigger) {
for (const segment of internalSegments){
if (trigger.includes(segment)) {
trigger = trigger.replace(segment, "");
}
}
if (trigger.length > 1 && trigger.endsWith("/")) {
trigger = trigger.slice(0, -1);
}
return trigger;
}
const store = (0, _unistore.default)({
appUrl: null,
bindAddr: null,
bootstrap: true
});
let lastStore = {
appUrl: null,
bindAddr: null,
bootstrap: true
};
function hasStoreChanged(nextStore) {
if ([
...new Set([
...Object.keys(lastStore),
...Object.keys(nextStore)
])
].every((key)=>Object.is(lastStore[key], nextStore[key]))) {
return false;
}
lastStore = nextStore;
return true;
}
let startTime = 0;
let trigger = "" // default, use empty string for trigger
;
let triggerUrl = undefined;
let loadingLogTimer = null;
let traceSpan = null;
store.subscribe((state)=>{
if (!hasStoreChanged(state)) {
return;
}
if (state.bootstrap) {
return;
}
if (state.loading) {
if (state.trigger) {
trigger = formatTrigger(state.trigger);
triggerUrl = state.url;
if (trigger !== "initial") {
traceSpan = (0, _trace.trace)("compile-path", undefined, {
trigger: trigger
});
if (!loadingLogTimer) {
// Only log compiling if compiled is not finished in 3 seconds
loadingLogTimer = setTimeout(()=>{
if (triggerUrl && triggerUrl !== trigger && process.env.NEXT_TRIGGER_URL) {
_log.wait(`Compiling ${trigger} (${triggerUrl}) ...`);
} else {
_log.wait(`Compiling ${trigger} ...`);
}
}, MAX_LOG_SKIP_DURATION);
}
}
}
if (startTime === 0) {
startTime = Date.now();
}
return;
}
if (state.errors) {
// Log compilation errors
_log.error(state.errors[0]);
const cleanError = (0, _stripansi.default)(state.errors[0]);
if (cleanError.indexOf("SyntaxError") > -1) {
const matches = cleanError.match(/\[.*\]=/);
if (matches) {
for (const match of matches){
const prop = (match.split("]").shift() || "").slice(1);
console.log(`AMP bind syntax [${prop}]='' is not supported in JSX, use 'data-amp-bind-${prop}' instead. https://nextjs.org/docs/messages/amp-bind-jsx-alt`);
}
return;
}
}
startTime = 0;
// Ensure traces are flushed after each compile in development mode
(0, _trace.flushAllTraces)();
(0, _swc.teardownTraceSubscriber)();
(0, _swc.teardownHeapProfiler)();
return;
}
let timeMessage = "";
if (startTime) {
const time = Date.now() - startTime;
startTime = 0;
timeMessage = " " + (time > 2000 ? `in ${Math.round(time / 100) / 10}s` : `in ${time}ms`);
}
let modulesMessage = "";
if (state.totalModulesCount) {
modulesMessage = ` (${state.totalModulesCount} modules)`;
}
if (state.warnings) {
_log.warn(state.warnings.join("\n\n"));
// Ensure traces are flushed after each compile in development mode
(0, _trace.flushAllTraces)();
(0, _swc.teardownTraceSubscriber)();
(0, _swc.teardownHeapProfiler)();
return;
}
if (state.typeChecking) {
_log.info(`bundled ${trigger}${timeMessage}${modulesMessage}, type checking...`);
return;
}
if (trigger === "initial") {
trigger = "";
} else {
if (loadingLogTimer) {
clearTimeout(loadingLogTimer);
loadingLogTimer = null;
}
if (traceSpan) {
traceSpan.stop();
traceSpan = null;
}
_log.event(`Compiled${trigger ? " " + trigger : ""}${timeMessage}${modulesMessage}`);
trigger = "";
}
// Ensure traces are flushed after each compile in development mode
(0, _trace.flushAllTraces)();
(0, _swc.teardownTraceSubscriber)();
(0, _swc.teardownHeapProfiler)();
});
//# sourceMappingURL=store.js.map

View File

@@ -0,0 +1,6 @@
/* globals self */ "use strict";
const fetchModule = self.fetch.bind(self);
module.exports = fetchModule;
module.exports.default = module.exports;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,7 @@
/* globals self */ "use strict";
exports.Headers = self.Headers;
exports.Request = self.Request;
exports.Response = self.Response;
exports.fetch = self.fetch;
//# sourceMappingURL=whatwg-fetch.js.map

View File

@@ -0,0 +1,6 @@
"use strict";
var assign = Object.assign.bind(Object);
module.exports = assign;
module.exports.default = module.exports;
//# sourceMappingURL=object-assign.js.map

View File

@@ -0,0 +1,4 @@
// noop
"use strict";
//# sourceMappingURL=auto.js.map

View File

@@ -0,0 +1,4 @@
"use strict";
module.exports = Object.assign;
//# sourceMappingURL=implementation.js.map

View File

@@ -0,0 +1,6 @@
"use strict";
module.exports = function() {
return Object.assign;
};
//# sourceMappingURL=polyfill.js.map

View File

@@ -0,0 +1,6 @@
"use strict";
module.exports = function() {
return Object.assign;
};
//# sourceMappingURL=shim.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
"use strict";
var _global_process, _global_process1;
module.exports = ((_global_process = global.process) == null ? void 0 : _global_process.env) && typeof ((_global_process1 = global.process) == null ? void 0 : _global_process1.env) === "object" ? global.process : require("next/dist/compiled/process");
//# sourceMappingURL=process.js.map

View File

@@ -0,0 +1,964 @@
/* eslint-disable @typescript-eslint/no-use-before-define */ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createDefineEnv: null,
getBinaryMetadata: null,
getSupportedArchTriples: null,
initCustomTraceSubscriber: null,
initHeapProfiler: null,
isWasm: null,
loadBindings: null,
lockfilePatchPromise: null,
minify: null,
minifySync: null,
parse: null,
teardownHeapProfiler: null,
teardownTraceSubscriber: null,
transform: null,
transformSync: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createDefineEnv: function() {
return createDefineEnv;
},
getBinaryMetadata: function() {
return getBinaryMetadata;
},
getSupportedArchTriples: function() {
return getSupportedArchTriples;
},
initCustomTraceSubscriber: function() {
return initCustomTraceSubscriber;
},
initHeapProfiler: function() {
return initHeapProfiler;
},
isWasm: function() {
return isWasm;
},
loadBindings: function() {
return loadBindings;
},
lockfilePatchPromise: function() {
return lockfilePatchPromise;
},
minify: function() {
return minify;
},
minifySync: function() {
return minifySync;
},
parse: function() {
return parse;
},
teardownHeapProfiler: function() {
return teardownHeapProfiler;
},
teardownTraceSubscriber: function() {
return teardownTraceSubscriber;
},
transform: function() {
return transform;
},
transformSync: function() {
return transformSync;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _url = require("url");
const _os = require("os");
const _triples = require("next/dist/compiled/@napi-rs/triples");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../output/log"));
const _options = require("./options");
const _swcloadfailure = require("../../telemetry/events/swc-load-failure");
const _patchincorrectlockfile = require("../../lib/patch-incorrect-lockfile");
const _downloadswc = require("../../lib/download-swc");
const _util = require("util");
const _defineenvplugin = require("../webpack/plugins/define-env-plugin");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const nextVersion = "14.2.5";
const ArchName = (0, _os.arch)();
const PlatformName = (0, _os.platform)();
const infoLog = (...args)=>{
if (process.env.NEXT_PRIVATE_BUILD_WORKER) {
return;
}
if (process.env.DEBUG) {
_log.info(...args);
}
};
const getSupportedArchTriples = ()=>{
const { darwin, win32, linux, freebsd, android } = _triples.platformArchTriples;
return {
darwin,
win32: {
arm64: win32.arm64,
ia32: win32.ia32.filter((triple)=>triple.abi === "msvc"),
x64: win32.x64.filter((triple)=>triple.abi === "msvc")
},
linux: {
// linux[x64] includes `gnux32` abi, with x64 arch.
x64: linux.x64.filter((triple)=>triple.abi !== "gnux32"),
arm64: linux.arm64,
// This target is being deprecated, however we keep it in `knownDefaultWasmFallbackTriples` for now
arm: linux.arm
},
// Below targets are being deprecated, however we keep it in `knownDefaultWasmFallbackTriples` for now
freebsd: {
x64: freebsd.x64
},
android: {
arm64: android.arm64,
arm: android.arm
}
};
};
const triples = (()=>{
var _supportedArchTriples_PlatformName, _platformArchTriples_PlatformName;
const supportedArchTriples = getSupportedArchTriples();
const targetTriple = (_supportedArchTriples_PlatformName = supportedArchTriples[PlatformName]) == null ? void 0 : _supportedArchTriples_PlatformName[ArchName];
// If we have supported triple, return it right away
if (targetTriple) {
return targetTriple;
}
// If there isn't corresponding target triple in `supportedArchTriples`, check if it's excluded from original raw triples
// Otherwise, it is completely unsupported platforms.
let rawTargetTriple = (_platformArchTriples_PlatformName = _triples.platformArchTriples[PlatformName]) == null ? void 0 : _platformArchTriples_PlatformName[ArchName];
if (rawTargetTriple) {
_log.warn(`Trying to load next-swc for target triple ${rawTargetTriple}, but there next-swc does not have native bindings support`);
} else {
_log.warn(`Trying to load next-swc for unsupported platforms ${PlatformName}/${ArchName}`);
}
return [];
})();
// Allow to specify an absolute path to the custom turbopack binary to load.
// If one of env variables is set, `loadNative` will try to use any turbo-* interfaces from specified
// binary instead. This will not affect existing swc's transform, or other interfaces. This is thin,
// naive interface - `loadBindings` will not validate neither path nor the binary.
//
// Note these are internal flag: there's no stability, feature guarantee.
const __INTERNAL_CUSTOM_TURBOPACK_BINDINGS = process.env.__INTERNAL_CUSTOM_TURBOPACK_BINDINGS;
function checkVersionMismatch(pkgData) {
const version = pkgData.version;
if (version && version !== nextVersion) {
_log.warn(`Mismatching @next/swc version, detected: ${version} while Next.js is on ${nextVersion}. Please ensure these match`);
}
}
// These are the platforms we'll try to load wasm bindings first,
// only try to load native bindings if loading wasm binding somehow fails.
// Fallback to native binding is for migration period only,
// once we can verify loading-wasm-first won't cause visible regressions,
// we'll not include native bindings for these platform at all.
const knownDefaultWasmFallbackTriples = [
"x86_64-unknown-freebsd",
"aarch64-linux-android",
"arm-linux-androideabi",
"armv7-unknown-linux-gnueabihf",
"i686-pc-windows-msvc"
];
// The last attempt's error code returned when cjs require to native bindings fails.
// If node.js throws an error without error code, this should be `unknown` instead of undefined.
// For the wasm-first targets (`knownDefaultWasmFallbackTriples`) this will be `unsupported_target`.
let lastNativeBindingsLoadErrorCode = undefined;
let nativeBindings;
let wasmBindings;
let downloadWasmPromise;
let pendingBindings;
let swcTraceFlushGuard;
let swcHeapProfilerFlushGuard;
let downloadNativeBindingsPromise = undefined;
const lockfilePatchPromise = {};
async function loadBindings(useWasmBinary = false) {
// Increase Rust stack size as some npm packages being compiled need more than the default.
if (!process.env.RUST_MIN_STACK) {
process.env.RUST_MIN_STACK = "8388608";
}
if (pendingBindings) {
return pendingBindings;
}
// rust needs stdout to be blocking, otherwise it will throw an error (on macOS at least) when writing a lot of data (logs) to it
// see https://github.com/napi-rs/napi-rs/issues/1630
// and https://github.com/nodejs/node/blob/main/doc/api/process.md#a-note-on-process-io
if (process.stdout._handle != null) {
// @ts-ignore
process.stdout._handle.setBlocking == null ? void 0 : process.stdout._handle.setBlocking.call(process.stdout._handle, true);
}
if (process.stderr._handle != null) {
// @ts-ignore
process.stderr._handle.setBlocking == null ? void 0 : process.stderr._handle.setBlocking.call(process.stderr._handle, true);
}
pendingBindings = new Promise(async (resolve, _reject)=>{
if (!lockfilePatchPromise.cur) {
// always run lockfile check once so that it gets patched
// even if it doesn't fail to load locally
lockfilePatchPromise.cur = (0, _patchincorrectlockfile.patchIncorrectLockfile)(process.cwd()).catch(console.error);
}
let attempts = [];
const disableWasmFallback = process.env.NEXT_DISABLE_SWC_WASM;
const unsupportedPlatform = triples.some((triple)=>!!(triple == null ? void 0 : triple.raw) && knownDefaultWasmFallbackTriples.includes(triple.raw));
const isWebContainer = process.versions.webcontainer;
const shouldLoadWasmFallbackFirst = !disableWasmFallback && unsupportedPlatform && useWasmBinary || isWebContainer;
if (!unsupportedPlatform && useWasmBinary) {
_log.warn(`experimental.useWasmBinary is not an option for supported platform ${PlatformName}/${ArchName} and will be ignored.`);
}
if (shouldLoadWasmFallbackFirst) {
lastNativeBindingsLoadErrorCode = "unsupported_target";
const fallbackBindings = await tryLoadWasmWithFallback(attempts);
if (fallbackBindings) {
return resolve(fallbackBindings);
}
}
// Trickle down loading `fallback` bindings:
//
// - First, try to load native bindings installed in node_modules.
// - If that fails with `ERR_MODULE_NOT_FOUND`, treat it as case of https://github.com/npm/cli/issues/4828
// that host system where generated package lock is not matching to the guest system running on, try to manually
// download corresponding target triple and load it. This won't be triggered if native bindings are failed to load
// with other reasons than `ERR_MODULE_NOT_FOUND`.
// - Lastly, falls back to wasm binding where possible.
try {
return resolve(loadNative());
} catch (a) {
if (Array.isArray(a) && a.every((m)=>m.includes("it was not installed"))) {
let fallbackBindings = await tryLoadNativeWithFallback(attempts);
if (fallbackBindings) {
return resolve(fallbackBindings);
}
}
attempts = attempts.concat(a);
}
logLoadFailure(attempts, true);
});
return pendingBindings;
}
async function tryLoadNativeWithFallback(attempts) {
const nativeBindingsDirectory = _path.default.join(_path.default.dirname(require.resolve("next/package.json")), "next-swc-fallback");
if (!downloadNativeBindingsPromise) {
downloadNativeBindingsPromise = (0, _downloadswc.downloadNativeNextSwc)(nextVersion, nativeBindingsDirectory, triples.map((triple)=>triple.platformArchABI));
}
await downloadNativeBindingsPromise;
try {
let bindings = loadNative(nativeBindingsDirectory);
return bindings;
} catch (a) {
attempts.concat(a);
}
return undefined;
}
async function tryLoadWasmWithFallback(attempts) {
try {
let bindings = await loadWasm("");
// @ts-expect-error TODO: this event has a wrong type.
(0, _swcloadfailure.eventSwcLoadFailure)({
wasm: "enabled",
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode
});
return bindings;
} catch (a) {
attempts = attempts.concat(a);
}
try {
// if not installed already download wasm package on-demand
// we download to a custom directory instead of to node_modules
// as node_module import attempts are cached and can't be re-attempted
// x-ref: https://github.com/nodejs/modules/issues/307
const wasmDirectory = _path.default.join(_path.default.dirname(require.resolve("next/package.json")), "wasm");
if (!downloadWasmPromise) {
downloadWasmPromise = (0, _downloadswc.downloadWasmSwc)(nextVersion, wasmDirectory);
}
await downloadWasmPromise;
let bindings = await loadWasm(wasmDirectory);
// @ts-expect-error TODO: this event has a wrong type.
(0, _swcloadfailure.eventSwcLoadFailure)({
wasm: "fallback",
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode
});
// still log native load attempts so user is
// aware it failed and should be fixed
for (const attempt of attempts){
_log.warn(attempt);
}
return bindings;
} catch (a) {
attempts = attempts.concat(a);
}
}
function loadBindingsSync() {
let attempts = [];
try {
return loadNative();
} catch (a) {
attempts = attempts.concat(a);
}
// we can leverage the wasm bindings if they are already
// loaded
if (wasmBindings) {
return wasmBindings;
}
logLoadFailure(attempts);
}
let loggingLoadFailure = false;
function logLoadFailure(attempts, triedWasm = false) {
// make sure we only emit the event and log the failure once
if (loggingLoadFailure) return;
loggingLoadFailure = true;
for (let attempt of attempts){
_log.warn(attempt);
}
// @ts-expect-error TODO: this event has a wrong type.
(0, _swcloadfailure.eventSwcLoadFailure)({
wasm: triedWasm ? "failed" : undefined,
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode
}).then(()=>lockfilePatchPromise.cur || Promise.resolve()).finally(()=>{
_log.error(`Failed to load SWC binary for ${PlatformName}/${ArchName}, see more info here: https://nextjs.org/docs/messages/failed-loading-swc`);
process.exit(1);
});
}
function createDefineEnv({ isTurbopack, clientRouterFilters, config, dev, distDir, fetchCacheKeyPrefix, hasRewrites, middlewareMatchers }) {
let defineEnv = {
client: [],
edge: [],
nodejs: []
};
for (const variant of Object.keys(defineEnv)){
defineEnv[variant] = rustifyEnv((0, _defineenvplugin.getDefineEnv)({
isTurbopack,
clientRouterFilters,
config,
dev,
distDir,
fetchCacheKeyPrefix,
hasRewrites,
isClient: variant === "client",
isEdgeServer: variant === "edge",
isNodeOrEdgeCompilation: variant === "nodejs" || variant === "edge",
isNodeServer: variant === "nodejs",
middlewareMatchers
}));
}
return defineEnv;
}
function rustifyEnv(env) {
return Object.entries(env).filter(([_, value])=>value != null).map(([name, value])=>({
name,
value
}));
}
// TODO(sokra) Support wasm option.
function bindingToApi(binding, _wasm) {
const cancel = new class Cancel extends Error {
}();
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
async function withErrorCause(fn) {
try {
return await fn();
} catch (nativeError) {
throw new Error(nativeError.message, {
cause: nativeError
});
}
}
/**
* Calls a native function and streams the result.
* If useBuffer is true, all values will be preserved, potentially buffered
* if consumed slower than produced. Else, only the latest value will be
* preserved.
*/ function subscribe(useBuffer, nativeFunction) {
// A buffer of produced items. This will only contain values if the
// consumer is slower than the producer.
let buffer = [];
// A deferred value waiting for the next produced item. This will only
// exist if the consumer is faster than the producer.
let waiting;
let canceled = false;
// The native function will call this every time it emits a new result. We
// either need to notify a waiting consumer, or buffer the new result until
// the consumer catches up.
const emitResult = (err, value)=>{
if (waiting) {
let { resolve, reject } = waiting;
waiting = undefined;
if (err) reject(err);
else resolve(value);
} else {
const item = {
err,
value
};
if (useBuffer) buffer.push(item);
else buffer[0] = item;
}
};
const iterator = async function*() {
const task = await withErrorCause(()=>nativeFunction(emitResult));
try {
while(!canceled){
if (buffer.length > 0) {
const item = buffer.shift();
if (item.err) throw item.err;
yield item.value;
} else {
// eslint-disable-next-line no-loop-func
yield new Promise((resolve, reject)=>{
waiting = {
resolve,
reject
};
});
}
}
} catch (e) {
if (e === cancel) return;
throw e;
} finally{
binding.rootTaskDispose(task);
}
}();
iterator.return = async ()=>{
canceled = true;
if (waiting) waiting.reject(cancel);
return {
value: undefined,
done: true
};
};
return iterator;
}
async function rustifyProjectOptions(options) {
return {
...options,
nextConfig: options.nextConfig && await serializeNextConfig(options.nextConfig, options.projectPath),
jsConfig: options.jsConfig && JSON.stringify(options.jsConfig),
env: options.env && rustifyEnv(options.env),
defineEnv: options.defineEnv
};
}
class ProjectImpl {
constructor(nativeProject){
this._nativeProject = nativeProject;
}
async update(options) {
await withErrorCause(async ()=>binding.projectUpdate(this._nativeProject, await rustifyProjectOptions(options)));
}
entrypointsSubscribe() {
const subscription = subscribe(false, async (callback)=>binding.projectEntrypointsSubscribe(this._nativeProject, callback));
return async function*() {
for await (const entrypoints of subscription){
const routes = new Map();
for (const { pathname, ...nativeRoute } of entrypoints.routes){
let route;
const routeType = nativeRoute.type;
switch(routeType){
case "page":
route = {
type: "page",
htmlEndpoint: new EndpointImpl(nativeRoute.htmlEndpoint),
dataEndpoint: new EndpointImpl(nativeRoute.dataEndpoint)
};
break;
case "page-api":
route = {
type: "page-api",
endpoint: new EndpointImpl(nativeRoute.endpoint)
};
break;
case "app-page":
route = {
type: "app-page",
pages: nativeRoute.pages.map((page)=>({
originalName: page.originalName,
htmlEndpoint: new EndpointImpl(page.htmlEndpoint),
rscEndpoint: new EndpointImpl(page.rscEndpoint)
}))
};
break;
case "app-route":
route = {
type: "app-route",
originalName: nativeRoute.originalName,
endpoint: new EndpointImpl(nativeRoute.endpoint)
};
break;
case "conflict":
route = {
type: "conflict"
};
break;
default:
const _exhaustiveCheck = routeType;
invariant(nativeRoute, ()=>`Unknown route type: ${_exhaustiveCheck}`);
}
routes.set(pathname, route);
}
const napiMiddlewareToMiddleware = (middleware)=>({
endpoint: new EndpointImpl(middleware.endpoint),
runtime: middleware.runtime,
matcher: middleware.matcher
});
const middleware = entrypoints.middleware ? napiMiddlewareToMiddleware(entrypoints.middleware) : undefined;
const napiInstrumentationToInstrumentation = (instrumentation)=>({
nodeJs: new EndpointImpl(instrumentation.nodeJs),
edge: new EndpointImpl(instrumentation.edge)
});
const instrumentation = entrypoints.instrumentation ? napiInstrumentationToInstrumentation(entrypoints.instrumentation) : undefined;
yield {
routes,
middleware,
instrumentation,
pagesDocumentEndpoint: new EndpointImpl(entrypoints.pagesDocumentEndpoint),
pagesAppEndpoint: new EndpointImpl(entrypoints.pagesAppEndpoint),
pagesErrorEndpoint: new EndpointImpl(entrypoints.pagesErrorEndpoint),
issues: entrypoints.issues,
diagnostics: entrypoints.diagnostics
};
}
}();
}
hmrEvents(identifier) {
return subscribe(true, async (callback)=>binding.projectHmrEvents(this._nativeProject, identifier, callback));
}
hmrIdentifiersSubscribe() {
return subscribe(false, async (callback)=>binding.projectHmrIdentifiersSubscribe(this._nativeProject, callback));
}
traceSource(stackFrame) {
return binding.projectTraceSource(this._nativeProject, stackFrame);
}
getSourceForAsset(filePath) {
return binding.projectGetSourceForAsset(this._nativeProject, filePath);
}
updateInfoSubscribe(aggregationMs) {
const subscription = subscribe(true, async (callback)=>binding.projectUpdateInfoSubscribe(this._nativeProject, aggregationMs, callback));
return subscription;
}
}
class EndpointImpl {
constructor(nativeEndpoint){
this._nativeEndpoint = nativeEndpoint;
}
async writeToDisk() {
return await withErrorCause(()=>binding.endpointWriteToDisk(this._nativeEndpoint));
}
async clientChanged() {
const clientSubscription = subscribe(false, async (callback)=>binding.endpointClientChangedSubscribe(await this._nativeEndpoint, callback));
await clientSubscription.next();
return clientSubscription;
}
async serverChanged(includeIssues) {
const serverSubscription = subscribe(false, async (callback)=>binding.endpointServerChangedSubscribe(await this._nativeEndpoint, includeIssues, callback));
await serverSubscription.next();
return serverSubscription;
}
}
async function serializeNextConfig(nextConfig, projectPath) {
var _nextConfig_experimental_turbo, _nextConfig_experimental;
// Avoid mutating the existing `nextConfig` object.
let nextConfigSerializable = {
...nextConfig
};
nextConfigSerializable.generateBuildId = await (nextConfig.generateBuildId == null ? void 0 : nextConfig.generateBuildId.call(nextConfig));
// TODO: these functions takes arguments, have to be supported in a different way
nextConfigSerializable.exportPathMap = {};
nextConfigSerializable.webpack = nextConfig.webpack && {};
if ((_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : (_nextConfig_experimental_turbo = _nextConfig_experimental.turbo) == null ? void 0 : _nextConfig_experimental_turbo.rules) {
var _nextConfig_experimental_turbo1;
ensureLoadersHaveSerializableOptions((_nextConfig_experimental_turbo1 = nextConfig.experimental.turbo) == null ? void 0 : _nextConfig_experimental_turbo1.rules);
}
nextConfigSerializable.modularizeImports = nextConfigSerializable.modularizeImports ? Object.fromEntries(Object.entries(nextConfigSerializable.modularizeImports).map(([mod, config])=>[
mod,
{
...config,
transform: typeof config.transform === "string" ? config.transform : Object.entries(config.transform).map(([key, value])=>[
key,
value
])
}
])) : undefined;
// loaderFile is an absolute path, we need it to be relative for turbopack.
if (nextConfigSerializable.images.loaderFile) {
nextConfigSerializable.images = {
...nextConfig.images,
loaderFile: "./" + _path.default.relative(projectPath, nextConfig.images.loaderFile)
};
}
return JSON.stringify(nextConfigSerializable, null, 2);
}
function ensureLoadersHaveSerializableOptions(turbopackRules) {
for (const [glob, rule] of Object.entries(turbopackRules)){
if (Array.isArray(rule)) {
checkLoaderItems(rule, glob);
} else {
checkConfigItem(rule, glob);
}
}
function checkConfigItem(rule, glob) {
if (!rule) return;
if ("loaders" in rule) {
checkLoaderItems(rule.loaders, glob);
} else {
for(const key in rule){
const inner = rule[key];
if (typeof inner === "object" && inner) {
checkConfigItem(inner, glob);
}
}
}
}
function checkLoaderItems(loaderItems, glob) {
for (const loaderItem of loaderItems){
if (typeof loaderItem !== "string" && !(0, _util.isDeepStrictEqual)(loaderItem, JSON.parse(JSON.stringify(loaderItem)))) {
throw new Error(`loader ${loaderItem.loader} for match "${glob}" does not have serializable options. Ensure that options passed are plain JavaScript objects and values.`);
}
}
}
}
async function createProject(options, turboEngineOptions) {
return new ProjectImpl(await binding.projectNew(await rustifyProjectOptions(options), turboEngineOptions || {}));
}
return createProject;
}
async function loadWasm(importPath = "") {
if (wasmBindings) {
return wasmBindings;
}
let attempts = [];
for (let pkg of [
"@next/swc-wasm-nodejs",
"@next/swc-wasm-web"
]){
try {
let pkgPath = pkg;
if (importPath) {
// the import path must be exact when not in node_modules
pkgPath = _path.default.join(importPath, pkg, "wasm.js");
}
let bindings = await import((0, _url.pathToFileURL)(pkgPath).toString());
if (pkg === "@next/swc-wasm-web") {
bindings = await bindings.default();
}
infoLog("next-swc build: wasm build @next/swc-wasm-web");
// Note wasm binary does not support async intefaces yet, all async
// interface coereces to sync interfaces.
wasmBindings = {
isWasm: true,
transform (src, options) {
// TODO: we can remove fallback to sync interface once new stable version of next-swc gets published (current v12.2)
return (bindings == null ? void 0 : bindings.transform) ? bindings.transform(src.toString(), options) : Promise.resolve(bindings.transformSync(src.toString(), options));
},
transformSync (src, options) {
return bindings.transformSync(src.toString(), options);
},
minify (src, options) {
return (bindings == null ? void 0 : bindings.minify) ? bindings.minify(src.toString(), options) : Promise.resolve(bindings.minifySync(src.toString(), options));
},
minifySync (src, options) {
return bindings.minifySync(src.toString(), options);
},
parse (src, options) {
return (bindings == null ? void 0 : bindings.parse) ? bindings.parse(src.toString(), options) : Promise.resolve(bindings.parseSync(src.toString(), options));
},
parseSync (src, options) {
return bindings.parseSync(src.toString(), options);
},
getTargetTriple () {
return undefined;
},
turbo: {
startTrace: ()=>{
_log.error("Wasm binding does not support trace yet");
},
entrypoints: {
stream: (turboTasks, rootDir, applicationDir, pageExtensions, callbackFn)=>{
return bindings.streamEntrypoints(turboTasks, rootDir, applicationDir, pageExtensions, callbackFn);
},
get: (turboTasks, rootDir, applicationDir, pageExtensions)=>{
return bindings.getEntrypoints(turboTasks, rootDir, applicationDir, pageExtensions);
}
}
},
mdx: {
compile: (src, options)=>bindings.mdxCompile(src, getMdxOptions(options)),
compileSync: (src, options)=>bindings.mdxCompileSync(src, getMdxOptions(options))
}
};
return wasmBindings;
} catch (e) {
// Only log attempts for loading wasm when loading as fallback
if (importPath) {
if ((e == null ? void 0 : e.code) === "ERR_MODULE_NOT_FOUND") {
attempts.push(`Attempted to load ${pkg}, but it was not installed`);
} else {
attempts.push(`Attempted to load ${pkg}, but an error occurred: ${e.message ?? e}`);
}
}
}
}
throw attempts;
}
function loadNative(importPath) {
if (nativeBindings) {
return nativeBindings;
}
const customBindings = !!__INTERNAL_CUSTOM_TURBOPACK_BINDINGS ? require(__INTERNAL_CUSTOM_TURBOPACK_BINDINGS) : null;
let bindings;
let attempts = [];
for (const triple of triples){
try {
bindings = require(`@next/swc/native/next-swc.${triple.platformArchABI}.node`);
infoLog("next-swc build: local built @next/swc");
break;
} catch (e) {}
}
if (!bindings) {
for (const triple of triples){
let pkg = importPath ? _path.default.join(importPath, `@next/swc-${triple.platformArchABI}`, `next-swc.${triple.platformArchABI}.node`) : `@next/swc-${triple.platformArchABI}`;
try {
bindings = require(pkg);
if (!importPath) {
checkVersionMismatch(require(`${pkg}/package.json`));
}
break;
} catch (e) {
if ((e == null ? void 0 : e.code) === "MODULE_NOT_FOUND") {
attempts.push(`Attempted to load ${pkg}, but it was not installed`);
} else {
attempts.push(`Attempted to load ${pkg}, but an error occurred: ${e.message ?? e}`);
}
lastNativeBindingsLoadErrorCode = (e == null ? void 0 : e.code) ?? "unknown";
}
}
}
if (bindings) {
nativeBindings = {
isWasm: false,
transform (src, options) {
var _options_jsc;
const isModule = typeof src !== "undefined" && typeof src !== "string" && !Buffer.isBuffer(src);
options = options || {};
if (options == null ? void 0 : (_options_jsc = options.jsc) == null ? void 0 : _options_jsc.parser) {
options.jsc.parser.syntax = options.jsc.parser.syntax ?? "ecmascript";
}
return bindings.transform(isModule ? JSON.stringify(src) : src, isModule, toBuffer(options));
},
transformSync (src, options) {
var _options_jsc;
if (typeof src === "undefined") {
throw new Error("transformSync doesn't implement reading the file from filesystem");
} else if (Buffer.isBuffer(src)) {
throw new Error("transformSync doesn't implement taking the source code as Buffer");
}
const isModule = typeof src !== "string";
options = options || {};
if (options == null ? void 0 : (_options_jsc = options.jsc) == null ? void 0 : _options_jsc.parser) {
options.jsc.parser.syntax = options.jsc.parser.syntax ?? "ecmascript";
}
return bindings.transformSync(isModule ? JSON.stringify(src) : src, isModule, toBuffer(options));
},
minify (src, options) {
return bindings.minify(toBuffer(src), toBuffer(options ?? {}));
},
minifySync (src, options) {
return bindings.minifySync(toBuffer(src), toBuffer(options ?? {}));
},
parse (src, options) {
return bindings.parse(src, toBuffer(options ?? {}));
},
getTargetTriple: bindings.getTargetTriple,
initCustomTraceSubscriber: bindings.initCustomTraceSubscriber,
teardownTraceSubscriber: bindings.teardownTraceSubscriber,
initHeapProfiler: bindings.initHeapProfiler,
teardownHeapProfiler: bindings.teardownHeapProfiler,
turbo: {
startTrace: (options = {}, turboTasks)=>{
initHeapProfiler();
return (customBindings ?? bindings).runTurboTracing(toBuffer({
exact: true,
...options
}), turboTasks);
},
createTurboTasks: (memoryLimit)=>bindings.createTurboTasks(memoryLimit),
entrypoints: {
stream: (turboTasks, rootDir, applicationDir, pageExtensions, fn)=>{
return (customBindings ?? bindings).streamEntrypoints(turboTasks, rootDir, applicationDir, pageExtensions, fn);
},
get: (turboTasks, rootDir, applicationDir, pageExtensions)=>{
return (customBindings ?? bindings).getEntrypoints(turboTasks, rootDir, applicationDir, pageExtensions);
}
},
createProject: bindingToApi(customBindings ?? bindings, false)
},
mdx: {
compile: (src, options)=>bindings.mdxCompile(src, toBuffer(getMdxOptions(options))),
compileSync: (src, options)=>bindings.mdxCompileSync(src, toBuffer(getMdxOptions(options)))
},
css: {
lightning: {
transform: (transformOptions)=>bindings.lightningCssTransform(transformOptions),
transformStyleAttr: (transformAttrOptions)=>bindings.lightningCssTransformStyleAttribute(transformAttrOptions)
}
}
};
return nativeBindings;
}
throw attempts;
}
/// Build a mdx options object contains default values that
/// can be parsed with serde_wasm_bindgen.
function getMdxOptions(options = {}) {
return {
...options,
development: options.development ?? false,
jsx: options.jsx ?? false,
parse: options.parse ?? {
gfmStrikethroughSingleTilde: true,
mathTextSingleDollar: true
}
};
}
function toBuffer(t) {
return Buffer.from(JSON.stringify(t));
}
async function isWasm() {
let bindings = await loadBindings();
return bindings.isWasm;
}
async function transform(src, options) {
let bindings = await loadBindings();
return bindings.transform(src, options);
}
function transformSync(src, options) {
let bindings = loadBindingsSync();
return bindings.transformSync(src, options);
}
async function minify(src, options) {
let bindings = await loadBindings();
return bindings.minify(src, options);
}
function minifySync(src, options) {
let bindings = loadBindingsSync();
return bindings.minifySync(src, options);
}
async function parse(src, options) {
let bindings = await loadBindings();
let parserOptions = (0, _options.getParserOptions)(options);
return bindings.parse(src, parserOptions).then((astStr)=>JSON.parse(astStr));
}
function getBinaryMetadata() {
var _bindings_getTargetTriple;
let bindings;
try {
bindings = loadNative();
} catch (e) {
// Suppress exceptions, this fn allows to fail to load native bindings
}
return {
target: bindings == null ? void 0 : (_bindings_getTargetTriple = bindings.getTargetTriple) == null ? void 0 : _bindings_getTargetTriple.call(bindings)
};
}
const initCustomTraceSubscriber = (traceFileName)=>{
if (!swcTraceFlushGuard) {
// Wasm binary doesn't support trace emission
let bindings = loadNative();
swcTraceFlushGuard = bindings.initCustomTraceSubscriber(traceFileName);
}
};
const initHeapProfiler = ()=>{
try {
if (!swcHeapProfilerFlushGuard) {
let bindings = loadNative();
swcHeapProfilerFlushGuard = bindings.initHeapProfiler();
}
} catch (_) {
// Suppress exceptions, this fn allows to fail to load native bindings
}
};
const teardownHeapProfiler = (()=>{
let flushed = false;
return ()=>{
if (!flushed) {
flushed = true;
try {
let bindings = loadNative();
if (swcHeapProfilerFlushGuard) {
bindings.teardownHeapProfiler(swcHeapProfilerFlushGuard);
}
} catch (e) {
// Suppress exceptions, this fn allows to fail to load native bindings
}
}
};
})();
const teardownTraceSubscriber = (()=>{
let flushed = false;
return ()=>{
if (!flushed) {
flushed = true;
try {
let bindings = loadNative();
if (swcTraceFlushGuard) {
bindings.teardownTraceSubscriber(swcTraceFlushGuard);
}
} catch (e) {
// Suppress exceptions, this fn allows to fail to load native bindings
}
}
};
})();
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,356 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getJestSWCOptions: null,
getLoaderSWCOptions: null,
getParserOptions: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getJestSWCOptions: function() {
return getJestSWCOptions;
},
getLoaderSWCOptions: function() {
return getLoaderSWCOptions;
},
getParserOptions: function() {
return getParserOptions;
}
});
const _constants = require("../../lib/constants");
const nextDistPath = /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/;
const nodeModulesPath = /[\\/]node_modules[\\/]/;
const regeneratorRuntimePath = require.resolve("next/dist/compiled/regenerator-runtime");
function isTypeScriptFile(filename) {
return filename.endsWith(".ts") || filename.endsWith(".tsx");
}
function isCommonJSFile(filename) {
return filename.endsWith(".cjs");
}
// Ensure Next.js internals and .cjs files are output as CJS modules,
// By default all modules are output as ESM or will treated as CJS if next-swc/auto-cjs plugin detects file is CJS.
function shouldOutputCommonJs(filename) {
return isCommonJSFile(filename) || nextDistPath.test(filename);
}
function getParserOptions({ filename, jsConfig, ...rest }) {
var _jsConfig_compilerOptions;
const isTSFile = filename.endsWith(".ts");
const hasTsSyntax = isTypeScriptFile(filename);
const enableDecorators = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.experimentalDecorators);
return {
...rest,
syntax: hasTsSyntax ? "typescript" : "ecmascript",
dynamicImport: true,
decorators: enableDecorators,
// Exclude regular TypeScript files from React transformation to prevent e.g. generic parameters and angle-bracket type assertion from being interpreted as JSX tags.
[hasTsSyntax ? "tsx" : "jsx"]: !isTSFile,
importAssertions: true
};
}
function getBaseSWCOptions({ filename, jest, development, hasReactRefresh, globalWindow, esm, modularizeImports, swcPlugins, compilerOptions, resolvedBaseUrl, jsConfig, swcCacheDir, serverComponents, bundleLayer }) {
var _jsConfig_compilerOptions, _jsConfig_compilerOptions1, _jsConfig_compilerOptions2, _jsConfig_compilerOptions3, _jsConfig_compilerOptions4;
const isReactServerLayer = bundleLayer === _constants.WEBPACK_LAYERS.reactServerComponents;
const parserConfig = getParserOptions({
filename,
jsConfig
});
const paths = jsConfig == null ? void 0 : (_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.paths;
const enableDecorators = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions1 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions1.experimentalDecorators);
const emitDecoratorMetadata = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions2 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions2.emitDecoratorMetadata);
const useDefineForClassFields = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions3 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions3.useDefineForClassFields);
const plugins = (swcPlugins ?? []).filter(Array.isArray).map(([name, options])=>[
require.resolve(name),
options
]);
return {
jsc: {
...resolvedBaseUrl && paths ? {
baseUrl: resolvedBaseUrl.baseUrl,
paths
} : {},
externalHelpers: !process.versions.pnp && !jest,
parser: parserConfig,
experimental: {
keepImportAttributes: true,
emitAssertForImportAttributes: true,
plugins,
cacheRoot: swcCacheDir
},
transform: {
// Enables https://github.com/swc-project/swc/blob/0359deb4841be743d73db4536d4a22ac797d7f65/crates/swc_ecma_ext_transforms/src/jest.rs
...jest ? {
hidden: {
jest: true
}
} : {},
legacyDecorator: enableDecorators,
decoratorMetadata: emitDecoratorMetadata,
useDefineForClassFields: useDefineForClassFields,
react: {
importSource: (jsConfig == null ? void 0 : (_jsConfig_compilerOptions4 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions4.jsxImportSource) ?? ((compilerOptions == null ? void 0 : compilerOptions.emotion) && !isReactServerLayer ? "@emotion/react" : "react"),
runtime: "automatic",
pragmaFrag: "React.Fragment",
throwIfNamespace: true,
development: !!development,
useBuiltins: true,
refresh: !!hasReactRefresh
},
optimizer: {
simplify: false,
globals: jest ? null : {
typeofs: {
window: globalWindow ? "object" : "undefined"
},
envs: {
NODE_ENV: development ? '"development"' : '"production"'
}
}
},
regenerator: {
importPath: regeneratorRuntimePath
}
}
},
sourceMaps: jest ? "inline" : undefined,
removeConsole: compilerOptions == null ? void 0 : compilerOptions.removeConsole,
// disable "reactRemoveProperties" when "jest" is true
// otherwise the setting from next.config.js will be used
reactRemoveProperties: jest ? false : compilerOptions == null ? void 0 : compilerOptions.reactRemoveProperties,
// Map the k-v map to an array of pairs.
modularizeImports: modularizeImports ? Object.fromEntries(Object.entries(modularizeImports).map(([mod, config])=>[
mod,
{
...config,
transform: typeof config.transform === "string" ? config.transform : Object.entries(config.transform).map(([key, value])=>[
key,
value
])
}
])) : undefined,
relay: compilerOptions == null ? void 0 : compilerOptions.relay,
// Always transform styled-jsx and error when `client-only` condition is triggered
styledJsx: {},
// Disable css-in-js libs (without client-only integration) transform on server layer for server components
...!isReactServerLayer && {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
emotion: getEmotionOptions(compilerOptions == null ? void 0 : compilerOptions.emotion, development),
// eslint-disable-next-line @typescript-eslint/no-use-before-define
styledComponents: getStyledComponentsOptions(compilerOptions == null ? void 0 : compilerOptions.styledComponents, development)
},
serverComponents: serverComponents && !jest ? {
isReactServerLayer
} : undefined,
serverActions: serverComponents && !jest ? {
// always enable server actions
// TODO: remove this option
enabled: true,
isReactServerLayer
} : undefined,
// For app router we prefer to bundle ESM,
// On server side of pages router we prefer CJS.
preferEsm: esm
};
}
function getStyledComponentsOptions(styledComponentsConfig, development) {
if (!styledComponentsConfig) {
return null;
} else if (typeof styledComponentsConfig === "object") {
return {
...styledComponentsConfig,
displayName: styledComponentsConfig.displayName ?? Boolean(development)
};
} else {
return {
displayName: Boolean(development)
};
}
}
function getEmotionOptions(emotionConfig, development) {
if (!emotionConfig) {
return null;
}
let autoLabel = !!development;
switch(typeof emotionConfig === "object" && emotionConfig.autoLabel){
case "never":
autoLabel = false;
break;
case "always":
autoLabel = true;
break;
case "dev-only":
default:
break;
}
return {
enabled: true,
autoLabel,
sourcemap: development,
...typeof emotionConfig === "object" && {
importMap: emotionConfig.importMap,
labelFormat: emotionConfig.labelFormat,
sourcemap: development && emotionConfig.sourceMap
}
};
}
function getJestSWCOptions({ isServer, filename, esm, modularizeImports, swcPlugins, compilerOptions, jsConfig, resolvedBaseUrl, pagesDir }) {
let baseOptions = getBaseSWCOptions({
filename,
jest: true,
development: false,
hasReactRefresh: false,
globalWindow: !isServer,
modularizeImports,
swcPlugins,
compilerOptions,
jsConfig,
resolvedBaseUrl,
esm,
// Don't apply server layer transformations for Jest
// Disable server / client graph assertions for Jest
bundleLayer: undefined,
serverComponents: false
});
const useCjsModules = shouldOutputCommonJs(filename);
return {
...baseOptions,
env: {
targets: {
// Targets the current version of Node.js
node: process.versions.node
}
},
module: {
type: esm && !useCjsModules ? "es6" : "commonjs"
},
disableNextSsg: true,
disablePageConfig: true,
pagesDir
};
}
function getLoaderSWCOptions({ // This is not passed yet as "paths" resolving is handled by webpack currently.
// resolvedBaseUrl,
filename, development, isServer, pagesDir, appDir, isPageFile, hasReactRefresh, modularizeImports, optimizeServerReact, optimizePackageImports, swcPlugins, compilerOptions, jsConfig, supportedBrowsers, swcCacheDir, relativeFilePathFromRoot, serverComponents, bundleLayer, esm }) {
let baseOptions = getBaseSWCOptions({
filename,
development,
globalWindow: !isServer,
hasReactRefresh,
modularizeImports,
swcPlugins,
compilerOptions,
jsConfig,
// resolvedBaseUrl,
swcCacheDir,
bundleLayer,
serverComponents,
esm: !!esm
});
baseOptions.fontLoaders = {
fontLoaders: [
"next/font/local",
"next/font/google",
// TODO: remove this in the next major version
"@next/font/local",
"@next/font/google"
],
relativeFilePathFromRoot
};
baseOptions.cjsRequireOptimizer = {
packages: {
"next/server": {
transforms: {
NextRequest: "next/dist/server/web/spec-extension/request",
NextResponse: "next/dist/server/web/spec-extension/response",
ImageResponse: "next/dist/server/web/spec-extension/image-response",
userAgentFromString: "next/dist/server/web/spec-extension/user-agent",
userAgent: "next/dist/server/web/spec-extension/user-agent"
}
}
}
};
if (optimizeServerReact && isServer && !development) {
baseOptions.optimizeServerReact = {
optimize_use_state: false
};
}
// Modularize import optimization for barrel files
if (optimizePackageImports) {
baseOptions.autoModularizeImports = {
packages: optimizePackageImports
};
}
const isNodeModules = nodeModulesPath.test(filename);
const isAppBrowserLayer = bundleLayer === _constants.WEBPACK_LAYERS.appPagesBrowser;
const moduleResolutionConfig = shouldOutputCommonJs(filename) ? {
module: {
type: "commonjs"
}
} : {};
let options;
if (isServer) {
options = {
...baseOptions,
...moduleResolutionConfig,
// Disables getStaticProps/getServerSideProps tree shaking on the server compilation for pages
disableNextSsg: true,
disablePageConfig: true,
isDevelopment: development,
isServerCompiler: isServer,
pagesDir,
appDir,
preferEsm: !!esm,
isPageFile,
env: {
targets: {
// Targets the current version of Node.js
node: process.versions.node
}
}
};
} else {
options = {
...baseOptions,
...moduleResolutionConfig,
disableNextSsg: !isPageFile,
isDevelopment: development,
isServerCompiler: isServer,
pagesDir,
appDir,
isPageFile,
...supportedBrowsers && supportedBrowsers.length > 0 ? {
env: {
targets: supportedBrowsers
}
} : {}
};
if (!options.env) {
// Matches default @babel/preset-env behavior
options.jsc.target = "es5";
}
}
// For node_modules in app browser layer, we don't need to do any server side transformation.
// Only keep server actions transform to discover server actions from client components.
if (isAppBrowserLayer && isNodeModules) {
var _options_jsc_transform_optimizer_globals;
options.disableNextSsg = true;
options.disablePageConfig = true;
options.isPageFile = false;
options.optimizeServerReact = undefined;
options.cjsRequireOptimizer = undefined;
// Disable optimizer for node_modules in app browser layer, to avoid unnecessary replacement.
// e.g. typeof window could result differently in js worker or browser.
if ((_options_jsc_transform_optimizer_globals = options.jsc.transform.optimizer.globals) == null ? void 0 : _options_jsc_transform_optimizer_globals.typeofs) {
delete options.jsc.transform.optimizer.globals.typeofs.window;
}
}
return options;
}
//# sourceMappingURL=options.js.map

1581
.next/standalone/node_modules/next/dist/build/utils.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
edgeConditionNames: null,
getMainField: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
edgeConditionNames: function() {
return edgeConditionNames;
},
getMainField: function() {
return getMainField;
}
});
const _constants = require("../../shared/lib/constants");
const edgeConditionNames = [
"edge-light",
"worker",
// inherits the default conditions
"..."
];
const mainFieldsPerCompiler = {
// For default case, prefer CJS over ESM on server side. e.g. pages dir SSR
[_constants.COMPILER_NAMES.server]: [
"main",
"module"
],
[_constants.COMPILER_NAMES.client]: [
"browser",
"module",
"main"
],
[_constants.COMPILER_NAMES.edgeServer]: edgeConditionNames,
// For bundling-all strategy, prefer ESM over CJS
"server-esm": [
"module",
"main"
]
};
function getMainField(compilerType, preferEsm) {
if (compilerType === _constants.COMPILER_NAMES.edgeServer) {
return edgeConditionNames;
} else if (compilerType === _constants.COMPILER_NAMES.client) {
return mainFieldsPerCompiler[_constants.COMPILER_NAMES.client];
}
// Prefer module fields over main fields for isomorphic packages on server layer
return preferEsm ? mainFieldsPerCompiler["server-esm"] : mainFieldsPerCompiler[_constants.COMPILER_NAMES.server];
}
//# sourceMappingURL=resolve.js.map

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "base", {
enumerable: true,
get: function() {
return base;
}
});
const _lodashcurry = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lodash.curry"));
const _constants = require("../../../../shared/lib/constants");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const base = (0, _lodashcurry.default)(function base(ctx, config) {
config.mode = ctx.isDevelopment ? "development" : "production";
config.name = ctx.isServer ? ctx.isEdgeRuntime ? _constants.COMPILER_NAMES.edgeServer : _constants.COMPILER_NAMES.server : _constants.COMPILER_NAMES.client;
config.target = !ctx.targetWeb ? "node18.17" // 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,568 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
css: null,
lazyPostCSS: null,
regexLikeCss: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
css: function() {
return css;
},
lazyPostCSS: function() {
return lazyPostCSS;
},
regexLikeCss: function() {
return regexLikeCss;
}
});
const _lodashcurry = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lodash.curry"));
const _helpers = require("../../helpers");
const _utils = require("../../utils");
const _loaders = require("./loaders");
const _nextfont = require("./loaders/next-font");
const _messages = require("./messages");
const _plugins = require("./plugins");
const _nonnullable = require("../../../../../lib/non-nullable");
const _constants = require("../../../../../lib/constants");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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: [
_constants.WEBPACK_LAYERS.reactServerComponents,
_constants.WEBPACK_LAYERS.serverSideRendering,
_constants.WEBPACK_LAYERS.appPagesBrowser
]
};
const PAGES_LAYER_RULE = {
not: [
_constants.WEBPACK_LAYERS.reactServerComponents,
_constants.WEBPACK_LAYERS.serverSideRendering,
_constants.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;
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 (0, _plugins.getPostCssPlugins)(rootDirectory, supportedBrowsers, disablePostcssPresetEnv);
return {
postcss,
postcssWithPlugins: postcss(postCssPlugins)
};
})();
}
return postcssInstancePromise;
}
const css = (0, _lodashcurry.default)(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((0, _helpers.loader)({
oneOf: [
markRemovable({
sideEffects: false,
test: fontLoaderTarget,
use: (0, _nextfont.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((0, _helpers.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: (0, _messages.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`.
(0, _helpers.loader)({
oneOf: [
// For app dir, we need to match the specific app layer.
ctx.hasAppDir ? markRemovable({
sideEffects: true,
test: regexCssModules,
issuerLayer: APP_LAYER_RULE,
use: [
{
loader: require.resolve("../../../loaders/next-flight-css-loader"),
options: {
cssModules: true
}
},
...(0, _loaders.getCssModuleLoader)({
...ctx,
isAppDir: true
}, lazyPostCSSInitializer)
]
}) : null,
markRemovable({
sideEffects: true,
test: regexCssModules,
issuerLayer: PAGES_LAYER_RULE,
use: (0, _loaders.getCssModuleLoader)({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer)
})
].filter(_nonnullable.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`.
(0, _helpers.loader)({
oneOf: [
// For app dir, we need to match the specific app layer.
ctx.hasAppDir ? markRemovable({
sideEffects: true,
test: regexSassModules,
issuerLayer: APP_LAYER_RULE,
use: [
{
loader: require.resolve("../../../loaders/next-flight-css-loader"),
options: {
cssModules: true
}
},
...(0, _loaders.getCssModuleLoader)({
...ctx,
isAppDir: true
}, lazyPostCSSInitializer, sassPreprocessors)
]
}) : null,
markRemovable({
sideEffects: true,
test: regexSassModules,
issuerLayer: PAGES_LAYER_RULE,
use: (0, _loaders.getCssModuleLoader)({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer, sassPreprocessors)
})
].filter(_nonnullable.nonNullable)
}), // Throw an error for CSS Modules used outside their supported scope
(0, _helpers.loader)({
oneOf: [
markRemovable({
test: [
regexCssModules,
regexSassModules
],
use: {
loader: "error-loader",
options: {
reason: (0, _messages.getLocalModuleImportError)()
}
}
})
]
}));
// Global CSS and SASS support.
if (ctx.isServer) {
fns.push((0, _helpers.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.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((0, _helpers.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
}
},
...(0, _loaders.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
}
},
...(0, _loaders.getGlobalCssLoader)({
...ctx,
isAppDir: true
}, lazyPostCSSInitializer, sassPreprocessors)
]
})
] : [],
markRemovable({
sideEffects: true,
test: regexCssGlobal,
include: allowedPagesGlobalCSSPath,
issuer: allowedPagesGlobalCSSIssuer,
issuerLayer: PAGES_LAYER_RULE,
use: (0, _loaders.getGlobalCssLoader)({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer)
}),
markRemovable({
sideEffects: true,
test: regexSassGlobal,
include: allowedPagesGlobalCSSPath,
issuer: allowedPagesGlobalCSSIssuer,
issuerLayer: PAGES_LAYER_RULE,
use: (0, _loaders.getGlobalCssLoader)({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer, sassPreprocessors)
})
].filter(_nonnullable.nonNullable)
}));
if (ctx.customAppFile) {
fns.push((0, _helpers.loader)({
oneOf: [
markRemovable({
sideEffects: true,
test: regexCssGlobal,
issuer: {
and: [
ctx.customAppFile
]
},
use: (0, _loaders.getGlobalCssLoader)({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer)
})
]
}), (0, _helpers.loader)({
oneOf: [
markRemovable({
sideEffects: true,
test: regexSassGlobal,
issuer: {
and: [
ctx.customAppFile
]
},
use: (0, _loaders.getGlobalCssLoader)({
...ctx,
isAppDir: false
}, lazyPostCSSInitializer, sassPreprocessors)
})
]
}));
}
}
// Throw an error for Global CSS used inside of `node_modules`
if (!shouldIncludeExternalCSSImports) {
fns.push((0, _helpers.loader)({
oneOf: [
markRemovable({
test: [
regexCssGlobal,
regexSassGlobal
],
issuer: {
and: [
/node_modules/
]
},
use: {
loader: "error-loader",
options: {
reason: (0, _messages.getGlobalModuleImportError)()
}
}
})
]
}));
}
// Throw an error for Global CSS used outside of our custom <App> file
fns.push((0, _helpers.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: (0, _messages.getGlobalImportError)()
}
}
})
]
}));
if (ctx.isClient) {
// Automatically transform references to files (i.e. url()) into URLs
// e.g. url(./logo.svg)
fns.push((0, _helpers.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((0, _helpers.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 = (0, _utils.pipe)(...fns);
return fn(config);
});
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getClientStyleLoader", {
enumerable: true,
get: function() {
return getClientStyleLoader;
}
});
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,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "cssFileResolve", {
enumerable: true,
get: function() {
return cssFileResolve;
}
});
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,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getCssModuleLocalIdent", {
enumerable: true,
get: function() {
return getCssModuleLocalIdent;
}
});
const _loaderutils3 = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/loader-utils3"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const regexLikeIndexModule = /(?<!pages[\\/])index\.module\.(scss|sass|css)$/;
function getCssModuleLocalIdent(context, _, exportName, options) {
const relativePath = _path.default.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 = _loaderutils3.default.getHashDigest(Buffer.from(`filePath:${relativePath}#className:${exportName}`), "sha1", "base64", 5);
// Have webpack interpolate the `[folder]` or `[name]` to its real value.
return _loaderutils3.default.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,62 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getGlobalCssLoader", {
enumerable: true,
get: function() {
return getGlobalCssLoader;
}
});
const _client = require("./client");
const _fileresolve = require("./file-resolve");
function getGlobalCssLoader(ctx, postcss, preProcessors = []) {
const loaders = [];
if (ctx.isClient) {
// Add appropriate development more or production mode style
// loader
loaders.push((0, _client.getClientStyleLoader)({
hasAppDir: ctx.hasAppDir,
isAppDir: ctx.isAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix
}));
}
if (ctx.experimental.useLightningcss) {
loaders.push({
loader: require.resolve("../../../../loaders/lightningcss-loader/src"),
options: {
importLoaders: 1 + preProcessors.length,
url: (url, resourcePath)=>(0, _fileresolve.cssFileResolve)(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>(0, _fileresolve.cssFileResolve)(url, resourcePath, ctx.experimental.urlImports),
targets: ctx.supportedBrowsers
}
});
} else {
// 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)=>(0, _fileresolve.cssFileResolve)(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>(0, _fileresolve.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,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && __export(require("./global")) && __export(require("./modules"));
_export_star(require("./global"), exports);
_export_star(require("./modules"), exports);
function _export_star(from, to) {
Object.keys(from).forEach(function(k) {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
Object.defineProperty(to, k, {
enumerable: true,
get: function() {
return from[k];
}
});
}
});
return from;
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,84 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getCssModuleLoader", {
enumerable: true,
get: function() {
return getCssModuleLoader;
}
});
const _client = require("./client");
const _fileresolve = require("./file-resolve");
const _getCssModuleLocalIdent = require("./getCssModuleLocalIdent");
function getCssModuleLoader(ctx, postcss, preProcessors = []) {
const loaders = [];
if (ctx.isClient) {
// Add appropriate development more or production mode style
// loader
loaders.push((0, _client.getClientStyleLoader)({
hasAppDir: ctx.hasAppDir,
isAppDir: ctx.isAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix
}));
}
if (ctx.experimental.useLightningcss) {
loaders.push({
loader: require.resolve("../../../../loaders/lightningcss-loader/src"),
options: {
importLoaders: 1 + preProcessors.length,
url: (url, resourcePath)=>(0, _fileresolve.cssFileResolve)(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>(0, _fileresolve.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
},
targets: ctx.supportedBrowsers
}
});
} else {
// 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)=>(0, _fileresolve.cssFileResolve)(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>(0, _fileresolve.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.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,62 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getNextFontLoader", {
enumerable: true,
get: function() {
return getNextFontLoader;
}
});
const _client = require("./client");
const _fileresolve = require("./file-resolve");
function getNextFontLoader(ctx, postcss, fontLoaderPath) {
const loaders = [];
if (ctx.isClient) {
// Add appropriate development mode or production mode style
// loader
loaders.push((0, _client.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)=>(0, _fileresolve.cssFileResolve)(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>(0, _fileresolve.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,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getCustomDocumentError: null,
getGlobalImportError: null,
getGlobalModuleImportError: null,
getLocalModuleImportError: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getCustomDocumentError: function() {
return getCustomDocumentError;
},
getGlobalImportError: function() {
return getGlobalImportError;
},
getGlobalModuleImportError: function() {
return getGlobalModuleImportError;
},
getLocalModuleImportError: function() {
return getLocalModuleImportError;
}
});
const _picocolors = require("../../../../../lib/picocolors");
function getGlobalImportError() {
return `Global CSS ${(0, _picocolors.bold)("cannot")} be imported from files other than your ${(0, _picocolors.bold)("Custom <App>")}. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to ${(0, _picocolors.cyan)("pages/_app.js")}. Or convert the import to Component-Level CSS (CSS Modules).\nRead more: https://nextjs.org/docs/messages/css-global`;
}
function getGlobalModuleImportError() {
return `Global CSS ${(0, _picocolors.bold)("cannot")} be imported from within ${(0, _picocolors.bold)("node_modules")}.\nRead more: https://nextjs.org/docs/messages/css-npm`;
}
function getLocalModuleImportError() {
return `CSS Modules ${(0, _picocolors.bold)("cannot")} be imported from within ${(0, _picocolors.bold)("node_modules")}.\nRead more: https://nextjs.org/docs/messages/css-modules-npm`;
}
function getCustomDocumentError() {
return `CSS ${(0, _picocolors.bold)("cannot")} be imported within ${(0, _picocolors.cyan)("pages/_document.js")}. Please move global styles to ${(0, _picocolors.cyan)("pages/_app.js")}.`;
}
//# sourceMappingURL=messages.js.map

View File

@@ -0,0 +1,162 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getPostCssPlugins", {
enumerable: true,
get: function() {
return getPostCssPlugins;
}
});
const _picocolors = require("../../../../../lib/picocolors");
const _findconfig = require("../../../../../lib/find-config");
const genericErrorText = "Malformed PostCSS Configuration";
function getError_NullConfig(pluginName) {
return `${(0, _picocolors.red)((0, _picocolors.bold)("Error"))}: Your PostCSS configuration for '${pluginName}' cannot have ${(0, _picocolors.bold)("null")} configuration.\nTo disable '${pluginName}', pass ${(0, _picocolors.bold)("false")}, otherwise, pass ${(0, _picocolors.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(`${(0, _picocolors.yellow)((0, _picocolors.bold)("Warning"))}: Please remove the ${(0, _picocolors.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);
}
async function getPostCssPlugins(dir, supportedBrowsers, disablePostcssPresetEnv = false) {
let config = await (0, _findconfig.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(`${(0, _picocolors.yellow)((0, _picocolors.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(`${(0, _picocolors.yellow)((0, _picocolors.bold)("Warning"))}: A ${(0, _picocolors.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(`${(0, _picocolors.red)((0, _picocolors.bold)("Error"))}: A PostCSS Plugin must be provided as a ${(0, _picocolors.bold)("string")}. Instead, we got: '${pluginName}'.\n` + "Read more: https://nextjs.org/docs/messages/postcss-shape");
} else {
console.error(`${(0, _picocolors.red)((0, _picocolors.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(`${(0, _picocolors.red)((0, _picocolors.bold)("Error"))}: A PostCSS Plugin was passed as a function using require(), but it must be provided as a ${(0, _picocolors.bold)("string")}.\nRead more: https://nextjs.org/docs/messages/postcss-shape`);
throw new Error(genericErrorText);
} else {
console.error(`${(0, _picocolors.red)((0, _picocolors.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,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "images", {
enumerable: true,
get: function() {
return images;
}
});
const _lodashcurry = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lodash.curry"));
const _webpackconfig = require("../../../../webpack-config");
const _helpers = require("../../helpers");
const _utils = require("../../utils");
const _messages = require("./messages");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const images = (0, _lodashcurry.default)(async function images(_ctx, config) {
const fns = [
(0, _helpers.loader)({
oneOf: [
{
test: _webpackconfig.nextImageLoaderRegex,
use: {
loader: "error-loader",
options: {
reason: (0, _messages.getCustomDocumentImageError)()
}
},
issuer: /pages[\\/]_document\./
}
]
})
];
const fn = (0, _utils.pipe)(...fns);
return fn(config);
});
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getCustomDocumentImageError", {
enumerable: true,
get: function() {
return getCustomDocumentImageError;
}
});
const _picocolors = require("../../../../../lib/picocolors");
function getCustomDocumentImageError() {
return `Images ${(0, _picocolors.bold)("cannot")} be imported within ${(0, _picocolors.cyan)("pages/_document.js")}. Please move image imports that need to be displayed on every page into ${(0, _picocolors.cyan)("pages/_app.js")}.\nRead more: https://nextjs.org/docs/messages/custom-document-image-import`;
}
//# sourceMappingURL=messages.js.map

View File

@@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
loader: null,
plugin: null,
unshiftLoader: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
loader: function() {
return loader;
},
plugin: function() {
return plugin;
},
unshiftLoader: function() {
return unshiftLoader;
}
});
const _lodashcurry = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lodash.curry"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const loader = (0, _lodashcurry.default)(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;
});
const unshiftLoader = (0, _lodashcurry.default)(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;
});
const plugin = (0, _lodashcurry.default)(function plugin(p, config) {
if (!config.plugins) {
config.plugins = [];
}
config.plugins.push(p);
return config;
});
//# sourceMappingURL=helpers.js.map

View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "buildConfiguration", {
enumerable: true,
get: function() {
return buildConfiguration;
}
});
const _base = require("./blocks/base");
const _css = require("./blocks/css");
const _images = require("./blocks/images");
const _utils = require("./utils");
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 = [
(0, _base.base)(ctx),
(0, _css.css)(ctx)
];
if (!disableStaticImages) {
fns.push((0, _images.images)(ctx));
}
const fn = (0, _utils.pipe)(...fns);
return fn(config);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "pipe", {
enumerable: true,
get: function() {
return pipe;
}
});
const pipe = (...fns)=>(param)=>fns.reduce(async (result, next)=>next(await result), param);
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return CssSyntaxError;
}
});
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,89 @@
/*
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.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return _default;
}
});
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);
};
const _default = camelCase;
//# sourceMappingURL=camelcase.js.map

View File

@@ -0,0 +1,269 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return loader;
}
});
const _CssSyntaxError = /*#__PURE__*/ _interop_require_default(require("./CssSyntaxError"));
const _Warning = /*#__PURE__*/ _interop_require_default(require("../../postcss-loader/src/Warning"));
const _stringifyrequest = require("../../../stringify-request");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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
};
}
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 exports1 = 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)=>(0, _stringifyrequest.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)=>(0, _stringifyrequest.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: exports1,
context: this.context,
rootContext: this.rootContext,
resolver: icssResolver,
urlHandler: (url)=>(0, _stringifyrequest.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.default(error) : error;
}
for (const warning of result.warnings()){
this.emitWarning(new _Warning.default(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: (0, _stringifyrequest.stringifyRequest)(this, require.resolve("./runtime/api"))
});
}
const importCode = getImportCode(imports, options);
const moduleCode = getModuleCode(result, api, replacements, options, this);
const exportCode = getExportCode(exports1, replacements, options);
return `${importCode}${moduleCode}${exportCode}`;
}).then((code)=>{
callback(null, code);
}, (err)=>{
callback(err);
});
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
icssParser: null,
importParser: null,
urlParser: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
icssParser: function() {
return _postcssicssparser.default;
},
importParser: function() {
return _postcssimportparser.default;
},
urlParser: function() {
return _postcssurlparser.default;
}
});
const _postcssimportparser = /*#__PURE__*/ _interop_require_default(require("./postcss-import-parser"));
const _postcssicssparser = /*#__PURE__*/ _interop_require_default(require("./postcss-icss-parser"));
const _postcssurlparser = /*#__PURE__*/ _interop_require_default(require("./postcss-url-parser"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,107 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return _default;
}
});
const _icssutils = require("next/dist/compiled/icss-utils");
const _utils = require("../utils");
const plugin = (options = {})=>{
return {
postcssPlugin: "postcss-icss-parser",
async OnceExit (root) {
const importReplacements = Object.create(null);
const { icssImports, icssExports } = (0, _icssutils.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 = (0, _utils.requestify)((0, _utils.normalizeUrl)(normalizedUrl, true), options.rootContext);
const doResolve = async ()=>{
const { resolver, context } = options;
const resolvedUrl = await (0, _utils.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) {
(0, _icssutils.replaceSymbols)(root, importReplacements);
}
for (const name of Object.keys(icssExports)){
const value = (0, _icssutils.replaceValueSymbols)(icssExports[name], importReplacements);
options.exports.push({
name,
value
});
}
}
};
};
plugin.postcss = true;
const _default = plugin;
//# sourceMappingURL=postcss-icss-parser.js.map

View File

@@ -0,0 +1,207 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return _default;
}
});
const _postcssvalueparser = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/postcss-value-parser"));
const _utils = require("../utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched && matched[2] === "true") {
return;
}
}
const prevNode = atRule.prev();
if (prevNode && prevNode.type === "comment") {
const matched = prevNode.text.match(_utils.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 } = (0, _postcssvalueparser.default)(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 : _postcssvalueparser.default.stringify(paramsNodes[0].nodes);
}
url = (0, _utils.normalizeUrl)(url, isStringValue);
const isRequestable = (0, _utils.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 = _postcssvalueparser.default.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 = (0, _utils.requestify)(url, options.rootContext);
const { resolver, context } = options;
const resolvedUrl = await (0, _utils.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;
const _default = plugin;
//# sourceMappingURL=postcss-import-parser.js.map

View File

@@ -0,0 +1,327 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return _default;
}
});
const _postcssvalueparser = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/postcss-value-parser"));
const _utils = require("../utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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(_utils.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 ((0, _utils.isDataUrl)(url) && isSupportDataURLInNewURL) {
try {
decodeURIComponent(url);
} catch (ignoreError) {
return false;
}
return true;
}
if (!(0, _utils.isUrlRequestable)(url)) {
return false;
}
return true;
}
function parseDeclaration(declaration, key, result, isSupportDataURLInNewURL) {
if (!needParseDeclaration.test(declaration[key])) {
return;
}
const parsed = (0, _postcssvalueparser.default)(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(_utils.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(_utils.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 : _postcssvalueparser.default.stringify(nodes);
url = (0, _utils.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 : _postcssvalueparser.default.stringify(nodes);
url = (0, _utils.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 = (0, _utils.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 ((0, _utils.isDataUrl)(url)) {
// eslint-disable-next-line consistent-return
return parsedDeclaration;
}
const [pathname, query, hashOrQuery] = url.split(/(\?)?#/, 3);
let hash = query ? "?" : "";
hash += hashOrQuery ? `#${hashOrQuery}` : "";
const { needToResolveURL, rootContext } = options;
const request = (0, _utils.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 (0, _utils.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;
const _default = plugin;
//# sourceMappingURL=postcss-url-parser.js.map

View File

@@ -0,0 +1,91 @@
/*
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
"use strict";
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,26 @@
"use strict";
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,463 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
dashesCamelCase: null,
getExportCode: null,
getFilter: null,
getImportCode: null,
getModuleCode: null,
getModulesPlugins: null,
getPreRequester: null,
isDataUrl: null,
isUrlRequestable: null,
normalizeSourceMap: null,
normalizeSourceMapForRuntime: null,
normalizeUrl: null,
requestify: null,
resolveRequests: null,
shouldUseIcssPlugin: null,
shouldUseImportPlugin: null,
shouldUseModulesPlugins: null,
shouldUseURLPlugin: null,
sort: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
dashesCamelCase: function() {
return dashesCamelCase;
},
getExportCode: function() {
return getExportCode;
},
getFilter: function() {
return getFilter;
},
getImportCode: function() {
return getImportCode;
},
getModuleCode: function() {
return getModuleCode;
},
getModulesPlugins: function() {
return getModulesPlugins;
},
getPreRequester: function() {
return getPreRequester;
},
isDataUrl: function() {
return isDataUrl;
},
isUrlRequestable: function() {
return isUrlRequestable;
},
normalizeSourceMap: function() {
return normalizeSourceMap;
},
// For lightningcss-loader
normalizeSourceMapForRuntime: function() {
return normalizeSourceMapForRuntime;
},
normalizeUrl: function() {
return normalizeUrl;
},
requestify: function() {
return requestify;
},
resolveRequests: function() {
return resolveRequests;
},
shouldUseIcssPlugin: function() {
return shouldUseIcssPlugin;
},
shouldUseImportPlugin: function() {
return shouldUseImportPlugin;
},
shouldUseModulesPlugins: function() {
return shouldUseModulesPlugins;
},
shouldUseURLPlugin: function() {
return shouldUseURLPlugin;
},
sort: function() {
return sort;
}
});
const _url = require("url");
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _loaderutils3 = require("next/dist/compiled/loader-utils3");
const _postcssmodulesvalues = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/postcss-modules-values"));
const _postcssmoduleslocalbydefault = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/postcss-modules-local-by-default"));
const _postcssmodulesextractimports = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/postcss-modules-extract-imports"));
const _postcssmodulesscope = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/postcss-modules-scope"));
const _camelcase = /*#__PURE__*/ _interop_require_default(require("./camelcase"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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.default.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 (0, _url.fileURLToPath)(url);
}
if (/^[a-z][a-z0-9+.-]*:/i.test(url)) {
return url;
}
return url.charAt(0) === "/" ? (0, _loaderutils3.urlToRequest)(url, rootContext) : (0, _loaderutils3.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 = [
_postcssmodulesvalues.default,
(0, _postcssmoduleslocalbydefault.default)({
mode
}),
(0, _postcssmodulesextractimports.default)(),
(0, _postcssmodulesscope.default)({
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.default.resolve(sourceRoot, normalizePath(source)) : normalizePath(source);
return _path.default.relative(_path.default.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.default.dirname(loaderContext.resourcePath);
const absoluteSource = _path.default.resolve(resourceDirname, source);
const contextifyPath = normalizePath(_path.default.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((0, _camelcase.default)(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(exports1, replacements, options) {
let code = "// Exports\n";
let localsCode = "";
const addExportToLocalsCode = (name, value)=>{
if (options.modules.namedExport) {
localsCode += `export const ${(0, _camelcase.default)(name)} = ${JSON.stringify(value)};\n`;
} else {
if (localsCode) {
localsCode += `,\n`;
}
localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
}
};
for (const { name, value } of exports1){
switch(options.modules.exportLocalsConvention){
case "camelCase":
{
addExportToLocalsCode(name, value);
const modifiedName = (0, _camelcase.default)(name);
if (modifiedName !== name) {
addExportToLocalsCode(modifiedName, value);
}
break;
}
case "camelCaseOnly":
{
addExportToLocalsCode((0, _camelcase.default)(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((0, _camelcase.default)(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;
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getModuleBuildInfo", {
enumerable: true,
get: function() {
return getModuleBuildInfo;
}
});
function getModuleBuildInfo(webpackModule) {
return webpackModule.buildInfo;
}
//# sourceMappingURL=get-module-build-info.js.map

View File

@@ -0,0 +1,156 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getExportCode: null,
getImportCode: null,
getModuleCode: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getExportCode: function() {
return getExportCode;
},
getImportCode: function() {
return getImportCode;
},
getModuleCode: function() {
return getModuleCode;
}
});
const _camelcase = /*#__PURE__*/ _interop_require_default(require("../../css-loader/src/camelcase"));
const _utils = require("../../css-loader/src/utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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 getModuleCode(result, api, replacements, options, loaderContext) {
if (options.modules.exportOnlyLocals === true) {
return "";
}
const sourceMapValue = options.sourceMap ? `,${(0, _utils.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((0, _camelcase.default)(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 getExportCode(exports1, replacements, options) {
let code = "// Exports\n";
let localsCode = "";
const addExportToLocalsCode = (name, value)=>{
if (options.modules.namedExport) {
localsCode += `export const ${(0, _camelcase.default)(name)} = ${JSON.stringify(value)};\n`;
} else {
if (localsCode) {
localsCode += `,\n`;
}
localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
}
};
for (const { name, value } of exports1){
switch(options.modules.exportLocalsConvention){
case "camelCase":
{
addExportToLocalsCode(name, value);
const modifiedName = (0, _camelcase.default)(name);
if (modifiedName !== name) {
addExportToLocalsCode(modifiedName, value);
}
break;
}
case "camelCaseOnly":
{
addExportToLocalsCode((0, _camelcase.default)(name), value);
break;
}
case "dashes":
{
addExportToLocalsCode(name, value);
const modifiedName = (0, _utils.dashesCamelCase)(name);
if (modifiedName !== name) {
addExportToLocalsCode(modifiedName, value);
}
break;
}
case "dashesOnly":
{
addExportToLocalsCode((0, _utils.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((0, _camelcase.default)(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;
}
//# sourceMappingURL=codegen.js.map

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
LightningCssMinifyPlugin: null,
default: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
LightningCssMinifyPlugin: function() {
return _minify.LightningCssMinifyPlugin;
},
default: function() {
return _default;
}
});
const _loader = require("./loader");
const _minify = require("./minify");
const _default = _loader.LightningCssLoader;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ECacheKey", {
enumerable: true,
get: function() {
return ECacheKey;
}
});
var ECacheKey;
(function(ECacheKey) {
ECacheKey["loader"] = "loader";
ECacheKey["minify"] = "minify";
})(ECacheKey || (ECacheKey = {}));
//# sourceMappingURL=interface.js.map

View File

@@ -0,0 +1,410 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
LightningCssLoader: null,
raw: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
LightningCssLoader: function() {
return LightningCssLoader;
},
raw: function() {
return raw;
}
});
const _utils = require("./utils");
const _codegen = require("./codegen");
const _utils1 = require("../../css-loader/src/utils");
const _stringifyrequest = require("../../../stringify-request");
const _interface = require("./interface");
const encoder = new TextEncoder();
const moduleRegExp = /\.module\.\w+$/i;
function createUrlAndImportVisitor(visitorOptions, apis, imports, replacements, replacedUrls, replacedImportUrls) {
const importUrlToNameMap = new Map();
let hasUrlImportHelper = false;
const urlToNameMap = new Map();
const urlToReplacementMap = new Map();
let urlIndex = -1;
let importUrlIndex = -1;
function handleUrl(u) {
let url = u.url;
const needKeep = visitorOptions.urlFilter(url);
if (!needKeep) {
return u;
}
if ((0, _utils1.isDataUrl)(url)) {
return u;
}
urlIndex++;
replacedUrls.set(urlIndex, url);
url = `__NEXT_LIGHTNINGCSS_LOADER_URL_REPLACE_${urlIndex}__`;
const [, query, hashOrQuery] = url.split(/(\?)?#/, 3);
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
let hash = query ? "?" : "";
hash += hashOrQuery ? `#${hashOrQuery}` : "";
if (!hasUrlImportHelper) {
imports.push({
type: "get_url_import",
importName: "___CSS_LOADER_GET_URL_IMPORT___",
url: JSON.stringify(require.resolve("../../css-loader/src/runtime/getUrl.js")),
index: -1
});
hasUrlImportHelper = true;
}
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = urlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${urlToNameMap.size}___`;
urlToNameMap.set(newUrl, importName);
imports.push({
type: "url",
importName,
url: JSON.stringify(newUrl),
index: urlIndex
});
}
// This should be true for string-urls in image-set
const needQuotes = false;
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);
replacements.push({
replacementName,
importName,
hash,
needQuotes
});
}
return {
loc: u.loc,
url: replacementName
};
}
return {
Rule: {
import (node) {
if (visitorOptions.importFilter) {
const needKeep = visitorOptions.importFilter(node.value.url, node.value.media);
if (!needKeep) {
return node;
}
}
let url = node.value.url;
importUrlIndex++;
replacedImportUrls.set(importUrlIndex, url);
url = `__NEXT_LIGHTNINGCSS_LOADER_IMPORT_URL_REPLACE_${importUrlIndex}__`;
// TODO: Use identical logic as valueParser.stringify()
const media = node.value.media.mediaQueries.length ? JSON.stringify(node.value.media.mediaQueries) : undefined;
const isRequestable = (0, _utils1.isUrlRequestable)(url);
let prefix;
if (isRequestable) {
const queryParts = url.split("!");
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
}
if (!isRequestable) {
apis.push({
url,
media
});
// Bug of lightningcss
return {
type: "ignored",
value: ""
};
}
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = importUrlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_AT_RULE_IMPORT_${importUrlToNameMap.size}___`;
importUrlToNameMap.set(newUrl, importName);
const importUrl = visitorOptions.urlHandler(newUrl);
imports.push({
type: "rule_import",
importName,
url: importUrl
});
}
apis.push({
importName,
media
});
// Bug of lightningcss
return {
type: "ignored",
value: ""
};
}
},
Url (node) {
return handleUrl(node);
}
};
}
function createIcssVisitor({ apis, imports, replacements, replacedUrls, urlHandler }) {
let index = -1;
let replacementIndex = -1;
return {
Declaration: {
composes (node) {
if (node.property === "unparsed") {
return;
}
const specifier = node.value.from;
if ((specifier == null ? void 0 : specifier.type) !== "file") {
return;
}
let url = specifier.value;
if (!url) {
return;
}
index++;
replacedUrls.set(index, url);
url = `__NEXT_LIGHTNINGCSS_LOADER_ICSS_URL_REPLACE_${index}__`;
const importName = `___CSS_LOADER_ICSS_IMPORT_${imports.length}___`;
imports.push({
type: "icss_import",
importName,
icss: true,
url: urlHandler(url),
index
});
apis.push({
importName,
dedupe: true,
index
});
const newNames = [];
for (const localName of node.value.names){
replacementIndex++;
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${index}_REPLACEMENT_${replacementIndex}___`;
replacements.push({
replacementName,
importName,
localName
});
newNames.push(replacementName);
}
return {
property: "composes",
value: {
loc: node.value.loc,
names: newNames,
from: specifier
}
};
}
}
};
}
const LOADER_NAME = `lightningcss-loader`;
async function LightningCssLoader(source, prevMap) {
var _options_modules;
const done = this.async();
const options = this.getOptions();
const { implementation, targets: userTargets, ...opts } = options;
options.modules ??= {};
if (implementation && typeof implementation.transformCss !== "function") {
done(new TypeError(`[${LOADER_NAME}]: options.implementation.transformCss must be an 'lightningcss' transform function. Received ${typeof implementation.transformCss}`));
return;
}
const exports1 = [];
const imports = [];
const icssImports = [];
const apis = [];
const replacements = [];
if (((_options_modules = options.modules) == null ? void 0 : _options_modules.exportOnlyLocals) !== true) {
imports.unshift({
type: "api_import",
importName: "___CSS_LOADER_API_IMPORT___",
url: (0, _stringifyrequest.stringifyRequest)(this, require.resolve("../../css-loader/src/runtime/api"))
});
}
const { loadBindings } = require("next/dist/build/swc");
const transform = (implementation == null ? void 0 : implementation.transformCss) ?? (await loadBindings()).css.lightning.transform;
const replacedUrls = new Map();
const icssReplacedUrls = new Map();
const replacedImportUrls = new Map();
const urlImportVisitor = createUrlAndImportVisitor({
urlHandler: (url)=>(0, _stringifyrequest.stringifyRequest)(this, (0, _utils1.getPreRequester)(this)(options.importLoaders ?? 0) + url),
urlFilter: (0, _utils1.getFilter)(options.url, this.resourcePath),
importFilter: (0, _utils1.getFilter)(options.import, this.resourcePath),
context: this.context
}, apis, imports, replacements, replacedUrls, replacedImportUrls);
const icssVisitor = createIcssVisitor({
apis,
imports: icssImports,
replacements,
replacedUrls: icssReplacedUrls,
urlHandler: (url)=>(0, _stringifyrequest.stringifyRequest)(this, (0, _utils1.getPreRequester)(this)(options.importLoaders) + url)
});
// This works by returned visitors are not conflicting.
// naive workaround for composeVisitors, as we do not directly depends on lightningcss's npm pkg
// but next-swc provides bindings
const visitor = {
...urlImportVisitor,
...icssVisitor
};
try {
const { code, map, exports: moduleExports } = transform({
...opts,
visitor,
cssModules: options.modules && moduleRegExp.test(this.resourcePath) ? {
pattern: process.env.__NEXT_TEST_MODE ? "[name]__[local]" : "[name]__[hash]__[local]"
} : undefined,
filename: this.resourcePath,
code: encoder.encode(source),
sourceMap: this.sourceMap,
targets: (0, _utils.getTargets)({
targets: userTargets,
key: _interface.ECacheKey.loader
}),
inputSourceMap: this.sourceMap && prevMap ? JSON.stringify(prevMap) : undefined,
include: 1
});
let cssCodeAsString = code.toString();
if (moduleExports) {
for(const name in moduleExports){
if (Object.prototype.hasOwnProperty.call(moduleExports, name)) {
const v = moduleExports[name];
let value = v.name;
for (const compose of v.composes){
value += ` ${compose.name}`;
}
exports1.push({
name,
value
});
}
}
}
if (replacedUrls.size !== 0) {
const urlResolver = this.getResolve({
conditionNames: [
"asset"
],
mainFields: [
"asset"
],
mainFiles: [],
extensions: []
});
for (const [index, url] of replacedUrls.entries()){
const [pathname] = url.split(/(\?)?#/, 3);
const request = (0, _utils1.requestify)(pathname, this.rootContext);
const resolvedUrl = await (0, _utils1.resolveRequests)(urlResolver, this.context, [
...new Set([
request,
url
])
]);
for (const importItem of imports){
importItem.url = importItem.url.replace(`__NEXT_LIGHTNINGCSS_LOADER_URL_REPLACE_${index}__`, resolvedUrl ?? url);
}
}
}
if (replacedImportUrls.size !== 0) {
const importResolver = this.getResolve({
conditionNames: [
"style"
],
extensions: [
".css"
],
mainFields: [
"css",
"style",
"main",
"..."
],
mainFiles: [
"index",
"..."
],
restrictions: [
/\.css$/i
]
});
for (const [index, url] of replacedImportUrls.entries()){
const [pathname] = url.split(/(\?)?#/, 3);
const request = (0, _utils1.requestify)(pathname, this.rootContext);
const resolvedUrl = await (0, _utils1.resolveRequests)(importResolver, this.context, [
...new Set([
request,
url
])
]);
for (const importItem of imports){
importItem.url = importItem.url.replace(`__NEXT_LIGHTNINGCSS_LOADER_IMPORT_URL_REPLACE_${index}__`, resolvedUrl ?? url);
}
}
}
if (icssReplacedUrls.size !== 0) {
const icssResolver = this.getResolve({
conditionNames: [
"style"
],
extensions: [],
mainFields: [
"css",
"style",
"main",
"..."
],
mainFiles: [
"index",
"..."
]
});
for (const [index, url] of icssReplacedUrls.entries()){
const [pathname] = url.split(/(\?)?#/, 3);
const request = (0, _utils1.requestify)(pathname, this.rootContext);
const resolvedUrl = await (0, _utils1.resolveRequests)(icssResolver, this.context, [
...new Set([
url,
request
])
]);
for (const importItem of icssImports){
importItem.url = importItem.url.replace(`__NEXT_LIGHTNINGCSS_LOADER_ICSS_URL_REPLACE_${index}__`, resolvedUrl ?? url);
}
}
}
imports.push(...icssImports);
const importCode = (0, _codegen.getImportCode)(imports, options);
const moduleCode = (0, _codegen.getModuleCode)({
css: cssCodeAsString,
map
}, apis, replacements, options, this);
const exportCode = (0, _codegen.getExportCode)(exports1, replacements, options);
const esCode = `${importCode}${moduleCode}${exportCode}`;
done(null, esCode, map && JSON.parse(map.toString()));
} catch (error) {
console.error("lightningcss-loader error", error);
done(error);
}
}
const raw = true;
//# sourceMappingURL=loader.js.map

View File

@@ -0,0 +1,90 @@
// @ts-ignore
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "LightningCssMinifyPlugin", {
enumerable: true,
get: function() {
return LightningCssMinifyPlugin;
}
});
const _webpack = require("next/dist/compiled/webpack/webpack");
const _webpacksources3 = require("next/dist/compiled/webpack-sources3");
const _interface = require("./interface");
const _utils = require("./utils");
const _buffer = require("buffer");
const PLUGIN_NAME = "lightning-css-minify";
const CSS_FILE_REG = /\.css(?:\?.*)?$/i;
class LightningCssMinifyPlugin {
constructor(opts = {}){
const { implementation, ...otherOpts } = opts;
if (implementation && typeof implementation.transformCss !== "function") {
throw new TypeError(`[LightningCssMinifyPlugin]: implementation.transformCss must be an 'lightningcss' transform function. Received ${typeof implementation.transformCss}`);
}
this.transform = implementation == null ? void 0 : implementation.transformCss;
this.options = otherOpts;
}
apply(compiler) {
const meta = JSON.stringify({
name: "@next/lightningcss-loader",
version: "0.0.0",
options: this.options
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
compilation.hooks.chunkHash.tap(PLUGIN_NAME, (_, hash)=>hash.update(meta));
compilation.hooks.processAssets.tapPromise({
name: PLUGIN_NAME,
stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
additionalAssets: true
}, async ()=>await this.transformAssets(compilation));
compilation.hooks.statsPrinter.tap(PLUGIN_NAME, (statsPrinter)=>{
statsPrinter.hooks.print.for("asset.info.minimized")// @ts-ignore
.tap(PLUGIN_NAME, (minimized, { green, formatFlag })=>{
// @ts-ignore
return minimized ? green(formatFlag("minimized")) : undefined;
});
});
});
}
async transformAssets(compilation) {
const { options: { devtool } } = compilation.compiler;
if (!this.transform) {
const { loadBindings } = require("next/dist/build/swc");
this.transform = (await loadBindings()).css.lightning.transform;
}
const sourcemap = this.options.sourceMap === undefined ? devtool && devtool.includes("source-map") : this.options.sourceMap;
const { include, exclude, test: testRegExp, targets: userTargets, ...transformOptions } = this.options;
const assets = compilation.getAssets().filter((asset)=>// Filter out already minimized
!asset.info.minimized && // Filter out by file type
(testRegExp || CSS_FILE_REG).test(asset.name) && _webpack.ModuleFilenameHelpers.matchObject({
include,
exclude
}, asset.name));
await Promise.all(assets.map(async (asset)=>{
const { source, map } = asset.source.sourceAndMap();
const sourceAsString = source.toString();
const code = typeof source === "string" ? _buffer.Buffer.from(source) : source;
const targets = (0, _utils.getTargets)({
targets: userTargets,
key: _interface.ECacheKey.minify
});
const result = await this.transform({
filename: asset.name,
code,
minify: true,
sourceMap: sourcemap,
targets,
...transformOptions
});
const codeString = result.code.toString();
compilation.updateAsset(asset.name, // @ts-ignore
sourcemap ? new _webpacksources3.SourceMapSource(codeString, asset.name, JSON.parse(result.map.toString()), sourceAsString, map, true) : new _webpacksources3.RawSource(codeString), {
...asset.info,
minimized: true
});
}));
}
}
//# sourceMappingURL=minify.js.map

View File

@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getTargets", {
enumerable: true,
get: function() {
return getTargets;
}
});
let targetsCache = {};
/**
* Convert a version number to a single 24-bit number
*
* https://github.com/lumeland/lume/blob/4cc75599006df423a14befc06d3ed8493c645b09/plugins/lightningcss.ts#L160
*/ function version(major, minor = 0, patch = 0) {
return major << 16 | minor << 8 | patch;
}
function parseVersion(v) {
return v.split(".").reduce((acc, val)=>{
if (!acc) {
return null;
}
const parsed = parseInt(val, 10);
if (isNaN(parsed)) {
return null;
}
acc.push(parsed);
return acc;
}, []);
}
function browserslistToTargets(targets) {
return targets.reduce((acc, value)=>{
const [name, v] = value.split(" ");
const parsedVersion = parseVersion(v);
if (!parsedVersion) {
return acc;
}
const versionDigit = version(parsedVersion[0], parsedVersion[1], parsedVersion[2]);
if (name === "and_qq" || name === "and_uc" || name === "baidu" || name === "bb" || name === "kaios" || name === "op_mini") {
return acc;
}
if (acc[name] == null || versionDigit < acc[name]) {
acc[name] = versionDigit;
}
return acc;
}, {});
}
const getTargets = (opts)=>{
const cache = targetsCache[opts.key];
if (cache) {
return cache;
}
const result = browserslistToTargets(opts.targets ?? []);
return targetsCache[opts.key] = result;
};
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,52 @@
/**
* 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.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return _default;
}
});
const _crypto = /*#__PURE__*/ _interop_require_default(require("crypto"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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.default.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;
};
const _default = NextServerCSSLoader;
//# sourceMappingURL=next-flight-css-loader.js.map

View File

@@ -0,0 +1,129 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
default: null,
getAssumedSourceType: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
default: function() {
return transformSource;
},
getAssumedSourceType: function() {
return getAssumedSourceType;
}
});
const _constants = require("../../../../lib/constants");
const _constants1 = require("../../../../shared/lib/constants");
const _warnonce = require("../../../../shared/lib/utils/warn-once");
const _getpagestaticinfo = require("../../../analysis/get-page-static-info");
const _utils = require("../../utils");
const _getmodulebuildinfo = require("../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";
function getAssumedSourceType(mod, sourceType) {
var _buildInfo_rsc, _buildInfo_rsc1;
const buildInfo = (0, _getmodulebuildinfo.getModuleBuildInfo)(mod);
const detectedClientEntryType = buildInfo == null ? void 0 : (_buildInfo_rsc = buildInfo.rsc) == null ? void 0 : _buildInfo_rsc.clientEntryType;
const clientRefs = (buildInfo == null ? void 0 : (_buildInfo_rsc1 = buildInfo.rsc) == null ? void 0 : _buildInfo_rsc1.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";
}
}
return assumedSourceType;
}
function transformSource(source, sourceMap) {
var _this__module_matchResource, _this__module, _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 = (0, _getmodulebuildinfo.getModuleBuildInfo)(this._module);
buildInfo.rsc = (0, _getpagestaticinfo.getRSCModuleInformation)(source, true);
// Resource key is the unique identifier for the resource. When RSC renders
// a client module, that key is used to identify that module across all compiler
// layers.
//
// Usually it's the module's file path + the export name (e.g. `foo.js#bar`).
// But with Barrel Optimizations, one file can be splitted into multiple modules,
// so when you import `foo.js#bar` and `foo.js#baz`, they are actually different
// "foo.js" being created by the Barrel Loader (one only exports `bar`, the other
// only exports `baz`).
//
// Because of that, we must add another query param to the resource key to
// differentiate them.
let resourceKey = this.resourcePath;
if ((_this__module = this._module) == null ? void 0 : (_this__module_matchResource = _this__module.matchResource) == null ? void 0 : _this__module_matchResource.startsWith(_constants1.BARREL_OPTIMIZATION_PREFIX)) {
resourceKey = (0, _utils.formatBarrelOptimizedResource)(resourceKey, this._module.matchResource);
}
// A client boundary.
if (((_buildInfo_rsc = buildInfo.rsc) == null ? void 0 : _buildInfo_rsc.type) === _constants1.RSC_MODULE_TYPES.client) {
var _this__module_parser, _this__module1;
const assumedSourceType = getAssumedSourceType(this._module, (_this__module1 = this._module) == null ? void 0 : (_this__module_parser = _this__module1.parser) == null ? void 0 : _this__module_parser.sourceType);
const clientRefs = buildInfo.rsc.clientRefs;
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\`${resourceKey}\`)
// 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[''] = createProxy(String.raw\`${resourceKey}#\`);`;
} else if (ref === "default") {
esmSource += `\
export { __esModule, $$typeof };
export default createProxy(String.raw\`${resourceKey}#default\`);
`;
} else {
esmSource += `
const e${cnt} = createProxy(String.raw\`${resourceKey}#${ref}\`);
export { e${cnt++} as ${ref} };`;
}
}
this.callback(null, esmSource, sourceMap);
return;
}
}
if (((_buildInfo_rsc1 = buildInfo.rsc) == null ? void 0 : _buildInfo_rsc1.type) !== _constants1.RSC_MODULE_TYPES.client) {
if (noopHeadPath === this.resourcePath) {
(0, _warnonce.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.`);
}
}
const replacedSource = source.replace(_constants.RSC_MOD_REF_PROXY_ALIAS, MODULE_PROXY_PATH);
this.callback(null, replacedSource, sourceMap);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
decodeMatchers: null,
default: null,
encodeMatchers: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
decodeMatchers: function() {
return decodeMatchers;
},
default: function() {
return middlewareLoader;
},
encodeMatchers: function() {
return encodeMatchers;
}
});
const _getmodulebuildinfo = require("./get-module-build-info");
const _constants = require("../../../lib/constants");
const _loadentrypoint = require("../../load-entrypoint");
function encodeMatchers(matchers) {
return Buffer.from(JSON.stringify(matchers)).toString("base64");
}
function decodeMatchers(encodedMatchers) {
return JSON.parse(Buffer.from(encodedMatchers, "base64").toString());
}
async function middlewareLoader() {
const { absolutePagePath, page, rootDir, matchers: encodedMatchers, preferredRegion, middlewareConfig: middlewareConfigBase64 } = this.getOptions();
const matchers = encodedMatchers ? decodeMatchers(encodedMatchers) : undefined;
const pagePath = this.utils.contextify(this.context || this.rootContext, absolutePagePath);
const middlewareConfig = JSON.parse(Buffer.from(middlewareConfigBase64, "base64").toString());
const buildInfo = (0, _getmodulebuildinfo.getModuleBuildInfo)(this._module);
buildInfo.nextEdgeMiddleware = {
matchers,
page: page.replace(new RegExp(`/${_constants.MIDDLEWARE_LOCATION_REGEXP}$`), "") || "/"
};
buildInfo.rootDir = rootDir;
buildInfo.route = {
page,
absolutePagePath,
preferredRegion,
middlewareConfig
};
return await (0, _loadentrypoint.loadEntrypoint)("middleware", {
VAR_USERLAND: pagePath,
VAR_DEFINITION_PAGE: page
});
}
//# sourceMappingURL=next-middleware-loader.js.map

View File

@@ -0,0 +1,129 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
default: null,
getRouteLoaderEntry: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
default: function() {
return _default;
},
getRouteLoaderEntry: function() {
return getRouteLoaderEntry;
}
});
const _querystring = require("querystring");
const _getmodulebuildinfo = require("../get-module-build-info");
const _routekind = require("../../../../server/future/route-kind");
const _normalizepagepath = require("../../../../shared/lib/page-path/normalize-page-path");
const _utils = require("../utils");
const _utils1 = require("../../../utils");
const _loadentrypoint = require("../../../load-entrypoint");
function getRouteLoaderEntry(options) {
switch(options.kind){
case _routekind.RouteKind.PAGES:
{
const query = {
kind: options.kind,
page: options.page,
preferredRegion: options.preferredRegion,
absolutePagePath: options.absolutePagePath,
// These are the path references to the internal components that may be
// overridden by userland components.
absoluteAppPath: options.pages["/_app"],
absoluteDocumentPath: options.pages["/_document"],
middlewareConfigBase64: (0, _utils.encodeToBase64)(options.middlewareConfig)
};
return `next-route-loader?${(0, _querystring.stringify)(query)}!`;
}
case _routekind.RouteKind.PAGES_API:
{
const query = {
kind: options.kind,
page: options.page,
preferredRegion: options.preferredRegion,
absolutePagePath: options.absolutePagePath,
middlewareConfigBase64: (0, _utils.encodeToBase64)(options.middlewareConfig)
};
return `next-route-loader?${(0, _querystring.stringify)(query)}!`;
}
default:
{
throw new Error("Invariant: Unexpected route kind");
}
}
}
const loadPages = async ({ page, absolutePagePath, absoluteDocumentPath, absoluteAppPath, preferredRegion, middlewareConfigBase64 }, buildInfo)=>{
const middlewareConfig = (0, _utils.decodeFromBase64)(middlewareConfigBase64);
// Attach build info to the module.
buildInfo.route = {
page,
absolutePagePath,
preferredRegion,
middlewareConfig
};
let file = await (0, _loadentrypoint.loadEntrypoint)("pages", {
VAR_USERLAND: absolutePagePath,
VAR_MODULE_DOCUMENT: absoluteDocumentPath,
VAR_MODULE_APP: absoluteAppPath,
VAR_DEFINITION_PAGE: (0, _normalizepagepath.normalizePagePath)(page),
VAR_DEFINITION_PATHNAME: page
});
if ((0, _utils1.isInstrumentationHookFile)(page)) {
// When we're building the instrumentation page (only when the
// instrumentation file conflicts with a page also labeled
// /instrumentation) hoist the `register` method.
file += '\nexport const register = hoist(userland, "register")';
}
return file;
};
const loadPagesAPI = async ({ page, absolutePagePath, preferredRegion, middlewareConfigBase64 }, buildInfo)=>{
const middlewareConfig = (0, _utils.decodeFromBase64)(middlewareConfigBase64);
// Attach build info to the module.
buildInfo.route = {
page,
absolutePagePath,
preferredRegion,
middlewareConfig
};
return await (0, _loadentrypoint.loadEntrypoint)("pages-api", {
VAR_USERLAND: absolutePagePath,
VAR_DEFINITION_PAGE: (0, _normalizepagepath.normalizePagePath)(page),
VAR_DEFINITION_PATHNAME: page
});
};
/**
* Handles the `next-route-loader` options.
* @returns the loader definition function
*/ const loader = async function() {
if (!this._module) {
throw new Error("Invariant: expected this to reference a module");
}
const buildInfo = (0, _getmodulebuildinfo.getModuleBuildInfo)(this._module);
const opts = this.getOptions();
switch(opts.kind){
case _routekind.RouteKind.PAGES:
{
return await loadPages(opts, buildInfo);
}
case _routekind.RouteKind.PAGES_API:
{
return await loadPagesAPI(opts, buildInfo);
}
default:
{
throw new Error("Invariant: Unexpected route kind");
}
}
};
const _default = loader;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,40 @@
/**
* **PostCSS Syntax Error**
*
* Loader wrapper for postcss syntax errors
*
* @class SyntaxError
* @extends Error
*
* @param {Object} err CssSyntaxError
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return PostCSSSyntaxError;
}
});
class PostCSSSyntaxError extends Error {
constructor(error){
super(error);
const { line, column, reason, plugin, file } = error;
this.name = "SyntaxError";
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
this.message += `(${line}:${column}) `;
}
this.message += plugin ? `${plugin}: ` : "";
this.message += file ? `${file} ` : "<css input> ";
this.message += reason;
const code = error.showSourceCode();
if (code) {
this.message += `\n\n${code}\n`;
}
this.stack = false;
}
}
//# sourceMappingURL=Error.js.map

View File

@@ -0,0 +1,35 @@
/**
* **PostCSS Plugin Warning**
*
* Loader wrapper for postcss plugin warnings (`root.messages`)
*
* @class Warning
* @extends Error
*
* @param {Object} warning PostCSS Warning
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return Warning;
}
});
class Warning extends Error {
constructor(warning){
super(warning);
const { text, line, column, plugin } = warning;
this.name = "Warning";
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
this.message += `(${line}:${column}) `;
}
this.message += plugin ? `${plugin}: ` : "";
this.message += text;
this.stack = false;
}
}
//# sourceMappingURL=Warning.js.map

View File

@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, /**
* **PostCSS Loader**
*
* Loads && processes CSS with [PostCSS](https://github.com/postcss/postcss)
*/ "default", {
enumerable: true,
get: function() {
return loader;
}
});
const _Warning = /*#__PURE__*/ _interop_require_default(require("./Warning"));
const _Error = /*#__PURE__*/ _interop_require_default(require("./Error"));
const _utils = require("./utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function loader(/** Source */ content, /** Source Map */ sourceMap, meta) {
const loaderSpan = this.currentTraceSpan.traceChild("postcss-loader");
const callback = this.async();
loaderSpan.traceAsyncFn(async ()=>{
const options = this.getOptions();
const file = this.resourcePath;
const useSourceMap = typeof options.sourceMap !== "undefined" ? options.sourceMap : this.sourceMap;
const processOptions = {
from: file,
to: file
};
if (useSourceMap) {
processOptions.map = {
inline: false,
annotation: false,
...processOptions.map
};
}
if (sourceMap && processOptions.map) {
processOptions.map.prev = loaderSpan.traceChild("normalize-source-map").traceFn(()=>(0, _utils.normalizeSourceMap)(sourceMap, this.context));
}
let root;
// Reuse PostCSS AST from other loaders
if (meta && meta.ast && meta.ast.type === "postcss") {
({ root } = meta.ast);
loaderSpan.setAttribute("astUsed", "true");
}
// Initializes postcss with plugins
const { postcssWithPlugins } = await options.postcss();
let result;
try {
result = await loaderSpan.traceChild("postcss-process").traceAsyncFn(()=>postcssWithPlugins.process(root || content, processOptions));
} catch (error) {
if (error.file) {
this.addDependency(error.file);
}
if (error.name === "CssSyntaxError") {
throw new _Error.default(error);
}
throw error;
}
for (const warning of result.warnings()){
this.emitWarning(new _Warning.default(warning));
}
for (const message of result.messages){
// eslint-disable-next-line default-case
switch(message.type){
case "dependency":
this.addDependency(message.file);
break;
case "build-dependency":
this.addBuildDependency(message.file);
break;
case "missing-dependency":
this.addMissingDependency(message.file);
break;
case "context-dependency":
this.addContextDependency(message.file);
break;
case "dir-dependency":
this.addContextDependency(message.dir);
break;
case "asset":
if (message.content && message.file) {
this.emitFile(message.file, message.content, message.sourceMap, message.info);
}
}
}
// eslint-disable-next-line no-undefined
let map = result.map ? result.map.toJSON() : undefined;
if (map && useSourceMap) {
map = (0, _utils.normalizeSourceMapAfterPostcss)(map, this.context);
}
const ast = {
type: "postcss",
version: result.processor.version,
root: result.root
};
return [
result.css,
map,
{
ast
}
];
}).then(([css, map, { ast }])=>{
callback == null ? void 0 : callback(null, css, map, {
ast
});
}, (err)=>{
callback == null ? void 0 : callback(err);
});
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,89 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
normalizeSourceMap: null,
normalizeSourceMapAfterPostcss: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
normalizeSourceMap: function() {
return normalizeSourceMap;
},
normalizeSourceMapAfterPostcss: function() {
return normalizeSourceMapAfterPostcss;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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, resourceContext) {
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) {
newMap.sources = newMap.sources.map((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.default.resolve(sourceRoot, _path.default.normalize(source)) : _path.default.normalize(source);
return _path.default.relative(resourceContext, absoluteSource);
}
return source;
});
}
return newMap;
}
function normalizeSourceMapAfterPostcss(map, resourceContext) {
const newMap = map;
// result.map.file is an optional property that provides the output filename.
// Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
// eslint-disable-next-line no-param-reassign
delete newMap.file;
// eslint-disable-next-line no-param-reassign
newMap.sourceRoot = "";
// eslint-disable-next-line no-param-reassign
newMap.sources = newMap.sources.map((source)=>{
if (source.indexOf("<") === 0) {
return source;
}
const sourceType = getURLType(source);
// Do no touch `scheme-relative`, `path-absolute` and `absolute` types
if (sourceType === "path-relative") {
return _path.default.resolve(resourceContext, source);
}
return source;
});
return newMap;
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,100 @@
/*
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
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.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, /**
* A webpack loader that resolves absolute url() paths relative to their original source file.
* Requires source-maps to do any meaningful work.
*/ "default", {
enumerable: true,
get: function() {
return resolveUrlLoader;
}
});
const _sourcemap = require("next/dist/compiled/source-map");
const _valueprocessor = /*#__PURE__*/ _interop_require_default(require("./lib/value-processor"));
const _joinfunction = require("./lib/join-function");
const _postcss = /*#__PURE__*/ _interop_require_default(require("./lib/postcss"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function resolveUrlLoader(/** Css content */ content, /** The source-map */ sourceMap) {
const options = Object.assign({
sourceMap: this.sourceMap,
silent: false,
absolute: false,
keepQuery: false,
root: false,
debug: false,
join: _joinfunction.defaultJoin
}, this.getOptions());
let sourceMapConsumer;
if (sourceMap) {
sourceMapConsumer = new _sourcemap.SourceMapConsumer(sourceMap);
}
const callback = this.async();
const { postcss } = options.postcss ? await options.postcss() : {
postcss: require("postcss")
};
(0, _postcss.default)(postcss, this.resourcePath, content, {
outputSourceMap: Boolean(options.sourceMap),
transformDeclaration: (0, _valueprocessor.default)(this.resourcePath, options),
inputSourceMap: sourceMap,
sourceMapConsumer: sourceMapConsumer
})// eslint-disable-next-line @typescript-eslint/no-use-before-define
.catch(onFailure)// eslint-disable-next-line @typescript-eslint/no-use-before-define
.then(onSuccess);
function onFailure(error) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
callback(encodeError("CSS error", error));
}
function onSuccess(reworked) {
if (reworked) {
// complete with source-map
// source-map sources are relative to the file being processed
if (options.sourceMap) {
callback(null, reworked.content, reworked.map);
} else {
callback(null, reworked.content);
}
}
}
function encodeError(label, exception) {
return new Error([
"resolve-url-loader",
": ",
[
label
].concat(typeof exception === "string" && exception || exception instanceof Error && [
exception.message,
exception.stack.split("\n", 2)[1].trim()
] || []).filter(Boolean).join("\n ")
].join(""));
}
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,70 @@
/*
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
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.
*/ /**
* Prepend file:// protocol to source path string or source-map sources.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
prepend: null,
remove: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
prepend: function() {
return prepend;
},
remove: function() {
return remove;
}
});
function prepend(candidate) {
if (typeof candidate === "string") {
return "file://" + candidate;
} else if (candidate && typeof candidate === "object" && Array.isArray(candidate.sources)) {
return Object.assign({}, candidate, {
sources: candidate.sources.map(prepend)
});
} else {
throw new Error("expected string|object");
}
}
function remove(candidate) {
if (typeof candidate === "string") {
return candidate.replace(/^file:\/{2}/, "");
} else if (candidate && typeof candidate === "object" && Array.isArray(candidate.sources)) {
return Object.assign({}, candidate, {
sources: candidate.sources.map(remove)
});
} else {
throw new Error("expected string|object");
}
}
//# sourceMappingURL=file-protocol.js.map

View File

@@ -0,0 +1,186 @@
// TODO: Remove use of `any` type. Fix no-use-before-define violations.
/* eslint-disable @typescript-eslint/no-use-before-define */ /*
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
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.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "defaultJoin", {
enumerable: true,
get: function() {
return defaultJoin;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const compose = (f, g)=>(...args)=>f(g(...args));
const simpleJoin = compose(_path.default.normalize, _path.default.join);
const defaultJoin = createJoinForPredicate(function predicate(_, uri, base, i, next) {
const absolute = simpleJoin(base, uri);
return _fs.default.existsSync(absolute) ? absolute : next(i === 0 ? absolute : null);
}, "defaultJoin");
function* createIterator(arr) {
for (const i of arr){
yield i;
}
}
/**
* Define a join function by a predicate that tests possible base paths from an iterator.
*
* The `predicate` is of the form:
*
* ```
* function(filename, uri, base, i, next):string|null
* ```
*
* Given the uri and base it should either return:
* - an absolute path success
* - a call to `next(null)` as failure
* - a call to `next(absolute)` where absolute is placeholder and the iterator continues
*
* The value given to `next(...)` is only used if success does not eventually occur.
*
* The `file` value is typically unused but useful if you would like to differentiate behaviour.
*
* You can write a much simpler function than this if you have specific requirements.
*
*/ function createJoinForPredicate(/** predicate A function that tests values */ predicate, /** Optional name for the resulting join function */ name) {
/**
* A factory for a join function with logging.
*/ function join(/** The current file being processed */ filename, /** An options hash */ options) {
const log = createDebugLogger(options.debug);
/**
* Join function proper.
*
* For absolute uri only `uri` will be provided. In this case we substitute any `root` given in options.
*
* Returns Just the uri where base is empty or the uri appended to the base
*/ return function joinProper(/** A uri path, relative or absolute */ uri, /** Optional absolute base path or iterator thereof */ baseOrIteratorOrAbsent) {
const iterator = typeof baseOrIteratorOrAbsent === "undefined" && createIterator([
options.root
]) || typeof baseOrIteratorOrAbsent === "string" && createIterator([
baseOrIteratorOrAbsent
]) || baseOrIteratorOrAbsent;
const result = runIterator([]);
log(createJoinMsg, [
filename,
uri,
result,
result.isFound
]);
return typeof result.absolute === "string" ? result.absolute : uri;
function runIterator(accumulator) {
const nextItem = iterator.next();
var base = !nextItem.done && nextItem.value;
if (typeof base === "string") {
const element = predicate(filename, uri, base, accumulator.length, next);
if (typeof element === "string" && _path.default.isAbsolute(element)) {
return Object.assign(accumulator.concat(base), {
isFound: true,
absolute: element
});
} else if (Array.isArray(element)) {
return element;
} else {
throw new Error("predicate must return an absolute path or the result of calling next()");
}
} else {
return accumulator;
}
function next(fallback) {
return runIterator(Object.assign(accumulator.concat(base), typeof fallback === "string" && {
absolute: fallback
}));
}
}
};
}
function toString() {
return "[Function: " + name + "]";
}
return Object.assign(join, name && {
valueOf: toString,
toString: toString
});
}
/**
* Format a debug message.
* Return Formatted message
*/ function createJoinMsg(/** The file being processed by webpack */ file, /** A uri path, relative or absolute */ uri, /** Absolute base paths up to and including the found one */ bases, /** Indicates the last base was correct */ isFound) {
return [
"resolve-url-loader: " + pathToString(file) + ": " + uri,
//
...bases.map(pathToString).filter(Boolean),
...isFound ? [
"FOUND"
] : [
"NOT FOUND"
]
].join("\n ");
/**
* If given path is within `process.cwd()` then show relative posix path, otherwise show absolute posix path.
*
* Returns A relative or absolute path
*/ function pathToString(/** An absolute path */ absolute) {
if (!absolute) {
return null;
} else {
const relative = _path.default.relative(process.cwd(), absolute).split(_path.default.sep);
return (relative[0] === ".." ? absolute.split(_path.default.sep) : [
"."
].concat(relative).filter(Boolean)).join("/");
}
}
}
exports.createJoinMsg = createJoinMsg;
/**
* A factory for a log function predicated on the given debug parameter.
*
* The logging function created accepts a function that formats a message and parameters that the function utilises.
* Presuming the message function may be expensive we only call it if logging is enabled.
*
* The log messages are de-duplicated based on the parameters, so it is assumed they are simple types that stringify
* well.
*
* Returns A logging function possibly degenerate
*/ function createDebugLogger(/** A boolean or debug function */ debug) {
const log = !!debug && (typeof debug === "function" ? debug : console.log);
const cache = {};
return log ? actuallyLog : noop;
function noop() {}
function actuallyLog(msgFn, params) {
const key = JSON.stringify(params);
if (!cache[key]) {
cache[key] = true;
log(msgFn.apply(null, params));
}
}
}
exports.createDebugLogger = createDebugLogger;
//# sourceMappingURL=join-function.js.map

View File

@@ -0,0 +1,90 @@
/*
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
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.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return process;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _fileprotocol = require("./file-protocol");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const ORPHAN_CR_REGEX = /\r(?!\n)(.|\n)?/g;
function process(postcss, sourceFile, sourceContent, params) {
// #107 libsass emits orphan CR not considered newline, postcss does consider newline (content vs source-map mismatch)
postcssPlugin.postcss = true;
// prepend file protocol to all sources to avoid problems with source map
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return postcss([
postcssPlugin
]).process(sourceContent, {
from: (0, _fileprotocol.prepend)(sourceFile),
map: params.outputSourceMap && {
prev: !!params.inputSourceMap && (0, _fileprotocol.prepend)(params.inputSourceMap),
inline: false,
annotation: false,
sourcesContent: true
}
}).then((result)=>({
content: result.css,
map: params.outputSourceMap ? (0, _fileprotocol.remove)(result.map.toJSON()) : null
}));
/**
* Plugin for postcss that follows SASS transpilation.
*/ function postcssPlugin() {
return {
postcssPlugin: "postcss-resolve-url",
Once: function(root) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
root.walkDecls(eachDeclaration);
}
};
/**
* Process a declaration from the syntax tree.
* @param declaration
*/ function eachDeclaration(declaration) {
const isValid = declaration.value && declaration.value.indexOf("url") >= 0;
if (isValid) {
// reverse the original source-map to find the original source file before transpilation
const startPosApparent = declaration.source.start, startPosOriginal = params.sourceMapConsumer && params.sourceMapConsumer.originalPositionFor(startPosApparent);
// we require a valid directory for the specified file
const directory = startPosOriginal && startPosOriginal.source && (0, _fileprotocol.remove)(_path.default.dirname(startPosOriginal.source));
if (directory) {
declaration.value = params.transformDeclaration(declaration.value, directory);
} else if (params.sourceMapConsumer) {
throw new Error("source-map information is not available at url() declaration " + (ORPHAN_CR_REGEX.test(sourceContent) ? "(found orphan CR, try removeCR option)" : "(no orphan CR found)"));
}
}
}
}
}
//# sourceMappingURL=postcss.js.map

View File

@@ -0,0 +1,99 @@
/*
The MIT License (MIT)
Copyright (c) 2016 Ben Holloway
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.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return _default;
}
});
const _loaderutils2 = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/loader-utils2"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function valueProcessor(filename, options) {
const URL_STATEMENT_REGEX = /(url\s*\()\s*(?:(['"])((?:(?!\2).)*)(\2)|([^'"](?:(?!\)).)*[^'"]))\s*(\))/g;
const directory = _path.default.dirname(filename);
const join = options.join(filename, options);
/**
* Process the given CSS declaration value.
*
*/ return function transformValue(/** A declaration value that may or may not contain a url() statement */ value, /** An absolute path that may be the correct base or an Iterator thereof */ candidate) {
// allow multiple url() values in the declaration
// split by url statements and process the content
// additional capture groups are needed to match quotations correctly
// escaped quotations are not considered
return value.split(URL_STATEMENT_REGEX).map((token, i, arr)=>{
// we can get groups as undefined under certain match circumstances
const initialised = token || "";
// the content of the url() statement is either in group 3 or group 5
const mod = i % 7;
if (mod === 3 || mod === 5) {
// detect quoted url and unescape backslashes
const before = arr[i - 1], after = arr[i + 1], isQuoted = before === after && (before === "'" || before === '"'), unescaped = isQuoted ? initialised.replace(/\\{2}/g, "\\") : initialised;
// split into uri and query/hash and then find the absolute path to the uri
const split = unescaped.split(/([?#])/g), uri = split[0], absolute = // eslint-disable-next-line @typescript-eslint/no-use-before-define
testIsRelative(uri) && join(uri, candidate) || // eslint-disable-next-line @typescript-eslint/no-use-before-define
testIsAbsolute(uri) && join(uri), query = options.keepQuery ? split.slice(1).join("") : "";
// use the absolute path in absolute mode or else relative path (or default to initialised)
// #6 - backslashes are not legal in URI
if (!absolute) {
return initialised;
} else if (options.absolute) {
return absolute.replace(/\\/g, "/") + query;
} else {
return _loaderutils2.default.urlToRequest(_path.default.relative(directory, absolute).replace(/\\/g, "/") + query);
}
} else {
return initialised;
}
}).join("");
};
/**
* The loaderUtils.isUrlRequest() doesn't support windows absolute paths on principle. We do not subscribe to that
* dogma so we add path.isAbsolute() check to allow them.
*
* We also eliminate module relative (~) paths.
*
* Returns true for relative uri
*/ function testIsRelative(/** A uri string possibly empty or undefined */ uri) {
return !!uri && _loaderutils2.default.isUrlRequest(uri, false) && !_path.default.isAbsolute(uri) && uri.indexOf("~") !== 0;
}
/**
* The loaderUtils.isUrlRequest() doesn't support windows absolute paths on principle. We do not subscribe to that
* dogma so we add path.isAbsolute() check to allow them.
*
* Returns true for absolute uri
*/ function testIsAbsolute(/** A uri string possibly empty or undefined */ uri) {
return !!uri && typeof options.root === "string" && _loaderutils2.default.isUrlRequest(uri, options.root) && (/^\//.test(uri) || _path.default.isAbsolute(uri));
}
}
const _default = valueProcessor;
//# sourceMappingURL=value-processor.js.map

View File

@@ -0,0 +1,104 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
decodeFromBase64: null,
encodeToBase64: null,
generateActionId: null,
getActions: null,
getLoaderModuleNamedExports: null,
isCSSMod: null,
isClientComponentEntryModule: null,
regexCSS: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
decodeFromBase64: function() {
return decodeFromBase64;
},
encodeToBase64: function() {
return encodeToBase64;
},
generateActionId: function() {
return generateActionId;
},
getActions: function() {
return getActions;
},
getLoaderModuleNamedExports: function() {
return getLoaderModuleNamedExports;
},
isCSSMod: function() {
return isCSSMod;
},
isClientComponentEntryModule: function() {
return isClientComponentEntryModule;
},
regexCSS: function() {
return regexCSS;
}
});
const _crypto = require("crypto");
const _constants = require("../../../shared/lib/constants");
const imageExtensions = [
"jpg",
"jpeg",
"png",
"webp",
"avif",
"ico",
"svg"
];
const imageRegex = new RegExp(`\\.(${imageExtensions.join("|")})$`);
function isClientComponentEntryModule(mod) {
const rscInfo = mod.buildInfo.rsc;
const hasClientDirective = rscInfo == null ? void 0 : rscInfo.isClientRef;
const isActionLayerEntry = (rscInfo == null ? void 0 : rscInfo.actions) && (rscInfo == null ? void 0 : rscInfo.type) === _constants.RSC_MODULE_TYPES.client;
return hasClientDirective || isActionLayerEntry || imageRegex.test(mod.resource);
}
const regexCSS = /\.(css|scss|sass)(\?.*)?$/;
function isCSSMod(mod) {
var _mod_loaders;
return !!(mod.type === "css/mini-extract" || mod.resource && regexCSS.test(mod.resource) || ((_mod_loaders = mod.loaders) == null ? void 0 : _mod_loaders.some(({ loader })=>loader.includes("next-style-loader/index.js") || loader.includes("mini-css-extract-plugin/loader.js") || loader.includes("@vanilla-extract/webpack-plugin/loader/"))));
}
function getActions(mod) {
var _mod_buildInfo_rsc, _mod_buildInfo;
return (_mod_buildInfo = mod.buildInfo) == null ? void 0 : (_mod_buildInfo_rsc = _mod_buildInfo.rsc) == null ? void 0 : _mod_buildInfo_rsc.actions;
}
function generateActionId(filePath, exportName) {
return (0, _crypto.createHash)("sha1").update(filePath + ":" + exportName).digest("hex");
}
function encodeToBase64(obj) {
return Buffer.from(JSON.stringify(obj)).toString("base64");
}
function decodeFromBase64(str) {
return JSON.parse(Buffer.from(str, "base64").toString("utf8"));
}
async function getLoaderModuleNamedExports(resourcePath, context) {
var _mod_dependencies;
const mod = await new Promise((res, rej)=>{
context.loadModule(resourcePath, (err, _source, _sourceMap, module1)=>{
if (err) {
return rej(err);
}
res(module1);
});
});
const exportNames = ((_mod_dependencies = mod.dependencies) == null ? void 0 : _mod_dependencies.filter((dep)=>{
return [
"HarmonyExportImportedSpecifierDependency",
"HarmonyExportSpecifierDependency"
].includes(dep.constructor.name) && "name" in dep && dep.name !== "default";
}).map((dep)=>{
return dep.name;
})) || [];
return exportNames;
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "AppBuildManifestPlugin", {
enumerable: true,
get: function() {
return AppBuildManifestPlugin;
}
});
const _webpack = require("next/dist/compiled/webpack/webpack");
const _constants = require("../../../shared/lib/constants");
const _buildmanifestplugin = require("./build-manifest-plugin");
const _getapproutefromentrypoint = /*#__PURE__*/ _interop_require_default(require("../../../server/get-app-route-from-entrypoint"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const PLUGIN_NAME = "AppBuildManifestPlugin";
class AppBuildManifestPlugin {
constructor(options){
this.dev = options.dev;
}
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory })=>{
compilation.dependencyFactories.set(_webpack.webpack.dependencies.ModuleDependency, normalModuleFactory);
compilation.dependencyTemplates.set(_webpack.webpack.dependencies.ModuleDependency, new _webpack.webpack.dependencies.NullDependency.Template());
});
compiler.hooks.make.tap(PLUGIN_NAME, (compilation)=>{
compilation.hooks.processAssets.tap({
name: PLUGIN_NAME,
stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, (assets)=>this.createAsset(assets, compilation));
});
}
createAsset(assets, compilation) {
const manifest = {
pages: {}
};
const mainFiles = new Set((0, _buildmanifestplugin.getEntrypointFiles)(compilation.entrypoints.get(_constants.CLIENT_STATIC_FILES_RUNTIME_MAIN_APP)));
for (const entrypoint of compilation.entrypoints.values()){
if (!entrypoint.name) {
continue;
}
if (_constants.SYSTEM_ENTRYPOINTS.has(entrypoint.name)) {
continue;
}
const pagePath = (0, _getapproutefromentrypoint.default)(entrypoint.name);
if (!pagePath) {
continue;
}
const filesForPage = (0, _buildmanifestplugin.getEntrypointFiles)(entrypoint);
manifest.pages[pagePath] = [
...new Set([
...mainFiles,
...filesForPage
])
];
}
const json = JSON.stringify(manifest, null, 2);
assets[_constants.APP_BUILD_MANIFEST] = new _webpack.sources.RawSource(json);
}
}
//# sourceMappingURL=app-build-manifest-plugin.js.map

View File

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

View File

@@ -0,0 +1,67 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "CopyFilePlugin", {
enumerable: true,
get: function() {
return CopyFilePlugin;
}
});
const _fs = require("fs");
const _loaderutils3 = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/loader-utils3"));
const _webpack = require("next/dist/compiled/webpack/webpack");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const PLUGIN_NAME = "CopyFilePlugin";
class CopyFilePlugin {
constructor({ filePath, cacheKey, name, info }){
this.filePath = filePath;
this.cacheKey = cacheKey;
this.name = name;
this.info = info;
}
apply(compiler) {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation)=>{
const cache = compilation.getCache("CopyFilePlugin");
const hook = compilation.hooks.processAssets;
hook.tapPromise({
name: PLUGIN_NAME,
stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, async ()=>{
if (cache) {
const cachedResult = await cache.getPromise(this.filePath, this.cacheKey);
if (cachedResult) {
const { file, source } = cachedResult;
compilation.emitAsset(file, source, {
...this.info
});
return;
}
}
const content = await _fs.promises.readFile(this.filePath, "utf8");
const file = _loaderutils3.default.interpolateName({
resourcePath: this.filePath
}, this.name, {
content,
context: compiler.context
});
const source = new _webpack.sources.RawSource(content);
if (cache) {
await cache.storePromise(this.filePath, this.cacheKey, {
file,
source
});
}
compilation.emitAsset(file, source, {
...this.info
});
});
});
}
}
//# sourceMappingURL=copy-file-plugin.js.map

View File

@@ -0,0 +1,277 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "CssChunkingPlugin", {
enumerable: true,
get: function() {
return CssChunkingPlugin;
}
});
const PLUGIN_NAME = "CssChunkingPlugin";
/**
* Merge chunks until they are bigger than the target size.
*/ const MIN_CSS_CHUNK_SIZE = 30 * 1024;
/**
* Avoid merging chunks when they would be bigger than this size.
*/ const MAX_CSS_CHUNK_SIZE = 100 * 1024;
function isGlobalCss(module) {
return !/\.module\.(css|scss|sass)$/.test(module.nameForCondition() || "");
}
class CssChunkingPlugin {
constructor(strict){
this.strict = strict;
}
apply(compiler) {
const strict = this.strict;
const summary = !!process.env.CSS_CHUNKING_SUMMARY;
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation)=>{
let once = false;
compilation.hooks.optimizeChunks.tap({
name: PLUGIN_NAME,
stage: 5
}, ()=>{
if (once) {
return;
}
once = true;
const chunkGraph = compilation.chunkGraph;
let changed = undefined;
const chunkStates = new Map();
const chunkStatesByModule = new Map();
// Collect all css modules in chunks and the execpted order of them
for (const chunk of compilation.chunks){
var _chunk_name;
if ((_chunk_name = chunk.name) == null ? void 0 : _chunk_name.startsWith("pages/")) continue;
const modules = [];
for (const module of chunkGraph.getChunkModulesIterable(chunk)){
var _module_type;
if (!((_module_type = module.type) == null ? void 0 : _module_type.startsWith("css"))) continue;
modules.push(module);
}
if (!modules.length) continue;
const chunkState = {
chunk,
modules,
order: 0,
requests: modules.length
};
chunkStates.set(chunk, chunkState);
for(let i = 0; i < modules.length; i++){
const module = modules[i];
let moduleChunkStates = chunkStatesByModule.get(module);
if (!moduleChunkStates) {
moduleChunkStates = new Map();
chunkStatesByModule.set(module, moduleChunkStates);
}
moduleChunkStates.set(chunkState, i);
chunkStatesByModule.set(module, moduleChunkStates);
}
}
// Sort modules by their index sum
const orderedModules = [];
for (const [module, moduleChunkStates] of chunkStatesByModule){
let sum = 0;
for (const i of moduleChunkStates.values()){
sum += i;
}
orderedModules.push({
module,
sum
});
}
orderedModules.sort((a, b)=>a.sum - b.sum);
// A queue of modules that still need to be processed
const remainingModules = new Set(orderedModules.map(({ module })=>module));
// In loose mode we guess the dependents of modules from the order
// assuming that when a module is a dependency of another module
// it will always appear before it in every chunk.
const allDependents = new Map();
if (!this.strict) {
for (const b of remainingModules){
const dependent = new Set();
loop: for (const a of remainingModules){
if (a === b) continue;
// check if a depends on b
for (const [chunkState, ia] of chunkStatesByModule.get(a)){
const bChunkStates = chunkStatesByModule.get(b);
const ib = bChunkStates.get(chunkState);
if (ib === undefined) {
continue loop;
}
if (ib > ia) {
continue loop;
}
}
dependent.add(a);
}
if (dependent.size > 0) allDependents.set(b, dependent);
}
}
// Stores the new chunk for every module
const newChunksByModule = new Map();
// Process through all modules
for (const startModule of remainingModules){
let globalCssMode = isGlobalCss(startModule);
// The current position of processing in all selected chunks
let allChunkStates = new Map(chunkStatesByModule.get(startModule));
// The list of modules that goes into the new chunk
const newChunkModules = new Set([
startModule
]);
// The current size of the new chunk
let currentSize = startModule.size();
// A pool of potential modules where the next module is selected from.
// It's filled from the next module of the selected modules in every chunk.
// It also keeps some metadata to improve performance [size, chunkStates].
const potentialNextModules = new Map();
for (const [chunkState, i] of allChunkStates){
const nextModule = chunkState.modules[i + 1];
if (nextModule && remainingModules.has(nextModule)) {
potentialNextModules.set(nextModule, [
nextModule.size(),
chunkStatesByModule.get(nextModule)
]);
}
}
// Try to add modules to the chunk until a break condition is met
let cont;
do {
cont = false;
// We try to select a module that reduces request count and
// has the highest number of requests
const orderedPotentialNextModules = [];
for (const [nextModule, [size, nextChunkStates]] of potentialNextModules){
let maxRequests = 0;
for (const chunkState of nextChunkStates.keys()){
// There is always some overlap
if (allChunkStates.has(chunkState)) {
maxRequests = Math.max(maxRequests, chunkState.requests);
}
}
orderedPotentialNextModules.push([
nextModule,
size,
nextChunkStates,
maxRequests
]);
}
orderedPotentialNextModules.sort((a, b)=>b[3] - a[3] || (a[0].identifier() < b[0].identifier() ? -1 : 1));
// Try every potential module
loop: for (const [nextModule, size, nextChunkStates] of orderedPotentialNextModules){
if (currentSize + size > MAX_CSS_CHUNK_SIZE) {
continue;
}
if (!strict) {
// In loose mode we only check if the dependencies are not violated
const dependent = allDependents.get(nextModule);
if (dependent) {
for (const dep of dependent){
if (newChunkModules.has(dep)) {
continue loop;
}
}
}
} else {
// In strict mode we check that none of the order in any chunk is changed by adding the module
for (const [chunkState, i] of nextChunkStates){
const prevState = allChunkStates.get(chunkState);
if (prevState === undefined) {
// New chunk group, can add it, but should we?
// We only add that if below min size
if (currentSize < MIN_CSS_CHUNK_SIZE) {
continue;
} else {
continue loop;
}
} else if (prevState + 1 === i) {
continue;
} else {
continue loop;
}
}
}
// Global CSS must not leak into unrelated chunks
const nextIsGlobalCss = isGlobalCss(nextModule);
if (nextIsGlobalCss && globalCssMode) {
if (allChunkStates.size !== nextChunkStates.size) {
continue;
}
}
if (globalCssMode) {
for (const chunkState of nextChunkStates.keys()){
if (!allChunkStates.has(chunkState)) {
continue loop;
}
}
}
if (nextIsGlobalCss) {
for (const chunkState of allChunkStates.keys()){
if (!nextChunkStates.has(chunkState)) {
continue loop;
}
}
}
potentialNextModules.delete(nextModule);
currentSize += size;
if (nextIsGlobalCss) {
globalCssMode = true;
}
for (const [chunkState, i] of nextChunkStates){
if (allChunkStates.has(chunkState)) {
// This reduces the request count of the chunk group
chunkState.requests--;
}
allChunkStates.set(chunkState, i);
const newNextModule = chunkState.modules[i + 1];
if (newNextModule && remainingModules.has(newNextModule) && !newChunkModules.has(newNextModule)) {
potentialNextModules.set(newNextModule, [
newNextModule.size(),
chunkStatesByModule.get(newNextModule)
]);
}
}
newChunkModules.add(nextModule);
cont = true;
break;
}
}while (cont);
const newChunk = compilation.addChunk();
newChunk.preventIntegration = true;
newChunk.idNameHints.add("css");
for (const module of newChunkModules){
remainingModules.delete(module);
chunkGraph.connectChunkAndModule(newChunk, module);
newChunksByModule.set(module, newChunk);
}
changed = true;
}
for (const { chunk, modules } of chunkStates.values()){
const chunks = new Set();
for (const module of modules){
const newChunk = newChunksByModule.get(module);
if (newChunk) {
chunkGraph.disconnectChunkAndModule(chunk, module);
if (chunks.has(newChunk)) continue;
chunks.add(newChunk);
chunk.split(newChunk);
}
}
}
if (summary) {
console.log("Top 20 chunks by request count:");
const orderedChunkStates = [
...chunkStates.values()
];
orderedChunkStates.sort((a, b)=>b.requests - a.requests);
for (const { chunk, modules, requests } of orderedChunkStates.slice(0, 20)){
console.log(`- ${requests} requests for ${chunk.name} (has ${modules.length} modules)`);
}
}
return changed;
});
});
}
}
//# sourceMappingURL=css-chunking-plugin.js.map

View File

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

View File

@@ -0,0 +1,172 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getDefineEnv: null,
getDefineEnvPlugin: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getDefineEnv: function() {
return getDefineEnv;
},
getDefineEnvPlugin: function() {
return getDefineEnvPlugin;
}
});
const _webpack = require("next/dist/compiled/webpack/webpack");
const _needsexperimentalreact = require("../../../lib/needs-experimental-react");
function errorIfEnvConflicted(config, key) {
const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key);
const hasNextRuntimeKey = key === "NEXT_RUNTIME";
if (isPrivateKey || hasNextRuntimeKey) {
throw new Error(`The key "${key}" under "env" in ${config.configFileName} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`);
}
}
/**
* Collects all environment variables that are using the `NEXT_PUBLIC_` prefix.
*/ function getNextPublicEnvironmentVariables() {
const defineEnv = {};
for(const key in process.env){
if (key.startsWith("NEXT_PUBLIC_")) {
const value = process.env[key];
if (value) {
defineEnv[`process.env.${key}`] = value;
}
}
}
return defineEnv;
}
/**
* Collects the `env` config value from the Next.js config.
*/ function getNextConfigEnv(config) {
// Refactored code below to use for-of
const defineEnv = {};
const env = config.env;
for(const key in env){
const value = env[key];
if (value) {
errorIfEnvConflicted(config, key);
defineEnv[`process.env.${key}`] = value;
}
}
return defineEnv;
}
/**
* Serializes the DefineEnv config so that it can be inserted into the code by Webpack/Turbopack, JSON stringifies each value.
*/ function serializeDefineEnv(defineEnv) {
const defineEnvStringified = {};
for(const key in defineEnv){
const value = defineEnv[key];
defineEnvStringified[key] = JSON.stringify(value);
}
return defineEnvStringified;
}
function getImageConfig(config, dev) {
var _config_images, _config_images1;
return {
"process.env.__NEXT_IMAGE_OPTS": {
deviceSizes: config.images.deviceSizes,
imageSizes: config.images.imageSizes,
path: config.images.path,
loader: config.images.loader,
dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,
unoptimized: config == null ? void 0 : (_config_images = config.images) == null ? void 0 : _config_images.unoptimized,
...dev ? {
// pass domains in development to allow validating on the client
domains: config.images.domains,
remotePatterns: (_config_images1 = config.images) == null ? void 0 : _config_images1.remotePatterns,
output: config.output
} : {}
}
};
}
function getDefineEnv({ isTurbopack, clientRouterFilters, config, dev, distDir, fetchCacheKeyPrefix, hasRewrites, isClient, isEdgeServer, isNodeOrEdgeCompilation, isNodeServer, middlewareMatchers }) {
var _config_experimental_staleTimes, _config_experimental_staleTimes1, _config_experimental_staleTimes2, _config_experimental_staleTimes3, _config_i18n;
const defineEnv = {
// internal field to identify the plugin config
__NEXT_DEFINE_ENV: true,
...getNextPublicEnvironmentVariables(),
...getNextConfigEnv(config),
...!isEdgeServer ? {} : {
EdgeRuntime: /**
* Cloud providers can set this environment variable to allow users
* and library authors to have different implementations based on
* the runtime they are running with, if it's not using `edge-runtime`
*/ process.env.NEXT_EDGE_RUNTIME_PROVIDER ?? "edge-runtime"
},
"process.turbopack": isTurbopack,
"process.env.TURBOPACK": isTurbopack,
// TODO: enforce `NODE_ENV` on `process.env`, and add a test:
"process.env.NODE_ENV": dev ? "development" : "production",
"process.env.NEXT_RUNTIME": isEdgeServer ? "edge" : isNodeServer ? "nodejs" : "",
"process.env.NEXT_MINIMAL": "",
"process.env.__NEXT_PPR": config.experimental.ppr === true,
"process.env.NEXT_DEPLOYMENT_ID": config.deploymentId || false,
"process.env.__NEXT_FETCH_CACHE_KEY_PREFIX": fetchCacheKeyPrefix ?? "",
"process.env.__NEXT_MIDDLEWARE_MATCHERS": middlewareMatchers ?? [],
"process.env.__NEXT_MANUAL_CLIENT_BASE_PATH": config.experimental.manualClientBasePath ?? false,
"process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME": JSON.stringify(isNaN(Number((_config_experimental_staleTimes = config.experimental.staleTimes) == null ? void 0 : _config_experimental_staleTimes.dynamic)) ? 30 // 30 seconds
: (_config_experimental_staleTimes1 = config.experimental.staleTimes) == null ? void 0 : _config_experimental_staleTimes1.dynamic),
"process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME": JSON.stringify(isNaN(Number((_config_experimental_staleTimes2 = config.experimental.staleTimes) == null ? void 0 : _config_experimental_staleTimes2.static)) ? 5 * 60 // 5 minutes
: (_config_experimental_staleTimes3 = config.experimental.staleTimes) == null ? void 0 : _config_experimental_staleTimes3.static),
"process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED": config.experimental.clientRouterFilter ?? true,
"process.env.__NEXT_CLIENT_ROUTER_S_FILTER": (clientRouterFilters == null ? void 0 : clientRouterFilters.staticFilter) ?? false,
"process.env.__NEXT_CLIENT_ROUTER_D_FILTER": (clientRouterFilters == null ? void 0 : clientRouterFilters.dynamicFilter) ?? false,
"process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE": config.experimental.optimisticClientCache ?? true,
"process.env.__NEXT_MIDDLEWARE_PREFETCH": config.experimental.middlewarePrefetch ?? "flexible",
"process.env.__NEXT_CROSS_ORIGIN": config.crossOrigin,
"process.browser": isClient,
"process.env.__NEXT_TEST_MODE": process.env.__NEXT_TEST_MODE ?? false,
// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
...dev && (isClient ?? isEdgeServer) ? {
"process.env.__NEXT_DIST_DIR": distDir
} : {},
"process.env.__NEXT_TRAILING_SLASH": config.trailingSlash,
"process.env.__NEXT_BUILD_INDICATOR": config.devIndicators.buildActivity ?? true,
"process.env.__NEXT_BUILD_INDICATOR_POSITION": config.devIndicators.buildActivityPosition ?? "bottom-right",
"process.env.__NEXT_STRICT_MODE": config.reactStrictMode === null ? false : config.reactStrictMode,
"process.env.__NEXT_STRICT_MODE_APP": // When next.config.js does not have reactStrictMode it's enabled by default.
config.reactStrictMode === null ? true : config.reactStrictMode,
"process.env.__NEXT_OPTIMIZE_FONTS": !dev && config.optimizeFonts,
"process.env.__NEXT_OPTIMIZE_CSS": (config.experimental.optimizeCss && !dev) ?? false,
"process.env.__NEXT_SCRIPT_WORKERS": (config.experimental.nextScriptWorkers && !dev) ?? false,
"process.env.__NEXT_SCROLL_RESTORATION": config.experimental.scrollRestoration ?? false,
...getImageConfig(config, dev),
"process.env.__NEXT_ROUTER_BASEPATH": config.basePath,
"process.env.__NEXT_STRICT_NEXT_HEAD": config.experimental.strictNextHead ?? false,
"process.env.__NEXT_HAS_REWRITES": hasRewrites,
"process.env.__NEXT_CONFIG_OUTPUT": config.output,
"process.env.__NEXT_I18N_SUPPORT": !!config.i18n,
"process.env.__NEXT_I18N_DOMAINS": ((_config_i18n = config.i18n) == null ? void 0 : _config_i18n.domains) ?? false,
"process.env.__NEXT_ANALYTICS_ID": config.analyticsId,
"process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE": config.skipMiddlewareUrlNormalize,
"process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE": config.experimental.externalMiddlewareRewritesResolve ?? false,
"process.env.__NEXT_MANUAL_TRAILING_SLASH": config.skipTrailingSlashRedirect,
"process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION": (config.experimental.webVitalsAttribution && config.experimental.webVitalsAttribution.length > 0) ?? false,
"process.env.__NEXT_WEB_VITALS_ATTRIBUTION": config.experimental.webVitalsAttribution ?? false,
"process.env.__NEXT_LINK_NO_TOUCH_START": config.experimental.linkNoTouchStart ?? false,
"process.env.__NEXT_ASSET_PREFIX": config.assetPrefix,
...isNodeOrEdgeCompilation ? {
// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
// This is typically found in unmaintained modules from the
// pre-webpack era (common in server-side code)
"global.GENTLY": false
} : undefined,
...isNodeOrEdgeCompilation ? {
"process.env.__NEXT_EXPERIMENTAL_REACT": (0, _needsexperimentalreact.needsExperimentalReact)(config)
} : undefined
};
return serializeDefineEnv(defineEnv);
}
function getDefineEnvPlugin(options) {
return new _webpack.webpack.DefinePlugin(getDefineEnv(options));
}
//# sourceMappingURL=define-env-plugin.js.map

View File

@@ -0,0 +1,699 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "FlightClientEntryPlugin", {
enumerable: true,
get: function() {
return FlightClientEntryPlugin;
}
});
const _webpack = require("next/dist/compiled/webpack/webpack");
const _querystring = require("querystring");
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _ondemandentryhandler = require("../../../server/dev/on-demand-entry-handler");
const _constants = require("../../../lib/constants");
const _constants1 = require("../../../shared/lib/constants");
const _utils = require("../loaders/utils");
const _utils1 = require("../utils");
const _normalizepathsep = require("../../../shared/lib/page-path/normalize-path-sep");
const _buildcontext = require("../../build-context");
const _pagetypes = require("../../../lib/page-types");
const _utils2 = require("../../utils");
const _getmodulebuildinfo = require("../loaders/get-module-build-info");
const _nextflightloader = require("../loaders/next-flight-loader");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const PLUGIN_NAME = "FlightClientEntryPlugin";
const pluginState = (0, _buildcontext.getProxiedPluginState)({
// A map to track "action" -> "list of bundles".
serverActions: {},
edgeServerActions: {},
actionModServerId: {},
actionModEdgeServerId: {},
// Mapping of resource path to module id for server/edge server.
serverModuleIds: {},
edgeServerModuleIds: {},
// Collect modules from server/edge compiler in client layer,
// and detect if it's been used, and mark it as `async: true` for react.
// So that react could unwrap the async module from promise and render module itself.
// Use an object to simulate Set lookup
ASYNC_CLIENT_MODULES: {},
injectedClientEntries: {}
});
function deduplicateCSSImportsForEntry(mergedCSSimports) {
// If multiple entry module connections are having the same CSS import,
// we only need to have one module to keep track of that CSS import.
// It is based on the fact that if a page or a layout is rendered in the
// given entry, all its parent layouts are always rendered too.
// This can avoid duplicate CSS imports in the generated CSS manifest,
// for example, if a page and its parent layout are both using the same
// CSS import, we only need to have the layout to keep track of that CSS
// import.
// To achieve this, we need to first collect all the CSS imports from
// every connection, and deduplicate them in the order of layers from
// top to bottom. The implementation can be generally described as:
// - Sort by number of `/` in the request path (the more `/`, the deeper)
// - When in the same depth, sort by the filename (template < layout < page and others)
// Sort the connections as described above.
const sortedCSSImports = Object.entries(mergedCSSimports).sort((a, b)=>{
const [aPath] = a;
const [bPath] = b;
const aDepth = aPath.split("/").length;
const bDepth = bPath.split("/").length;
if (aDepth !== bDepth) {
return aDepth - bDepth;
}
const aName = _path.default.parse(aPath).name;
const bName = _path.default.parse(bPath).name;
const indexA = [
"template",
"layout"
].indexOf(aName);
const indexB = [
"template",
"layout"
].indexOf(bName);
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
const dedupedCSSImports = {};
const trackedCSSImports = new Set();
for (const [entryName, cssImports] of sortedCSSImports){
for (const cssImport of cssImports){
if (trackedCSSImports.has(cssImport)) continue;
// Only track CSS imports that are in files that can inherit CSS.
const filename = _path.default.parse(entryName).name;
if ([
"template",
"layout"
].includes(filename)) {
trackedCSSImports.add(cssImport);
}
if (!dedupedCSSImports[entryName]) {
dedupedCSSImports[entryName] = [];
}
dedupedCSSImports[entryName].push(cssImport);
}
}
return dedupedCSSImports;
}
class FlightClientEntryPlugin {
constructor(options){
this.dev = options.dev;
this.appDir = options.appDir;
this.isEdgeServer = options.isEdgeServer;
this.assetPrefix = !this.dev && !this.isEdgeServer ? "../" : "";
this.encryptionKey = options.encryptionKey;
}
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory })=>{
compilation.dependencyFactories.set(_webpack.webpack.dependencies.ModuleDependency, normalModuleFactory);
compilation.dependencyTemplates.set(_webpack.webpack.dependencies.ModuleDependency, new _webpack.webpack.dependencies.NullDependency.Template());
});
compiler.hooks.finishMake.tapPromise(PLUGIN_NAME, (compilation)=>this.createClientEntries(compiler, compilation));
compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation)=>{
const recordModule = (modId, mod)=>{
var _mod_resourceResolveData, _mod_resourceResolveData1;
// Match Resource is undefined unless an import is using the inline match resource syntax
// https://webpack.js.org/api/loaders/#inline-matchresource
const modPath = mod.matchResource || ((_mod_resourceResolveData = mod.resourceResolveData) == null ? void 0 : _mod_resourceResolveData.path);
const modQuery = ((_mod_resourceResolveData1 = mod.resourceResolveData) == null ? void 0 : _mod_resourceResolveData1.query) || "";
// query is already part of mod.resource
// so it's only necessary to add it for matchResource or mod.resourceResolveData
const modResource = modPath ? modPath.startsWith(_constants1.BARREL_OPTIMIZATION_PREFIX) ? (0, _utils1.formatBarrelOptimizedResource)(mod.resource, modPath) : modPath + modQuery : mod.resource;
if (mod.layer !== _constants.WEBPACK_LAYERS.serverSideRendering) {
return;
}
// Check mod resource to exclude the empty resource module like virtual module created by next-flight-client-entry-loader
if (typeof modId !== "undefined" && modResource) {
// Note that this isn't that reliable as webpack is still possible to assign
// additional queries to make sure there's no conflict even using the `named`
// module ID strategy.
let ssrNamedModuleId = _path.default.relative(compiler.context, modResource);
if (!ssrNamedModuleId.startsWith(".")) {
// TODO use getModuleId instead
ssrNamedModuleId = `./${(0, _normalizepathsep.normalizePathSep)(ssrNamedModuleId)}`;
}
if (this.isEdgeServer) {
pluginState.edgeServerModuleIds[ssrNamedModuleId.replace(/\/next\/dist\/esm\//, "/next/dist/")] = modId;
} else {
pluginState.serverModuleIds[ssrNamedModuleId] = modId;
}
}
};
(0, _utils1.traverseModules)(compilation, (mod, _chunk, _chunkGroup, modId)=>{
if (mod && mod.resource && !(0, _utils2.isWebpackServerOnlyLayer)(mod.layer)) {
if (compilation.moduleGraph.isAsync(mod)) {
// The module must has resolved resource path so it's not a new entry created with loader.
// Checking the module layer to make sure it's from client layers (SSR or browser, not RSC).
pluginState.ASYNC_CLIENT_MODULES[mod.resource] = true;
}
}
if (modId) recordModule(modId, mod);
});
});
compiler.hooks.make.tap(PLUGIN_NAME, (compilation)=>{
compilation.hooks.processAssets.tapPromise({
name: PLUGIN_NAME,
stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH
}, (assets)=>this.createActionAssets(compilation, assets));
});
}
async createClientEntries(compiler, compilation) {
const addClientEntryAndSSRModulesList = [];
const createdSSRDependenciesForEntry = {};
const addActionEntryList = [];
const actionMapsPerEntry = {};
const createdActions = new Set();
// For each SC server compilation entry, we need to create its corresponding
// client component entry.
(0, _utils1.forEachEntryModule)(compilation, ({ name, entryModule })=>{
const internalClientComponentEntryImports = {};
const actionEntryImports = new Map();
const clientEntriesToInject = [];
const mergedCSSimports = {};
for (const connection of (0, _utils1.getModuleReferencesInOrder)(entryModule, compilation.moduleGraph)){
// Entry can be any user defined entry files such as layout, page, error, loading, etc.
const entryRequest = connection.dependency.request;
const { clientComponentImports, actionImports, cssImports } = this.collectComponentInfoFromServerEntryDependency({
entryRequest,
compilation,
resolvedModule: connection.resolvedModule
});
actionImports.forEach(([dep, names])=>actionEntryImports.set(dep, names));
const isAbsoluteRequest = _path.default.isAbsolute(entryRequest);
// Next.js internals are put into a separate entry.
if (!isAbsoluteRequest) {
Object.keys(clientComponentImports).forEach((value)=>internalClientComponentEntryImports[value] = new Set());
continue;
}
// TODO-APP: Enable these lines. This ensures no entrypoint is created for layout/page when there are no client components.
// Currently disabled because it causes test failures in CI.
// if (clientImports.length === 0 && actionImports.length === 0) {
// continue
// }
const relativeRequest = isAbsoluteRequest ? _path.default.relative(compilation.options.context, entryRequest) : entryRequest;
// Replace file suffix as `.js` will be added.
const bundlePath = (0, _normalizepathsep.normalizePathSep)(relativeRequest.replace(/\.[^.\\/]+$/, "").replace(/^src[\\/]/, ""));
Object.assign(mergedCSSimports, cssImports);
clientEntriesToInject.push({
compiler,
compilation,
entryName: name,
clientComponentImports,
bundlePath,
absolutePagePath: entryRequest
});
// The webpack implementation of writing the client reference manifest relies on all entrypoints writing a page.js even when there is no client components in the page.
// It needs the file in order to write the reference manifest for the path in the `.next/server` folder.
// TODO-APP: This could be better handled, however Turbopack does not have the same problem as we resolve client components in a single graph.
if (name === `app${_constants1.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY}` && bundlePath === "app/not-found") {
clientEntriesToInject.push({
compiler,
compilation,
entryName: name,
clientComponentImports: {},
bundlePath: `app${_constants1.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY}`,
absolutePagePath: entryRequest
});
}
}
// Make sure CSS imports are deduplicated before injecting the client entry
// and SSR modules.
const dedupedCSSImports = deduplicateCSSImportsForEntry(mergedCSSimports);
for (const clientEntryToInject of clientEntriesToInject){
const injected = this.injectClientEntryAndSSRModules({
...clientEntryToInject,
clientImports: {
...clientEntryToInject.clientComponentImports,
...(dedupedCSSImports[clientEntryToInject.absolutePagePath] || []).reduce((res, curr)=>{
res[curr] = new Set();
return res;
}, {})
}
});
// Track all created SSR dependencies for each entry from the server layer.
if (!createdSSRDependenciesForEntry[clientEntryToInject.entryName]) {
createdSSRDependenciesForEntry[clientEntryToInject.entryName] = [];
}
createdSSRDependenciesForEntry[clientEntryToInject.entryName].push(injected[2]);
addClientEntryAndSSRModulesList.push(injected);
}
// Create internal app
addClientEntryAndSSRModulesList.push(this.injectClientEntryAndSSRModules({
compiler,
compilation,
entryName: name,
clientImports: {
...internalClientComponentEntryImports
},
bundlePath: _constants1.APP_CLIENT_INTERNALS
}));
if (actionEntryImports.size > 0) {
if (!actionMapsPerEntry[name]) {
actionMapsPerEntry[name] = new Map();
}
actionMapsPerEntry[name] = new Map([
...actionMapsPerEntry[name],
...actionEntryImports
]);
}
});
for (const [name, actionEntryImports] of Object.entries(actionMapsPerEntry)){
for (const [dep, actionNames] of actionEntryImports){
for (const actionName of actionNames){
createdActions.add(name + "@" + dep + "@" + actionName);
}
}
addActionEntryList.push(this.injectActionEntry({
compiler,
compilation,
actions: actionEntryImports,
entryName: name,
bundlePath: name
}));
}
compilation.hooks.finishModules.tapPromise(PLUGIN_NAME, async ()=>{
const addedClientActionEntryList = [];
const actionMapsPerClientEntry = {};
// We need to create extra action entries that are created from the
// client layer.
// Start from each entry's created SSR dependency from our previous step.
for (const [name, ssrEntryDependencies] of Object.entries(createdSSRDependenciesForEntry)){
// Collect from all entries, e.g. layout.js, page.js, loading.js, ...
// add aggregate them.
const actionEntryImports = this.collectClientActionsFromDependencies({
compilation,
dependencies: ssrEntryDependencies
});
if (actionEntryImports.size > 0) {
if (!actionMapsPerClientEntry[name]) {
actionMapsPerClientEntry[name] = new Map();
}
actionMapsPerClientEntry[name] = new Map([
...actionMapsPerClientEntry[name],
...actionEntryImports
]);
}
}
for (const [name, actionEntryImports] of Object.entries(actionMapsPerClientEntry)){
// If an action method is already created in the server layer, we don't
// need to create it again in the action layer.
// This is to avoid duplicate action instances and make sure the module
// state is shared.
let remainingClientImportedActions = false;
const remainingActionEntryImports = new Map();
for (const [dep, actionNames] of actionEntryImports){
const remainingActionNames = [];
for (const actionName of actionNames){
const id = name + "@" + dep + "@" + actionName;
if (!createdActions.has(id)) {
remainingActionNames.push(actionName);
}
}
if (remainingActionNames.length > 0) {
remainingActionEntryImports.set(dep, remainingActionNames);
remainingClientImportedActions = true;
}
}
if (remainingClientImportedActions) {
addedClientActionEntryList.push(this.injectActionEntry({
compiler,
compilation,
actions: remainingActionEntryImports,
entryName: name,
bundlePath: name,
fromClient: true
}));
}
}
await Promise.all(addedClientActionEntryList);
return;
});
// Invalidate in development to trigger recompilation
const invalidator = (0, _ondemandentryhandler.getInvalidator)(compiler.outputPath);
// Check if any of the entry injections need an invalidation
if (invalidator && addClientEntryAndSSRModulesList.some(([shouldInvalidate])=>shouldInvalidate === true)) {
invalidator.invalidate([
_constants1.COMPILER_NAMES.client
]);
}
// Client compiler is invalidated before awaiting the compilation of the SSR client component entries
// so that the client compiler is running in parallel to the server compiler.
await Promise.all(addClientEntryAndSSRModulesList.map((addClientEntryAndSSRModules)=>addClientEntryAndSSRModules[1]));
// Wait for action entries to be added.
await Promise.all(addActionEntryList);
}
collectClientActionsFromDependencies({ compilation, dependencies }) {
// action file path -> action names
const collectedActions = new Map();
// Keep track of checked modules to avoid infinite loops with recursive imports.
const visitedModule = new Set();
const visitedEntry = new Set();
const collectActions = ({ entryRequest, resolvedModule })=>{
const collectActionsInDep = (mod)=>{
var _mod_resourceResolveData, _mod_resourceResolveData1, _mod_matchResource;
if (!mod) return;
const modPath = ((_mod_resourceResolveData = mod.resourceResolveData) == null ? void 0 : _mod_resourceResolveData.path) || "";
// We have to always use the resolved request here to make sure the
// server and client are using the same module path (required by RSC), as
// the server compiler and client compiler have different resolve configs.
let modRequest = modPath + (((_mod_resourceResolveData1 = mod.resourceResolveData) == null ? void 0 : _mod_resourceResolveData1.query) || "");
// For the barrel optimization, we need to use the match resource instead
// because there will be 2 modules for the same file (same resource path)
// but they're different modules and can't be deduped via `visitedModule`.
// The first module is a virtual re-export module created by the loader.
if ((_mod_matchResource = mod.matchResource) == null ? void 0 : _mod_matchResource.startsWith(_constants1.BARREL_OPTIMIZATION_PREFIX)) {
modRequest = mod.matchResource + ":" + modRequest;
}
if (!modRequest || visitedModule.has(modRequest)) return;
visitedModule.add(modRequest);
const actions = (0, _utils.getActions)(mod);
if (actions) {
collectedActions.set(modRequest, actions);
}
(0, _utils1.getModuleReferencesInOrder)(mod, compilation.moduleGraph).forEach((connection)=>{
collectActionsInDep(connection.resolvedModule);
});
};
// Don't traverse the module graph anymore once hitting the action layer.
if (entryRequest && !entryRequest.includes("next-flight-action-entry-loader")) {
// Traverse the module graph to find all client components.
collectActionsInDep(resolvedModule);
}
};
for (const entryDependency of dependencies){
const ssrEntryModule = compilation.moduleGraph.getResolvedModule(entryDependency);
for (const connection of (0, _utils1.getModuleReferencesInOrder)(ssrEntryModule, compilation.moduleGraph)){
const dependency = connection.dependency;
const request = dependency.request;
// It is possible that the same entry is added multiple times in the
// connection graph. We can just skip these to speed up the process.
if (visitedEntry.has(request)) continue;
visitedEntry.add(request);
collectActions({
entryRequest: request,
resolvedModule: connection.resolvedModule
});
}
}
return collectedActions;
}
collectComponentInfoFromServerEntryDependency({ entryRequest, compilation, resolvedModule }) {
// Keep track of checked modules to avoid infinite loops with recursive imports.
const visited = new Set();
// Info to collect.
const clientComponentImports = {};
const actionImports = [];
const CSSImports = new Set();
const filterClientComponents = (mod, importedIdentifiers)=>{
var _mod_resourceResolveData, _mod_resourceResolveData1, _mod_matchResource;
if (!mod) return;
const isCSS = (0, _utils.isCSSMod)(mod);
const modPath = ((_mod_resourceResolveData = mod.resourceResolveData) == null ? void 0 : _mod_resourceResolveData.path) || "";
// We have to always use the resolved request here to make sure the
// server and client are using the same module path (required by RSC), as
// the server compiler and client compiler have different resolve configs.
let modRequest = modPath + ((_mod_resourceResolveData1 = mod.resourceResolveData) == null ? void 0 : _mod_resourceResolveData1.query);
// Context modules don't have a resource path, we use the identifier instead.
if (mod.constructor.name === "ContextModule") {
modRequest = mod._identifier;
}
// For the barrel optimization, we need to use the match resource instead
// because there will be 2 modules for the same file (same resource path)
// but they're different modules and can't be deduped via `visitedModule`.
// The first module is a virtual re-export module created by the loader.
if ((_mod_matchResource = mod.matchResource) == null ? void 0 : _mod_matchResource.startsWith(_constants1.BARREL_OPTIMIZATION_PREFIX)) {
modRequest = mod.matchResource + ":" + modRequest;
}
if (!modRequest) return;
if (visited.has(modRequest)) {
if (clientComponentImports[modRequest]) {
addClientImport(mod, modRequest, clientComponentImports, importedIdentifiers, false);
}
return;
}
visited.add(modRequest);
const actions = (0, _utils.getActions)(mod);
if (actions) {
actionImports.push([
modRequest,
actions
]);
}
const webpackRuntime = this.isEdgeServer ? _constants1.EDGE_RUNTIME_WEBPACK : _constants1.DEFAULT_RUNTIME_WEBPACK;
if (isCSS) {
const sideEffectFree = mod.factoryMeta && mod.factoryMeta.sideEffectFree;
if (sideEffectFree) {
const unused = !compilation.moduleGraph.getExportsInfo(mod).isModuleUsed(webpackRuntime);
if (unused) return;
}
CSSImports.add(modRequest);
} else if ((0, _utils.isClientComponentEntryModule)(mod)) {
if (!clientComponentImports[modRequest]) {
clientComponentImports[modRequest] = new Set();
}
addClientImport(mod, modRequest, clientComponentImports, importedIdentifiers, true);
return;
}
(0, _utils1.getModuleReferencesInOrder)(mod, compilation.moduleGraph).forEach((connection)=>{
var _connection_dependency;
let dependencyIds = [];
const depModule = connection.resolvedModule;
// `ids` are the identifiers that are imported from the dependency,
// if it's present, it's an array of strings.
if ((_connection_dependency = connection.dependency) == null ? void 0 : _connection_dependency.ids) {
dependencyIds.push(...connection.dependency.ids);
} else {
dependencyIds = [
"*"
];
}
filterClientComponents(depModule, dependencyIds);
});
};
// Traverse the module graph to find all client components.
filterClientComponents(resolvedModule, []);
return {
clientComponentImports,
cssImports: CSSImports.size ? {
[entryRequest]: Array.from(CSSImports)
} : {},
actionImports
};
}
injectClientEntryAndSSRModules({ compiler, compilation, entryName, clientImports, bundlePath, absolutePagePath }) {
let shouldInvalidate = false;
const loaderOptions = {
modules: Object.keys(clientImports).sort((a, b)=>_utils.regexCSS.test(b) ? 1 : a.localeCompare(b)).map((clientImportPath)=>({
request: clientImportPath,
ids: [
...clientImports[clientImportPath]
]
})),
server: false
};
// For the client entry, we always use the CJS build of Next.js. If the
// server is using the ESM build (when using the Edge runtime), we need to
// replace them.
const clientBrowserLoader = `next-flight-client-entry-loader?${(0, _querystring.stringify)({
modules: (this.isEdgeServer ? loaderOptions.modules.map(({ request, ids })=>({
request: request.replace(/[\\/]next[\\/]dist[\\/]esm[\\/]/, "/next/dist/".replace(/\//g, _path.default.sep)),
ids
})) : loaderOptions.modules).map((x)=>JSON.stringify(x)),
server: false
})}!`;
const clientSSRLoader = `next-flight-client-entry-loader?${(0, _querystring.stringify)({
modules: loaderOptions.modules.map((x)=>JSON.stringify(x)),
server: true
})}!`;
// Add for the client compilation
// Inject the entry to the client compiler.
if (this.dev) {
const entries = (0, _ondemandentryhandler.getEntries)(compiler.outputPath);
const pageKey = (0, _ondemandentryhandler.getEntryKey)(_constants1.COMPILER_NAMES.client, _pagetypes.PAGE_TYPES.APP, bundlePath);
if (!entries[pageKey]) {
entries[pageKey] = {
type: _ondemandentryhandler.EntryTypes.CHILD_ENTRY,
parentEntries: new Set([
entryName
]),
absoluteEntryFilePath: absolutePagePath,
bundlePath,
request: clientBrowserLoader,
dispose: false,
lastActiveTime: Date.now()
};
shouldInvalidate = true;
} else {
const entryData = entries[pageKey];
// New version of the client loader
if (entryData.request !== clientBrowserLoader) {
entryData.request = clientBrowserLoader;
shouldInvalidate = true;
}
if (entryData.type === _ondemandentryhandler.EntryTypes.CHILD_ENTRY) {
entryData.parentEntries.add(entryName);
}
entryData.dispose = false;
entryData.lastActiveTime = Date.now();
}
} else {
pluginState.injectedClientEntries[bundlePath] = clientBrowserLoader;
}
// Inject the entry to the server compiler (__ssr__).
const clientComponentEntryDep = _webpack.webpack.EntryPlugin.createDependency(clientSSRLoader, {
name: bundlePath
});
return [
shouldInvalidate,
// Add the dependency to the server compiler.
// This promise is awaited later using `Promise.all` in order to parallelize adding the entries.
// It ensures we can parallelize the SSR and Client compiler entries.
this.addEntry(compilation, // Reuse compilation context.
compiler.context, clientComponentEntryDep, {
// By using the same entry name
name: entryName,
// Layer should be client for the SSR modules
// This ensures the client components are bundled on client layer
layer: _constants.WEBPACK_LAYERS.serverSideRendering
}),
clientComponentEntryDep
];
}
injectActionEntry({ compiler, compilation, actions, entryName, bundlePath, fromClient }) {
const actionsArray = Array.from(actions.entries());
const actionLoader = `next-flight-action-entry-loader?${(0, _querystring.stringify)({
actions: JSON.stringify(actionsArray),
__client_imported__: fromClient
})}!`;
const currentCompilerServerActions = this.isEdgeServer ? pluginState.edgeServerActions : pluginState.serverActions;
for (const [p, names] of actionsArray){
for (const name of names){
const id = (0, _utils.generateActionId)(p, name);
if (typeof currentCompilerServerActions[id] === "undefined") {
currentCompilerServerActions[id] = {
workers: {},
layer: {}
};
}
currentCompilerServerActions[id].workers[bundlePath] = "";
currentCompilerServerActions[id].layer[bundlePath] = fromClient ? _constants.WEBPACK_LAYERS.actionBrowser : _constants.WEBPACK_LAYERS.reactServerComponents;
}
}
// Inject the entry to the server compiler
const actionEntryDep = _webpack.webpack.EntryPlugin.createDependency(actionLoader, {
name: bundlePath
});
return this.addEntry(compilation, // Reuse compilation context.
compiler.context, actionEntryDep, {
name: entryName,
layer: fromClient ? _constants.WEBPACK_LAYERS.actionBrowser : _constants.WEBPACK_LAYERS.reactServerComponents
});
}
addEntry(compilation, context, dependency, options) /* Promise<module> */ {
return new Promise((resolve, reject)=>{
const entry = compilation.entries.get(options.name);
entry.includeDependencies.push(dependency);
compilation.hooks.addEntry.call(entry, options);
compilation.addModuleTree({
context,
dependency,
contextInfo: {
issuerLayer: options.layer
}
}, (err, module)=>{
if (err) {
compilation.hooks.failedEntry.call(dependency, options, err);
return reject(err);
}
compilation.hooks.succeedEntry.call(dependency, options, module);
return resolve(module);
});
});
}
async createActionAssets(compilation, assets) {
const serverActions = {};
const edgeServerActions = {};
(0, _utils1.traverseModules)(compilation, (mod, _chunk, chunkGroup, modId)=>{
// Go through all action entries and record the module ID for each entry.
if (chunkGroup.name && mod.request && modId && /next-flight-action-entry-loader/.test(mod.request)) {
const fromClient = /&__client_imported__=true/.test(mod.request);
const mapping = this.isEdgeServer ? pluginState.actionModEdgeServerId : pluginState.actionModServerId;
if (!mapping[chunkGroup.name]) {
mapping[chunkGroup.name] = {};
}
mapping[chunkGroup.name][fromClient ? "client" : "server"] = modId;
}
});
for(let id in pluginState.serverActions){
const action = pluginState.serverActions[id];
for(let name in action.workers){
const modId = pluginState.actionModServerId[name][action.layer[name] === _constants.WEBPACK_LAYERS.actionBrowser ? "client" : "server"];
action.workers[name] = modId;
}
serverActions[id] = action;
}
for(let id in pluginState.edgeServerActions){
const action = pluginState.edgeServerActions[id];
for(let name in action.workers){
const modId = pluginState.actionModEdgeServerId[name][action.layer[name] === _constants.WEBPACK_LAYERS.actionBrowser ? "client" : "server"];
action.workers[name] = modId;
}
edgeServerActions[id] = action;
}
const json = JSON.stringify({
node: serverActions,
edge: edgeServerActions,
encryptionKey: this.encryptionKey
}, null, this.dev ? 2 : undefined);
assets[`${this.assetPrefix}${_constants1.SERVER_REFERENCE_MANIFEST}.js`] = new _webpack.sources.RawSource(`self.__RSC_SERVER_MANIFEST=${JSON.stringify(json)}`);
assets[`${this.assetPrefix}${_constants1.SERVER_REFERENCE_MANIFEST}.json`] = new _webpack.sources.RawSource(json);
}
}
function addClientImport(mod, modRequest, clientComponentImports, importedIdentifiers, isFirstImport) {
var _getModuleBuildInfo_rsc;
const clientEntryType = (_getModuleBuildInfo_rsc = (0, _getmodulebuildinfo.getModuleBuildInfo)(mod).rsc) == null ? void 0 : _getModuleBuildInfo_rsc.clientEntryType;
const isCjsModule = clientEntryType === "cjs";
const assumedSourceType = (0, _nextflightloader.getAssumedSourceType)(mod, isCjsModule ? "commonjs" : "auto");
const clientImportsSet = clientComponentImports[modRequest];
if (importedIdentifiers[0] === "*") {
// If there's collected import path with named import identifiers,
// or there's nothing in collected imports are empty.
// we should include the whole module.
if (!isFirstImport && [
...clientImportsSet
][0] !== "*") {
clientComponentImports[modRequest] = new Set([
"*"
]);
}
} else {
const isAutoModuleSourceType = assumedSourceType === "auto";
if (isAutoModuleSourceType) {
clientComponentImports[modRequest] = new Set([
"*"
]);
} else {
// If it's not analyzed as named ESM exports, e.g. if it's mixing `export *` with named exports,
// We'll include all modules since it's not able to do tree-shaking.
for (const name of importedIdentifiers){
// For cjs module default import, we include the whole module since
const isCjsDefaultImport = isCjsModule && name === "default";
// Always include __esModule along with cjs module default export,
// to make sure it work with client module proxy from React.
if (isCjsDefaultImport) {
clientComponentImports[modRequest].add("__esModule");
}
clientComponentImports[modRequest].add(name);
}
}
}
}
//# sourceMappingURL=flight-client-entry-plugin.js.map

View File

@@ -0,0 +1,351 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ClientReferenceManifestPlugin", {
enumerable: true,
get: function() {
return ClientReferenceManifestPlugin;
}
});
const _path = /*#__PURE__*/ _interop_require_wildcard(require("path"));
const _webpack = require("next/dist/compiled/webpack/webpack");
const _constants = require("../../../shared/lib/constants");
const _buildcontext = require("../../build-context");
const _constants1 = require("../../../lib/constants");
const _normalizepagepath = require("../../../shared/lib/page-path/normalize-page-path");
const _deploymentid = require("../../deployment-id");
const _utils = require("../utils");
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const pluginState = (0, _buildcontext.getProxiedPluginState)({
serverModuleIds: {},
edgeServerModuleIds: {},
// Use an object to simulate Set lookup
ASYNC_CLIENT_MODULES: {}
});
function getAppPathRequiredChunks(chunkGroup, excludedFiles) {
const deploymentIdChunkQuery = (0, _deploymentid.getDeploymentIdQueryOrEmptyString)();
const chunks = [];
chunkGroup.chunks.forEach((chunk)=>{
if (_constants.SYSTEM_ENTRYPOINTS.has(chunk.name || "")) {
return null;
}
// Get the actual chunk file names from the chunk file list.
// It's possible that the chunk is generated via `import()`, in
// that case the chunk file name will be '[name].[contenthash]'
// instead of '[name]-[chunkhash]'.
if (chunk.id != null) {
const chunkId = "" + chunk.id;
chunk.files.forEach((file)=>{
// It's possible that a chunk also emits CSS files, that will
// be handled separatedly.
if (!file.endsWith(".js")) return null;
if (file.endsWith(".hot-update.js")) return null;
if (excludedFiles.has(file)) return null;
// We encode the file as a URI because our server (and many other services such as S3)
// expect to receive reserved characters such as `[` and `]` as encoded. This was
// previously done for dynamic chunks by patching the webpack runtime but we want
// these filenames to be managed by React's Flight runtime instead and so we need
// to implement any special handling of the file name here.
return chunks.push(chunkId, encodeURI(file + deploymentIdChunkQuery));
});
}
});
return chunks;
}
// Normalize the entry names to their "group names" so a page can easily track
// all the manifest items it needs from parent groups by looking up the group
// segments:
// - app/foo/loading -> app/foo
// - app/foo/page -> app/foo
// - app/(group)/@named/foo/page -> app/foo
// - app/(.)foo/(..)bar/loading -> app/bar
// - app/[...catchAll]/page -> app
// - app/foo/@slot/[...catchAll]/page -> app/foo
function entryNameToGroupName(entryName) {
let groupName = entryName.slice(0, entryName.lastIndexOf("/"))// Remove slots
.replace(/\/@[^/]+/g, "")// Remove the group with lookahead to make sure it's not interception route
.replace(/\/\([^/]+\)(?=(\/|$))/g, "")// Remove catch-all routes since they should be part of the parent group that the catch-all would apply to.
// This is necessary to support parallel routes since multiple page components can be rendered on the same page.
// In order to do that, we need to ensure that the manifests are merged together by putting them in the same group.
.replace(/\/\[?\[\.\.\.[^\]]*\]\]?/g, "");
// Interception routes
groupName = groupName.replace(/^.+\/\(\.\.\.\)/g, "app/").replace(/\/\(\.\)/g, "/");
// Interception routes (recursive)
while(/\/[^/]+\/\(\.\.\)/.test(groupName)){
groupName = groupName.replace(/\/[^/]+\/\(\.\.\)/g, "/");
}
return groupName;
}
function mergeManifest(manifest, manifestToMerge) {
Object.assign(manifest.clientModules, manifestToMerge.clientModules);
Object.assign(manifest.ssrModuleMapping, manifestToMerge.ssrModuleMapping);
Object.assign(manifest.edgeSSRModuleMapping, manifestToMerge.edgeSSRModuleMapping);
Object.assign(manifest.entryCSSFiles, manifestToMerge.entryCSSFiles);
}
const PLUGIN_NAME = "ClientReferenceManifestPlugin";
class ClientReferenceManifestPlugin {
constructor(options){
this.dev = false;
this.dev = options.dev;
this.appDir = options.appDir;
this.appDirBase = _path.default.dirname(this.appDir) + _path.default.sep;
}
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory })=>{
compilation.dependencyFactories.set(_webpack.webpack.dependencies.ModuleDependency, normalModuleFactory);
compilation.dependencyTemplates.set(_webpack.webpack.dependencies.ModuleDependency, new _webpack.webpack.dependencies.NullDependency.Template());
compilation.hooks.processAssets.tap({
name: PLUGIN_NAME,
// Have to be in the optimize stage to run after updating the CSS
// asset hash via extract mini css plugin.
stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH
}, (assets)=>this.createAsset(assets, compilation, compiler.context));
});
}
createAsset(assets, compilation, context) {
var _compilation_entrypoints_get;
const manifestsPerGroup = new Map();
const manifestEntryFiles = [];
const configuredCrossOriginLoading = compilation.outputOptions.crossOriginLoading;
const crossOriginMode = typeof configuredCrossOriginLoading === "string" ? configuredCrossOriginLoading === "use-credentials" ? configuredCrossOriginLoading : "anonymous" : null;
if (typeof compilation.outputOptions.publicPath !== "string") {
throw new Error("Expected webpack publicPath to be a string when using App Router. To customize where static assets are loaded from, use the `assetPrefix` option in next.config.js. If you are customizing your webpack config please make sure you are not modifying or removing the publicPath configuration option");
}
const prefix = compilation.outputOptions.publicPath || "";
// We want to omit any files that will always be loaded on any App Router page
// because they will already be loaded by the main entrypoint.
const rootMainFiles = new Set();
(_compilation_entrypoints_get = compilation.entrypoints.get(_constants.CLIENT_STATIC_FILES_RUNTIME_MAIN_APP)) == null ? void 0 : _compilation_entrypoints_get.getFiles().forEach((file)=>{
if (/(?<!\.hot-update)\.(js|css)($|\?)/.test(file)) {
rootMainFiles.add(file.replace(/\\/g, "/"));
}
});
for (let [entryName, entrypoint] of compilation.entrypoints){
if (entryName === _constants.CLIENT_STATIC_FILES_RUNTIME_MAIN_APP || entryName === _constants.APP_CLIENT_INTERNALS) {
entryName = "";
} else if (!/^app[\\/]/.test(entryName)) {
continue;
}
const manifest = {
moduleLoading: {
prefix,
crossOrigin: crossOriginMode
},
ssrModuleMapping: {},
edgeSSRModuleMapping: {},
clientModules: {},
entryCSSFiles: {}
};
// Absolute path without the extension
const chunkEntryName = (this.appDirBase + entryName).replace(/[\\/]/g, _path.default.sep);
manifest.entryCSSFiles[chunkEntryName] = entrypoint.getFiles().filter((f)=>!f.startsWith("static/css/pages/") && f.endsWith(".css"));
const requiredChunks = getAppPathRequiredChunks(entrypoint, rootMainFiles);
const recordModule = (modId, mod)=>{
var _mod_resourceResolveData, _mod_matchResource;
let resource = mod.type === "css/mini-extract" ? mod._identifier.slice(mod._identifier.lastIndexOf("!") + 1) : mod.resource;
if (!resource) {
return;
}
const moduleReferences = manifest.clientModules;
const moduleIdMapping = manifest.ssrModuleMapping;
const edgeModuleIdMapping = manifest.edgeSSRModuleMapping;
// Note that this isn't that reliable as webpack is still possible to assign
// additional queries to make sure there's no conflict even using the `named`
// module ID strategy.
let ssrNamedModuleId = (0, _path.relative)(context, ((_mod_resourceResolveData = mod.resourceResolveData) == null ? void 0 : _mod_resourceResolveData.path) || resource);
if (!ssrNamedModuleId.startsWith(".")) ssrNamedModuleId = `./${ssrNamedModuleId.replace(/\\/g, "/")}`;
const isAsyncModule = !!pluginState.ASYNC_CLIENT_MODULES[mod.resource];
// The client compiler will always use the CJS Next.js build, so here we
// also add the mapping for the ESM build (Edge runtime) to consume.
const esmResource = /[\\/]next[\\/]dist[\\/]/.test(resource) ? resource.replace(/[\\/]next[\\/]dist[\\/]/, "/next/dist/esm/".replace(/\//g, _path.default.sep)) : null;
// An extra query param is added to the resource key when it's optimized
// through the Barrel Loader. That's because the same file might be created
// as multiple modules (depending on what you import from it).
// See also: webpack/loaders/next-flight-loader/index.ts.
if ((_mod_matchResource = mod.matchResource) == null ? void 0 : _mod_matchResource.startsWith(_constants.BARREL_OPTIMIZATION_PREFIX)) {
ssrNamedModuleId = (0, _utils.formatBarrelOptimizedResource)(ssrNamedModuleId, mod.matchResource);
resource = (0, _utils.formatBarrelOptimizedResource)(resource, mod.matchResource);
}
function addClientReference() {
const exportName = resource;
manifest.clientModules[exportName] = {
id: modId,
name: "*",
chunks: requiredChunks,
async: isAsyncModule
};
if (esmResource) {
const edgeExportName = esmResource;
manifest.clientModules[edgeExportName] = manifest.clientModules[exportName];
}
}
function addSSRIdMapping() {
const exportName = resource;
if (typeof pluginState.serverModuleIds[ssrNamedModuleId] !== "undefined") {
moduleIdMapping[modId] = moduleIdMapping[modId] || {};
moduleIdMapping[modId]["*"] = {
...manifest.clientModules[exportName],
// During SSR, we don't have external chunks to load on the server
// side with our architecture of Webpack / Turbopack. We can keep
// this field empty to save some bytes.
chunks: [],
id: pluginState.serverModuleIds[ssrNamedModuleId]
};
}
if (typeof pluginState.edgeServerModuleIds[ssrNamedModuleId] !== "undefined") {
edgeModuleIdMapping[modId] = edgeModuleIdMapping[modId] || {};
edgeModuleIdMapping[modId]["*"] = {
...manifest.clientModules[exportName],
// During SSR, we don't have external chunks to load on the server
// side with our architecture of Webpack / Turbopack. We can keep
// this field empty to save some bytes.
chunks: [],
id: pluginState.edgeServerModuleIds[ssrNamedModuleId]
};
}
}
addClientReference();
addSSRIdMapping();
manifest.clientModules = moduleReferences;
manifest.ssrModuleMapping = moduleIdMapping;
manifest.edgeSSRModuleMapping = edgeModuleIdMapping;
};
const checkedChunkGroups = new Set();
const checkedChunks = new Set();
function recordChunkGroup(chunkGroup) {
// Ensure recursion is stopped if we've already checked this chunk group.
if (checkedChunkGroups.has(chunkGroup)) return;
checkedChunkGroups.add(chunkGroup);
// Only apply following logic to client module requests from client entry,
// or if the module is marked as client module. That's because other
// client modules don't need to be in the manifest at all as they're
// never be referenced by the server/client boundary.
// This saves a lot of bytes in the manifest.
chunkGroup.chunks.forEach((chunk)=>{
// Ensure recursion is stopped if we've already checked this chunk.
if (checkedChunks.has(chunk)) return;
checkedChunks.add(chunk);
const entryMods = compilation.chunkGraph.getChunkEntryModulesIterable(chunk);
for (const mod of entryMods){
if (mod.layer !== _constants1.WEBPACK_LAYERS.appPagesBrowser) continue;
const request = mod.request;
if (!request || !request.includes("next-flight-client-entry-loader.js?")) {
continue;
}
const connections = (0, _utils.getModuleReferencesInOrder)(mod, compilation.moduleGraph);
for (const connection of connections){
const dependency = connection.dependency;
if (!dependency) continue;
const clientEntryMod = compilation.moduleGraph.getResolvedModule(dependency);
const modId = compilation.chunkGraph.getModuleId(clientEntryMod);
if (modId !== null) {
recordModule(modId, clientEntryMod);
} else {
var _connection_module;
// If this is a concatenation, register each child to the parent ID.
if (((_connection_module = connection.module) == null ? void 0 : _connection_module.constructor.name) === "ConcatenatedModule") {
const concatenatedMod = connection.module;
const concatenatedModId = compilation.chunkGraph.getModuleId(concatenatedMod);
recordModule(concatenatedModId, clientEntryMod);
}
}
}
}
});
// Walk through all children chunk groups too.
for (const child of chunkGroup.childrenIterable){
recordChunkGroup(child);
}
}
recordChunkGroup(entrypoint);
// A page's entry name can have extensions. For example, these are both valid:
// - app/foo/page
// - app/foo/page.page
if (/\/page(\.[^/]+)?$/.test(entryName)) {
manifestEntryFiles.push(entryName.replace(/\/page(\.[^/]+)?$/, "/page"));
}
const groupName = entryNameToGroupName(entryName);
if (!manifestsPerGroup.has(groupName)) {
manifestsPerGroup.set(groupName, []);
}
manifestsPerGroup.get(groupName).push(manifest);
}
// Generate per-page manifests.
for (const pageName of manifestEntryFiles){
const mergedManifest = {
moduleLoading: {
prefix,
crossOrigin: crossOriginMode
},
ssrModuleMapping: {},
edgeSSRModuleMapping: {},
clientModules: {},
entryCSSFiles: {}
};
const segments = [
...entryNameToGroupName(pageName).split("/"),
"page"
];
let group = "";
for (const segment of segments){
for (const manifest of manifestsPerGroup.get(group) || []){
mergeManifest(mergedManifest, manifest);
}
group += (group ? "/" : "") + segment;
}
const json = JSON.stringify(mergedManifest);
const pagePath = pageName.replace(/%5F/g, "_");
const pageBundlePath = (0, _normalizepagepath.normalizePagePath)(pagePath.slice("app".length));
assets["server/app" + pageBundlePath + "_" + _constants.CLIENT_REFERENCE_MANIFEST + ".js"] = new _webpack.sources.RawSource(`globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST[${JSON.stringify(pagePath.slice("app".length))}]=${json}`);
}
pluginState.ASYNC_CLIENT_MODULES = {};
}
}
//# sourceMappingURL=flight-manifest-plugin.js.map

View File

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

View File

@@ -0,0 +1,219 @@
/**
* This webpack resolver is largely based on TypeScript's "paths" handling
* The TypeScript license can be found here:
* https://github.com/microsoft/TypeScript/blob/214df64e287804577afa1fea0184c18c40f7d1ca/LICENSE.txt
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
JsConfigPathsPlugin: null,
findBestPatternMatch: null,
hasZeroOrOneAsteriskCharacter: null,
isString: null,
matchPatternOrExact: null,
matchedText: null,
pathIsRelative: null,
patternText: null,
tryParsePattern: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
JsConfigPathsPlugin: function() {
return JsConfigPathsPlugin;
},
findBestPatternMatch: function() {
return findBestPatternMatch;
},
hasZeroOrOneAsteriskCharacter: function() {
return hasZeroOrOneAsteriskCharacter;
},
isString: function() {
return isString;
},
matchPatternOrExact: function() {
return matchPatternOrExact;
},
matchedText: function() {
return matchedText;
},
pathIsRelative: function() {
return pathIsRelative;
},
patternText: function() {
return patternText;
},
tryParsePattern: function() {
return tryParsePattern;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _debug = require("next/dist/compiled/debug");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const log = (0, _debug.debug)("next:jsconfig-paths-plugin");
const asterisk = 0x2a;
function hasZeroOrOneAsteriskCharacter(str) {
let seenAsterisk = false;
for(let i = 0; i < str.length; i++){
if (str.charCodeAt(i) === asterisk) {
if (!seenAsterisk) {
seenAsterisk = true;
} else {
// have already seen asterisk
return false;
}
}
}
return true;
}
function pathIsRelative(testPath) {
return /^\.\.?($|[\\/])/.test(testPath);
}
function tryParsePattern(pattern) {
// This should be verified outside of here and a proper error thrown.
const indexOfStar = pattern.indexOf("*");
return indexOfStar === -1 ? undefined : {
prefix: pattern.slice(0, indexOfStar),
suffix: pattern.slice(indexOfStar + 1)
};
}
function isPatternMatch({ prefix, suffix }, candidate) {
return candidate.length >= prefix.length + suffix.length && candidate.startsWith(prefix) && candidate.endsWith(suffix);
}
function findBestPatternMatch(values, getPattern, candidate) {
let matchedValue;
// use length of prefix as betterness criteria
let longestMatchPrefixLength = -1;
for (const v of values){
const pattern = getPattern(v);
if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
longestMatchPrefixLength = pattern.prefix.length;
matchedValue = v;
}
}
return matchedValue;
}
function matchPatternOrExact(patternStrings, candidate) {
const patterns = [];
for (const patternString of patternStrings){
if (!hasZeroOrOneAsteriskCharacter(patternString)) continue;
const pattern = tryParsePattern(patternString);
if (pattern) {
patterns.push(pattern);
} else if (patternString === candidate) {
// pattern was matched as is - no need to search further
return patternString;
}
}
return findBestPatternMatch(patterns, (_)=>_, candidate);
}
function isString(text) {
return typeof text === "string";
}
function matchedText(pattern, candidate) {
return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
}
function patternText({ prefix, suffix }) {
return `${prefix}*${suffix}`;
}
/**
* Calls the iterator function for each entry of the array
* until the first result or error is reached
*/ function forEachBail(array, iterator, callback) {
if (array.length === 0) return callback();
let i = 0;
const next = ()=>{
let loop = undefined;
iterator(array[i++], (err, result)=>{
if (err || result !== undefined || i >= array.length) {
return callback(err, result);
}
if (loop === false) while(next());
loop = true;
});
if (!loop) loop = false;
return loop;
};
while(next());
}
const NODE_MODULES_REGEX = /node_modules/;
class JsConfigPathsPlugin {
constructor(paths, resolvedBaseUrl){
this.paths = paths;
this.resolvedBaseUrl = resolvedBaseUrl;
this.jsConfigPlugin = true;
log("tsconfig.json or jsconfig.json paths: %O", paths);
log("resolved baseUrl: %s", resolvedBaseUrl);
}
apply(resolver) {
const target = resolver.ensureHook("resolve");
resolver.getHook("described-resolve").tapAsync("JsConfigPathsPlugin", (request, resolveContext, callback)=>{
const resolvedBaseUrl = this.resolvedBaseUrl;
if (resolvedBaseUrl === undefined) {
return callback();
}
const paths = this.paths;
const pathsKeys = Object.keys(paths);
// If no aliases are added bail out
if (pathsKeys.length === 0) {
log("paths are empty, bailing out");
return callback();
}
const moduleName = request.request;
// Exclude node_modules from paths support (speeds up resolving)
if (request.path.match(NODE_MODULES_REGEX)) {
log("skipping request as it is inside node_modules %s", moduleName);
return callback();
}
if (_path.default.posix.isAbsolute(moduleName) || process.platform === "win32" && _path.default.win32.isAbsolute(moduleName)) {
log("skipping request as it is an absolute path %s", moduleName);
return callback();
}
if (pathIsRelative(moduleName)) {
log("skipping request as it is a relative path %s", moduleName);
return callback();
}
// log('starting to resolve request %s', moduleName)
// If the module name does not match any of the patterns in `paths` we hand off resolving to webpack
const matchedPattern = matchPatternOrExact(pathsKeys, moduleName);
if (!matchedPattern) {
log("moduleName did not match any paths pattern %s", moduleName);
return callback();
}
const matchedStar = isString(matchedPattern) ? undefined : matchedText(matchedPattern, moduleName);
const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern);
let triedPaths = [];
forEachBail(paths[matchedPatternText], (subst, pathCallback)=>{
const curPath = matchedStar ? subst.replace("*", matchedStar) : subst;
// Ensure .d.ts is not matched
if (curPath.endsWith(".d.ts")) {
// try next path candidate
return pathCallback();
}
const candidate = _path.default.join(resolvedBaseUrl.baseUrl, curPath);
const obj = Object.assign({}, request, {
request: candidate
});
resolver.doResolve(target, obj, `Aliased with tsconfig.json or jsconfig.json ${matchedPatternText} to ${candidate}`, resolveContext, (resolverErr, resolverResult)=>{
if (resolverErr || resolverResult === undefined) {
triedPaths.push(candidate);
// try next path candidate
return pathCallback();
}
return pathCallback(resolverErr, resolverResult);
});
}, callback);
});
}
}
//# sourceMappingURL=jsconfig-paths-plugin.js.map

View File

@@ -0,0 +1,114 @@
/*
This plugin is based on the internal one in webpack but heavily modified to use a different caching heuristic.
https://github.com/webpack/webpack/blob/853bfda35a0080605c09e1bdeb0103bcb9367a10/lib/cache/MemoryWithGcCachePlugin.js#L15
https://github.com/webpack/webpack/blob/main/LICENSE
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ /*
The change in this plugin compared to the built-in one in webpack is that this plugin always cleans up after 5 compilations.
The built-in plugin only cleans up "total modules / max generations".
The default for max generations is 5, so 1/5th of the modules would be marked for deletion.
This plugin instead always checks the cache and decreases the time to live of all entries. That way memory is cleaned up earlier.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "MemoryWithGcCachePlugin", {
enumerable: true,
get: function() {
return MemoryWithGcCachePlugin;
}
});
// Used to hook into the memory stage of the webpack caching
const CACHE_STAGE_MEMORY = -10 // TODO: Somehow webpack.Cache.STAGE_MEMORY doesn't work.
;
const PLUGIN_NAME = "NextJsMemoryWithGcCachePlugin";
class MemoryWithGcCachePlugin {
constructor({ maxGenerations }){
this.maxGenerations = maxGenerations;
}
apply(compiler) {
const maxGenerations = this.maxGenerations;
/**
* The memory cache
*/ const cache = new Map();
/**
* Cache cleanup implementation
*/ function decreaseTTLAndEvict() {
for (const [identifier, entry] of cache){
// Decrease item time to live
entry.ttl--;
// if ttl is 0 or below, evict entry from the cache
if (entry.ttl <= 0) {
cache.delete(identifier);
}
}
}
compiler.hooks.afterDone.tap(PLUGIN_NAME, decreaseTTLAndEvict);
compiler.cache.hooks.store.tap({
name: PLUGIN_NAME,
stage: CACHE_STAGE_MEMORY
}, (identifier, etag, data)=>{
cache.set(identifier, {
etag,
data,
ttl: maxGenerations
});
});
compiler.cache.hooks.get.tap({
name: PLUGIN_NAME,
stage: CACHE_STAGE_MEMORY
}, (identifier, etag, gotHandlers)=>{
const cacheEntry = cache.get(identifier);
// Item found
if (cacheEntry !== undefined) {
// When cache entry is hit we reset the counter.
cacheEntry.ttl = maxGenerations;
// Handles `null` separately as it doesn't have an etag.
if (cacheEntry.data === null) {
return null;
}
return cacheEntry.etag === etag ? cacheEntry.data : null;
}
// Handle case where other cache does have the identifier, puts it into the memory cache
gotHandlers.push((result, callback)=>{
cache.set(identifier, {
// Handles `null` separately as it doesn't have an etag.
etag: result === null ? null : etag,
data: result,
ttl: maxGenerations
});
return callback();
});
// No item found
return undefined;
});
compiler.cache.hooks.shutdown.tap({
name: PLUGIN_NAME,
stage: CACHE_STAGE_MEMORY
}, ()=>{
cache.clear();
});
}
}
//# sourceMappingURL=memory-with-gc-cache-plugin.js.map

View File

@@ -0,0 +1,559 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
SUPPORTED_NATIVE_MODULES: null,
default: null,
getEdgePolyfilledModules: null,
handleWebpackExternalForEdgeRuntime: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
SUPPORTED_NATIVE_MODULES: function() {
return SUPPORTED_NATIVE_MODULES;
},
default: function() {
return MiddlewarePlugin;
},
getEdgePolyfilledModules: function() {
return getEdgePolyfilledModules;
},
handleWebpackExternalForEdgeRuntime: function() {
return handleWebpackExternalForEdgeRuntime;
}
});
const _routeregex = require("../../../shared/lib/router/utils/route-regex");
const _getmodulebuildinfo = require("../loaders/get-module-build-info");
const _utils = require("../../../shared/lib/router/utils");
const _webpack = require("next/dist/compiled/webpack/webpack");
const _picomatch = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/picomatch"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _constants = require("../../../shared/lib/constants");
const _shared = require("../../../trace/shared");
const _events = require("../../../telemetry/events");
const _apppaths = require("../../../shared/lib/router/utils/app-paths");
const _constants1 = require("../../../lib/constants");
const _generateinterceptionroutesrewrites = require("../../../lib/generate-interception-routes-rewrites");
const _parsedynamiccodeevaluationerror = require("./wellknown-errors-plugin/parse-dynamic-code-evaluation-error");
const _utils1 = require("../utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const KNOWN_SAFE_DYNAMIC_PACKAGES = require("../../../lib/known-edge-safe-packages.json");
const NAME = "MiddlewarePlugin";
const MANIFEST_VERSION = 3;
/**
* Checks the value of usingIndirectEval and when it is a set of modules it
* check if any of the modules is actually being used. If the value is
* simply truthy it will return true.
*/ function isUsingIndirectEvalAndUsedByExports(args) {
const { moduleGraph, runtime, module: module1, usingIndirectEval, wp } = args;
if (typeof usingIndirectEval === "boolean") {
return usingIndirectEval;
}
const exportsInfo = moduleGraph.getExportsInfo(module1);
for (const exportName of usingIndirectEval){
if (exportsInfo.getUsed(exportName, runtime) !== wp.UsageState.Unused) {
return true;
}
}
return false;
}
function getEntryFiles(entryFiles, meta, hasInstrumentationHook, opts) {
const files = [];
if (meta.edgeSSR) {
if (meta.edgeSSR.isServerComponent) {
files.push(`server/${_constants.SERVER_REFERENCE_MANIFEST}.js`);
if (opts.sriEnabled) {
files.push(`server/${_constants.SUBRESOURCE_INTEGRITY_MANIFEST}.js`);
}
files.push(...entryFiles.filter((file)=>file.startsWith("app/") && !file.endsWith(".hot-update.js")).map((file)=>"server/" + file.replace(".js", "_" + _constants.CLIENT_REFERENCE_MANIFEST + ".js")));
}
files.push(`server/${_constants.MIDDLEWARE_BUILD_MANIFEST}.js`, `server/${_constants.MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`, `server/${_constants.NEXT_FONT_MANIFEST}.js`, `server/${_constants.INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`);
}
if (hasInstrumentationHook) {
files.push(`server/edge-${_constants1.INSTRUMENTATION_HOOK_FILENAME}.js`);
}
if (process.env.NODE_ENV === "production") {
files.push(_constants.PRERENDER_MANIFEST.replace("json", "js"));
}
files.push(...entryFiles.filter((file)=>!file.endsWith(".hot-update.js")).map((file)=>"server/" + file));
return files;
}
function getCreateAssets(params) {
const { compilation, metadataByEntry, opts } = params;
return (assets)=>{
const middlewareManifest = {
version: MANIFEST_VERSION,
middleware: {},
functions: {},
sortedMiddleware: []
};
const hasInstrumentationHook = compilation.entrypoints.has(_constants1.INSTRUMENTATION_HOOK_FILENAME);
// we only emit this entry for the edge runtime since it doesn't have access to a routes manifest
// and we don't need to provide the entire route manifest, just the interception routes.
const interceptionRewrites = JSON.stringify(opts.rewrites.beforeFiles.filter(_generateinterceptionroutesrewrites.isInterceptionRouteRewrite));
assets[`${_constants.INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`] = new _webpack.sources.RawSource(`self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(interceptionRewrites)}`);
for (const entrypoint of compilation.entrypoints.values()){
var _metadata_edgeMiddleware, _metadata_edgeSSR, _metadata_edgeApiFunction, _metadata_edgeSSR1, _metadata_edgeMiddleware1;
if (!entrypoint.name) {
continue;
}
// There should always be metadata for the entrypoint.
const metadata = metadataByEntry.get(entrypoint.name);
const page = (metadata == null ? void 0 : (_metadata_edgeMiddleware = metadata.edgeMiddleware) == null ? void 0 : _metadata_edgeMiddleware.page) || (metadata == null ? void 0 : (_metadata_edgeSSR = metadata.edgeSSR) == null ? void 0 : _metadata_edgeSSR.page) || (metadata == null ? void 0 : (_metadata_edgeApiFunction = metadata.edgeApiFunction) == null ? void 0 : _metadata_edgeApiFunction.page);
if (!page) {
continue;
}
const matcherSource = ((_metadata_edgeSSR1 = metadata.edgeSSR) == null ? void 0 : _metadata_edgeSSR1.isAppDir) ? (0, _apppaths.normalizeAppPath)(page) : page;
const catchAll = !metadata.edgeSSR && !metadata.edgeApiFunction;
const { namedRegex } = (0, _routeregex.getNamedMiddlewareRegex)(matcherSource, {
catchAll
});
const matchers = (metadata == null ? void 0 : (_metadata_edgeMiddleware1 = metadata.edgeMiddleware) == null ? void 0 : _metadata_edgeMiddleware1.matchers) ?? [
{
regexp: namedRegex,
originalSource: page === "/" && catchAll ? "/:path*" : matcherSource
}
];
const isEdgeFunction = !!(metadata.edgeApiFunction || metadata.edgeSSR);
const edgeFunctionDefinition = {
files: getEntryFiles(entrypoint.getFiles(), metadata, hasInstrumentationHook, opts),
name: entrypoint.name,
page: page,
matchers,
wasm: Array.from(metadata.wasmBindings, ([name, filePath])=>({
name,
filePath
})),
assets: Array.from(metadata.assetBindings, ([name, filePath])=>({
name,
filePath
})),
environments: opts.edgeEnvironments,
...metadata.regions && {
regions: metadata.regions
}
};
if (isEdgeFunction) {
middlewareManifest.functions[page] = edgeFunctionDefinition;
} else {
middlewareManifest.middleware[page] = edgeFunctionDefinition;
}
}
middlewareManifest.sortedMiddleware = (0, _utils.getSortedRoutes)(Object.keys(middlewareManifest.middleware));
assets[_constants.MIDDLEWARE_MANIFEST] = new _webpack.sources.RawSource(JSON.stringify(middlewareManifest, null, 2));
};
}
function buildWebpackError({ message, loc, compilation, entryModule, parser }) {
const error = new compilation.compiler.webpack.WebpackError(message);
error.name = NAME;
const module1 = entryModule ?? (parser == null ? void 0 : parser.state.current);
if (module1) {
error.module = module1;
}
error.loc = loc;
return error;
}
function isInMiddlewareLayer(parser) {
var _parser_state_module;
return ((_parser_state_module = parser.state.module) == null ? void 0 : _parser_state_module.layer) === "middleware";
}
function isNodeJsModule(moduleName) {
return require("module").builtinModules.includes(moduleName);
}
function isDynamicCodeEvaluationAllowed(fileName, middlewareConfig, rootDir) {
// Some packages are known to use `eval` but are safe to use in the Edge
// Runtime because the dynamic code will never be executed.
if (KNOWN_SAFE_DYNAMIC_PACKAGES.some((pkg)=>fileName.includes(`/node_modules/${pkg}/`.replace(/\//g, _path.default.sep)))) {
return true;
}
const name = fileName.replace(rootDir ?? "", "");
return (0, _picomatch.default)((middlewareConfig == null ? void 0 : middlewareConfig.unstable_allowDynamicGlobs) ?? [])(name);
}
function buildUnsupportedApiError({ apiName, loc, ...rest }) {
return buildWebpackError({
message: `A Node.js API is used (${apiName} at line: ${loc.start.line}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`,
loc,
...rest
});
}
function registerUnsupportedApiHooks(parser, compilation) {
for (const expression of _constants.EDGE_UNSUPPORTED_NODE_APIS){
const warnForUnsupportedApi = (node)=>{
if (!isInMiddlewareLayer(parser)) {
return;
}
compilation.warnings.push(buildUnsupportedApiError({
compilation,
parser,
apiName: expression,
...node
}));
return true;
};
parser.hooks.call.for(expression).tap(NAME, warnForUnsupportedApi);
parser.hooks.expression.for(expression).tap(NAME, warnForUnsupportedApi);
parser.hooks.callMemberChain.for(expression).tap(NAME, warnForUnsupportedApi);
parser.hooks.expressionMemberChain.for(expression).tap(NAME, warnForUnsupportedApi);
}
const warnForUnsupportedProcessApi = (node, [callee])=>{
if (!isInMiddlewareLayer(parser) || callee === "env") {
return;
}
compilation.warnings.push(buildUnsupportedApiError({
compilation,
parser,
apiName: `process.${callee}`,
...node
}));
return true;
};
parser.hooks.callMemberChain.for("process").tap(NAME, warnForUnsupportedProcessApi);
parser.hooks.expressionMemberChain.for("process").tap(NAME, warnForUnsupportedProcessApi);
}
function getCodeAnalyzer(params) {
return (parser)=>{
const { dev, compiler: { webpack: wp }, compilation } = params;
const { hooks } = parser;
/**
* For an expression this will check the graph to ensure it is being used
* by exports. Then it will store in the module buildInfo a boolean to
* express that it contains dynamic code and, if it is available, the
* module path that is using it.
*/ const handleExpression = ()=>{
if (!isInMiddlewareLayer(parser)) {
return;
}
wp.optimize.InnerGraph.onUsage(parser.state, (used = true)=>{
const buildInfo = (0, _getmodulebuildinfo.getModuleBuildInfo)(parser.state.module);
if (buildInfo.usingIndirectEval === true || used === false) {
return;
}
if (!buildInfo.usingIndirectEval || used === true) {
buildInfo.usingIndirectEval = used;
return;
}
buildInfo.usingIndirectEval = new Set([
...Array.from(buildInfo.usingIndirectEval),
...Array.from(used)
]);
});
};
/**
* This expression handler allows to wrap a dynamic code expression with a
* function call where we can warn about dynamic code not being allowed
* but actually execute the expression.
*/ const handleWrapExpression = (expr)=>{
if (!isInMiddlewareLayer(parser)) {
return;
}
const { ConstDependency } = wp.dependencies;
const dep1 = new ConstDependency("__next_eval__(function() { return ", expr.range[0]);
dep1.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep1);
const dep2 = new ConstDependency("})", expr.range[1]);
dep2.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep2);
handleExpression();
return true;
};
/**
* This expression handler allows to wrap a WebAssembly.compile invocation with a
* function call where we can warn about WASM code generation not being allowed
* but actually execute the expression.
*/ const handleWrapWasmCompileExpression = (expr)=>{
if (!isInMiddlewareLayer(parser)) {
return;
}
const { ConstDependency } = wp.dependencies;
const dep1 = new ConstDependency("__next_webassembly_compile__(function() { return ", expr.range[0]);
dep1.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep1);
const dep2 = new ConstDependency("})", expr.range[1]);
dep2.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep2);
handleExpression();
};
/**
* This expression handler allows to wrap a WebAssembly.instatiate invocation with a
* function call where we can warn about WASM code generation not being allowed
* but actually execute the expression.
*
* Note that we don't update `usingIndirectEval`, i.e. we don't abort a production build
* since we can't determine statically if the first parameter is a module (legit use) or
* a buffer (dynamic code generation).
*/ const handleWrapWasmInstantiateExpression = (expr)=>{
if (!isInMiddlewareLayer(parser)) {
return;
}
if (dev) {
const { ConstDependency } = wp.dependencies;
const dep1 = new ConstDependency("__next_webassembly_instantiate__(function() { return ", expr.range[0]);
dep1.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep1);
const dep2 = new ConstDependency("})", expr.range[1]);
dep2.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep2);
}
};
/**
* Handler to store original source location of static and dynamic imports into module's buildInfo.
*/ const handleImport = (node)=>{
var _node_source;
if (isInMiddlewareLayer(parser) && ((_node_source = node.source) == null ? void 0 : _node_source.value) && (node == null ? void 0 : node.loc)) {
var _node_source_value;
const { module: module1, source } = parser.state;
const buildInfo = (0, _getmodulebuildinfo.getModuleBuildInfo)(module1);
if (!buildInfo.importLocByPath) {
buildInfo.importLocByPath = new Map();
}
const importedModule = (_node_source_value = node.source.value) == null ? void 0 : _node_source_value.toString();
buildInfo.importLocByPath.set(importedModule, {
sourcePosition: {
...node.loc.start,
source: module1.identifier()
},
sourceContent: source.toString()
});
if (!dev && isNodeJsModule(importedModule)) {
compilation.warnings.push(buildWebpackError({
message: `A Node.js module is loaded ('${importedModule}' at line ${node.loc.start.line}) which is not supported in the Edge Runtime.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`,
compilation,
parser,
...node
}));
}
}
};
/**
* A noop handler to skip analyzing some cases.
* Order matters: for it to work, it must be registered first
*/ const skip = ()=>isInMiddlewareLayer(parser) ? true : undefined;
for (const prefix of [
"",
"global."
]){
hooks.expression.for(`${prefix}Function.prototype`).tap(NAME, skip);
hooks.expression.for(`${prefix}Function.bind`).tap(NAME, skip);
hooks.call.for(`${prefix}eval`).tap(NAME, handleWrapExpression);
hooks.call.for(`${prefix}Function`).tap(NAME, handleWrapExpression);
hooks.new.for(`${prefix}Function`).tap(NAME, handleWrapExpression);
hooks.call.for(`${prefix}WebAssembly.compile`).tap(NAME, handleWrapWasmCompileExpression);
hooks.call.for(`${prefix}WebAssembly.instantiate`).tap(NAME, handleWrapWasmInstantiateExpression);
}
hooks.importCall.tap(NAME, handleImport);
hooks.import.tap(NAME, handleImport);
if (!dev) {
// do not issue compilation warning on dev: invoking code will provide details
registerUnsupportedApiHooks(parser, compilation);
}
};
}
function getExtractMetadata(params) {
const { dev, compilation, metadataByEntry, compiler } = params;
const { webpack: wp } = compiler;
return async ()=>{
metadataByEntry.clear();
const telemetry = _shared.traceGlobals.get("telemetry");
for (const [entryName, entry] of compilation.entries){
var _entry_dependencies, _route_middlewareConfig;
if (entry.options.runtime !== _constants.EDGE_RUNTIME_WEBPACK) {
continue;
}
const entryDependency = (_entry_dependencies = entry.dependencies) == null ? void 0 : _entry_dependencies[0];
const resolvedModule = compilation.moduleGraph.getResolvedModule(entryDependency);
if (!resolvedModule) {
continue;
}
const { rootDir, route } = (0, _getmodulebuildinfo.getModuleBuildInfo)(resolvedModule);
const { moduleGraph } = compilation;
const modules = new Set();
const addEntriesFromDependency = (dependency)=>{
const module1 = moduleGraph.getModule(dependency);
if (module1) {
modules.add(module1);
}
};
entry.dependencies.forEach(addEntriesFromDependency);
entry.includeDependencies.forEach(addEntriesFromDependency);
const entryMetadata = {
wasmBindings: new Map(),
assetBindings: new Map()
};
if (route == null ? void 0 : (_route_middlewareConfig = route.middlewareConfig) == null ? void 0 : _route_middlewareConfig.regions) {
entryMetadata.regions = route.middlewareConfig.regions;
}
if (route == null ? void 0 : route.preferredRegion) {
const preferredRegion = route.preferredRegion;
entryMetadata.regions = // Ensures preferredRegion is always an array in the manifest.
typeof preferredRegion === "string" ? [
preferredRegion
] : preferredRegion;
}
let ogImageGenerationCount = 0;
for (const module1 of modules){
const buildInfo = (0, _getmodulebuildinfo.getModuleBuildInfo)(module1);
/**
* Check if it uses the image generation feature.
*/ if (!dev) {
const resource = module1.resource;
const hasOGImageGeneration = resource && /[\\/]node_modules[\\/]@vercel[\\/]og[\\/]dist[\\/]index\.(edge|node)\.js$|[\\/]next[\\/]dist[\\/](esm[\\/])?server[\\/]og[\\/]image-response\.js$/.test(resource);
if (hasOGImageGeneration) {
ogImageGenerationCount++;
}
}
/**
* When building for production checks if the module is using `eval`
* and in such case produces a compilation error. The module has to
* be in use.
*/ if (!dev && buildInfo.usingIndirectEval && isUsingIndirectEvalAndUsedByExports({
module: module1,
moduleGraph,
runtime: wp.util.runtime.getEntryRuntime(compilation, entryName),
usingIndirectEval: buildInfo.usingIndirectEval,
wp
})) {
var _route_middlewareConfig1;
const id = module1.identifier();
if (/node_modules[\\/]regenerator-runtime[\\/]runtime\.js/.test(id)) {
continue;
}
if (route == null ? void 0 : (_route_middlewareConfig1 = route.middlewareConfig) == null ? void 0 : _route_middlewareConfig1.unstable_allowDynamicGlobs) {
telemetry == null ? void 0 : telemetry.record({
eventName: "NEXT_EDGE_ALLOW_DYNAMIC_USED",
payload: {
file: route == null ? void 0 : route.absolutePagePath.replace(rootDir ?? "", ""),
config: route == null ? void 0 : route.middlewareConfig,
fileWithDynamicCode: module1.userRequest.replace(rootDir ?? "", "")
}
});
}
if (!isDynamicCodeEvaluationAllowed(module1.userRequest, route == null ? void 0 : route.middlewareConfig, rootDir)) {
const message = `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime ${typeof buildInfo.usingIndirectEval !== "boolean" ? `\nUsed by ${Array.from(buildInfo.usingIndirectEval).join(", ")}` : ""}\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`;
compilation.errors.push((0, _parsedynamiccodeevaluationerror.getDynamicCodeEvaluationError)(message, module1, compilation, compiler));
}
}
/**
* The entry module has to be either a page or a middleware and hold
* the corresponding metadata.
*/ if (buildInfo == null ? void 0 : buildInfo.nextEdgeSSR) {
entryMetadata.edgeSSR = buildInfo.nextEdgeSSR;
} else if (buildInfo == null ? void 0 : buildInfo.nextEdgeMiddleware) {
entryMetadata.edgeMiddleware = buildInfo.nextEdgeMiddleware;
} else if (buildInfo == null ? void 0 : buildInfo.nextEdgeApiFunction) {
entryMetadata.edgeApiFunction = buildInfo.nextEdgeApiFunction;
}
/**
* If the module is a WASM module we read the binding information and
* append it to the entry wasm bindings.
*/ if (buildInfo == null ? void 0 : buildInfo.nextWasmMiddlewareBinding) {
entryMetadata.wasmBindings.set(buildInfo.nextWasmMiddlewareBinding.name, buildInfo.nextWasmMiddlewareBinding.filePath);
}
if (buildInfo == null ? void 0 : buildInfo.nextAssetMiddlewareBinding) {
entryMetadata.assetBindings.set(buildInfo.nextAssetMiddlewareBinding.name, buildInfo.nextAssetMiddlewareBinding.filePath);
}
/**
* Append to the list of modules to process outgoingConnections from
* the module that is being processed.
*/ for (const conn of (0, _utils1.getModuleReferencesInOrder)(module1, moduleGraph)){
if (conn.module) {
modules.add(conn.module);
}
}
}
telemetry == null ? void 0 : telemetry.record({
eventName: _events.EVENT_BUILD_FEATURE_USAGE,
payload: {
featureName: "vercelImageGeneration",
invocationCount: ogImageGenerationCount
}
});
metadataByEntry.set(entryName, entryMetadata);
}
};
}
class MiddlewarePlugin {
constructor({ dev, sriEnabled, rewrites, edgeEnvironments }){
this.dev = dev;
this.sriEnabled = sriEnabled;
this.rewrites = rewrites;
this.edgeEnvironments = edgeEnvironments;
}
apply(compiler) {
compiler.hooks.compilation.tap(NAME, (compilation, params)=>{
const { hooks } = params.normalModuleFactory;
/**
* This is the static code analysis phase.
*/ const codeAnalyzer = getCodeAnalyzer({
dev: this.dev,
compiler,
compilation
});
hooks.parser.for("javascript/auto").tap(NAME, codeAnalyzer);
hooks.parser.for("javascript/dynamic").tap(NAME, codeAnalyzer);
hooks.parser.for("javascript/esm").tap(NAME, codeAnalyzer);
/**
* Extract all metadata for the entry points in a Map object.
*/ const metadataByEntry = new Map();
compilation.hooks.finishModules.tapPromise(NAME, getExtractMetadata({
compilation,
compiler,
dev: this.dev,
metadataByEntry
}));
/**
* Emit the middleware manifest.
*/ compilation.hooks.processAssets.tap({
name: "NextJsMiddlewareManifest",
stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, getCreateAssets({
compilation,
metadataByEntry,
opts: {
sriEnabled: this.sriEnabled,
rewrites: this.rewrites,
edgeEnvironments: this.edgeEnvironments
}
}));
});
}
}
const SUPPORTED_NATIVE_MODULES = [
"buffer",
"events",
"assert",
"util",
"async_hooks"
];
const supportedEdgePolyfills = new Set(SUPPORTED_NATIVE_MODULES);
function getEdgePolyfilledModules() {
const records = {};
for (const mod of SUPPORTED_NATIVE_MODULES){
records[mod] = `commonjs node:${mod}`;
records[`node:${mod}`] = `commonjs node:${mod}`;
}
return records;
}
async function handleWebpackExternalForEdgeRuntime({ request, context, contextInfo, getResolve }) {
if (contextInfo.issuerLayer === "middleware" && isNodeJsModule(request) && !supportedEdgePolyfills.has(request)) {
// allows user to provide and use their polyfills, as we do with buffer.
try {
await getResolve()(context, request);
} catch {
return `root globalThis.__import_unsupported('${request}')`;
}
}
}
//# sourceMappingURL=middleware-plugin.js.map

View File

@@ -0,0 +1,25 @@
// @ts-ignore: TODO: remove when webpack 5 is stable
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return NextMiniCssExtractPlugin;
}
});
const _minicssextractplugin = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/mini-css-extract-plugin"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
class NextMiniCssExtractPlugin extends _minicssextractplugin.default {
constructor(...args){
super(...args);
this.__next_css_remove = true;
}
}
//# sourceMappingURL=mini-css-extract-plugin.js.map

View File

@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
DropClientPage: null,
ampFirstEntryNamesMap: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
DropClientPage: function() {
return DropClientPage;
},
ampFirstEntryNamesMap: function() {
return ampFirstEntryNamesMap;
}
});
const _constants = require("../../../shared/lib/constants");
const ampFirstEntryNamesMap = new WeakMap();
const PLUGIN_NAME = "DropAmpFirstPagesPlugin";
class DropClientPage {
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory })=>{
// Recursively look up the issuer till it ends up at the root
function findEntryModule(mod) {
const queue = new Set([
mod
]);
for (const module1 of queue){
const incomingConnections = compilation.moduleGraph.getIncomingConnections(module1);
for (const incomingConnection of incomingConnections){
if (!incomingConnection.originModule) return module1;
queue.add(incomingConnection.originModule);
}
}
return null;
}
function handler(parser) {
function markAsAmpFirst() {
const entryModule = findEntryModule(parser.state.module);
if (!entryModule) {
return;
}
// @ts-ignore buildInfo exists on Module
entryModule.buildInfo.NEXT_ampFirst = true;
}
parser.hooks.preDeclarator.tap(PLUGIN_NAME, (declarator)=>{
var _declarator_id;
if ((declarator == null ? void 0 : (_declarator_id = declarator.id) == null ? void 0 : _declarator_id.name) === _constants.STRING_LITERAL_DROP_BUNDLE) {
markAsAmpFirst();
}
});
}
normalModuleFactory.hooks.parser.for("javascript/auto").tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser.for("javascript/esm").tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser.for("javascript/dynamic").tap(PLUGIN_NAME, handler);
if (!ampFirstEntryNamesMap.has(compilation)) {
ampFirstEntryNamesMap.set(compilation, []);
}
const ampFirstEntryNamesItem = ampFirstEntryNamesMap.get(compilation);
compilation.hooks.seal.tap(PLUGIN_NAME, ()=>{
for (const [name, entryData] of compilation.entries){
for (const dependency of entryData.dependencies){
var _module_buildInfo;
const module1 = compilation.moduleGraph.getModule(dependency);
if (module1 == null ? void 0 : (_module_buildInfo = module1.buildInfo) == null ? void 0 : _module_buildInfo.NEXT_ampFirst) {
ampFirstEntryNamesItem.push(name);
compilation.entries.delete(name);
}
}
}
});
});
}
constructor(){
this.ampPages = new Set();
}
}
//# sourceMappingURL=next-drop-client-page-plugin.js.map

View File

@@ -0,0 +1,120 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "NextFontManifestPlugin", {
enumerable: true,
get: function() {
return NextFontManifestPlugin;
}
});
const _webpack = require("next/dist/compiled/webpack/webpack");
const _getroutefromentrypoint = /*#__PURE__*/ _interop_require_default(require("../../../server/get-route-from-entrypoint"));
const _constants = require("../../../shared/lib/constants");
const _utils = require("../utils");
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const PLUGIN_NAME = "NextFontManifestPlugin";
/**
* When calling font functions with next/font, you can specify if you'd like the font to be preloaded (true by default).
* e.g.: const inter = Inter({ subsets: ['latin'], preload: true })
*
* In that case, next-font-loader will emit the font file as [name].p.[ext] instead of [name].[ext]
* This function returns those files from an array that can include both preloaded and non-preloaded files.
*/ function getPreloadedFontFiles(fontFiles) {
return fontFiles.filter((file)=>/\.p\.(woff|woff2|eot|ttf|otf)$/.test(file));
}
/**
* Similarly to getPreloadedFontFiles, but returns true if some of the files includes -s in the name.
* This means that a font is using size adjust in its fallback font.
* This was added to enable adding data-size-adjust="true" to the dom, used by the Google Aurora team to collect statistics.
*/ function getPageIsUsingSizeAdjust(fontFiles) {
return fontFiles.some((file)=>file.includes("-s"));
}
class NextFontManifestPlugin {
constructor(options){
this.appDir = options.appDir;
}
apply(compiler) {
compiler.hooks.make.tap(PLUGIN_NAME, (compilation)=>{
// In this stage the font files are emitted and we can collect all files emitted by each chunkGroup (entry).
compilation.hooks.processAssets.tap({
name: PLUGIN_NAME,
stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
}, (assets)=>{
const nextFontManifest = {
pages: {},
app: {},
appUsingSizeAdjust: false,
pagesUsingSizeAdjust: false
};
if (this.appDir) {
const appDirBase = _path.default.dirname(this.appDir) + _path.default.sep;
// After all modules are created, we collect the modules that was created by next-font-loader.
(0, _utils.traverseModules)(compilation, (mod, _chunk, chunkGroup)=>{
var _mod_request;
if (mod == null ? void 0 : (_mod_request = mod.request) == null ? void 0 : _mod_request.includes("/next-font-loader/index.js?")) {
var _mod_buildInfo;
if (!((_mod_buildInfo = mod.buildInfo) == null ? void 0 : _mod_buildInfo.assets)) return;
const chunkEntryName = (appDirBase + chunkGroup.name).replace(/[\\/]/g, _path.default.sep);
const modAssets = Object.keys(mod.buildInfo.assets);
const fontFiles = modAssets.filter((file)=>/\.(woff|woff2|eot|ttf|otf)$/.test(file));
// Look if size-adjust fallback font is being used
if (!nextFontManifest.appUsingSizeAdjust) {
nextFontManifest.appUsingSizeAdjust = getPageIsUsingSizeAdjust(fontFiles);
}
const preloadedFontFiles = getPreloadedFontFiles(fontFiles);
// Add an entry of the module's font files in the manifest.
// We'll add an entry even if no files should preload.
// When an entry is present but empty, instead of preloading the font files, a preconnect tag is added.
if (fontFiles.length > 0) {
if (!nextFontManifest.app[chunkEntryName]) {
nextFontManifest.app[chunkEntryName] = [];
}
nextFontManifest.app[chunkEntryName].push(...preloadedFontFiles);
}
}
}, (chunkGroup)=>{
var _chunkGroup_name;
// Only loop through entrypoints that are under app/.
return !!((_chunkGroup_name = chunkGroup.name) == null ? void 0 : _chunkGroup_name.startsWith("app/"));
});
}
// Look at all the entrypoints created for pages/.
for (const entrypoint of compilation.entrypoints.values()){
const pagePath = (0, _getroutefromentrypoint.default)(entrypoint.name);
if (!pagePath) {
continue;
}
// Get font files from the chunks included in the entrypoint.
const fontFiles = entrypoint.chunks.flatMap((chunk)=>[
...chunk.auxiliaryFiles
]).filter((file)=>/\.(woff|woff2|eot|ttf|otf)$/.test(file));
// Look if size-adjust fallback font is being used
if (!nextFontManifest.pagesUsingSizeAdjust) {
nextFontManifest.pagesUsingSizeAdjust = getPageIsUsingSizeAdjust(fontFiles);
}
const preloadedFontFiles = getPreloadedFontFiles(fontFiles);
// Add an entry of the route's font files in the manifest.
// We'll add an entry even if no files should preload.
// When an entry is present but empty, instead of preloading the font files, a preconnect tag is added.
if (fontFiles.length > 0) {
nextFontManifest.pages[pagePath] = preloadedFontFiles;
}
}
const manifest = JSON.stringify(nextFontManifest, null);
// Create manifest for edge
assets[`server/${_constants.NEXT_FONT_MANIFEST}.js`] = new _webpack.sources.RawSource(`self.__NEXT_FONT_MANIFEST=${JSON.stringify(manifest)}`);
// Create manifest for server
assets[`server/${_constants.NEXT_FONT_MANIFEST}.json`] = new _webpack.sources.RawSource(manifest);
});
});
return;
}
}
//# sourceMappingURL=next-font-manifest-plugin.js.map

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