main repo

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

View File

@@ -0,0 +1,187 @@
export 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";
}
export 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);
}
}
/**
* Extracts the value of an exported const variable named `exportedName`
* (e.g. "export const config = { runtime: 'edge' }") from swc's AST.
* The value must be one of (or throws UnsupportedValueError):
* - string
* - boolean
* - number
* - null
* - undefined
* - array containing values listed in this list
* - object containing values listed in this list
*
* Throws NoSuchDeclarationError if the declaration is not found.
*/ export function extractExportedConstValue(module, exportedName) {
for (const moduleItem of module.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 @@
{"version":3,"sources":["../../../src/build/analysis/extract-const-value.ts"],"names":["NoSuchDeclarationError","Error","isExportDeclaration","node","type","isVariableDeclaration","isIdentifier","isBooleanLiteral","isNullLiteral","isStringLiteral","isNumericLiteral","isArrayExpression","isObjectExpression","isKeyValueProperty","isRegExpLiteral","isTemplateLiteral","UnsupportedValueError","constructor","message","paths","codePath","path","extractValue","value","RegExp","pattern","flags","undefined","arr","i","len","elements","length","elem","spread","push","expression","obj","prop","properties","key","expressions","cooked","raw","quasis","extractExportedConstValue","module","exportedName","moduleItem","body","declaration","kind","decl","declarations","id","init"],"mappings":"AAiBA,OAAO,MAAMA,+BAA+BC;AAAO;AAEnD,SAASC,oBAAoBC,IAAU;IACrC,OAAOA,KAAKC,IAAI,KAAK;AACvB;AAEA,SAASC,sBAAsBF,IAAU;IACvC,OAAOA,KAAKC,IAAI,KAAK;AACvB;AAEA,SAASE,aAAaH,IAAU;IAC9B,OAAOA,KAAKC,IAAI,KAAK;AACvB;AAEA,SAASG,iBAAiBJ,IAAU;IAClC,OAAOA,KAAKC,IAAI,KAAK;AACvB;AAEA,SAASI,cAAcL,IAAU;IAC/B,OAAOA,KAAKC,IAAI,KAAK;AACvB;AAEA,SAASK,gBAAgBN,IAAU;IACjC,OAAOA,KAAKC,IAAI,KAAK;AACvB;AAEA,SAASM,iBAAiBP,IAAU;IAClC,OAAOA,KAAKC,IAAI,KAAK;AACvB;AAEA,SAASO,kBAAkBR,IAAU;IACnC,OAAOA,KAAKC,IAAI,KAAK;AACvB;AAEA,SAASQ,mBAAmBT,IAAU;IACpC,OAAOA,KAAKC,I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QAEA,OAAOH;IACT,OAAO,IAAItB,kBAAkBZ,OAAO;QAClC,aAAa;QACb,IAAIA,KAAKsC,WAAW,CAACT,MAAM,KAAK,GAAG;YACjC,sDAAsD;YACtD,MAAM,IAAIhB,sBACR,iDACAK;QAEJ;QAEA,4EAA4E;QAC5E,2EAA2E;QAC3E,kFAAkF;QAClF,wBAAwB;QACxB,mFAAmF;QACnF,EAAE;QACF,4EAA4E;QAC5E,qEAAqE;QACrE,gGAAgG;QAChG,MAAM,CAAC,EAAEqB,MAAM,EAAEC,GAAG,EAAE,CAAC,GAAGxC,KAAKyC,MAAM;QAErC,OAAOF,UAAUC;IACnB,OAAO;QACL,MAAM,IAAI3B,sBACR,CAAC,uBAAuB,EAAEb,KAAKC,IAAI,CAAC,CAAC,CAAC,EACtCiB;IAEJ;AACF;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASwB,0BACdC,MAAc,EACdC,YAAoB;IAEpB,KAAK,MAAMC,cAAcF,OAAOG,IAAI,CAAE;QACpC,IAAI,CAAC/C,oBAAoB8C,aAAa;YACpC;QACF;QAEA,MAAME,cAAcF,WAAWE,WAAW;QAC1C,IAAI,CAAC7C,sBAAsB6C,cAAc;YACvC;QACF;QAEA,IAAIA,YAAYC,IAAI,KAAK,SAAS;YAChC;QACF;QAEA,KAAK,MAAMC,QAAQF,YAAYG,YAAY,CAAE;YAC3C,IACE/C,aAAa8C,KAAKE,EAAE,KACpBF,KAAKE,EAAE,CAAC/B,KAAK,KAAKwB,gBAClBK,KAAKG,IAAI,EACT;gBACA,OAAOjC,aAAa8B,KAAKG,IAAI,EAAE;oBAACR;iBAAa;YAC/C;QACF;IACF;IAEA,MAAM,IAAI/C;AACZ"}

View File

@@ -0,0 +1,421 @@
import { promises as fs } from "fs";
import LRUCache from "next/dist/compiled/lru-cache";
import { matcher } from "next/dist/compiled/micromatch";
import { extractExportedConstValue, UnsupportedValueError } from "./extract-const-value";
import { parseModule } from "./parse-module";
import * as Log from "../output/log";
import { SERVER_RUNTIME } from "../../lib/constants";
import { checkCustomRoutes } from "../../lib/load-custom-routes";
import { tryToParsePath } from "../../lib/try-to-parse-path";
import { isAPIRoute } from "../../lib/is-api-route";
import { isEdgeRuntime } from "../../lib/is-edge-runtime";
import { RSC_MODULE_TYPES } from "../../shared/lib/constants";
// 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";
export function getRSCModuleInformation(source, isServerLayer) {
var _source_match_, _source_match, _clientInfoMatch_;
const actions = (_source_match = source.match(ACTION_MODULE_LABEL)) == null ? void 0 : (_source_match_ = _source_match[1]) == null ? void 0 : _source_match_.split(",");
const clientInfoMatch = source.match(CLIENT_MODULE_LABEL);
const isClientRef = !!clientInfoMatch;
if (!isServerLayer) {
return {
type: 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 ? RSC_MODULE_TYPES.client : 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.readFile(filePath, {
encoding: "utf8"
});
} catch (error) {
if (shouldThrow) {
error.message = `Next.js ERROR: Failed to read file ${filePath}:\n${error.message}`;
throw error;
}
}
}
export 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
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;
});
checkCustomRoutes(routes, "middleware");
return routes.map((r)=>{
const { source, ...rest } = r;
const parsedPage = 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 {
matcher(glob);
} catch (err) {
throw new Error(`${pageFilePath} exported 'config.unstable_allowDynamic' contains invalid pattern '${glob}': ${err.message}`);
}
}
}
return result;
}
const apiRouteWarnings = new LRUCache({
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({
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);
}
// Detect if metadata routes is a dynamic route, which containing
// generateImageMetadata or generateSitemaps as export
export async function isDynamicMetadataRoute(pageFilePath) {
const fileContent = await tryToReadFile(pageFilePath, true) || "";
if (!/generateImageMetadata|generateSitemaps/.test(fileContent)) return false;
const swcAST = await parseModule(pageFilePath, fileContent);
const exportsInfo = checkExports(swcAST, pageFilePath);
return !exportsInfo.generateImageMetadata || !exportsInfo.generateSitemaps;
}
/**
* For a given pageFilePath and nextConfig, if the config supports it, this
* function will read the file and return the runtime that should be used.
* It will look into the file content only if the page *requires* a runtime
* to be specified, that is, when gSSP or gSP is used.
* Related discussion: https://github.com/vercel/next.js/discussions/34179
*/ export async function getPageStaticInfo(params) {
const { isDev, pageFilePath, nextConfig, page, pageType } = params;
const fileContent = await tryToReadFile(pageFilePath, !isDev) || "";
if (/runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const/.test(fileContent)) {
const swcAST = await 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;
try {
config = extractExportedConstValue(swcAST, "config");
} catch (e) {
if (e instanceof UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e);
}
// `export config` doesn't exist, or other unknown error throw by swc, silence them
}
const extraConfig = {};
if (extraProperties && pageType === "app") {
for (const prop of extraProperties){
if (!AUTHORIZED_EXTRA_ROUTER_PROPS.includes(prop)) continue;
try {
extraConfig[prop] = extractExportedConstValue(swcAST, prop);
} catch (e) {
if (e instanceof UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e);
}
}
}
} else if (pageType === "pages") {
for(const key in config){
if (!AUTHORIZED_EXTRA_ROUTER_PROPS.includes(key)) continue;
extraConfig[key] = config[key];
}
}
if (pageType === "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 === "app") {
resolvedRuntime = runtime;
} else {
resolvedRuntime = runtime || config.runtime;
}
if (typeof resolvedRuntime !== "undefined" && resolvedRuntime !== SERVER_RUNTIME.nodejs && !isEdgeRuntime(resolvedRuntime)) {
const options = Object.values(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 === "app";
const isAnAPIRoute = isAPIRoute(page == null ? void 0 : page.replace(/^(?:\/src)?\/pages\//, "/"));
resolvedRuntime = isEdgeRuntime(resolvedRuntime) || requiresServerRuntime ? resolvedRuntime : undefined;
if (resolvedRuntime === SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdge(isAnAPIRoute ? page : null);
}
if (resolvedRuntime === SERVER_RUNTIME.edge && pageType === "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 === "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: RSC_MODULE_TYPES.server,
generateStaticParams: false,
amp: false,
runtime: undefined
};
}
//# sourceMappingURL=get-page-static-info.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
import LRUCache from "next/dist/compiled/lru-cache";
import { withPromiseCache } from "../../lib/with-promise-cache";
import { createHash } from "crypto";
import { parse } from "../swc";
/**
* Parses a module with SWC using an LRU cache where the parsed module will
* be indexed by a sha of its content holding up to 500 entries.
*/ export const parseModule = withPromiseCache(new LRUCache({
max: 500
}), async (filename, content)=>parse(content, {
isModule: "unknown",
filename
}).catch(()=>null), (_, content)=>createHash("sha1").update(content).digest("hex"));
//# sourceMappingURL=parse-module.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/analysis/parse-module.ts"],"names":["LRUCache","withPromiseCache","createHash","parse","parseModule","max","filename","content","isModule","catch","_","update","digest"],"mappings":"AAAA,OAAOA,cAAc,+BAA8B;AACnD,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,KAAK,QAAQ,SAAQ;AAE9B;;;CAGC,GACD,OAAO,MAAMC,cAAcH,iBACzB,IAAID,SAAsB;IAAEK,KAAK;AAAI,IACrC,OAAOC,UAAkBC,UACvBJ,MAAMI,SAAS;QAAEC,UAAU;QAAWF;IAAS,GAAGG,KAAK,CAAC,IAAM,OAChE,CAACC,GAAGH,UAAYL,WAAW,QAAQS,MAAM,CAACJ,SAASK,MAAM,CAAC,QAC3D"}

View File

@@ -0,0 +1,278 @@
import { readFileSync } from "fs";
import JSON5 from "next/dist/compiled/json5";
import { createConfigItem, loadOptions } from "next/dist/compiled/babel/core";
import loadConfig from "next/dist/compiled/babel/core-lib-config";
import { consumeIterator } from "./util";
import * as Log from "../../output/log";
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 ? createConfigItem(require("../plugins/commonjs"), {
type: "plugin"
}) : null;
const reactRefreshItem = hasReactRefresh ? createConfigItem([
require("next/dist/compiled/react-refresh/babel"),
{
skipEnvCheck: true
}
], {
type: "plugin"
}) : null;
const pageConfigItem = !isServer && isPageFile ? createConfigItem([
require("../plugins/next-page-config")
], {
type: "plugin"
}) : null;
const disallowExportAllItem = !isServer && isPageFile ? createConfigItem([
require("../plugins/next-page-disallow-re-export-all-exports")
], {
type: "plugin"
}) : null;
const transformDefineItem = 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 ? createConfigItem([
require.resolve("../plugins/next-ssg-transform")
], {
type: "plugin"
}) : null;
const commonJsItem = isNextDist ? createConfigItem(require("next/dist/compiled/babel/plugin-transform-modules-commonjs"), {
type: "plugin"
}) : null;
const nextFontUnsupported = 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 = readFileSync(configFilePath, "utf8");
return JSON5.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 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 } = 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,
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 = loadOptions(options);
const config = consumeIterator(loadConfig(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();
export default 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

File diff suppressed because one or more lines are too long

23
node_modules/next/dist/esm/build/babel/loader/index.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import transform from "./transform";
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.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);
});
};
export default nextBabelLoaderOuter;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/babel/loader/index.ts"],"names":["transform","nextBabelLoader","parentTrace","inputSource","inputSourceMap","filename","resourcePath","target","loaderOptions","traceChild","traceFn","getOptions","loaderSpanInner","code","transformedSource","map","outputSourceMap","call","nextBabelLoaderOuter","callback","async","loaderSpan","currentTraceSpan","traceAsyncFn","then","err"],"mappings":"AACA,OAAOA,eAAe,cAAa;AAGnC,eAAeC,gBAEbC,WAAiB,EACjBC,WAAmB,EACnBC,cAAyC;IAEzC,MAAMC,WAAW,IAAI,CAACC,YAAY;IAClC,MAAMC,SAAS,IAAI,CAACA,MAAM;IAC1B,MAAMC,gBAAgBN,YACnBO,UAAU,CAAC,cACZ,+DAA+D;KAC9DC,OAAO,CAAC,IAAM,IAAI,CAACC,UAAU;IAEhC,MAAMC,kBAAkBV,YAAYO,UAAU,CAAC;IAC/C,MAAM,EAAEI,MAAMC,iBAAiB,EAAEC,KAAKC,eAAe,EAAE,GACrDJ,gBAAgBF,OAAO,CAAC,IACtBV,UAAUiB,IAAI,CACZ,IAAI,EACJd,aACAC,gBACAI,eACAH,UACAE,QACAK;IAIN,OAAO;QAACE;QAAmBE;KAAgB;AAC7C;AAEA,MAAME,uBAAuB,SAASA,qBAEpCf,WAAmB,EACnBC,cAAyC;IAEzC,MAAMe,WAAW,IAAI,CAACC,KAAK;IAE3B,MAAMC,aAAa,IAAI,CAACC,gBAAgB,CAACb,UAAU,CAAC;IACpDY,WACGE,YAAY,CAAC,IACZtB,gBAAgBgB,IAAI,CAAC,IAAI,EAAEI,YAAYlB,aAAaC,iBAErDoB,IAAI,CACH,CAAC,CAACV,mBAAmBE,gBAAqB,GACxCG,4BAAAA,SAAW,MAAML,mBAAmBE,mBAAmBZ,iBACzD,CAACqB;QACCN,4BAAAA,SAAWM;IACb;AAEN;AAEA,eAAeP,qBAAoB"}

View File

@@ -0,0 +1,82 @@
/*
* Partially adapted from @babel/core (MIT license).
*/ import traverse from "next/dist/compiled/babel/traverse";
import generate from "next/dist/compiled/babel/generator";
import normalizeFile from "next/dist/compiled/babel/core-lib-normalize-file";
import normalizeOpts from "next/dist/compiled/babel/core-lib-normalize-opts";
import loadBlockHoistPlugin from "next/dist/compiled/babel/core-lib-block-hoist-plugin";
import PluginPass from "next/dist/compiled/babel/core-lib-plugin-pass";
import getConfig from "./get-config";
import { consumeIterator } from "./util";
function getTraversalParams(file, pluginPairs) {
const passPairs = [];
const passes = [];
const visitors = [];
for (const plugin of pluginPairs.concat(loadBlockHoistPlugin())){
const pass = new PluginPass(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.visitors.merge(visitors, passes, // @ts-ignore - the exported types are incorrect here
file.opts.wrapPluginVisitorMethod);
parentSpan.traceChild("babel-turbo-traverse").traceFn(()=>traverse(file.ast, visitor, file.scope));
invokePluginPost(file, passPairs);
}
function transformAst(file, babelConfig, parentSpan) {
for (const pluginPairs of babelConfig.passes){
transformAstPass(file, pluginPairs, parentSpan);
}
}
export default function transform(source, inputSourceMap, loaderOptions, filename, target, parentSpan) {
const getConfigSpan = parentSpan.traceChild("babel-turbo-get-config");
const babelConfig = getConfig.call(this, {
source,
loaderOptions,
inputSourceMap,
target,
filename
});
getConfigSpan.stop();
const normalizeSpan = parentSpan.traceChild("babel-turbo-normalize-file");
const file = consumeIterator(normalizeFile(babelConfig.passes, normalizeOpts(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 } = generate(file.ast, file.opts.generatorOpts, file.code);
generateSpan.stop();
return {
code,
map
};
}
//# sourceMappingURL=transform.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/babel/loader/transform.ts"],"names":["traverse","generate","normalizeFile","normalizeOpts","loadBlockHoistPlugin","PluginPass","getConfig","consumeIterator","getTraversalParams","file","pluginPairs","passPairs","passes","visitors","plugin","concat","pass","key","options","push","visitor","invokePluginPre","pre","call","invokePluginPost","post","transformAstPass","parentSpan","merge","opts","wrapPluginVisitorMethod","traceChild","traceFn","ast","scope","transformAst","babelConfig","transform","source","inputSourceMap","loaderOptions","filename","target","getConfigSpan","stop","normalizeSpan","transformSpan","generateSpan","code","map","generatorOpts"],"mappings":"AAAA;;CAEC,GAED,OAAOA,cAAc,oCAAmC;AACxD,OAAOC,cAAc,qCAAoC;AACzD,OAAOC,mBAAmB,mDAAkD;AAC5E,OAAOC,mBAAmB,mDAAkD;AAC5E,OAAOC,0BAA0B,uDAAsD;AACvF,OAAOC,gBAAgB,gDAA+C;AAEtE,OAAOC,eAAe,eAAc;AACpC,SAASC,eAAe,QAAQ,SAAQ;AAIxC,SAASC,mBAAmBC,IAAS,EAAEC,WAAkB;IACvD,MAAMC,YAAY,EAAE;IACpB,MAAMC,SAAS,EAAE;IACjB,MAAMC,WAA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AEA,eAAe,SAASU,UAEtBC,MAAc,EACdC,cAAyC,EACzCC,aAAkB,EAClBC,QAAgB,EAChBC,MAAc,EACdf,UAAgB;IAEhB,MAAMgB,gBAAgBhB,WAAWI,UAAU,CAAC;IAC5C,MAAMK,cAAc9B,UAAUiB,IAAI,CAAC,IAAI,EAAE;QACvCe;QACAE;QACAD;QACAG;QACAD;IACF;IACAE,cAAcC,IAAI;IAElB,MAAMC,gBAAgBlB,WAAWI,UAAU,CAAC;IAC5C,MAAMtB,OAAOF,gBACXL,cAAckC,YAAYxB,MAAM,EAAET,cAAciC,cAAcE;IAEhEO,cAAcD,IAAI;IAElB,MAAME,gBAAgBnB,WAAWI,UAAU,CAAC;IAC5CI,aAAa1B,MAAM2B,aAAaU;IAChCA,cAAcF,IAAI;IAElB,MAAMG,eAAepB,WAAWI,UAAU,CAAC;IAC3C,MAAM,EAAEiB,IAAI,EAAEC,GAAG,EAAE,GAAGhD,SAASQ,KAAKwB,GAAG,EAAExB,KAAKoB,IAAI,CAACqB,aAAa,EAAEzC,KAAKuC,IAAI;IAC3ED,aAAaH,IAAI;IAEjB,OAAO;QAAEI;QAAMC;IAAI;AACrB"}

View File

@@ -0,0 +1,20 @@
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { Span } from '../../../trace'
export interface NextJsLoaderContext extends webpack.LoaderContext<{}> {
currentTraceSpan: Span
target: string
}
export interface NextBabelLoaderOptions {
hasJsxRuntime: boolean
hasReactRefresh: boolean
isServer: boolean
development: boolean
pagesDir: string
sourceMaps?: any[]
overrides: any
caller: any
configFile: string | undefined
cwd: string
}

10
node_modules/next/dist/esm/build/babel/loader/util.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
export function consumeIterator(iter) {
while(true){
const { value, done } = iter.next();
if (done) {
return value;
}
}
}
//# sourceMappingURL=util.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/babel/loader/util.ts"],"names":["consumeIterator","iter","value","done","next"],"mappings":"AAAA,OAAO,SAASA,gBAAgBC,IAAmB;IACjD,MAAO,KAAM;QACX,MAAM,EAAEC,KAAK,EAAEC,IAAI,EAAE,GAAGF,KAAKG,IAAI;QACjC,IAAID,MAAM;YACR,OAAOD;QACT;IACF;AACF"}

View File

@@ -0,0 +1,26 @@
export default function AmpAttributePatcher() {
return {
visitor: {
JSXOpeningElement (path) {
const openingElement = path.node;
const { name, attributes } = openingElement;
if (!(name && name.type === "JSXIdentifier")) {
return;
}
if (!name.name.startsWith("amp-")) {
return;
}
for (const attribute of attributes){
if (attribute.type !== "JSXAttribute") {
continue;
}
if (attribute.name.name === "className") {
attribute.name.name = "class";
}
}
}
}
};
}
//# sourceMappingURL=amp-attributes.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/babel/plugins/amp-attributes.ts"],"names":["AmpAttributePatcher","visitor","JSXOpeningElement","path","openingElement","node","name","attributes","type","startsWith","attribute"],"mappings":"AAEA,eAAe,SAASA;IACtB,OAAO;QACLC,SAAS;YACPC,mBAAkBC,IAAuC;gBACvD,MAAMC,iBAAiBD,KAAKE,IAAI;gBAEhC,MAAM,EAAEC,IAAI,EAAEC,UAAU,EAAE,GAAGH;gBAC7B,IAAI,CAAEE,CAAAA,QAAQA,KAAKE,IAAI,KAAK,eAAc,GAAI;oBAC5C;gBACF;gBAEA,IAAI,CAACF,KAAKA,IAAI,CAACG,UAAU,CAAC,SAAS;oBACjC;gBACF;gBAEA,KAAK,MAAMC,aAAaH,WAAY;oBAClC,IAAIG,UAAUF,IAAI,KAAK,gBAAgB;wBACrC;oBACF;oBAEA,IAAIE,UAAUJ,IAAI,CAACA,IAAI,KAAK,aAAa;wBACvCI,UAAUJ,IAAI,CAACA,IAAI,GAAG;oBACxB;gBACF;YACF;QACF;IACF;AACF"}

View File

@@ -0,0 +1,27 @@
import commonjsPlugin from "next/dist/compiled/babel/plugin-transform-modules-commonjs";
// Handle module.exports in user code
export default function CommonJSModulePlugin(...args) {
const commonjs = commonjsPlugin(...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 @@
{"version":3,"sources":["../../../../src/build/babel/plugins/commonjs.ts"],"names":["commonjsPlugin","CommonJSModulePlugin","args","commonjs","visitor","Program","exit","path","state","foundModuleExports","traverse","MemberExpression","expressionPath","node","object","name","property","call"],"mappings":"AACA,OAAOA,oBAAoB,6DAA4D;AAEvF,qCAAqC;AACrC,eAAe,SAASC,qBAAqB,GAAGC,IAAS;IACvD,MAAMC,WAAWH,kBAAkBE;IACnC,OAAO;QACLE,SAAS;YACPC,SAAS;gBACPC,MAAKC,IAA6B,EAAEC,KAAK;oBACvC,IAAIC,qBAAqB;oBACzBF,KAAKG,QAAQ,CAAC;wBACZC,kBAAiBC,cAAmB;4BAClC,IAAIA,eAAeC,IAAI,CAACC,MAAM,CAACC,IAAI,KAAK,UAAU;4BAClD,IAAIH,eAAeC,IAAI,CAACG,QAAQ,CAACD,IAAI,KAAK,WAAW;4BACrDN,qBAAqB;wBACvB;oBACF;oBAEA,IAAI,CAACA,oBAAoB;wBACvB;oBACF;oBAEAN,SAASC,OAAO,CAACC,OAAO,CAACC,IAAI,CAACW,IAAI,CAAC,IAAI,EAAEV,MAAMC;gBACjD;YACF;QACF;IACF;AACF"}

View File

@@ -0,0 +1,59 @@
import jsx from "next/dist/compiled/babel/plugin-syntax-jsx";
export default function({ types: t }) {
return {
inherits: jsx,
visitor: {
JSXElement (_path, state) {
state.set("jsx", true);
},
// Fragment syntax is still JSX since it compiles to createElement(),
// but JSXFragment is not a JSXElement
JSXFragment (_path, state) {
state.set("jsx", true);
},
Program: {
exit (path, state) {
if (state.get("jsx")) {
const pragma = t.identifier(state.opts.pragma);
let importAs = pragma;
// if there's already a React in scope, use that instead of adding an import
const existingBinding = state.opts.reuseImport !== false && state.opts.importAs && path.scope.getBinding(state.opts.importAs);
// var _jsx = _pragma.createElement;
if (state.opts.property) {
if (state.opts.importAs) {
importAs = t.identifier(state.opts.importAs);
} else {
importAs = path.scope.generateUidIdentifier("pragma");
}
const mapping = t.variableDeclaration("var", [
t.variableDeclarator(pragma, t.memberExpression(importAs, t.identifier(state.opts.property)))
]);
// if the React binding came from a require('react'),
// make sure that our usage comes after it.
let newPath;
if (existingBinding && t.isVariableDeclarator(existingBinding.path.node) && t.isCallExpression(existingBinding.path.node.init) && t.isIdentifier(existingBinding.path.node.init.callee) && existingBinding.path.node.init.callee.name === "require") {
[newPath] = existingBinding.path.parentPath.insertAfter(mapping);
} else {
[newPath] = path.unshiftContainer("body", mapping);
}
for (const declar of newPath.get("declarations")){
path.scope.registerBinding(newPath.node.kind, declar);
}
}
if (!existingBinding) {
const importSpecifier = t.importDeclaration([
state.opts.import ? t.importSpecifier(importAs, t.identifier(state.opts.import)) : state.opts.importNamespace ? t.importNamespaceSpecifier(importAs) : t.importDefaultSpecifier(importAs)
], t.stringLiteral(state.opts.module || "react"));
const [newPath] = path.unshiftContainer("body", importSpecifier);
for (const specifier of newPath.get("specifiers")){
path.scope.registerBinding("module", specifier);
}
}
}
}
}
}
};
}
//# sourceMappingURL=jsx-pragma.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/babel/plugins/jsx-pragma.ts"],"names":["jsx","types","t","inherits","visitor","JSXElement","_path","state","set","JSXFragment","Program","exit","path","get","pragma","identifier","opts","importAs","existingBinding","reuseImport","scope","getBinding","property","generateUidIdentifier","mapping","variableDeclaration","variableDeclarator","memberExpression","newPath","isVariableDeclarator","node","isCallExpression","init","isIdentifier","callee","name","parentPath","insertAfter","unshiftContainer","declar","registerBinding","kind","importSpecifier","importDeclaration","import","importNamespace","importNamespaceSpecifier","importDefaultSpecifier","stringLiteral","module","specifier"],"m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AACkB,IAAI,CAACE,IAAI,KACjD9B,EAAE+B,YAAY,CAACf,gBAAgBN,IAAI,CAACkB,IAAI,CAACE,IAAI,CAACE,MAAM,KACpDhB,gBAAgBN,IAAI,CAACkB,IAAI,CAACE,IAAI,CAACE,MAAM,CAACC,IAAI,KAAK,WAC/C;gCACC,CAACP,QAAQ,GACRV,gBAAgBN,IAAI,CAACwB,UAAU,CAACC,WAAW,CAACb;4BAChD,OAAO;gCACJ,CAACI,QAAQ,GAAGhB,KAAK0B,gBAAgB,CAAC,QAAQd;4BAC7C;4BAEA,KAAK,MAAMe,UAAUX,QAAQf,GAAG,CAAC,gBAAiB;gCAChDD,KAAKQ,KAAK,CAACoB,eAAe,CACxBZ,QAAQE,IAAI,CAACW,IAAI,EACjBF;4BAEJ;wBACF;wBAEA,IAAI,CAACrB,iBAAiB;4BACpB,MAAMwB,kBAAkBxC,EAAEyC,iBAAiB,CACzC;gCACEpC,MAAMS,IAAI,CAAC4B,MAAM,GAEb1C,EAAEwC,eAAe,CACfzB,UACAf,EAAEa,UAAU,CAACR,MAAMS,IAAI,CAAC4B,MAAM,KAEhCrC,MAAMS,IAAI,CAAC6B,eAAe,GAC1B3C,EAAE4C,wBAAwB,CAAC7B,YAE3Bf,EAAE6C,sBAAsB,CAAC9B;6BAC9B,EACDf,EAAE8C,aAAa,CAACzC,MAAMS,IAAI,CAACiC,MAAM,IAAI;4BAGvC,MAAM,CAACrB,QAAQ,GAAGhB,KAAK0B,gBAAgB,CAAC,QAAQI;4BAChD,KAAK,MAAMQ,aAAatB,QAAQf,GAAG,CAAC,cAAe;gCACjDD,KAAKQ,KAAK,CAACoB,eAAe,CACxB,UACAU;4BAEJ;wBACF;oBACF;gBACF;YACF;QACF;IACF;AACF"}

View File

@@ -0,0 +1,22 @@
export default 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 @@
{"version":3,"sources":["../../../../src/build/babel/plugins/next-font-unsupported.ts"],"names":["NextPageDisallowReExportAllExports","visitor","ImportDeclaration","path","includes","node","source","value","err","SyntaxError","code","loc","start","end"],"mappings":"AAEA,eAAe,SAASA;IACtB,OAAO;QACLC,SAAS;YACPC,mBAAkBC,IAAuC;gBACvD,IACE;oBACE;oBACA;oBACA;oBACA;iBACD,CAACC,QAAQ,CAACD,KAAKE,IAAI,CAACC,MAAM,CAACC,KAAK,GACjC;wBAMEJ,gBAAwBA;oBAL1B,MAAMK,MAAM,IAAIC,YACd,CAAC,yKAAyK,CAAC;oBAE3KD,IAAYE,IAAI,GAAG;oBACnBF,IAAYG,GAAG,GACfR,EAAAA,iBAAAA,KAAKE,IAAI,CAACM,GAAG,qBAAbR,eAAeS,KAAK,OAAIT,kBAAAA,KAAKE,IAAI,CAACM,GAAG,qBAAbR,gBAAeU,GAAG,KAAIV,KAAKE,IAAI,CAACM,GAAG;oBAC7D,MAAMH;gBACR;YACF;QACF;IACF;AACF"}

View File

@@ -0,0 +1,106 @@
import { types as BabelTypes } from "next/dist/compiled/babel/core";
import { STRING_LITERAL_DROP_BUNDLE } from "../../../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(STRING_LITERAL_DROP_BUNDLE), t.stringLiteral(`${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`;
}
// config to parsing pageConfig for client bundles
export default function nextPageConfig({ types: t }) {
return {
visitor: {
Program: {
enter (path, state) {
path.traverse({
ExportDeclaration (exportPath, exportState) {
var _exportPath_node_specifiers;
if (BabelTypes.isExportNamedDeclaration(exportPath) && ((_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;
})) && BabelTypes.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 (BabelTypes.isStringLiteral(exportPath.node.source)) {
throw new Error(errorMessage(exportState, `Expected object but got import`));
// import hello from 'world'
// export { hello as config }
} else if (BabelTypes.isIdentifier(specifier.local)) {
var _exportPath_scope_getBinding1;
if (BabelTypes.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 (!BabelTypes.isIdentifier(declaration.id, {
name: CONFIG_KEY
})) {
continue;
}
let { init } = declaration;
if (BabelTypes.isTSAsExpression(init)) {
init = init.expression;
}
if (!BabelTypes.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 (BabelTypes.isSpreadElement(prop)) {
throw new Error(errorMessage(exportState, `Property spread is not allowed`));
}
const { name } = prop.key;
if (BabelTypes.isIdentifier(prop.key, {
name: "amp"
})) {
if (!BabelTypes.isObjectProperty(prop)) {
throw new Error(errorMessage(exportState, `Invalid property "${name}"`));
}
if (!BabelTypes.isBooleanLiteral(prop.value) && !BabelTypes.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 @@
{"version":3,"sources":["../../../../src/build/babel/plugins/next-page-config.ts"],"names":["types","BabelTypes","STRING_LITERAL_DROP_BUNDLE","CONFIG_KEY","replaceBundle","path","t","parentPath","replaceWith","program","variableDeclaration","variableDeclarator","identifier","stringLiteral","Date","now","errorMessage","state","details","pageName","filename","split","cwd","pop","nextPageConfig","visitor","Program","enter","traverse","ExportDeclaration","exportPath","exportState","isExportNamedDeclaration","node","specifiers","some","specifier","isIdentifier","exported","name","value","isStringLiteral","source","Error","ExportNamedDeclaration","bundleDropped","declaration","length","config","declarations","scope","getBinding","filter","Boolean","local","isImportSpecifier","id","init","isTSAsExpression","expression","isObjectExpression","got","type","prop","properties","isSpreadElement","key","isObjectProperty","isBooleanLiteral","amp","file","opts","caller","isDev"],"mappings":"AAA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C,uBAAwByC,MAAM,CAACC,KAAK,GAAE;oCACzC,uDAAuD;oCACvD,wDAAwD;oCACxDrE,cAAc0B,YAAYxB;gCAC5B;gCACAyB,YAAYc,aAAa,GAAG;gCAC5B;4BACF;wBACF;oBACF,GACA5B;gBAEJ;YACF;QACF;IACF;AACF"}

View File

@@ -0,0 +1,15 @@
export default 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 @@
{"version":3,"sources":["../../../../src/build/babel/plugins/next-page-disallow-re-export-all-exports.ts"],"names":["NextPageDisallowReExportAllExports","visitor","ExportAllDeclaration","path","err","SyntaxError","code","loc","node","start","end"],"mappings":"AAEA,eAAe,SAASA;IACtB,OAAO;QACLC,SAAS;YACPC,sBAAqBC,IAA0C;oBAO3DA,gBAAwBA;gBAN1B,MAAMC,MAAM,IAAIC,YACd,CAAC,8GAA8G,CAAC,GAC9G,CAAC,8DAA8D,CAAC;gBAElED,IAAYE,IAAI,GAAG;gBACnBF,IAAYG,GAAG,GACfJ,EAAAA,iBAAAA,KAAKK,IAAI,CAACD,GAAG,qBAAbJ,eAAeM,KAAK,OAAIN,kBAAAA,KAAKK,IAAI,CAACD,GAAG,qBAAbJ,gBAAeO,GAAG,KAAIP,KAAKK,IAAI,CAACD,GAAG;gBAC7D,MAAMH;YACR;QACF;IACF;AACF"}

View File

@@ -0,0 +1,298 @@
import { SERVER_PROPS_SSG_CONFLICT } from "../../../lib/constants";
import { SERVER_PROPS_ID, STATIC_PROPS_ID } from "../../../shared/lib/constants";
export const EXPORT_NAME_GET_STATIC_PROPS = "getStaticProps";
export const EXPORT_NAME_GET_STATIC_PATHS = "getStaticPaths";
export 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 ? STATIC_PROPS_ID : 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(SERVER_PROPS_SSG_CONFLICT);
}
state.isServerProps = true;
} else {
if (state.isServerProps) {
throw new Error(SERVER_PROPS_SSG_CONFLICT);
}
state.isPrerender = true;
}
return true;
}
return false;
};
export default 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) || t.isVariableDeclarator(sweepPath.parentPath)) {
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

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,49 @@
// matches any hook-like (the default)
const isHook = /^use[A-Z]/;
// matches only built-in hooks provided by React et al
const isBuiltInHook = /^use(Callback|Context|DebugValue|Effect|ImperativeHandle|LayoutEffect|Memo|Reducer|Ref|State)$/;
export default function({ types: t }) {
const visitor = {
CallExpression (path, state) {
const onlyBuiltIns = state.opts.onlyBuiltIns;
// if specified, options.lib is a list of libraries that provide hook functions
const libs = state.opts.lib && (state.opts.lib === true ? [
"react",
"preact/hooks"
] : [].concat(state.opts.lib));
// skip function calls that are not the init of a variable declaration:
if (!t.isVariableDeclarator(path.parent)) return;
// skip function calls where the return value is not Array-destructured:
if (!t.isArrayPattern(path.parent.id)) return;
// name of the (hook) function being called:
const hookName = path.node.callee.name;
if (libs) {
const binding = path.scope.getBinding(hookName);
// not an import
if (!binding || binding.kind !== "module") return;
const specifier = binding.path.parent.source.value;
// not a match
if (!libs.some((lib)=>lib === specifier)) return;
}
// only match function calls with names that look like a hook
if (!(onlyBuiltIns ? isBuiltInHook : isHook).test(hookName)) return;
path.parent.id = t.objectPattern(path.parent.id.elements.reduce((patterns, element, i)=>{
if (element === null) {
return patterns;
}
return patterns.concat(t.objectProperty(t.numericLiteral(i), element));
}, []));
}
};
return {
name: "optimize-hook-destructuring",
visitor: {
// this is a workaround to run before preset-env destroys destructured assignments
Program (path, state) {
path.traverse(visitor, state);
}
}
};
}
//# sourceMappingURL=optimize-hook-destructuring.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/babel/plugins/optimize-hook-destructuring.ts"],"names":["isHook","isBuiltInHook","types","t","visitor","CallExpression","path","state","onlyBuiltIns","opts","libs","lib","concat","isVariableDeclarator","parent","isArrayPattern","id","hookName","node","callee","name","binding","scope","getBinding","kind","specifier","source","value","some","test","objectPattern","elements","reduce","patterns","element","i","objectProperty","numericLiteral","Program","traverse"],"mappings":"AAMA,sCAAsC;AACtC,MAAMA,SAAS;AAEf,sDAAsD;AACtD,MAAMC,gBACJ;AAEF,eAAe,SAAU,EACvBC,OAAOC,CAAC,EAGT;IACC,MAAMC,UAAU;QACdC,gBAAeC,IAAyC,EAAEC,KAAU;YAClE,MAAMC,eAAeD,MAAME,IAAI,CAACD,YAAY;YAE5C,+EAA+E;YAC/E,MAAME,OACJH,MAAME,IAAI,CAACE,GAAG,IACbJ,CAAAA,MAAME,IAAI,CAACE,GAAG,KAAK,OAChB;gBAAC;gBAAS;aAAe,GACzB,EAAE,CAACC,MAAM,CAACL,MAAME,IAAI,CAACE,GAAG,CAAA;YAE9B,uEAAuE;YACvE,IAAI,CAACR,EAAEU,oBAAoB,CAACP,KAAKQ,MAAM,GAAG;YAE1C,wEAAwE;YACxE,IAAI,CAACX,EAAEY,cAAc,CAACT,KAAKQ,MAAM,CAACE,EAAE,GAAG;YAEvC,4CAA4C;YAC5C,MAAMC,WAAW,AAACX,KAAKY,IAAI,CAACC,MAAM,CAA2BC,IAAI;YAEjE,IAAIV,MAAM;gBACR,MAAMW,UAAUf,KAAKgB,KAAK,CAACC,UAAU,CAACN;gBACtC,gBAAgB;gBAChB,IAAI,CAACI,WAAWA,QAAQG,IAAI,KAAK,UAAU;gBAE3C,MAAMC,YAAY,AAACJ,QAAQf,IAAI,CAACQ,MAAM,CACnCY,MAAM,CAACC,KAAK;gBACf,cAAc;gBACd,IAAI,CAACjB,KAAKkB,IAAI,CAAC,CAACjB,MAAaA,QAAQc,YAAY;YACnD;YAEA,6DAA6D;YAC7D,IAAI,CAAC,AAACjB,CAAAA,eAAeP,gBAAgBD,MAAK,EAAG6B,IAAI,CAACZ,WAAW;YAE7DX,KAAKQ,MAAM,CAACE,EAAE,GAAGb,EAAE2B,aAAa,CAC9BxB,KAAKQ,MAAM,CAACE,EAAE,CAACe,QAAQ,CAACC,MAAM,CAC5B,CAACC,UAAUC,SAASC;gBAClB,IAAID,YAAY,MAAM;oBACpB,OAAOD;gBACT;gBAEA,OAAOA,SAASrB,MAAM,CACpBT,EAAEiC,cAAc,CAACjC,EAAEkC,cAAc,CAACF,IAAID;YAE1C,GACA,EAAE;QAGR;IACF;IAEA,OAAO;QACLd,MAAM;QACNhB,SAAS;YACP,kFAAkF;YAClFkC,SAAQhC,IAAI,EAAEC,KAAK;gBACjBD,KAAKiC,QAAQ,CAACnC,SAASG;YACzB;QACF;IACF;AACF"}

View File

@@ -0,0 +1,140 @@
/**
COPYRIGHT (c) 2017-present James Kyle <me@thejameskyle.com>
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR
*/ // This file is https://github.com/jamiebuilds/react-loadable/blob/master/src/babel.js
// Modified to also look for `next/dynamic`
// Modified to put `webpack` and `modules` under `loadableGenerated` to be backwards compatible with next/dynamic which has a `modules` key
// Modified to support `dynamic(import('something'))` and `dynamic(import('something'), options)
import { relative as relativePath } from "path";
export default function({ types: t }) {
return {
visitor: {
ImportDeclaration (path, state) {
let source = path.node.source.value;
if (source !== "next/dynamic") return;
let defaultSpecifier = path.get("specifiers").find((specifier)=>{
return specifier.isImportDefaultSpecifier();
});
if (!defaultSpecifier) return;
const bindingName = defaultSpecifier.node.local.name;
const binding = path.scope.getBinding(bindingName);
if (!binding) {
return;
}
binding.referencePaths.forEach((refPath)=>{
var _state_file_opts_caller, _state_file_opts_caller1;
let callExpression = refPath.parentPath;
if (callExpression.isMemberExpression() && callExpression.node.computed === false) {
const property = callExpression.get("property");
if (!Array.isArray(property) && property.isIdentifier({
name: "Map"
})) {
callExpression = callExpression.parentPath;
}
}
if (!callExpression.isCallExpression()) return;
const callExpression_ = callExpression;
let args = callExpression_.get("arguments");
if (args.length > 2) {
throw callExpression_.buildCodeFrameError("next/dynamic only accepts 2 arguments");
}
if (!args[0]) {
return;
}
let loader;
let options;
if (args[0].isObjectExpression()) {
options = args[0];
} else {
if (!args[1]) {
callExpression_.node.arguments.push(t.objectExpression([]));
}
// This is needed as the code is modified above
args = callExpression_.get("arguments");
loader = args[0];
options = args[1];
}
if (!options.isObjectExpression()) return;
const options_ = options;
let properties = options_.get("properties");
let propertiesMap = {};
properties.forEach((property)=>{
const key = property.get("key");
propertiesMap[key.node.name] = property;
});
if (propertiesMap.loadableGenerated) {
return;
}
if (propertiesMap.loader) {
loader = propertiesMap.loader.get("value");
}
if (propertiesMap.modules) {
loader = propertiesMap.modules.get("value");
}
if (!loader || Array.isArray(loader)) {
return;
}
const dynamicImports = [];
const dynamicKeys = [];
if (propertiesMap.ssr) {
const ssr = propertiesMap.ssr.get("value");
const nodePath = Array.isArray(ssr) ? undefined : ssr;
if (nodePath) {
var _state_file_opts_caller2;
const nonSSR = nodePath.node.type === "BooleanLiteral" && nodePath.node.value === false;
// If `ssr` is set to `false`, erase the loader for server side
if (nonSSR && loader && ((_state_file_opts_caller2 = state.file.opts.caller) == null ? void 0 : _state_file_opts_caller2.isServer)) {
loader.replaceWith(t.arrowFunctionExpression([], t.nullLiteral(), true));
}
}
}
loader.traverse({
Import (importPath) {
var _state_file_opts_caller;
const importArguments = importPath.parentPath.get("arguments");
if (!Array.isArray(importArguments)) return;
const node = importArguments[0].node;
dynamicImports.push(node);
dynamicKeys.push(t.binaryExpression("+", t.stringLiteral((((_state_file_opts_caller = state.file.opts.caller) == null ? void 0 : _state_file_opts_caller.pagesDir) ? relativePath(state.file.opts.caller.pagesDir, state.file.opts.filename) : state.file.opts.filename) + " -> "), node));
}
});
if (!dynamicImports.length) return;
options.node.properties.push(t.objectProperty(t.identifier("loadableGenerated"), t.objectExpression(((_state_file_opts_caller = state.file.opts.caller) == null ? void 0 : _state_file_opts_caller.isDev) || ((_state_file_opts_caller1 = state.file.opts.caller) == null ? void 0 : _state_file_opts_caller1.isServer) ? [
t.objectProperty(t.identifier("modules"), t.arrayExpression(dynamicKeys))
] : [
t.objectProperty(t.identifier("webpack"), t.arrowFunctionExpression([], t.arrayExpression(dynamicImports.map((dynamicImport)=>{
return t.callExpression(t.memberExpression(t.identifier("require"), t.identifier("resolveWeak")), [
dynamicImport
]);
}))))
])));
// Turns `dynamic(import('something'))` into `dynamic(() => import('something'))` for backwards compat.
// This is the replicate the behavior in versions below Next.js 7 where we magically handled not executing the `import()` too.
// We'll deprecate this behavior and provide a codemod for it in 7.1.
if (loader.isCallExpression()) {
const arrowFunction = t.arrowFunctionExpression([], loader.node);
loader.replaceWith(arrowFunction);
}
});
}
}
};
}
//# sourceMappingURL=react-loadable-plugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/babel/plugins/react-loadable-plugin.ts"],"names":["relative","relativePath","types","t","visitor","ImportDeclaration","path","state","source","node","value","defaultSpecifier","get","find","specifier","isImportDefaultSpecifier","bindingName","local","name","binding","scope","getBinding","referencePaths","forEach","refPath","callExpression","parentPath","isMemberExpression","computed","property","Array","isArray","isIdentifier","isCallExpression","callExpression_","args","length","buildCodeFrameError","loader","options","isObjectExpression","arguments","push","objectExpression","options_","properties","propertiesMap","key","loadableGenerated","modules","dynamicImports","dynamicKeys","ssr","nodePath","undefined","nonSSR","type","file","opts","caller","isServer","replaceWith","arrowFunctionExpression","nullLiteral","traverse","Import","importPath","importArguments","binaryExpression","stringLiteral","pagesDir","filename","objectProperty","identifier","isDev","arrayExpression","map","dynamicImport","memberExpression","arrowFunction"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;AAmBA,GACA,sFAAsF;AACtF,2CAA2C;AAC3C,2IAA2I;AAC3I,gGAAgG;AAQhG,SAASA,YAAYC,YAAY,QAAQ,OAAM;AAE/C,eAAe,SAAU,EACvBC,OAAOC,CAAC,EAGT;IACC,OAAO;QACLC,SAAS;YACPC,mBACEC,IAA4C,EAC5CC,KAAU;gBAEV,IAAIC,SAASF,KAAKG,IAAI,CAACD,MAAM,CAACE,KAAK;gBACnC,IAAIF,WAAW,gBAAgB;gBAE/B,IAAIG,mBAAmBL,KAAKM,GAAG,CAAC,cAAcC,IAAI,CAAC,CAACC;oBAClD,OAAOA,U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iBAEf;gCAACI;6BAAc;wBAEnB;qBAIP;oBAKX,uGAAuG;oBACvG,8HAA8H;oBAC9H,qEAAqE;oBACrE,IAAIvC,OAAOL,gBAAgB,IAAI;wBAC7B,MAAM8C,gBAAgB5E,EAAE2D,uBAAuB,CAAC,EAAE,EAAExB,OAAO7B,IAAI;wBAC/D6B,OAAOuB,WAAW,CAACkB;oBACrB;gBACF;YACF;QACF;IACF;AACF"}

152
node_modules/next/dist/esm/build/babel/preset.js generated vendored Normal file
View File

@@ -0,0 +1,152 @@
import { dirname } from "path";
const isLoadIntentTest = process.env.NODE_ENV === "test";
const isLoadIntentDevelopment = process.env.NODE_ENV === "development";
// Resolve styled-jsx plugins
function styledJsxOptions(options) {
options = options || {};
options.styleModule = "styled-jsx/style";
if (!Array.isArray(options.plugins)) {
return options;
}
options.plugins = options.plugins.map((plugin)=>{
if (Array.isArray(plugin)) {
const [name, pluginOptions] = plugin;
return [
require.resolve(name),
pluginOptions
];
}
return require.resolve(plugin);
});
return options;
}
// Taken from https://github.com/babel/babel/commit/d60c5e1736543a6eac4b549553e107a9ba967051#diff-b4beead8ad9195361b4537601cc22532R158
function supportsStaticESM(caller) {
return !!(caller == null ? void 0 : caller.supportsStaticESM);
}
export default ((api, options = {})=>{
var _options_presetreact, _options_presetreact1;
const supportsESM = api.caller(supportsStaticESM);
const isServer = api.caller((caller)=>!!caller && caller.isServer);
const isCallerDevelopment = api.caller((caller)=>caller == null ? void 0 : caller.isDev);
// Look at external intent if used without a caller (e.g. via Jest):
const isTest = isCallerDevelopment == null && isLoadIntentTest;
// Look at external intent if used without a caller (e.g. Storybook):
const isDevelopment = isCallerDevelopment === true || isCallerDevelopment == null && isLoadIntentDevelopment;
// Default to production mode if not `test` nor `development`:
const isProduction = !(isTest || isDevelopment);
const isBabelLoader = api.caller((caller)=>!!caller && (caller.name === "babel-loader" || caller.name === "next-babel-turbo-loader"));
const useJsxRuntime = ((_options_presetreact = options["preset-react"]) == null ? void 0 : _options_presetreact.runtime) === "automatic" || Boolean(api.caller((caller)=>!!caller && caller.hasJsxRuntime)) && ((_options_presetreact1 = options["preset-react"]) == null ? void 0 : _options_presetreact1.runtime) !== "classic";
const presetEnvConfig = {
// In the test environment `modules` is often needed to be set to true, babel figures that out by itself using the `'auto'` option
// In production/development this option is set to `false` so that webpack can handle import/export with tree-shaking
modules: "auto",
exclude: [
"transform-typeof-symbol"
],
...options["preset-env"]
};
// When transpiling for the server or tests, target the current Node version
// if not explicitly specified:
if ((isServer || isTest) && (!presetEnvConfig.targets || !(typeof presetEnvConfig.targets === "object" && "node" in presetEnvConfig.targets))) {
presetEnvConfig.targets = {
// Targets the current process' version of Node. This requires apps be
// built and deployed on the same version of Node.
// This is the same as using "current" but explicit
node: process.versions.node
};
}
return {
sourceType: "unambiguous",
presets: [
[
require("next/dist/compiled/babel/preset-env"),
presetEnvConfig
],
[
require("next/dist/compiled/babel/preset-react"),
{
// This adds @babel/plugin-transform-react-jsx-source and
// @babel/plugin-transform-react-jsx-self automatically in development
development: isDevelopment || isTest,
...useJsxRuntime ? {
runtime: "automatic"
} : {
pragma: "__jsx"
},
...options["preset-react"]
}
],
[
require("next/dist/compiled/babel/preset-typescript"),
{
allowNamespaces: true,
...options["preset-typescript"]
}
]
],
plugins: [
!useJsxRuntime && [
require("./plugins/jsx-pragma"),
{
// This produces the following injected import for modules containing JSX:
// import React from 'react';
// var __jsx = React.createElement;
module: "react",
importAs: "React",
pragma: "__jsx",
property: "createElement"
}
],
[
require("./plugins/optimize-hook-destructuring"),
{
// only optimize hook functions imported from React/Preact
lib: true
}
],
require("next/dist/compiled/babel/plugin-syntax-dynamic-import"),
require("next/dist/compiled/babel/plugin-syntax-import-assertions"),
require("./plugins/react-loadable-plugin"),
[
require("next/dist/compiled/babel/plugin-proposal-class-properties"),
options["class-properties"] || {}
],
[
require("next/dist/compiled/babel/plugin-proposal-object-rest-spread"),
{
useBuiltIns: true
}
],
!isServer && [
require("next/dist/compiled/babel/plugin-transform-runtime"),
{
corejs: false,
helpers: true,
regenerator: true,
useESModules: supportsESM && presetEnvConfig.modules !== "commonjs",
absoluteRuntime: isBabelLoader ? dirname(require.resolve("next/dist/compiled/@babel/runtime/package.json")) : undefined,
...options["transform-runtime"]
}
],
[
isTest && options["styled-jsx"] && options["styled-jsx"]["babel-test"] ? require("styled-jsx/babel-test") : require("styled-jsx/babel"),
styledJsxOptions(options["styled-jsx"])
],
require("./plugins/amp-attributes"),
isProduction && [
require("next/dist/compiled/babel/plugin-transform-react-remove-prop-types"),
{
removeImport: true
}
],
isServer && require("next/dist/compiled/babel/plugin-syntax-bigint"),
// Always compile numeric separator because the resulting number is
// smaller.
require("next/dist/compiled/babel/plugin-proposal-numeric-separator"),
require("next/dist/compiled/babel/plugin-proposal-export-namespace-from")
].filter(Boolean)
};
});
//# sourceMappingURL=preset.js.map

1
node_modules/next/dist/esm/build/babel/preset.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/babel/preset.ts"],"names":["dirname","isLoadIntentTest","process","env","NODE_ENV","isLoadIntentDevelopment","styledJsxOptions","options","styleModule","Array","isArray","plugins","map","plugin","name","pluginOptions","require","resolve","supportsStaticESM","caller","api","supportsESM","isServer","isCallerDevelopment","isDev","isTest","isDevelopment","isProduction","isBabelLoader","useJsxRuntime","runtime","Boolean","hasJsxRuntime","presetEnvConfig","modules","exclude","targets","node","versions","sourceType","presets","development","pragma","allowNamespaces","module","importAs","property","lib","useBuiltIns","corejs","helpers","regenerator","useESModules","absoluteRuntime","undefined","removeImport","filter"],"mappings":"AACA,SAASA,OAAO,QAAQ,OAAM;AAE9B,MAAMC,mBAAmBC,QAAQC,GAAG,CAACC,QAAQ,KAAK;AAClD,MAAMC,0BAA0BH,QAAQC,GAAG,CAACC,QAAQ,KAAK;AAWzD,6BAA6B;AAC7B,SAASE,iBAAiBC,OAA8B;IACtDA,UAAUA,WAAW,CAAC;IACtBA,QAAQC,WAAW,GAAG;IAEtB,IAAI,CAACC,MAA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BACf;aACD;YACD,CAAC1B,YAAY;gBACXN,QAAQ;gBACR;oBACEiC,QAAQ;oBACRC,SAAS;oBACTC,aAAa;oBACbC,cAAc/B,eAAeY,gBAAgBC,OAAO,KAAK;oBACzDmB,iBAAiBzB,gBACb5B,QACEgB,QAAQC,OAAO,CACb,qDAGJqC;oBACJ,GAAG/C,OAAO,CAAC,oBAAoB;gBACjC;aACD;YACD;gBACEkB,UAAUlB,OAAO,CAAC,aAAa,IAAIA,OAAO,CAAC,aAAa,CAAC,aAAa,GAClES,QAAQ,2BACRA,QAAQ;gBACZV,iBAAiBC,OAAO,CAAC,aAAa;aACvC;YACDS,QAAQ;YACRW,gBAAgB;gBACdX,QAAQ;gBACR;oBACEuC,cAAc;gBAChB;aACD;YACDjC,YAAYN,QAAQ;YACpB,mEAAmE;YACnE,WAAW;YACXA,QAAQ;YACRA,QAAQ;SACT,CAACwC,MAAM,CAACzB;IACX;AACF,CAAA,EAAC"}

35
node_modules/next/dist/esm/build/build-context.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
// 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 = {};
export function resumePluginState(resumedState) {
Object.assign(pluginState, resumedState);
}
// This method gives you the plugin state with typed and mutable value fields
// behind a proxy so we can lazily initialize the values **after** resuming the
// plugin state.
export 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;
}
});
}
export function getPluginState() {
return pluginState;
}
// a global object to store context for the current build
// this is used to pass data between different steps of the build without having
// to pass it through function arguments.
// Not exhaustive, but should be extended to as needed whilst refactoring
export const NextBuildContext = {};
//# sourceMappingURL=build-context.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/build/build-context.ts"],"names":["pluginState","resumePluginState","resumedState","Object","assign","getProxiedPluginState","initialState","Proxy","get","target","key","set","value","getPluginState","NextBuildContext"],"mappings":"AAUA,4EAA4E;AAC5E,4EAA4E;AAC5E,+DAA+D;AAC/D,+CAA+C;AAC/C,IAAIA,cAAmC,CAAC;AACxC,OAAO,SAASC,kBAAkBC,YAAkC;IAClEC,OAAOC,MAAM,CAACJ,aAAaE;AAC7B;AAEA,6EAA6E;AAC7E,+EAA+E;AAC/E,gBAAgB;AAChB,OAAO,SAASG,sBACdC,YAAmB;IAEnB,OAAO,IAAIC,MAAMP,aAAa;QAC5BQ,KAAIC,MAAM,EAAEC,GAAW;YACrB,IAAI,OAAOD,MAAM,CAACC,IAAI,KAAK,aAAa;gBACtC,OAAQD,MAAM,CAACC,IAAI,GAAGJ,YAAY,CAACI,IAAI;YACzC;YACA,OAAOD,MAAM,CAACC,IAAI;QACpB;QACAC,KAAIF,MAAM,EAAEC,GAAW,EAAEE,KAAK;YAC5BH,MAAM,CAACC,IAAI,GAAGE;YACd,OAAO;QACT;IACF;AACF;AAEA,OAAO,SAASC;IACd,OAAOb;AACT;AAEA,yDAAyD;AACzD,gFAAgF;AAChF,yCAAyC;AACzC,yEAAyE;AACzE,OAAO,MAAMc,mBA0DR,CAAC,EAAC"}

69
node_modules/next/dist/esm/build/compiler.js generated vendored Normal file
View File

@@ -0,0 +1,69 @@
import { webpack } from "next/dist/compiled/webpack/webpack";
function generateStats(result, stat) {
const { errors, warnings } = stat.toJson({
preset: "errors-warnings",
moduleTrace: true
});
if (errors && errors.length > 0) {
result.errors.push(...errors);
}
if (warnings && warnings.length > 0) {
result.warnings.push(...warnings);
}
return result;
}
// Webpack 5 requires the compiler to be closed (to save caches)
// Webpack 4 does not have this close method so in order to be backwards compatible we check if it exists
function closeCompiler(compiler) {
return new Promise((resolve, reject)=>{
// @ts-ignore Close only exists on the compiler in webpack 5
return compiler.close((err)=>err ? reject(err) : resolve());
});
}
export function runCompiler(config, { runWebpackSpan, inputFileSystem }) {
return new Promise((resolve, reject)=>{
const compiler = webpack(config);
// Ensure we use the previous inputFileSystem
if (inputFileSystem) {
compiler.inputFileSystem = inputFileSystem;
}
compiler.fsStartTime = Date.now();
compiler.run((err, stats)=>{
const webpackCloseSpan = runWebpackSpan.traceChild("webpack-close", {
name: config.name
});
webpackCloseSpan.traceAsyncFn(()=>closeCompiler(compiler)).then(()=>{
if (err) {
const reason = err.stack ?? err.toString();
if (reason) {
return resolve([
{
errors: [
{
message: reason,
details: err.details
}
],
warnings: [],
stats
},
compiler.inputFileSystem
]);
}
return reject(err);
} else if (!stats) throw new Error("No Stats from webpack");
const result = webpackCloseSpan.traceChild("webpack-generate-error-stats").traceFn(()=>generateStats({
errors: [],
warnings: [],
stats
}, stats));
return resolve([
result,
compiler.inputFileSystem
]);
});
});
});
}
//# sourceMappingURL=compiler.js.map

1
node_modules/next/dist/esm/build/compiler.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/build/compiler.ts"],"names":["webpack","generateStats","result","stat","errors","warnings","toJson","preset","moduleTrace","length","push","closeCompiler","compiler","Promise","resolve","reject","close","err","runCompiler","config","runWebpackSpan","inputFileSystem","fsStartTime","Date","now","run","stats","webpackCloseSpan","traceChild","name","traceAsyncFn","then","reason","stack","toString","message","details","Error","traceFn"],"mappings":"AAAA,SAASA,OAAO,QAAQ,qCAAoC;AAS5D,SAASC,cACPC,MAAsB,EACtBC,IAAmB;IAEnB,MAAM,EAAEC,MAAM,EAAEC,QAAQ,EAAE,GAAGF,KAAKG,MAAM,CAAC;QACvCC,QAAQ;QACRC,aAAa;IACf;IACA,IAAIJ,UAAUA,OAAOK,MAAM,GAAG,GAAG;QAC/BP,OAAOE,MAAM,CAACM,IAAI,IAAIN;IACxB;IAEA,IAAIC,YAAYA,SAASI,MAAM,GAAG,GAAG;QACnCP,OAAOG,QAAQ,CAACK,IAAI,IAAIL;IAC1B;IAEA,OAAOH;AACT;AAEA,gEAAgE;AAChE,yGAAyG;AACzG,SAASS,cAAcC,QAAkD;IACvE,OAAO,IAAIC,QAAc,CAACC,SAASC;QACjC,4DAA4D;QAC5D,OAAOH,SAASI,KAAK,CAAC,CAACC,MAAcA,MAAMF,OAAOE,OAAOH;IAC3D;AACF;AAEA,OAAO,SAASI,YACdC,MAA6B,EAC7B,EACEC,cAAc,EACdC,eAAe,EACiC;IAElD,OAAO,IAAIR,QAAQ,CAACC,SAASC;QAC3B,MAAMH,WAAWZ,QAAQmB;QACzB,6CAA6C;QAC7C,IAAIE,iBAAiB;YACnBT,SAASS,eAAe,GAAGA;QAC7B;QACAT,SAASU,WAAW,GAAGC,KAAKC,GAAG;QAC/BZ,SAASa,GAAG,CAAC,CAACR,KAAKS;YACjB,MAAMC,mBAAmBP,eAAeQ,UAAU,CAAC,iBAAiB;gBAClEC,MAAMV,OAAOU,IAAI;YACnB;YACAF,iBACGG,YAAY,CAAC,IAAMnB,cAAcC,WACjCmB,IAAI,CAAC;gBACJ,IAAId,KAAK;oBACP,MAAMe,SAASf,IAAIgB,KAAK,IAAIhB,IAAIiB,QAAQ;oBACxC,IAAIF,QAAQ;wBACV,OAAOlB,QAAQ;4BACb;gCACEV,QAAQ;oCAAC;wCAAE+B,SAASH;wCAAQI,SAAS,AAACnB,IAAYmB,OAAO;oCAAC;iCAAE;gCAC5D/B,UAAU,EAAE;gCACZqB;4BACF;4BACAd,SAASS,eAAe;yBACzB;oBACH;oBACA,OAAON,OAAOE;gBAChB,OAAO,IAAI,CAACS,OAAO,MAAM,IAAIW,MAAM;gBAEnC,MAAMnC,SAASyB,iBACZC,UAAU,CAAC,gCACXU,OAAO,CAAC,IACPrC,cAAc;wBAAEG,QAAQ,EAAE;wBAAEC,UAAU,EAAE;wBAAEqB;oBAAM,GAAGA;gBAEvD,OAAOZ,QAAQ;oBAACZ;oBAAQU,SAASS,eAAe;iBAAC;YACnD;QACJ;IACF;AACF"}

536
node_modules/next/dist/esm/build/entries.js generated vendored Normal file
View File

@@ -0,0 +1,536 @@
import chalk from "next/dist/compiled/chalk";
import { posix, join, dirname, extname } from "path";
import { stringify } from "querystring";
import { PAGES_DIR_ALIAS, ROOT_DIR_ALIAS, APP_DIR_ALIAS, WEBPACK_LAYERS, INSTRUMENTATION_HOOK_FILENAME } from "../lib/constants";
import { isAPIRoute } from "../lib/is-api-route";
import { isEdgeRuntime } from "../lib/is-edge-runtime";
import { APP_CLIENT_INTERNALS, RSC_MODULE_TYPES } from "../shared/lib/constants";
import { CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, CLIENT_STATIC_FILES_RUNTIME_POLYFILLS, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, COMPILER_NAMES, EDGE_RUNTIME_WEBPACK } from "../shared/lib/constants";
import { warn } from "./output/log";
import { isMiddlewareFile, isMiddlewareFilename, isInstrumentationHookFile } from "./utils";
import { getPageStaticInfo } from "./analysis/get-page-static-info";
import { normalizePathSep } from "../shared/lib/page-path/normalize-path-sep";
import { normalizePagePath } from "../shared/lib/page-path/normalize-page-path";
import { normalizeAppPath } from "../shared/lib/router/utils/app-paths";
import { encodeMatchers } from "./webpack/loaders/next-middleware-loader";
import { isAppRouteRoute } from "../lib/is-app-route-route";
import { normalizeMetadataRoute } from "../lib/metadata/get-metadata-route";
import { fileExists } from "../lib/file-exists";
import { getRouteLoaderEntry } from "./webpack/loaders/next-route-loader";
import { isInternalComponent, isNonRoutePagesPage } from "../lib/is-internal-component";
import { isStaticMetadataRouteFile } from "../lib/metadata/is-metadata-route";
import { RouteKind } from "../server/future/route-kind";
import { encodeToBase64 } from "./webpack/loaders/utils";
export 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 = extname(a);
const bExt = 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;
};
}
export async function getStaticInfoIncludingLayouts({ isInsideAppDir, pageExtensions, pageFilePath, appDir, config, isDev, page }) {
const pageStaticInfo = await getPageStaticInfo({
nextConfig: config,
pageFilePath,
isDev,
page,
pageType: isInsideAppDir ? "app" : "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 = dirname(pageFilePath);
// Uses startsWith to not include directories further up.
while(dir.startsWith(appDir)){
for (const potentialLayoutFile of potentialLayoutFiles){
const layoutFile = join(dir, potentialLayoutFile);
if (!await fileExists(layoutFile)) {
continue;
}
layoutFiles.unshift(layoutFile);
}
// Walk up the directory tree
dir = join(dir, "..");
}
for (const layoutFile of layoutFiles){
const layoutStaticInfo = await getPageStaticInfo({
nextConfig: config,
pageFilePath: layoutFile,
isDev,
page,
pageType: isInsideAppDir ? "app" : "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 (isStaticMetadataRouteFile(relativePath)) {
delete staticInfo.runtime;
delete staticInfo.preferredRegion;
}
}
return staticInfo;
}
/**
* For a given page path removes the provided extensions.
*/ export function getPageFromPath(pagePath, pageExtensions) {
let page = normalizePathSep(pagePath.replace(new RegExp(`\\.+(${pageExtensions.join("|")})$`), ""));
page = page.replace(/\/index$/, "");
return page === "" ? "/" : page;
}
export function getPageFilePath({ absolutePagePath, pagesDir, appDir, rootDir }) {
if (absolutePagePath.startsWith(PAGES_DIR_ALIAS) && pagesDir) {
return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir);
}
if (absolutePagePath.startsWith(APP_DIR_ALIAS) && appDir) {
return absolutePagePath.replace(APP_DIR_ALIAS, appDir);
}
if (absolutePagePath.startsWith(ROOT_DIR_ALIAS)) {
return absolutePagePath.replace(ROOT_DIR_ALIAS, rootDir);
}
return require.resolve(absolutePagePath);
}
export function createPagesMapping({ isDev, pageExtensions, pagePaths, pagesType, pagesDir }) {
const isAppRoute = pagesType === "app";
const previousPages = {};
const pages = pagePaths.reduce((result, pagePath)=>{
// Do not process .d.ts files inside the `pages` folder
if (pagePath.endsWith(".d.ts") && pageExtensions.includes("ts")) {
return result;
}
let pageKey = getPageFromPath(pagePath, pageExtensions);
if (isAppRoute) {
pageKey = pageKey.replace(/%5F/g, "_");
pageKey = pageKey.replace(/^\/not-found$/g, "/_not-found");
}
if (pageKey in result) {
warn(`Duplicate page detected. ${chalk.cyan(join("pages", previousPages[pageKey]))} and ${chalk.cyan(join("pages", pagePath))} both resolve to ${chalk.cyan(pageKey)}.`);
} else {
previousPages[pageKey] = pagePath;
}
const normalizedPath = normalizePathSep(join(pagesType === "pages" ? PAGES_DIR_ALIAS : pagesType === "app" ? APP_DIR_ALIAS : ROOT_DIR_ALIAS, pagePath));
const route = pagesType === "app" ? normalizeMetadataRoute(pageKey) : pageKey;
result[route] = normalizedPath;
return result;
}, {});
if (pagesType === "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 && {
"/_not-found": "next/dist/client/components/not-found-error"
},
...pages
};
} else if (pagesType === "root") {
return 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 ? PAGES_DIR_ALIAS : "next/dist/pages";
return {
"/_app": `${root}/_app`,
"/_error": `${root}/_error`,
"/_document": `${root}/_document`,
...pages
};
}
export function getEdgeServerEntry(opts) {
var _opts_config_experimental_sri;
if (opts.pagesType === "app" && 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?${stringify(loaderParams)}!`,
layer: WEBPACK_LAYERS.reactServerComponents
};
}
if (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) ? encodeMatchers(opts.middleware.matchers) : "",
preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(JSON.stringify(opts.middlewareConfig || {})).toString("base64")
};
return `next-middleware-loader?${stringify(loaderParams)}!`;
}
if (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?${stringify(loaderParams)}!`;
}
if (isInstrumentationHookFile(opts.page)) {
return {
import: opts.absolutePagePath,
filename: `edge-${INSTRUMENTATION_HOOK_FILENAME}.js`
};
}
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),
incrementalCacheHandlerPath: opts.config.experimental.incrementalCacheHandlerPath,
preferredRegion: opts.preferredRegion,
middlewareConfig: Buffer.from(JSON.stringify(opts.middlewareConfig || {})).toString("base64"),
serverActionsBodySizeLimit: opts.config.experimental.serverActionsBodySizeLimit
};
return {
import: `next-edge-ssr-loader?${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 ? WEBPACK_LAYERS.serverSideRendering : undefined
};
}
export function getAppEntry(opts) {
return {
import: `next-app-loader?${stringify(opts)}!`,
layer: WEBPACK_LAYERS.reactServerComponents
};
}
export function getClientEntry(opts) {
const loaderOptions = {
absolutePagePath: opts.absolutePagePath,
page: opts.page
};
const pageLoader = `next-client-pages-loader?${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;
}
export function runDependingOnPageType(params) {
if (params.pageType === "root" && isInstrumentationHookFile(params.page)) {
params.onServer();
params.onEdgeServer();
return;
}
if (isMiddlewareFile(params.page)) {
params.onEdgeServer();
return;
}
if (isAPIRoute(params.page)) {
if (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 (isEdgeRuntime(params.pageRuntime)) {
params.onClient();
params.onEdgeServer();
return;
}
params.onClient();
params.onServer();
return;
}
export 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 = 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(APP_DIR_ALIAS, ""));
}
// 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 = normalizePagePath(page);
const clientBundlePath = posix.join(pagesType, bundleFile);
const serverBundlePath = pagesType === "pages" ? posix.join("pages", bundleFile) : pagesType === "app" ? 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(APP_DIR_ALIAS) || absolutePagePath.startsWith(appDir));
const staticInfo = await getStaticInfoIncludingLayouts({
isInsideAppDir,
pageExtensions,
pageFilePath,
appDir,
config,
isDev,
page
});
const isServerComponent = isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client;
if (isMiddlewareFile(page)) {
var _staticInfo_middleware;
middlewareMatchers = ((_staticInfo_middleware = staticInfo.middleware) == null ? void 0 : _staticInfo_middleware.matchers) ?? [
{
regexp: ".*",
originalSource: "/:path*"
}
];
}
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[normalizeAppPath(page)];
server[serverBundlePath] = getAppEntry({
page,
name: serverBundlePath,
pagePath: absolutePagePath,
appDir,
appPaths: matchedAppPaths,
pageExtensions,
basePath: config.basePath,
assetPrefix: config.assetPrefix,
nextConfigOutput: config.output,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: encodeToBase64(staticInfo.middleware || {})
});
} else if (isInstrumentationHookFile(page) && pagesType === "root") {
server[serverBundlePath.replace("src/", "")] = {
import: absolutePagePath,
// the '../' is needed to make sure the file is not chunked
filename: `../${INSTRUMENTATION_HOOK_FILENAME}.js`
};
} else if (isAPIRoute(page)) {
server[serverBundlePath] = [
getRouteLoaderEntry({
kind: RouteKind.PAGES_API,
page,
absolutePagePath,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: staticInfo.middleware || {}
})
];
} else if (!isMiddlewareFile(page) && !isInternalComponent(absolutePagePath) && !isNonRoutePagesPage(page)) {
server[serverBundlePath] = [
getRouteLoaderEntry({
kind: RouteKind.PAGES,
page,
pages,
absolutePagePath,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: staticInfo.middleware ?? {}
})
];
} else {
server[serverBundlePath] = [
absolutePagePath
];
}
},
onEdgeServer: ()=>{
let appDirLoader = "";
if (pagesType === "app") {
const matchedAppPaths = appPathsPerRoute[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;
}
const normalizedServerBundlePath = isInstrumentationHookFile(page) && pagesType === "root" ? serverBundlePath.replace("src/", "") : serverBundlePath;
edgeServer[normalizedServerBundlePath] = 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, "app");
promises.push(Promise.all(Object.keys(appPaths).map(entryHandler)));
}
if (rootPaths) {
promises.push(Promise.all(Object.keys(rootPaths).map(getEntryHandler(rootPaths, "root"))));
}
promises.push(Promise.all(Object.keys(pages).map(getEntryHandler(pages, "pages"))));
await Promise.all(promises);
return {
client,
server,
edgeServer,
middlewareMatchers
};
}
export function finalizeEntrypoint({ name, compilerType, value, isServerComponent, hasAppDir }) {
const entry = typeof value !== "object" || Array.isArray(value) ? {
import: value
} : value;
const isApi = name.startsWith("pages/api/");
switch(compilerType){
case COMPILER_NAMES.server:
{
return {
publicPath: isApi ? "" : undefined,
runtime: isApi ? "webpack-api-runtime" : "webpack-runtime",
layer: isApi ? WEBPACK_LAYERS.api : isServerComponent ? WEBPACK_LAYERS.reactServerComponents : undefined,
...entry
};
}
case COMPILER_NAMES.edgeServer:
{
return {
layer: isMiddlewareFilename(name) || isApi ? WEBPACK_LAYERS.middleware : undefined,
library: {
name: [
"_ENTRIES",
`middleware_[name]`
],
type: "assign"
},
runtime: EDGE_RUNTIME_WEBPACK,
asyncChunks: false,
...entry
};
}
case COMPILER_NAMES.client:
{
const isAppLayer = hasAppDir && (name === CLIENT_STATIC_FILES_RUNTIME_MAIN_APP || name === APP_CLIENT_INTERNALS || name.startsWith("app/"));
if (// Client special cases
name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS && name !== CLIENT_STATIC_FILES_RUNTIME_MAIN && name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP && name !== CLIENT_STATIC_FILES_RUNTIME_AMP && name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH) {
if (isAppLayer) {
return {
dependOn: CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
layer: WEBPACK_LAYERS.appPagesBrowser,
...entry
};
}
return {
dependOn: name.startsWith("pages/") && name !== "pages/_app" ? "pages/_app" : CLIENT_STATIC_FILES_RUNTIME_MAIN,
...entry
};
}
if (isAppLayer) {
return {
layer: WEBPACK_LAYERS.appPagesBrowser,
...entry
};
}
return entry;
}
default:
{
// Should never happen.
throw new Error("Invalid compiler type");
}
}
}
//# sourceMappingURL=entries.js.map

1
node_modules/next/dist/esm/build/entries.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

17
node_modules/next/dist/esm/build/generate-build-id.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
export async function generateBuildId(generate, fallback) {
let buildId = await generate();
// If there's no buildId defined we'll fall back
if (buildId === null) {
// We also create a new buildId if it contains the word `ad` to avoid false
// positives with ad blockers
while(!buildId || /ad/i.test(buildId)){
buildId = fallback();
}
}
if (typeof buildId !== "string") {
throw new Error("generateBuildId did not return a string. https://nextjs.org/docs/messages/generatebuildid-not-a-string");
}
return buildId.trim();
}
//# sourceMappingURL=generate-build-id.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/build/generate-build-id.ts"],"names":["generateBuildId","generate","fallback","buildId","test","Error","trim"],"mappings":"AAAA,OAAO,eAAeA,gBACpBC,QAAsD,EACtDC,QAAsB;IAEtB,IAAIC,UAAU,MAAMF;IACpB,gDAAgD;IAChD,IAAIE,YAAY,MAAM;QACpB,2EAA2E;QAC3E,6BAA6B;QAC7B,MAAO,CAACA,WAAW,MAAMC,IAAI,CAACD,SAAU;YACtCA,UAAUD;QACZ;IACF;IAEA,IAAI,OAAOC,YAAY,UAAU;QAC/B,MAAM,IAAIE,MACR;IAEJ;IAEA,OAAOF,QAAQG,IAAI;AACrB"}

View File

@@ -0,0 +1,25 @@
import { fileExists } from "../lib/file-exists";
import { join } from "path";
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"
];
export async function getBabelConfigFile(dir) {
for (const filename of BABEL_CONFIG_FILES){
const configFilePath = join(dir, filename);
const exists = await fileExists(configFilePath);
if (!exists) {
continue;
}
return configFilePath;
}
}
//# sourceMappingURL=get-babel-config-file.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/build/get-babel-config-file.ts"],"names":["fileExists","join","BABEL_CONFIG_FILES","getBabelConfigFile","dir","filename","configFilePath","exists"],"mappings":"AAAA,SAASA,UAAU,QAAQ,qBAAoB;AAC/C,SAASC,IAAI,QAAQ,OAAM;AAE3B,MAAMC,qBAAqB;IACzB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,OAAO,eAAeC,mBACpBC,GAAW;IAEX,KAAK,MAAMC,YAAYH,mBAAoB;QACzC,MAAMI,iBAAiBL,KAAKG,KAAKC;QACjC,MAAME,SAAS,MAAMP,WAAWM;QAChC,IAAI,CAACC,QAAQ;YACX;QACF;QACA,OAAOD;IACT;AACF"}

2075
node_modules/next/dist/esm/build/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/next/dist/esm/build/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

11
node_modules/next/dist/esm/build/is-writeable.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
import fs from "fs";
export async function isWriteable(directory) {
try {
await fs.promises.access(directory, (fs.constants || fs).W_OK);
return true;
} catch (err) {
return false;
}
}
//# sourceMappingURL=is-writeable.js.map

1
node_modules/next/dist/esm/build/is-writeable.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/build/is-writeable.ts"],"names":["fs","isWriteable","directory","promises","access","constants","W_OK","err"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AAEnB,OAAO,eAAeC,YAAYC,SAAiB;IACjD,IAAI;QACF,MAAMF,GAAGG,QAAQ,CAACC,MAAM,CAACF,WAAW,AAACF,CAAAA,GAAGK,SAAS,IAAIL,EAAC,EAAGM,IAAI;QAC7D,OAAO;IACT,EAAE,OAAOC,KAAK;QACZ,OAAO;IACT;AACF"}

97
node_modules/next/dist/esm/build/load-entrypoint.js generated vendored Normal file
View File

@@ -0,0 +1,97 @@
import fs from "fs/promises";
import path from "path";
// NOTE: this should be updated if this loader file is moved.
const PACKAGE_ROOT = path.normalize(path.join(__dirname, "../../.."));
const TEMPLATE_FOLDER = path.join(__dirname, "templates");
const TEMPLATES_ESM_FOLDER = path.normalize(path.join(__dirname, "../../dist/esm/build/templates"));
/**
* Load the entrypoint file from the ESM directory and performs string
* replacements of the template variables specified in the `replacements`
* argument.
*
* For non-string replacements, the template should use the
* `declare const ${key}: ${type}` syntax. to ensure that the type is correct
* and the typescript can compile. You may have to use `@ts-expect-error` to
* handle replacement values that are related to imports.
*
* @param entrypoint the entrypoint to load
* @param replacements the replacements to perform
* @returns the loaded file with the replacements
*/ export async function loadEntrypoint(entrypoint, replacements, injections) {
const filepath = path.resolve(path.join(TEMPLATES_ESM_FOLDER, `${entrypoint}.js`));
let file = await fs.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.relative(PACKAGE_ROOT, path.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`);
}
return file;
}
//# sourceMappingURL=load-entrypoint.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/build/load-entrypoint.ts"],"names":["fs","path","PACKAGE_ROOT","normalize","join","__dirname","TEMPLATE_FOLDER","TEMPLATES_ESM_FOLDER","loadEntrypoint","entrypoint","replacements","injections","filepath","resolve","file","readFile","count","replaceAll","_","fromRequest","importRequest","relative","replace","startsWith","Error","JSON","stringify","replaced","Set","RegExp","Object","keys","map","k","match","key","parse","add","matches","size","length","difference","filter","has","injected"],"mappings":"AAAA,OAAOA,QAAQ,cAAa;AAC5B,OAAOC,UAAU,OAAM;AAEvB,6DAA6D;AAC7D,MAAMC,eAAeD,KAAKE,SAAS,CAACF,KAAKG,IAAI,CAACC,WAAW;AACzD,MAAMC,kBAAkBL,KAAKG,IAAI,CAACC,WAAW;AAC7C,MAAME,uBAAuBN,KAAKE,SAAS,CACzCF,KAAKG,IAAI,CAACC,WAAW;AAGvB;;;;;;;;;;;;;CAaC,GAED,OAAO,eAAeG,eACpBC,UAA4D,EAC5DC,YAA6C,EAC7CC,UAAmC;IAEnC,MAAMC,WAAWX,KAAKY,OAAO,CAC3BZ,KAAKG,IAAI,CAACG,sBAAsB,CAAC,EAAEE,WAAW,GAAG,CAAC;IAGpD,IAAIK,OAAO,MAAMd,GAAGe,QAAQ,CAACH,UAAU;IAEvC,4EAA4E;IAC5E,4DAA4D;IAC5D,IAAII,QAAQ;IACZF,OAAOA,KAAKG,UAAU,CACpB,sCACA,SAAUC,CAAC,EAAEC,WAAW,EAAEC,aAAa;QACrCJ;QAEA,MAAMK,WAAWpB,KACdoB,QAAQ,CACPnB,cACAD,KAAKY,OAAO,CAACP,iBAAiBa,eAAeC,eAE/C,2DAA2D;SAC1DE,OAAO,CAAC,OAAO;QAElB,0EAA0E;QAC1E,uEAAuE;QACvE,oCAAoC;QACpC,IAAI,CAACD,SAASE,UAAU,CAAC,UAAU;YACjC,MAAM,IAAIC,MACR,CAAC,kEAAkE,EAAEH,SAAS,CAAC,CAAC;QAEpF;QAEA,OAAOF,cACH,C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AMwC,WAAW,IAAIhB;IACrB,IAAIjB,YAAY;QACd,iEAAiE;QACjEG,OAAOA,KAAKG,UAAU,CACpB,IAAIY,OAAO,CAAC,WAAW,EAAEC,OAAOC,IAAI,CAACpB,YAAYP,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,MAC/D,CAACc,GAAGiB;YACF,IAAI,CAAEA,CAAAA,OAAOxB,UAAS,GAAI;gBACxB,MAAM,IAAIa,MAAM,CAAC,gCAAgC,EAAEW,IAAI,CAAC;YAC1D;YAEAS,SAASP,GAAG,CAACF;YAEb,OAAO,CAAC,MAAM,EAAEA,IAAI,GAAG,EAAExB,UAAU,CAACwB,IAAI,CAAC,CAAC;QAC5C;IAEJ;IAEA,oDAAoD;IACpDG,UAAUxB,KAAKoB,KAAK,CAAC;IACrB,IAAII,SAAS;QACX,MAAM,IAAId,MACR,CAAC,oDAAoD,EAAEc,QAAQlC,IAAI,CACjE,MACA,CAAC;IAEP;IAEA,2DAA2D;IAC3D,IAAIwC,SAASL,IAAI,KAAKT,OAAOC,IAAI,CAACpB,cAAc,CAAC,GAAG6B,MAAM,EAAE;QAC1D,uEAAuE;QACvE,2EAA2E;QAC3E,8BAA8B;QAC9B,MAAMC,aAAaX,OAAOC,IAAI,CAACpB,cAAc,CAAC,GAAG+B,MAAM,CACrD,CAACP,MAAQ,CAACS,SAASD,GAAG,CAACR;QAGzB,MAAM,IAAIX,MACR,CAAC,sDAAsD,EAAEiB,WAAWrC,IAAI,CACtE,MACA,YAAY,CAAC;IAEnB;IAEA,OAAOU;AACT"}

83
node_modules/next/dist/esm/build/load-jsconfig.js generated vendored Normal file
View File

@@ -0,0 +1,83 @@
import path from "path";
import { fileExists } from "../lib/file-exists";
import * as Log from "./output/log";
import { getTypeScriptConfiguration } from "../lib/typescript/getTypeScriptConfiguration";
import { readFileSync } from "fs";
import isError from "../lib/is-error";
import { hasNecessaryDependencies } from "../lib/has-necessary-dependencies";
let TSCONFIG_WARNED = false;
function parseJsonFile(filePath) {
const JSON5 = require("next/dist/compiled/json5");
const contents = readFileSync(filePath, "utf8");
// Special case an empty file
if (contents.trim() === "") {
return {};
}
try {
return JSON5.parse(contents);
} catch (err) {
if (!isError(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}`);
}
}
export default async function loadJsConfig(dir, config) {
let typeScriptPath;
try {
const deps = await hasNecessaryDependencies(dir, [
{
pkg: "typescript",
file: "typescript/lib/typescript.js",
exportsRestrict: true
}
]);
typeScriptPath = deps.resolved.get("typescript");
} catch {}
const tsConfigPath = path.join(dir, config.typescript.tsconfigPath);
const useTypeScript = Boolean(typeScriptPath && await fileExists(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 getTypeScriptConfiguration(ts, tsConfigPath, true);
jsConfig = {
compilerOptions: tsConfig.options
};
implicitBaseurl = path.dirname(tsConfigPath);
}
const jsConfigPath = path.join(dir, "jsconfig.json");
if (!useTypeScript && await fileExists(jsConfigPath)) {
jsConfig = parseJsonFile(jsConfigPath);
implicitBaseurl = path.dirname(jsConfigPath);
}
let resolvedBaseUrl;
if (jsConfig) {
var _jsConfig_compilerOptions;
if ((_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.baseUrl) {
resolvedBaseUrl = path.resolve(dir, jsConfig.compilerOptions.baseUrl);
} else {
resolvedBaseUrl = implicitBaseurl;
}
}
return {
useTypeScript,
jsConfig,
resolvedBaseUrl
};
}
//# sourceMappingURL=load-jsconfig.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/build/load-jsconfig.ts"],"names":["path","fileExists","Log","getTypeScriptConfiguration","readFileSync","isError","hasNecessaryDependencies","TSCONFIG_WARNED","parseJsonFile","filePath","JSON5","require","contents","trim","parse","err","codeFrameColumns","codeFrame","String","start","line","lineNumber","column","columnNumber","message","highlightCode","Error","loadJsConfig","dir","config","typeScriptPath","deps","pkg","file","exportsRestrict","resolved","get","tsConfigPath","join","typescript","tsconfigPath","useTypeScript","Boolean","implicitBaseurl","jsConfig","info","ts","Promise","resolve","tsConfig","compilerOptions","options","dirname","jsConfigPath","resolvedBaseUrl","baseUrl"],"mappings":"AAAA,OAAOA,UAAU,OAAM;AACvB,SAASC,UAAU,QAAQ,qBAAoB;AAE/C,YAAYC,SAAS,eAAc;AACnC,SAASC,0BAA0B,QAAQ,+CAA8C;AACzF,SAASC,YAAY,QAAQ,KAAI;AACjC,OAAOC,aAAa,kBAAiB;AACrC,SAASC,wBAAwB,QAAQ,oCAAmC;AAE5E,IAAIC,kBAAkB;AAEtB,SAASC,cAAcC,QAAgB;IACrC,MAAMC,QAAQC,QAAQ;IACtB,MAAMC,WAAWR,aAAaK,UAAU;IAExC,6BAA6B;IAC7B,IAAIG,SAASC,IAAI,OAAO,IAAI;QAC1B,OAAO,CAAC;IACV;IAEA,IAAI;QACF,OAAOH,MAAMI,KAAK,CAACF;IACrB,EAAE,OAAOG,KAAK;QACZ,IAAI,CAACV,QAAQU,MAAM,MAAMA;QACzB,MAAM,EAAEC,gBAAgB,EAAE,GAAGL,QAAQ;QACrC,MAAMM,YAAYD,iBAChBE,OAAON,WACP;YACEO,OAAO;gBACLC,MAAM,AAACL,IAAwCM,UAAU,IAAI;gBAC7DC,QAAQ,AAACP,IAA0CQ,YAAY,IAAI;YACrE;QACF,GACA;YAAEC,SAAST,IAAIS,OAAO;YAAEC,eAAe;QAAK;QAE9C,MAAM,IAAIC,MAAM,CAAC,iBAAiB,EAAEjB,SAAS,IAAI,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ACF;IAEA,OAAO;QACLF;QACAG;QACAU;IACF;AACF"}

250
node_modules/next/dist/esm/build/output/index.js generated vendored Normal file
View File

@@ -0,0 +1,250 @@
import chalk from "next/dist/compiled/chalk";
import stripAnsi from "next/dist/compiled/strip-ansi";
import textTable from "next/dist/compiled/text-table";
import createStore from "next/dist/compiled/unistore";
import formatWebpackMessages from "../../client/dev/error-overlay/format-webpack-messages";
import { store as consoleStore } from "./store";
import { COMPILER_NAMES } from "../../shared/lib/constants";
export function startedDevelopmentServer(appUrl, bindAddr) {
consoleStore.setState({
appUrl,
bindAddr
});
}
export function formatAmpMessages(amp) {
let output = chalk.bold("Amp Validation") + "\n\n";
let messages = [];
const chalkError = chalk.red("error");
function ampError(page, error) {
messages.push([
page,
chalkError,
error.message,
error.specUrl || ""
]);
}
const chalkWarn = chalk.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 += textTable(messages, {
align: [
"l",
"l",
"l",
"l"
],
stringLength (str) {
return stripAnsi(str).length;
}
});
return output;
}
const buildStore = createStore({
// @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 } = state;
const { appUrl } = consoleStore.getState();
if (client.loading || server.loading || (edgeServer == null ? void 0 : edgeServer.loading)) {
consoleStore.setState({
bootstrap: false,
appUrl: appUrl,
// If it takes more than 3 seconds to compile, mark it as loading status
loading: true,
trigger
}, 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
consoleStore.setState({
...partialState,
errors: client.errors,
warnings: null
}, true);
} else if (server.errors && serverWasLoading) {
consoleStore.setState({
...partialState,
errors: server.errors,
warnings: null
}, true);
} else if (edgeServer.errors && edgeServerWasLoading) {
consoleStore.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) || []);
consoleStore.setState({
...partialState,
errors: null,
warnings: warnings.length === 0 ? null : warnings
}, true);
}
});
export 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), {})
});
}
export function watchCompilers(client, server, edgeServer) {
buildStore.setState({
client: {
loading: true
},
server: {
loading: true
},
edgeServer: {
loading: true
},
trigger: "initial"
});
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 } = formatWebpackMessages(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(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
});
} else {
buildStore.setState({
client: status
});
}
});
tapCompiler(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
});
} else {
buildStore.setState({
server: status
});
}
});
tapCompiler(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
});
} else {
buildStore.setState({
edgeServer: status
});
}
});
}
export function reportTrigger(trigger) {
buildStore.setState({
trigger
});
}
//# sourceMappingURL=index.js.map

1
node_modules/next/dist/esm/build/output/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

61
node_modules/next/dist/esm/build/output/log.js generated vendored Normal file
View File

@@ -0,0 +1,61 @@
import chalk from "../../lib/chalk";
export const prefixes = {
wait: chalk.white(chalk.bold("○")),
error: chalk.red(chalk.bold("X")),
warn: chalk.yellow(chalk.bold("⚠")),
ready: chalk.bold("▲"),
info: chalk.white(chalk.bold(" ")),
event: chalk.green(chalk.bold("✓")),
trace: chalk.magenta(chalk.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);
}
}
export function bootstrap(...message) {
console.log(" ", ...message);
}
export function wait(...message) {
prefixedLog("wait", ...message);
}
export function error(...message) {
prefixedLog("error", ...message);
}
export function warn(...message) {
prefixedLog("warn", ...message);
}
export function ready(...message) {
prefixedLog("ready", ...message);
}
export function info(...message) {
prefixedLog("info", ...message);
}
export function event(...message) {
prefixedLog("event", ...message);
}
export function trace(...message) {
prefixedLog("trace", ...message);
}
const warnOnceMessages = new Set();
export function warnOnce(...message) {
if (!warnOnceMessages.has(message[0])) {
warnOnceMessages.add(message.join(" "));
warn(...message);
}
}
//# sourceMappingURL=log.js.map

1
node_modules/next/dist/esm/build/output/log.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/output/log.ts"],"names":["chalk","prefixes","wait","white","bold","error","red","warn","yellow","ready","info","event","green","trace","magenta","LOGGING_METHOD","log","prefixedLog","prefixType","message","undefined","length","shift","consoleMethod","prefix","console","bootstrap","warnOnceMessages","Set","warnOnce","has","add","join"],"mappings":"AAAA,OAAOA,WAAW,kBAAiB;AAEnC,OAAO,MAAMC,WAAW;IACtBC,MAAMF,MAAMG,KAAK,CAACH,MAAMI,IAAI,CAAC;IAC7BC,OAAOL,MAAMM,GAAG,CAACN,MAAMI,IAAI,CAAC;IAC5BG,MAAMP,MAAMQ,MAAM,CAACR,MAAMI,IAAI,CAAC;IAC9BK,OAAOT,MAAMI,IAAI,CAAC;IAClBM,MAAMV,MAAMG,KAAK,CAACH,MAAMI,IAAI,CAAC;IAC7BO,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,IAAI,CAACQ,iBAAiBG,GAAG,CAACX,OAAO,CAAC,EAAE,GAAG;QACrCQ,iBAAiBI,GAAG,CAACZ,QAAQa,IAAI,CAAC;QAElCzB,QAAQY;IACV;AACF"}

118
node_modules/next/dist/esm/build/output/store.js generated vendored Normal file
View File

@@ -0,0 +1,118 @@
import createStore from "next/dist/compiled/unistore";
import stripAnsi from "next/dist/compiled/strip-ansi";
import { flushAllTraces } from "../../trace";
import { teardownCrashReporter, teardownHeapProfiler, teardownTraceSubscriber } from "../swc";
import * as Log from "./log";
const MAX_DURATION = 3 * 1000;
export const store = createStore({
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 loadingLogTimer = null;
store.subscribe((state)=>{
if (!hasStoreChanged(state)) {
return;
}
if (state.bootstrap) {
return;
}
if (state.loading) {
if (state.trigger) {
trigger = state.trigger;
if (trigger !== "initial") {
if (!loadingLogTimer) {
// Only log compiling if compiled is not finished in 3 seconds
loadingLogTimer = setTimeout(()=>{
Log.wait(`compiling ${trigger} ...`);
}, MAX_DURATION);
}
}
}
if (startTime === 0) {
startTime = Date.now();
}
return;
}
if (state.errors) {
Log.error(state.errors[0]);
const cleanError = stripAnsi(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
flushAllTraces();
teardownTraceSubscriber();
teardownHeapProfiler();
teardownCrashReporter();
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
flushAllTraces();
teardownTraceSubscriber();
teardownHeapProfiler();
teardownCrashReporter();
return;
}
if (state.typeChecking) {
Log.info(`bundled ${trigger}${timeMessage}${modulesMessage}, type checking...`);
return;
}
if (trigger === "initial") {
trigger = "";
} else {
if (loadingLogTimer) {
clearTimeout(loadingLogTimer);
loadingLogTimer = null;
}
Log.event(`Compiled${trigger ? " " + trigger : ""}${timeMessage}${modulesMessage}`);
trigger = "";
}
// Ensure traces are flushed after each compile in development mode
flushAllTraces();
teardownTraceSubscriber();
teardownHeapProfiler();
teardownCrashReporter();
});
//# sourceMappingURL=store.js.map

1
node_modules/next/dist/esm/build/output/store.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/output/store.ts"],"names":["createStore","stripAnsi","flushAllTraces","teardownCrashReporter","teardownHeapProfiler","teardownTraceSubscriber","Log","MAX_DURATION","store","appUrl","bindAddr","bootstrap","lastStore","hasStoreChanged","nextStore","Set","Object","keys","every","key","is","startTime","trigger","loadingLogTimer","subscribe","state","loading","setTimeout","wait","Date","now","errors","error","cleanError","indexOf","matches","match","prop","split","shift","slice","console","log","timeMessage","time","Math","round","modulesMessage","totalModulesCount","warnings","warn","join","typeChecking","info","clearTimeout","event"],"mappings":"AAAA,OAAOA,iBAAiB,8BAA6B;AACrD,OAAOC,eAAe,gCAA+B;AACrD,SAASC,cAAc,QAAQ,cAAa;AAC5C,SACEC,qBAAqB,EACrBC,oBAAoB,EACpBC,uBAAuB,QAClB,SAAQ;AACf,YAAYC,SAAS,QAAO;AAE5B,MAAMC,eAAe,I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EzB,UAAU;IACZ;IAEA,mEAAmE;IACnEpB;IACAG;IACAD;IACAD;AACF"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/polyfills/fetch/index.ts"],"names":["fetchModule","self","fetch","bind","module","exports","default"],"mappings":"AAAA,gBAAgB,GAChB,MAAMA,cAAcC,KAAKC,KAAK,CAACC,IAAI,CAACF;AACpCG,OAAOC,OAAO,GAAGL;AACjBI,OAAOC,OAAO,CAACC,OAAO,GAAGF,OAAOC,OAAO"}

View File

@@ -0,0 +1,6 @@
/* globals self */ 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 @@
{"version":3,"sources":["../../../../src/build/polyfills/fetch/whatwg-fetch.ts"],"names":["exports","Headers","self","Request","Response","fetch"],"mappings":"AAAA,gBAAgB,GAChBA,QAAQC,OAAO,GAAGC,KAAKD,OAAO;AAC9BD,QAAQG,OAAO,GAAGD,KAAKC,OAAO;AAC9BH,QAAQI,QAAQ,GAAGF,KAAKE,QAAQ;AAChCJ,QAAQK,KAAK,GAAGH,KAAKG,KAAK"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/polyfills/object-assign.ts"],"names":["assign","Object","bind","module","exports","default"],"mappings":"AAAA,IAAIA,SAASC,OAAOD,MAAM,CAACE,IAAI,CAACD;AAChCE,OAAOC,OAAO,GAAGJ;AACjBG,OAAOC,OAAO,CAACC,OAAO,GAAGF,OAAOC,OAAO"}

View File

@@ -0,0 +1,3 @@
// noop
//# sourceMappingURL=auto.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/polyfills/object.assign/auto.ts"],"names":[],"mappings":"AAAA,OAAO"}

View File

@@ -0,0 +1,3 @@
module.exports = Object.assign;
//# sourceMappingURL=implementation.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/polyfills/object.assign/implementation.ts"],"names":["module","exports","Object","assign"],"mappings":"AAAAA,OAAOC,OAAO,GAAGC,OAAOC,MAAM"}

View File

@@ -0,0 +1,18 @@
var assign = Object.assign.bind(Object);
function g() {
return assign;
}
Object.defineProperties(g(), {
implementation: {
get: g
},
shim: {
value: g
},
getPolyfill: {
value: g
}
});
module.exports = g();
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/polyfills/object.assign/index.ts"],"names":["assign","Object","bind","g","defineProperties","implementation","get","shim","value","getPolyfill","module","exports"],"mappings":"AAAA,IAAIA,SAASC,OAAOD,MAAM,CAACE,IAAI,CAACD;AAChC,SAASE;IACP,OAAOH;AACT;AACAC,OAAOG,gBAAgB,CAACD,KAAK;IAC3BE,gBAAgB;QAAEC,KAAKH;IAAE;IACzBI,MAAM;QAAEC,OAAOL;IAAE;IACjBM,aAAa;QAAED,OAAOL;IAAE;AAC1B;AACAO,OAAOC,OAAO,GAAGR"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/polyfills/object.assign/polyfill.ts"],"names":["module","exports","Object","assign"],"mappings":"AAAAA,OAAOC,OAAO,GAAG;IACf,OAAOC,OAAOC,MAAM;AACtB"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/build/polyfills/object.assign/shim.ts"],"names":["module","exports","Object","assign"],"mappings":"AAAAA,OAAOC,OAAO,GAAG;IACf,OAAOC,OAAOC,MAAM;AACtB"}

View File

@@ -0,0 +1,4 @@
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("../../compiled/process");
//# sourceMappingURL=process.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/polyfills/process.ts"],"names":["global","module","exports","process","env","require"],"mappings":"IACEA,iBAA8BA;AADhCC,OAAOC,OAAO,GACZF,EAAAA,kBAAAA,OAAOG,OAAO,qBAAdH,gBAAgBI,GAAG,KAAI,SAAOJ,mBAAAA,OAAOG,OAAO,qBAAdH,iBAAgBI,GAAG,MAAK,WAClDJ,OAAOG,OAAO,GACdE,QAAQ"}

67
node_modules/next/dist/esm/build/spinner.js generated vendored Normal file
View File

@@ -0,0 +1,67 @@
import ora from "next/dist/compiled/ora";
import * as Log from "./output/log";
const dotsSpinner = {
frames: [
".",
"..",
"..."
],
interval: 200
};
export default function createSpinner(text, options = {}, logFn = console.log) {
let spinner;
const prefixText = ` ${Log.prefixes.info} ${text}`;
// Add \r at beginning to reset the current line of loading status text
const suffixText = `\r ${Log.prefixes.event} ${text}`;
if (process.stdout.isTTY) {
spinner = ora({
text: undefined,
prefixText,
spinner: dotsSpinner,
stream: process.stdout,
...options
}).start();
// Add capturing of console.log/warn/error to allow pausing
// the spinner before logging and then restarting spinner after
const origLog = console.log;
const origWarn = console.warn;
const origError = console.error;
const origStop = spinner.stop.bind(spinner);
const origStopAndPersist = spinner.stopAndPersist.bind(spinner);
const logHandle = (method, args)=>{
origStop();
method(...args);
spinner.start();
};
console.log = (...args)=>logHandle(origLog, args);
console.warn = (...args)=>logHandle(origWarn, args);
console.error = (...args)=>logHandle(origError, args);
const resetLog = ()=>{
console.log = origLog;
console.warn = origWarn;
console.error = origError;
};
spinner.stop = ()=>{
origStop();
resetLog();
return spinner;
};
spinner.stopAndPersist = ()=>{
if (suffixText) {
if (spinner) {
spinner.text = suffixText;
} else {
logFn(suffixText);
}
}
origStopAndPersist();
resetLog();
return spinner;
};
} else if (prefixText || text) {
logFn(prefixText ? prefixText + "..." : text);
}
return spinner;
}
//# sourceMappingURL=spinner.js.map

1
node_modules/next/dist/esm/build/spinner.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/build/spinner.ts"],"names":["ora","Log","dotsSpinner","frames","interval","createSpinner","text","options","logFn","console","log","spinner","prefixText","prefixes","info","suffixText","event","process","stdout","isTTY","undefined","stream","start","origLog","origWarn","warn","origError","error","origStop","stop","bind","origStopAndPersist","stopAndPersist","logHandle","method","args","resetLog"],"mappings":"AAAA,OAAOA,SAAS,yBAAwB;AACxC,YAAYC,SAAS,eAAc;AAEnC,MAAMC,cAAc;IAClBC,QAAQ;QAAC;QAAK;QAAM;KAAM;IAC1BC,UAAU;AACZ;AAEA,eAAe,SAASC,cACtBC,IAAY,EACZC,UAAuB,CAAC,CAAC,EACzBC,QAAkCC,QAAQC,GAAG;IAE7C,IAAIC;IAEJ,MAAMC,aAAa,CAAC,CAAC,EAAEX,IAAIY,QAAQ,CAACC,IAAI,CAAC,CAAC,EAAER,KAAK,CAAC;IAClD,uEAAuE;IACvE,MAAMS,aAAa,CAAC,GAAG,EAAEd,IAAIY,QAAQ,CAACG,KAAK,CAAC,CAAC,EAAEV,KAAK,CAAC;IAErD,IAAIW,QAAQC,MAAM,CAACC,KAAK,EAAE;QACxBR,UAAUX,IAAI;YACZM,MAAMc;YACNR;YACAD,SAAST;YACTmB,QAAQJ,QAAQC,MAAM;YACtB,GAAGX,OAAO;QACZ,GAAGe,KAAK;QAER,2DAA2D;QAC3D,+DAA+D;QAC/D,MAAMC,UAAUd,QAAQC,GAAG;QAC3B,MAAMc,WAAWf,QAAQgB,IAAI;QAC7B,MAAMC,YAAYjB,QAAQkB,KAAK;QAC/B,MAAMC,WAAWjB,QAAQkB,IAAI,CAACC,IAAI,CAACnB;QACnC,MAAMoB,qBAAqBpB,QAAQqB,cAAc,CAACF,IAAI,CAACnB;QAEvD,MAAMsB,YAAY,CAACC,QAAaC;YAC9BP;YACAM,UAAUC;YACVxB,QAASW,KAAK;QAChB;QAEAb,QAAQC,GAAG,GAAG,CAAC,GAAGyB,OAAcF,UAAUV,SAASY;QACnD1B,QAAQgB,IAAI,GAAG,CAAC,GAAGU,OAAcF,UAAUT,UAAUW;QACrD1B,QAAQkB,KAAK,GAAG,CAAC,GAAGQ,OAAcF,UAAUP,WAAWS;QAEvD,MAAMC,WAAW;YACf3B,QAAQC,GAAG,GAAGa;YACdd,QAAQgB,IAAI,GAAGD;YACff,QAAQkB,KAAK,GAAGD;QAClB;QACAf,QAAQkB,IAAI,GAAG;YACbD;YACAQ;YACA,OAAOzB;QACT;QACAA,QAAQqB,cAAc,GAAG;YACvB,IAAIjB,YAAY;gBACd,IAAIJ,SAAS;oBACXA,QAAQL,IAAI,GAAGS;gBACjB,OAAO;oBACLP,MAAMO;gBACR;YACF;YACAgB;YACAK;YACA,OAAOzB;QACT;IACF,OAAO,IAAIC,cAAcN,MAAM;QAC7BE,MAAMI,aAAaA,aAAa,QAAQN;IAC1C;IAEA,OAAOK;AACT"}

884
node_modules/next/dist/esm/build/swc/index.js generated vendored Normal file
View File

@@ -0,0 +1,884 @@
/* eslint-disable @typescript-eslint/no-use-before-define */ import path from "path";
import { pathToFileURL } from "url";
import { platform, arch } from "os";
import { platformArchTriples } from "next/dist/compiled/@napi-rs/triples";
import * as Log from "../output/log";
import { getParserOptions } from "./options";
import { eventSwcLoadFailure } from "../../telemetry/events/swc-load-failure";
import { patchIncorrectLockfile } from "../../lib/patch-incorrect-lockfile";
import { downloadWasmSwc, downloadNativeNextSwc } from "../../lib/download-swc";
import { isDeepStrictEqual } from "util";
const nextVersion = "13.5.1";
const ArchName = arch();
const PlatformName = platform();
const infoLog = (...args)=>{
if (process.env.NEXT_PRIVATE_BUILD_WORKER) {
return;
}
if (process.env.DEBUG) {
Log.info(...args);
}
};
/**
* Based on napi-rs's target triples, returns triples that have corresponding next-swc binaries.
*/ export const getSupportedArchTriples = ()=>{
const { darwin, win32, linux, freebsd, android } = 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 = 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 swcCrashReporterFlushGuard;
let downloadNativeBindingsPromise = undefined;
export const lockfilePatchPromise = {};
export async function loadBindings() {
if (pendingBindings) {
return pendingBindings;
}
if (process.platform === "darwin") {
// 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(true);
}
if (process.stderr._handle != null) {
// @ts-ignore
process.stderr._handle.setBlocking(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 = patchIncorrectLockfile(process.cwd()).catch(console.error);
}
let attempts = [];
const disableWasmFallback = process.env.NEXT_DISABLE_SWC_WASM;
const shouldLoadWasmFallbackFirst = !disableWasmFallback && triples.some((triple)=>!!(triple == null ? void 0 : triple.raw) && knownDefaultWasmFallbackTriples.includes(triple.raw));
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);
}
// For these platforms we already tried to load wasm and failed, skip reattempt
if (!shouldLoadWasmFallbackFirst && !disableWasmFallback) {
const fallbackBindings = await tryLoadWasmWithFallback(attempts);
if (fallbackBindings) {
return resolve(fallbackBindings);
}
}
logLoadFailure(attempts, true);
});
return pendingBindings;
}
async function tryLoadNativeWithFallback(attempts) {
const nativeBindingsDirectory = path.join(path.dirname(require.resolve("next/package.json")), "next-swc-fallback");
if (!downloadNativeBindingsPromise) {
downloadNativeBindingsPromise = 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.
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.join(path.dirname(require.resolve("next/package.json")), "wasm");
if (!downloadWasmPromise) {
downloadWasmPromise = downloadWasmSwc(nextVersion, wasmDirectory);
}
await downloadWasmPromise;
let bindings = await loadWasm(pathToFileURL(wasmDirectory).href);
// @ts-expect-error TODO: this event has a wrong type.
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.
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);
});
}
export var ServerClientChangeType;
(function(ServerClientChangeType) {
ServerClientChangeType["Server"] = "Server";
ServerClientChangeType["Client"] = "Client";
ServerClientChangeType["Both"] = "Both";
})(ServerClientChangeType || (ServerClientChangeType = {}));
// 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;
}
/**
* Like Promise.race, except that we return an array of results so that you
* know which promise won. This also allows multiple promises to resolve
* before the awaiter finally continues execution, making multiple values
* available.
*/ function race(promises) {
return new Promise((resolve, reject)=>{
const results = [];
for(let i = 0; i < promises.length; i++){
const value = promises[i];
Promise.resolve(value).then((v)=>{
results[i] = v;
resolve(results);
}, (e)=>{
reject(e);
});
}
});
}
async function rustifyProjectOptions(options) {
return {
...options,
nextConfig: await serializeNextConfig(options.nextConfig),
jsConfig: JSON.stringify(options.jsConfig ?? {}),
env: Object.entries(options.env).map(([name, value])=>({
name,
value
}))
};
}
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",
htmlEndpoint: new EndpointImpl(nativeRoute.htmlEndpoint),
rscEndpoint: new EndpointImpl(nativeRoute.rscEndpoint)
};
break;
case "app-route":
route = {
type: "app-route",
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;
yield {
routes,
middleware,
pagesDocumentEndpoint: new EndpointImpl(entrypoints.pagesDocumentEndpoint),
pagesAppEndpoint: new EndpointImpl(entrypoints.pagesAppEndpoint),
pagesErrorEndpoint: new EndpointImpl(entrypoints.pagesErrorEndpoint),
issues: entrypoints.issues,
diagnostics: entrypoints.diagnostics
};
}
}();
}
hmrEvents(identifier) {
const subscription = subscribe(true, async (callback)=>binding.projectHmrEvents(this._nativeProject, identifier, callback));
return subscription;
}
hmrIdentifiersSubscribe() {
const subscription = subscribe(false, async (callback)=>binding.projectHmrIdentifiersSubscribe(this._nativeProject, callback));
return subscription;
}
updateInfoSubscribe() {
const subscription = subscribe(true, async (callback)=>binding.projectUpdateInfoSubscribe(this._nativeProject, callback));
return subscription;
}
}
class EndpointImpl {
constructor(nativeEndpoint){
this._nativeEndpoint = nativeEndpoint;
}
async writeToDisk() {
return await withErrorCause(()=>binding.endpointWriteToDisk(this._nativeEndpoint));
}
async changed() {
const serverSubscription = subscribe(false, async (callback)=>binding.endpointServerChangedSubscribe(await this._nativeEndpoint, callback));
const clientSubscription = subscribe(false, async (callback)=>binding.endpointClientChangedSubscribe(await this._nativeEndpoint, callback));
// The subscriptions will always emit once, which is the initial
// computation. This is not a change, so swallow it.
await Promise.all([
serverSubscription.next(),
clientSubscription.next()
]);
return async function*() {
try {
while(true){
const [server, client] = await race([
serverSubscription.next(),
clientSubscription.next()
]);
const done = (server == null ? void 0 : server.done) || (client == null ? void 0 : client.done);
if (done) {
break;
}
if (server && client) {
yield {
issues: server.value.issues.concat(client.value.issues),
diagnostics: server.value.diagnostics.concat(client.value.diagnostics),
type: "Both"
};
} else if (server) {
yield {
...server.value,
type: "Server"
};
} else {
yield {
...client.value,
type: "Client"
};
}
}
} finally{
serverSubscription.return == null ? void 0 : serverSubscription.return.call(serverSubscription);
clientSubscription.return == null ? void 0 : clientSubscription.return.call(clientSubscription);
}
}();
}
}
async function serializeNextConfig(nextConfig) {
var _nextConfig_experimental_turbo, _nextConfig_experimental;
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;
return JSON.stringify(nextConfigSerializable, null, 2);
}
function ensureLoadersHaveSerializableOptions(turbopackRules) {
for (const [glob, rule] of Object.entries(turbopackRules)){
const loaderItems = Array.isArray(rule) ? rule : rule.loaders;
for (const loaderItem of loaderItems){
if (typeof loaderItem !== "string" && !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.join(importPath, pkg, "wasm.js");
}
let bindings = await import(pkgPath);
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) {
const astStr = bindings.parseSync(src.toString(), options);
return astStr;
},
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.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) {
// Initialize crash reporter, as earliest as possible from any point of import.
// The first-time import to next-swc is not predicatble in the import tree of next.js, which makes
// we can't rely on explicit manual initialization as similar to trace reporter.
if (!swcCrashReporterFlushGuard) {
// Crash reports in next-swc should be treated in the same way we treat telemetry to opt out.
/* TODO: temporarily disable initialization while confirming logistics.
let telemetry = new Telemetry({ distDir: process.cwd() })
if (telemetry.isEnabled) {
swcCrashReporterFlushGuard = bindings.initCrashReporter?.()
}*/ }
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,
teardownCrashReporter: bindings.teardownCrashReporter,
turbo: {
nextBuild: (options)=>{
initHeapProfiler();
const ret = (customBindings ?? bindings).nextBuild(options);
return ret;
},
startTrace: (options = {}, turboTasks)=>{
initHeapProfiler();
const ret = (customBindings ?? bindings).runTurboTracing(toBuffer({
exact: true,
...options
}), turboTasks);
return ret;
},
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)))
}
};
return nativeBindings;
}
throw attempts;
}
/// Build a mdx options object contains default values that
/// can be parsed with serde_wasm_bindgen.
function getMdxOptions(options = {}) {
const ret = {
...options,
development: options.development ?? false,
jsx: options.jsx ?? false,
parse: options.parse ?? {
gfmStrikethroughSingleTilde: true,
mathTextSingleDollar: true
}
};
return ret;
}
function toBuffer(t) {
return Buffer.from(JSON.stringify(t));
}
export async function isWasm() {
let bindings = await loadBindings();
return bindings.isWasm;
}
export async function transform(src, options) {
let bindings = await loadBindings();
return bindings.transform(src, options);
}
export function transformSync(src, options) {
let bindings = loadBindingsSync();
return bindings.transformSync(src, options);
}
export async function minify(src, options) {
let bindings = await loadBindings();
return bindings.minify(src, options);
}
export function minifySync(src, options) {
let bindings = loadBindingsSync();
return bindings.minifySync(src, options);
}
export async function parse(src, options) {
let bindings = await loadBindings();
let parserOptions = getParserOptions(options);
return bindings.parse(src, parserOptions).then((astStr)=>JSON.parse(astStr));
}
export 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)
};
}
/**
* Initialize trace subscriber to emit traces.
*
*/ export const initCustomTraceSubscriber = (traceFileName)=>{
if (!swcTraceFlushGuard) {
// Wasm binary doesn't support trace emission
let bindings = loadNative();
swcTraceFlushGuard = bindings.initCustomTraceSubscriber(traceFileName);
}
};
/**
* Initialize heap profiler, if possible.
* Note this is not available in release build of next-swc by default,
* only available by manually building next-swc with specific flags.
* Calling in release build will not do anything.
*/ export const initHeapProfiler = ()=>{
try {
if (!swcHeapProfilerFlushGuard) {
let bindings = loadNative();
swcHeapProfilerFlushGuard = bindings.initHeapProfiler();
}
} catch (_) {
// Suppress exceptions, this fn allows to fail to load native bindings
}
};
/**
* Teardown heap profiler, if possible.
*
* Same as initialization, this is not available in release build of next-swc by default
* and calling it will not do anything.
*/ export 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
}
}
};
})();
/**
* Teardown swc's trace subscriber if there's an initialized flush guard exists.
*
* This is workaround to amend behavior with process.exit
* (https://github.com/vercel/next.js/blob/4db8c49cc31e4fc182391fae6903fb5ef4e8c66e/packages/next/bin/next.ts#L134=)
* seems preventing napi's cleanup hook execution (https://github.com/swc-project/swc/blob/main/crates/node/src/util.rs#L48-L51=),
*
* instead parent process manually drops guard when process gets signal to exit.
*/ export 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
}
}
};
})();
export const teardownCrashReporter = (()=>{
let flushed = false;
return ()=>{
if (!flushed) {
flushed = true;
try {
let bindings = loadNative();
if (swcCrashReporterFlushGuard) {
bindings.teardownCrashReporter(swcCrashReporterFlushGuard);
}
} catch (e) {
// Suppress exceptions, this fn allows to fail to load native bindings
}
}
};
})();
//# sourceMappingURL=index.js.map

1
node_modules/next/dist/esm/build/swc/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,65 @@
/*
Copyright (c) 2021 The swc Project Developers
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.
*/ import vm from "vm";
import { transformSync } from "./index";
import { getJestSWCOptions } from "./options";
// Jest use the `vm` [Module API](https://nodejs.org/api/vm.html#vm_class_vm_module) for ESM.
// see https://github.com/facebook/jest/issues/9430
const isSupportEsm = "Module" in vm;
function getJestConfig(jestConfig) {
return "config" in jestConfig ? jestConfig.config : jestConfig;
}
function isEsm(isEsmProject, filename, jestConfig) {
var _jestConfig_extensionsToTreatAsEsm;
return /\.jsx?$/.test(filename) && isEsmProject || ((_jestConfig_extensionsToTreatAsEsm = jestConfig.extensionsToTreatAsEsm) == null ? void 0 : _jestConfig_extensionsToTreatAsEsm.some((ext)=>filename.endsWith(ext)));
}
const createTransformer = (inputOptions)=>({
process (src, filename, jestOptions) {
const jestConfig = getJestConfig(jestOptions);
const swcTransformOpts = getJestSWCOptions({
isServer: jestConfig.testEnvironment === "node" || jestConfig.testEnvironment.includes("jest-environment-node"),
filename,
jsConfig: inputOptions == null ? void 0 : inputOptions.jsConfig,
resolvedBaseUrl: inputOptions == null ? void 0 : inputOptions.resolvedBaseUrl,
pagesDir: inputOptions == null ? void 0 : inputOptions.pagesDir,
hasServerComponents: inputOptions == null ? void 0 : inputOptions.hasServerComponents,
modularizeImports: inputOptions == null ? void 0 : inputOptions.modularizeImports,
swcPlugins: inputOptions == null ? void 0 : inputOptions.swcPlugins,
compilerOptions: inputOptions == null ? void 0 : inputOptions.compilerOptions,
esm: isSupportEsm && isEsm(Boolean(inputOptions == null ? void 0 : inputOptions.isEsmProject), filename, jestConfig)
});
return transformSync(src, {
...swcTransformOpts,
filename
});
}
});
module.exports = {
createTransformer
};
//# sourceMappingURL=jest-transformer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/swc/jest-transformer.ts"],"names":["vm","transformSync","getJestSWCOptions","isSupportEsm","getJestConfig","jestConfig","config","isEsm","isEsmProject","filename","test","extensionsToTreatAsEsm","some","ext","endsWith","createTransformer","inputOptions","process","src","jestOptions","swcTransformOpts","isServer","testEnvironment","includes","jsConfig","resolvedBaseUrl","pagesDir","hasServerComponents","modularizeImports","swcPlugins","compilerOptions","esm","Boolean","module","exports"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,GAEA,OAAOA,QAAQ,KAAI;AACnB,SAASC,aAAa,QAAQ,UAAS;AACvC,SAASC,iBAAiB,QAAQ,YAAW;AAqB7C,6FAA6F;AAC7F,mDAAmD;AACnD,MAAMC,eAAe,YAAYH;AAEjC,SAASI,cACPC,UAAmD;IAEnD,OAAO,YAAYA,aAEfA,WAAWC,MAAM,GAEhBD;AACP;AAEA,SAASE,MACPC,YAAqB,EACrBC,QAAgB,EAChBJ,UAAgC;QAI9BA;IAFF,OACE,AAAC,UAAUK,IAAI,CAACD,aAAaD,kBAC7BH,qCAAAA,WAAWM,sBAAsB,qBAAjCN,mCAAmCO,IAAI,CAAC,CAACC,MACvCJ,SAASK,QAAQ,CAACD;AAGxB;AAEA,MAAME,oBAGF,CAACC,eAAkB,CAAA;QACrBC,SAAQC,GAAG,EAAET,QAAQ,EAAEU,WAAW;YAChC,MAAMd,aAAaD,cAAce;YAEjC,MAAMC,mBAAmBlB,kBAAkB;gBACzCmB,UACEhB,WAAWiB,eAAe,KAAK,UAC/BjB,WAAWiB,eAAe,CAACC,QAAQ,CAAC;gBACtCd;gBACAe,QAAQ,EAAER,gCAAAA,aAAcQ,QAAQ;gBAChCC,eAAe,EAAET,gCAAAA,aAAcS,eAAe;gBAC9CC,QAAQ,EAAEV,gCAAAA,aAAcU,QAAQ;gBAChCC,mBAAmB,EAAEX,gCAAAA,aAAcW,mBAAmB;gBACtDC,iBAAiB,EAAEZ,gCAAAA,aAAcY,iBAAiB;gBAClDC,UAAU,EAAEb,gCAAAA,aAAca,UAAU;gBACpCC,eAAe,EAAEd,gCAAAA,aAAcc,eAAe;gBAC9CC,KACE5B,gBACAI,MAAMyB,QAAQhB,gCAAAA,aAAcR,YAAY,GAAGC,UAAUJ;YACzD;YAEA,OAAOJ,cAAciB,KAAK;gBAAE,GAAGE,gBAAgB;gBAAEX;YAAS;QAC5D;IACF,CAAA;AAEAwB,OAAOC,OAAO,GAAG;IAAEnB;AAAkB"}

297
node_modules/next/dist/esm/build/swc/options.js generated vendored Normal file
View File

@@ -0,0 +1,297 @@
const nextDistPath = /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/;
const regeneratorRuntimePath = require.resolve("next/dist/compiled/regenerator-runtime");
export function getParserOptions({ filename, jsConfig, ...rest }) {
var _jsConfig_compilerOptions;
const isTSFile = filename.endsWith(".ts");
const isTypeScript = isTSFile || filename.endsWith(".tsx");
const enableDecorators = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.experimentalDecorators);
return {
...rest,
syntax: isTypeScript ? "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.
[isTypeScript ? "tsx" : "jsx"]: !isTSFile,
importAssertions: true
};
}
function getBaseSWCOptions({ filename, jest, development, hasReactRefresh, globalWindow, modularizeImports, swcPlugins, compilerOptions, resolvedBaseUrl, jsConfig, swcCacheDir, isServerLayer, bundleTarget, hasServerComponents, isServerActionsEnabled }) {
var _jsConfig_compilerOptions, _jsConfig_compilerOptions1, _jsConfig_compilerOptions2, _jsConfig_compilerOptions3, _jsConfig_compilerOptions4;
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,
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) && !isServerLayer ? "@emotion/react" : "react"),
runtime: "automatic",
pragma: "React.createElement",
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
...!isServerLayer && {
// 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: hasServerComponents ? {
isServer: !!isServerLayer
} : undefined,
serverActions: hasServerComponents ? {
// TODO-APP: When Server Actions is stable, we need to remove this flag.
enabled: !!isServerActionsEnabled,
isServer: !!isServerLayer
} : undefined,
bundleTarget
};
}
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
}
};
}
export function getJestSWCOptions({ isServer, filename, esm, modularizeImports, swcPlugins, compilerOptions, jsConfig, resolvedBaseUrl, pagesDir, hasServerComponents }) {
let baseOptions = getBaseSWCOptions({
filename,
jest: true,
development: false,
hasReactRefresh: false,
globalWindow: !isServer,
modularizeImports,
swcPlugins,
compilerOptions,
jsConfig,
hasServerComponents,
resolvedBaseUrl,
// Don't apply server layer transformations for Jest
isServerLayer: false,
// Disable server / client graph assertions for Jest
bundleTarget: "default"
});
const isNextDist = nextDistPath.test(filename);
return {
...baseOptions,
env: {
targets: {
// Targets the current version of Node.js
node: process.versions.node
}
},
module: {
type: esm && !isNextDist ? "es6" : "commonjs"
},
disableNextSsg: true,
disablePageConfig: true,
pagesDir
};
}
export function getLoaderSWCOptions({ filename, development, isServer, pagesDir, appDir, isPageFile, hasReactRefresh, modularizeImports, optimizeServerReact, optimizePackageImports, swcPlugins, compilerOptions, jsConfig, supportedBrowsers, swcCacheDir, relativeFilePathFromRoot, hasServerComponents, isServerLayer, isServerActionsEnabled, optimizeBarrelExports, bundleTarget = "client" }) {
let baseOptions = getBaseSWCOptions({
filename,
development,
globalWindow: !isServer,
hasReactRefresh,
modularizeImports,
swcPlugins,
compilerOptions,
jsConfig,
// resolvedBaseUrl,
swcCacheDir,
hasServerComponents,
isServerLayer,
isServerActionsEnabled,
bundleTarget
});
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: true
};
}
// Modularize import optimization for barrel files
if (optimizePackageImports) {
baseOptions.autoModularizeImports = {
packages: optimizePackageImports
};
}
if (optimizeBarrelExports) {
baseOptions.optimizeBarrelExports = optimizeBarrelExports;
}
const isNextDist = nextDistPath.test(filename);
if (isServer) {
return {
...baseOptions,
// Disables getStaticProps/getServerSideProps tree shaking on the server compilation for pages
disableNextSsg: true,
disablePageConfig: true,
isDevelopment: development,
isServer,
pagesDir,
appDir,
isPageFile,
env: {
targets: {
// Targets the current version of Node.js
node: process.versions.node
}
}
};
} else {
const options = {
...baseOptions,
// Ensure Next.js internals are output as commonjs modules
...isNextDist ? {
module: {
type: "commonjs"
}
} : {},
disableNextSsg: !isPageFile,
isDevelopment: development,
isServer,
pagesDir,
appDir,
isPageFile,
...supportedBrowsers && supportedBrowsers.length > 0 ? {
env: {
targets: supportedBrowsers
}
} : {}
};
if (!options.env) {
// Matches default @babel/preset-env behavior
options.jsc.target = "es5";
}
return options;
}
}
//# sourceMappingURL=options.js.map

1
node_modules/next/dist/esm/build/swc/options.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

36
node_modules/next/dist/esm/build/templates/app-page.js generated vendored Normal file
View File

@@ -0,0 +1,36 @@
// @ts-ignore this need to be imported from next/dist to be external
import * as module from "next/dist/server/future/route-modules/app-page/module.compiled";
import { RouteKind } from "../../server/future/route-kind";
const AppPageRouteModule = module.AppPageRouteModule;
// We inject the tree and pages here so that we can use them in the route
// module.
// INJECT:tree
// INJECT:pages
export { tree, pages };
// @ts-expect-error - replaced by webpack/turbopack loader
export { default as GlobalError } from "VAR_MODULE_GLOBAL_ERROR";
// INJECT:__next_app_require__
// INJECT:__next_app_load_chunk__
export const originalPathname = "VAR_ORIGINAL_PATHNAME";
export const __next_app__ = {
require: __next_app_require__,
loadChunk: __next_app_load_chunk__
};
export * from "../../server/app-render/entry-base";
// Create and export the route module that will be consumed.
export const routeModule = new AppPageRouteModule({
definition: {
kind: RouteKind.APP_PAGE,
page: "VAR_DEFINITION_PAGE",
pathname: "VAR_DEFINITION_PATHNAME",
// The following aren't used in production.
bundlePath: "",
filename: "",
appPaths: []
},
userland: {
loaderTree: tree
}
});
//# sourceMappingURL=app-page.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/app-page.ts"],"names":["module","RouteKind","AppPageRouteModule","tree","pages","default","GlobalError","originalPathname","__next_app__","require","__next_app_require__","loadChunk","__next_app_load_chunk__","routeModule","definition","kind","APP_PAGE","page","pathname","bundlePath","filename","appPaths","userland","loaderTree"],"mappings":"AAEA,oEAAoE;AACpE,YAAYA,YAAY,iEAAgE;AACxF,SAASC,SAAS,QAAQ,iCAAgC;AAE1D,MAAMC,qBACJF,OAAOE,kBAAkB;AAM3B,yEAAyE;AACzE,UAAU;AACV,cAAc;AACd,eAAe;AAEf,SAASC,IAAI,EAAEC,KAAK,GAAE;AAEtB,0DAA0D;AAC1D,SAASC,WAAWC,WAAW,QAAQ,0BAAyB;AAMhE,8BAA8B;AAC9B,iCAAiC;AAEjC,OAAO,MAAMC,mBAAmB,wBAAuB;AACvD,OAAO,MAAMC,eAAe;IAC1BC,SAASC;IACTC,WAAWC;AACb,EAAC;AAED,cAAc,qCAAoC;AAElD,4DAA4D;AAC5D,OAAO,MAAMC,cAAc,IAAIX,mBAAmB;IAChDY,YAAY;QACVC,MAAMd,UAAUe,QAAQ;QACxBC,MAAM;QACNC,UAAU;QACV,2CAA2C;QAC3CC,YAAY;QACZC,UAAU;QACVC,UAAU,EAAE;IACd;IACAC,UAAU;QACRC,YAAYpB;IACd;AACF,GAAE"}

View File

@@ -0,0 +1,30 @@
import "../../server/node-polyfill-headers";
// @ts-ignore this need to be imported from next/dist to be external
import * as module from "next/dist/server/future/route-modules/app-route/module.compiled";
import { RouteKind } from "../../server/future/route-kind";
// @ts-expect-error - replaced by webpack/turbopack loader
import * as userland from "VAR_USERLAND";
const AppRouteRouteModule = module.AppRouteRouteModule;
// We inject the nextConfigOutput here so that we can use them in the route
// module.
// INJECT:nextConfigOutput
const routeModule = new AppRouteRouteModule({
definition: {
kind: RouteKind.APP_ROUTE,
page: "VAR_DEFINITION_PAGE",
pathname: "VAR_DEFINITION_PATHNAME",
filename: "VAR_DEFINITION_FILENAME",
bundlePath: "VAR_DEFINITION_BUNDLE_PATH"
},
resolvedPagePath: "VAR_RESOLVED_PAGE_PATH",
nextConfigOutput,
userland
});
// Pull out the exports that we need to expose from the module. This should
// be eliminated when we've moved the other routes to the new format. These
// are used to hook into the route.
const { requestAsyncStorage, staticGenerationAsyncStorage, serverHooks, headerHooks, staticGenerationBailout } = routeModule;
const originalPathname = "VAR_ORIGINAL_PATHNAME";
export { routeModule, requestAsyncStorage, staticGenerationAsyncStorage, serverHooks, headerHooks, staticGenerationBailout, originalPathname, };
//# sourceMappingURL=app-route.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/app-route.ts"],"names":["module","RouteKind","userland","AppRouteRouteModule","routeModule","definition","kind","APP_ROUTE","page","pathname","filename","bundlePath","resolvedPagePath","nextConfigOutput","requestAsyncStorage","staticGenerationAsyncStorage","serverHooks","headerHooks","staticGenerationBailout","originalPathname"],"mappings":"AAAA,OAAO,qCAAoC;AAE3C,oEAAoE;AACpE,YAAYA,YAAY,kEAAiE;AAGzF,SAASC,SAAS,QAAQ,iCAAgC;AAE1D,0DAA0D;AAC1D,YAAYC,cAAc,eAAc;AAExC,MAAMC,sBACJH,OAAOG,mBAAmB;AAO5B,2EAA2E;AAC3E,UAAU;AACV,0BAA0B;AAE1B,MAAMC,cAAc,IAAID,oBAAoB;IAC1CE,YAAY;QACVC,MAAML,UAAUM,SAAS;QACzBC,MAAM;QACNC,UAAU;QACVC,UAAU;QACVC,YAAY;IACd;IACAC,kBAAkB;IAClBC;IACAX;AACF;AAEA,2EAA2E;AAC3E,2EAA2E;AAC3E,mCAAmC;AACnC,MAAM,EACJY,mBAAmB,EACnBC,4BAA4B,EAC5BC,WAAW,EACXC,WAAW,EACXC,uBAAuB,EACxB,GAAGd;AAEJ,MAAMe,mBAAmB;AAEzB,SACEf,WAAW,EACXU,mBAAmB,EACnBC,4BAA4B,EAC5BC,WAAW,EACXC,WAAW,EACXC,uBAAuB,EACvBC,gBAAgB,KACjB"}

26
node_modules/next/dist/esm/build/templates/helpers.js generated vendored Normal file
View File

@@ -0,0 +1,26 @@
/**
* Hoists a name from a module or promised module.
*
* @param module the module to hoist the name from
* @param name the name to hoist
* @returns the value on the module (or promised module)
*/ export function hoist(module, name) {
// If the name is available in the module, return it.
if (name in module) {
return module[name];
}
// If a property called `then` exists, assume it's a promise and
// return a promise that resolves to the name.
if ("then" in module && typeof module.then === "function") {
return module.then((mod)=>hoist(mod, name));
}
// If we're trying to hoise the default export, and the module is a function,
// return the module itself.
if (typeof module === "function" && name === "default") {
return module;
}
// Otherwise, return undefined.
return undefined;
}
//# sourceMappingURL=helpers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/helpers.ts"],"names":["hoist","module","name","then","mod","undefined"],"mappings":"AAAA;;;;;;CAMC,GACD,OAAO,SAASA,MAAMC,MAAW,EAAEC,IAAY;IAC7C,qDAAqD;IACrD,IAAIA,QAAQD,QAAQ;QAClB,OAAOA,MAAM,CAACC,KAAK;IACrB;IAEA,gEAAgE;IAChE,8CAA8C;IAC9C,IAAI,UAAUD,UAAU,OAAOA,OAAOE,IAAI,KAAK,YAAY;QACzD,OAAOF,OAAOE,IAAI,CAAC,CAACC,MAAaJ,MAAMI,KAAKF;IAC9C;IAEA,6EAA6E;IAC7E,4BAA4B;IAC5B,IAAI,OAAOD,WAAW,cAAcC,SAAS,WAAW;QACtD,OAAOD;IACT;IAEA,+BAA+B;IAC/B,OAAOI;AACT"}

View File

@@ -0,0 +1,21 @@
import "../../server/web/globals";
import { adapter } from "../../server/web/adapter";
// Import the userland code.
// @ts-expect-error - replaced by webpack/turbopack loader
import * as _mod from "VAR_USERLAND";
const mod = {
..._mod
};
const handler = mod.middleware || mod.default;
if (typeof handler !== "function") {
throw new Error(`The Middleware must export a \`middleware\` or a \`default\` function`);
}
export default function(opts) {
return adapter({
...opts,
page: "",
handler
});
}
//# sourceMappingURL=middleware.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/middleware.ts"],"names":["adapter","_mod","mod","handler","middleware","default","Error","opts","page"],"mappings":"AAAA,OAAO,2BAA0B;AAEjC,SAASA,OAAO,QAAQ,2BAA0B;AAElD,4BAA4B;AAC5B,0DAA0D;AAC1D,YAAYC,UAAU,eAAc;AAEpC,MAAMC,MAAM;IAAE,GAAGD,IAAI;AAAC;AACtB,MAAME,UAAUD,IAAIE,UAAU,IAAIF,IAAIG,OAAO;AAE7C,IAAI,OAAOF,YAAY,YAAY;IACjC,MAAM,IAAIG,MACR,CAAC,qEAAqE,CAAC;AAE3E;AAEA,eAAe,SACbC,IAAmE;IAEnE,OAAOP,QAAQ;QACb,GAAGO,IAAI;QACPC,MAAM;QACNL;IACF;AACF"}

View File

@@ -0,0 +1,26 @@
// @ts-ignore this need to be imported from next/dist to be external
import * as module from "next/dist/server/future/route-modules/pages-api/module.compiled";
import { RouteKind } from "../../server/future/route-kind";
import { hoist } from "./helpers";
const PagesAPIRouteModule = module.PagesAPIRouteModule;
// Import the userland code.
// @ts-expect-error - replaced by webpack/turbopack loader
import * as userland from "VAR_USERLAND";
// Re-export the handler (should be the default export).
export default hoist(userland, "default");
// Re-export config.
export const config = hoist(userland, "config");
// Create and export the route module that will be consumed.
export const routeModule = new PagesAPIRouteModule({
definition: {
kind: RouteKind.PAGES_API,
page: "VAR_DEFINITION_PAGE",
pathname: "VAR_DEFINITION_PATHNAME",
// The following aren't used in production.
bundlePath: "",
filename: ""
},
userland
});
//# sourceMappingURL=pages-api.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/pages-api.ts"],"names":["module","RouteKind","hoist","PagesAPIRouteModule","userland","config","routeModule","definition","kind","PAGES_API","page","pathname","bundlePath","filename"],"mappings":"AAAA,oEAAoE;AACpE,YAAYA,YAAY,kEAAiE;AAEzF,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,KAAK,QAAQ,YAAW;AAEjC,MAAMC,sBACJH,OAAOG,mBAAmB;AAE5B,4BAA4B;AAC5B,0DAA0D;AAC1D,YAAYC,cAAc,eAAc;AAExC,wDAAwD;AACxD,eAAeF,MAAME,UAAU,WAAU;AAEzC,oBAAoB;AACpB,OAAO,MAAMC,SAASH,MAAME,UAAU,UAAS;AAE/C,4DAA4D;AAC5D,OAAO,MAAME,cAAc,IAAIH,oBAAoB;IACjDI,YAAY;QACVC,MAAMP,UAAUQ,SAAS;QACzBC,MAAM;QACNC,UAAU;QACV,2CAA2C;QAC3CC,YAAY;QACZC,UAAU;IACZ;IACAT;AACF,GAAE"}

View File

@@ -0,0 +1,20 @@
import "../../server/web/globals";
import { adapter } from "../../server/web/adapter";
import { IncrementalCache } from "../../server/lib/incremental-cache";
// Import the userland code.
// @ts-expect-error - replaced by webpack/turbopack loader
import handler from "VAR_USERLAND";
const page = "VAR_DEFINITION_PAGE";
if (typeof handler !== "function") {
throw new Error(`The Edge Function "pages${page}" must export a \`default\` function`);
}
export default function(opts) {
return adapter({
...opts,
IncrementalCache,
page: "VAR_DEFINITION_PATHNAME",
handler
});
}
//# sourceMappingURL=pages-edge-api.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/pages-edge-api.ts"],"names":["adapter","IncrementalCache","handler","page","Error","opts"],"mappings":"AAAA,OAAO,2BAA0B;AAEjC,SAASA,OAAO,QAAQ,2BAA0B;AAClD,SAASC,gBAAgB,QAAQ,qCAAoC;AAErE,4BAA4B;AAC5B,0DAA0D;AAC1D,OAAOC,aAAa,eAAc;AAElC,MAAMC,OAAO;AAEb,IAAI,OAAOD,YAAY,YAAY;IACjC,MAAM,IAAIE,MACR,CAAC,wBAAwB,EAAED,KAAK,oCAAoC,CAAC;AAEzE;AAEA,eAAe,SACbE,IAAmE;IAEnE,OAAOL,QAAQ;QACb,GAAGK,IAAI;QACPJ;QACAE,MAAM;QACND;IACF;AACF"}

45
node_modules/next/dist/esm/build/templates/pages.js generated vendored Normal file
View File

@@ -0,0 +1,45 @@
// @ts-ignore this need to be imported from next/dist to be external
import * as module from "next/dist/server/future/route-modules/pages/module.compiled";
import { RouteKind } from "../../server/future/route-kind";
import { hoist } from "./helpers";
// Import the app and document modules.
// @ts-expect-error - replaced by webpack/turbopack loader
import Document from "VAR_MODULE_DOCUMENT";
// @ts-expect-error - replaced by webpack/turbopack loader
import App from "VAR_MODULE_APP";
// Import the userland code.
// @ts-expect-error - replaced by webpack/turbopack loader
import * as userland from "VAR_USERLAND";
const PagesRouteModule = module.PagesRouteModule;
// Re-export the component (should be the default export).
export default hoist(userland, "default");
// Re-export methods.
export const getStaticProps = hoist(userland, "getStaticProps");
export const getStaticPaths = hoist(userland, "getStaticPaths");
export const getServerSideProps = hoist(userland, "getServerSideProps");
export const config = hoist(userland, "config");
export const reportWebVitals = hoist(userland, "reportWebVitals");
// Re-export legacy methods.
export const unstable_getStaticProps = hoist(userland, "unstable_getStaticProps");
export const unstable_getStaticPaths = hoist(userland, "unstable_getStaticPaths");
export const unstable_getStaticParams = hoist(userland, "unstable_getStaticParams");
export const unstable_getServerProps = hoist(userland, "unstable_getServerProps");
export const unstable_getServerSideProps = hoist(userland, "unstable_getServerSideProps");
// Create and export the route module that will be consumed.
export const routeModule = new PagesRouteModule({
definition: {
kind: RouteKind.PAGES,
page: "VAR_DEFINITION_PAGE",
pathname: "VAR_DEFINITION_PATHNAME",
// The following aren't used in production.
bundlePath: "",
filename: ""
},
components: {
App,
Document
},
userland
});
//# sourceMappingURL=pages.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/pages.ts"],"names":["module","RouteKind","hoist","Document","App","userland","PagesRouteModule","getStaticProps","getStaticPaths","getServerSideProps","config","reportWebVitals","unstable_getStaticProps","unstable_getStaticPaths","unstable_getStaticParams","unstable_getServerProps","unstable_getServerSideProps","routeModule","definition","kind","PAGES","page","pathname","bundlePath","filename","components"],"mappings":"AAAA,oEAAoE;AACpE,YAAYA,YAAY,8DAA6D;AACrF,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,KAAK,QAAQ,YAAW;AAEjC,uCAAuC;AACvC,0DAA0D;AAC1D,OAAOC,cAAc,sBAAqB;AAC1C,0DAA0D;AAC1D,OAAOC,SAAS,iBAAgB;AAEhC,4BAA4B;AAC5B,0DAA0D;AAC1D,YAAYC,cAAc,eAAc;AAExC,MAAMC,mBACJN,OAAOM,gBAAgB;AAEzB,0DAA0D;AAC1D,eAAeJ,MAAMG,UAAU,WAAU;AAEzC,qBAAqB;AACrB,OAAO,MAAME,iBAAiBL,MAAMG,UAAU,kBAAiB;AAC/D,OAAO,MAAMG,iBAAiBN,MAAMG,UAAU,kBAAiB;AAC/D,OAAO,MAAMI,qBAAqBP,MAAMG,UAAU,sBAAqB;AACvE,OAAO,MAAMK,SAASR,MAAMG,UAAU,UAAS;AAC/C,OAAO,MAAMM,kBAAkBT,MAAMG,UAAU,mBAAkB;AAEjE,4BAA4B;AAC5B,OAAO,MAAMO,0BAA0BV,MACrCG,UACA,2BACD;AACD,OAAO,MAAMQ,0BAA0BX,MACrCG,UACA,2BACD;AACD,OAAO,MAAMS,2BAA2BZ,MACtCG,UACA,4BACD;AACD,OAAO,MAAMU,0BAA0Bb,MACrCG,UACA,2BACD;AACD,OAAO,MAAMW,8BAA8Bd,MACzCG,UACA,+BACD;AAED,4DAA4D;AAC5D,OAAO,MAAMY,cAAc,IAAIX,iBAAiB;IAC9CY,YAAY;QACVC,MAAMlB,UAAUmB,KAAK;QACrBC,MAAM;QACNC,UAAU;QACV,2CAA2C;QAC3CC,YAAY;QACZC,UAAU;IACZ;IACAC,YAAY;QACVrB;QACAD;IACF;IACAE;AACF,GAAE"}

102
node_modules/next/dist/esm/build/type-check.js generated vendored Normal file
View File

@@ -0,0 +1,102 @@
import path from "path";
import * as Log from "./output/log";
import { Worker as JestWorker } from "next/dist/compiled/jest-worker";
import { verifyAndLint } from "../lib/verifyAndLint";
import createSpinner from "./spinner";
import { eventTypeCheckCompleted } from "../telemetry/events";
import isError from "../lib/is-error";
/**
* typescript will be loaded in "next/lib/verifyTypeScriptSetup" and
* then passed to "next/lib/typescript/runTypeCheck" as a parameter.
*
* Since it is impossible to pass a function from main thread to a worker,
* instead of running "next/lib/typescript/runTypeCheck" in a worker,
* we will run entire "next/lib/verifyTypeScriptSetup" in a worker instead.
*/ function verifyTypeScriptSetup(dir, distDir, intentDirs, typeCheckPreflight, tsconfigPath, disableStaticImages, cacheDir, enableWorkerThreads, hasAppDir, hasPagesDir) {
const typeCheckWorker = new JestWorker(require.resolve("../lib/verifyTypeScriptSetup"), {
numWorkers: 1,
enableWorkerThreads,
maxRetries: 0
});
typeCheckWorker.getStdout().pipe(process.stdout);
typeCheckWorker.getStderr().pipe(process.stderr);
return typeCheckWorker.verifyTypeScriptSetup({
dir,
distDir,
intentDirs,
typeCheckPreflight,
tsconfigPath,
disableStaticImages,
cacheDir,
hasAppDir,
hasPagesDir
}).then((result)=>{
typeCheckWorker.end();
return result;
});
}
export async function startTypeChecking({ cacheDir, config, dir, ignoreESLint, nextBuildSpan, pagesDir, runLint, shouldLint, telemetry, appDir }) {
const ignoreTypeScriptErrors = Boolean(config.typescript.ignoreBuildErrors);
const eslintCacheDir = path.join(cacheDir, "eslint/");
if (ignoreTypeScriptErrors) {
Log.info("Skipping validation of types");
}
if (runLint && ignoreESLint) {
// only print log when build require lint while ignoreESLint is enabled
Log.info("Skipping linting");
}
let typeCheckingAndLintingSpinnerPrefixText;
let typeCheckingAndLintingSpinner;
if (!ignoreTypeScriptErrors && shouldLint) {
typeCheckingAndLintingSpinnerPrefixText = "Linting and checking validity of types";
} else if (!ignoreTypeScriptErrors) {
typeCheckingAndLintingSpinnerPrefixText = "Checking validity of types";
} else if (shouldLint) {
typeCheckingAndLintingSpinnerPrefixText = "Linting";
}
// we will not create a spinner if both ignoreTypeScriptErrors and ignoreESLint are
// enabled, but we will still verifying project's tsconfig and dependencies.
if (typeCheckingAndLintingSpinnerPrefixText) {
typeCheckingAndLintingSpinner = createSpinner(typeCheckingAndLintingSpinnerPrefixText);
}
const typeCheckStart = process.hrtime();
try {
const [[verifyResult, typeCheckEnd]] = await Promise.all([
nextBuildSpan.traceChild("verify-typescript-setup").traceAsyncFn(()=>verifyTypeScriptSetup(dir, config.distDir, [
pagesDir,
appDir
].filter(Boolean), !ignoreTypeScriptErrors, config.typescript.tsconfigPath, config.images.disableStaticImages, cacheDir, config.experimental.workerThreads, !!appDir, !!pagesDir).then((resolved)=>{
const checkEnd = process.hrtime(typeCheckStart);
return [
resolved,
checkEnd
];
})),
shouldLint && nextBuildSpan.traceChild("verify-and-lint").traceAsyncFn(async ()=>{
var _config_eslint;
await verifyAndLint(dir, eslintCacheDir, (_config_eslint = config.eslint) == null ? void 0 : _config_eslint.dirs, config.experimental.workerThreads, telemetry);
})
]);
typeCheckingAndLintingSpinner == null ? void 0 : typeCheckingAndLintingSpinner.stopAndPersist();
if (!ignoreTypeScriptErrors && verifyResult) {
var _verifyResult_result, _verifyResult_result1, _verifyResult_result2;
telemetry.record(eventTypeCheckCompleted({
durationInSeconds: typeCheckEnd[0],
typescriptVersion: verifyResult.version,
inputFilesCount: (_verifyResult_result = verifyResult.result) == null ? void 0 : _verifyResult_result.inputFilesCount,
totalFilesCount: (_verifyResult_result1 = verifyResult.result) == null ? void 0 : _verifyResult_result1.totalFilesCount,
incremental: (_verifyResult_result2 = verifyResult.result) == null ? void 0 : _verifyResult_result2.incremental
}));
}
} catch (err) {
// prevent showing jest-worker internal error as it
// isn't helpful for users and clutters output
if (isError(err) && err.message === "Call retries were exceeded") {
await telemetry.flush();
process.exit(1);
}
throw err;
}
}
//# sourceMappingURL=type-check.js.map

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