create project

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

View File

@@ -0,0 +1,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

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,248 @@
import { promises as fs } from "fs";
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";
const CLIENT_MODULE_LABEL = `/* __next_internal_client_entry_do_not_use__ */`;
export function getRSCModuleType(source) {
return source.includes(CLIENT_MODULE_LABEL) ? RSC_MODULE_TYPES.client : RSC_MODULE_TYPES.server;
}
/**
* 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) {
if (Array.isArray(swcAST == null ? void 0 : swcAST.body)) {
try {
let runtime;
let ssr = false;
let ssg = false;
for (const node of swcAST.body){
var ref11, ref1, ref2, ref3;
if (node.type === "ExportDeclaration" && ((ref11 = node.declaration) == null ? void 0 : ref11.type) === "VariableDeclaration") {
var ref4, ref5;
const id = (ref5 = (ref4 = node.declaration) == null ? void 0 : ref4.declarations[0]) == null ? void 0 : ref5.id.value;
if (id === "runtime") {
var ref6, ref7;
runtime = (ref7 = (ref6 = node.declaration) == null ? void 0 : ref6.declarations[0]) == null ? void 0 : ref7.init.value;
}
}
if (node.type === "ExportDeclaration" && ((ref1 = node.declaration) == null ? void 0 : ref1.type) === "FunctionDeclaration" && [
"getStaticProps",
"getServerSideProps"
].includes((ref2 = node.declaration.identifier) == null ? void 0 : ref2.value)) {
ssg = node.declaration.identifier.value === "getStaticProps";
ssr = node.declaration.identifier.value === "getServerSideProps";
}
if (node.type === "ExportDeclaration" && ((ref3 = node.declaration) == null ? void 0 : ref3.type) === "VariableDeclaration") {
var ref8, ref9;
const id = (ref9 = (ref8 = node.declaration) == null ? void 0 : ref8.declarations[0]) == null ? void 0 : ref9.id.value;
if ([
"getStaticProps",
"getServerSideProps"
].includes(id)) {
ssg = id === "getStaticProps";
ssr = id === "getServerSideProps";
}
}
if (node.type === "ExportNamedDeclaration") {
const values = node.specifiers.map((specifier)=>{
var ref, ref10;
return specifier.type === "ExportSpecifier" && ((ref = specifier.orig) == null ? void 0 : ref.type) === "Identifier" && ((ref10 = specifier.orig) == null ? void 0 : ref10.value);
});
ssg = values.some((value)=>[
"getStaticProps"
].includes(value));
ssr = values.some((value)=>[
"getServerSideProps"
].includes(value));
}
}
return {
ssr,
ssg,
runtime
};
} catch (err) {}
}
return {
ssg: false,
ssr: false
};
}
async function tryToReadFile(filePath, shouldThrow) {
try {
return await fs.readFile(filePath, {
encoding: "utf8"
});
} catch (error) {
if (shouldThrow) {
throw error;
}
}
}
function getMiddlewareMatchers(matcherOrMatchers, nextConfig) {
let matchers = [];
if (Array.isArray(matcherOrMatchers)) {
matchers = matcherOrMatchers;
} else {
matchers.push(matcherOrMatchers);
}
const { i18n } = nextConfig;
let routes = matchers.map((m)=>typeof m === "string" ? {
source: m
} : m);
// 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([^/.]{1,})${isRoot ? "" : source}`;
}
source = `/:nextData(_next/data/[^/]{1,})?${source}${isRoot ? `(${nextConfig.i18n ? "|\\.json|" : ""}/?index|/?index\\.json)?` : "(.json)?"}`;
if (nextConfig.basePath) {
source = `${nextConfig.basePath}${source}`;
}
return {
...r,
source
};
});
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}`);
}
return {
...rest,
regexp: parsedPage.regexStr
};
});
}
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;
}
let warnedAboutExperimentalEdge = false;
function warnAboutExperimentalEdge() {
if (warnedAboutExperimentalEdge) {
return;
}
Log.warn(`You are using an experimental edge runtime, the API might change.`);
warnedAboutExperimentalEdge = true;
}
const warnedUnsupportedValueMap = new Map();
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);
}
/**
* 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) {
var ref;
const { isDev , pageFilePath , nextConfig , page , pageType } = params;
const fileContent = await tryToReadFile(pageFilePath, !isDev) || "";
if (/runtime|getStaticProps|getServerSideProps|export const config/.test(fileContent)) {
var ref15;
const swcAST = await parseModule(pageFilePath, fileContent);
const { ssg , ssr , runtime } = checkExports(swcAST);
const rsc = getRSCModuleType(fileContent);
// 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
}
// Currently, we use `export const config = { runtime: '...' }` to specify the page runtime.
// But 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 = runtime || config.runtime;
if (typeof resolvedRuntime !== "undefined" && resolvedRuntime !== SERVER_RUNTIME.nodejs && !isEdgeRuntime(resolvedRuntime)) {
const options = Object.values(SERVER_RUNTIME).join(", ");
if (typeof resolvedRuntime !== "string") {
Log.error(`The \`runtime\` config must be a string. Please leave it empty or choose one of: ${options}`);
} else {
Log.error(`Provided runtime "${resolvedRuntime}" is not supported. Please leave it empty or choose one of: ${options}`);
}
if (!isDev) {
process.exit(1);
}
}
const requiresServerRuntime = ssr || ssg || pageType === "app";
resolvedRuntime = isEdgeRuntime(resolvedRuntime) ? resolvedRuntime : requiresServerRuntime ? resolvedRuntime || ((ref15 = nextConfig.experimental) == null ? void 0 : ref15.runtime) : undefined;
if (resolvedRuntime === SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdge();
}
if (resolvedRuntime === SERVER_RUNTIME.edge && pageType === "pages" && page && !isAPIRoute(page.replace(/^\/pages\//, "/"))) {
const message = `Page ${page} provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.`;
Log.error(message);
if (!isDev) {
process.exit(1);
}
}
const middlewareConfig = getMiddlewareConfig(page ?? "middleware/edge API route", config, nextConfig);
return {
ssr,
ssg,
rsc,
...middlewareConfig && {
middleware: middlewareConfig
},
...resolvedRuntime && {
runtime: resolvedRuntime
}
};
}
return {
ssr: false,
ssg: false,
rsc: RSC_MODULE_TYPES.server,
runtime: (ref = nextConfig.experimental) == null ? void 0 : ref.runtime
};
}
//# 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":["../../../build/analysis/parse-module.ts"],"names":["LRUCache","withPromiseCache","createHash","parse","parseModule","max","filename","content","isModule","catch","_","update","digest"],"mappings":"AAAA,OAAOA,QAAQ,MAAM,8BAA8B,CAAA;AACnD,SAASC,gBAAgB,QAAQ,8BAA8B,CAAA;AAC/D,SAASC,UAAU,QAAQ,QAAQ,CAAA;AACnC,SAASC,KAAK,QAAQ,QAAQ,CAAA;AAE9B;;;GAGG,CACH,OAAO,MAAMC,WAAW,GAAGH,gBAAgB,CACzC,IAAID,QAAQ,CAAc;IAAEK,GAAG,EAAE,GAAG;CAAE,CAAC,EACvC,OAAOC,QAAgB,EAAEC,OAAe,GACtCJ,KAAK,CAACI,OAAO,EAAE;QAAEC,QAAQ,EAAE,SAAS;QAAEF,QAAQ;KAAE,CAAC,CAACG,KAAK,CAAC,IAAM,IAAI,CAAC,EACrE,CAACC,CAAC,EAAEH,OAAO,GAAKL,UAAU,CAAC,MAAM,CAAC,CAACS,MAAM,CAACJ,OAAO,CAAC,CAACK,MAAM,CAAC,KAAK,CAAC,CACjE,CAAA"}

View File

@@ -0,0 +1,219 @@
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 ref;
const { isServer , pagesDir } = loaderOptions;
const isPageFile = filename.startsWith(pagesDir);
const isNextDist = nextDistPath.test(filename);
const hasModuleExports = source.indexOf("module.exports") !== -1;
const fileExt = ((ref = fileExtensionRegex.exec(filename)) == null ? void 0 : ref[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.");
}
/**
* 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;
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 ? 0b0001 : 0) | (isPageFile ? 0b0010 : 0) | (isNextDist ? 0b0100 : 0) | (hasModuleExports ? 0b1000 : 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

View File

@@ -0,0 +1,25 @@
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])=>{
return 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":["../../../../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,SAAS,MAAM,aAAa,CAAA;AAGnC,eAAeC,eAAe,CAE5BC,WAAiB,EACjBC,WAAmB,EACnBC,cAAyC,EACzC;IACA,MAAMC,QAAQ,GAAG,IAAI,CAACC,YAAY;IAClC,MAAMC,MAAM,GAAG,IAAI,CAACA,MAAM;IAC1B,MAAMC,aAAa,GAAGN,WAAW,CAC9BO,UAAU,CAAC,aAAa,CAAC,AAC1B,+DAA+D;KAC9DC,OAAO,CAAC,IAAM,IAAI,CAACC,UAAU,EAAE,CAAC;IAEnC,MAAMC,eAAe,GAAGV,WAAW,CAACO,UAAU,CAAC,4BAA4B,CAAC;IAC5E,MAAM,EAAEI,IAAI,EAAEC,iBAAiB,CAAA,EAAEC,GAAG,EAAEC,eAAe,CAAA,EAAE,GACrDJ,eAAe,CAACF,OAAO,CAAC,IACtBV,SAAS,CAACiB,IAAI,CACZ,IAAI,EACJd,WAAW,EACXC,cAAc,EACdI,aAAa,EACbH,QAAQ,EACRE,MAAM,EACNK,eAAe,CAChB,CACF;IAEH,OAAO;QAACE,iBAAiB;QAAEE,eAAe;KAAC,CAAA;CAC5C;AAED,MAAME,oBAAoB,GAAG,SAASA,oBAAoB,CAExDf,WAAmB,EACnBC,cAAyC,EACzC;IACA,MAAMe,QAAQ,GAAG,IAAI,CAACC,KAAK,EAAE;IAE7B,MAAMC,UAAU,GAAG,IAAI,CAACC,gBAAgB,CAACb,UAAU,CAAC,yBAAyB,CAAC;IAC9EY,UAAU,CACPE,YAAY,CAAC,IACZtB,eAAe,CAACgB,IAAI,CAAC,IAAI,EAAEI,UAAU,EAAElB,WAAW,EAAEC,cAAc,CAAC,CACpE,CACAoB,IAAI,CACH,CAAC,CAACV,iBAAiB,EAAEE,eAAe,CAAM;QACxCG,OAAAA,QAAQ,QAA8D,GAAtEA,KAAAA,CAAsE,GAAtEA,QAAQ,CAAG,IAAI,EAAEL,iBAAiB,EAAEE,eAAe,IAAIZ,cAAc,CAAC,CAAA;KAAA,EACxE,CAACqB,GAAG,GAAK;QACPN,QAAQ,QAAO,GAAfA,KAAAA,CAAe,GAAfA,QAAQ,CAAGM,GAAG,CAAC,CAAA;KAChB,CACF;CACJ;AAED,eAAeP,oBAAoB,CAAA"}

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":["../../../../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;;GAEG,CAEH,OAAOA,QAAQ,MAAM,mCAAmC,CAAA;AACxD,OAAOC,QAAQ,MAAM,oCAAoC,CAAA;AACzD,OAAOC,aAAa,MAAM,kDAAkD,CAAA;AAC5E,OAAOC,aAAa,MAAM,kDAAkD,CAAA;AAC5E,OAAOC,oBAAoB,MAAM,sDAAsD,CAAA;AACvF,OAAOC,UAAU,MAAM,+CAA+C,CAAA;AAEtE,OAAOC,SAAS,MAAM,cAAc,CAAA;AACpC,SAASC,eAAe,QAAQ,QAAQ,CAAA;AAIxC,SAASC,kBAAkB,CAACC,IAAS,EAAEC,WAAkB,EAAE;IACzD,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1B,IAAI,EAAE2B,WAAW,EAAEU,aAAa,CAAC;IAC9CA,aAAa,CAACF,IAAI,EAAE;IAEpB,MAAMG,YAAY,GAAGpB,UAAU,CAACI,UAAU,CAAC,sBAAsB,CAAC;IAClE,MAAM,EAAEiB,IAAI,CAAA,EAAEC,GAAG,CAAA,EAAE,GAAGhD,QAAQ,CAACQ,IAAI,CAACwB,GAAG,EAAExB,IAAI,CAACoB,IAAI,CAACqB,aAAa,EAAEzC,IAAI,CAACuC,IAAI,CAAC;IAC5ED,YAAY,CAACH,IAAI,EAAE;IAEnB,OAAO;QAAEI,IAAI;QAAEC,GAAG;KAAE,CAAA;CACrB,CAAA"}

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
}

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":["../../../../build/babel/loader/util.ts"],"names":["consumeIterator","iter","value","done","next"],"mappings":"AAAA,OAAO,SAASA,eAAe,CAACC,IAAmB,EAAE;IACnD,MAAO,IAAI,CAAE;QACX,MAAM,EAAEC,KAAK,CAAA,EAAEC,IAAI,CAAA,EAAE,GAAGF,IAAI,CAACG,IAAI,EAAE;QACnC,IAAID,IAAI,EAAE;YACR,OAAOD,KAAK,CAAA;SACb;KACF;CACF"}

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":["../../../../build/babel/plugins/amp-attributes.ts"],"names":["AmpAttributePatcher","visitor","JSXOpeningElement","path","openingElement","node","name","attributes","type","startsWith","attribute"],"mappings":"AAEA,eAAe,SAASA,mBAAmB,GAAc;IACvD,OAAO;QACLC,OAAO,EAAE;YACPC,iBAAiB,EAACC,IAAuC,EAAE;gBACzD,MAAMC,cAAc,GAAGD,IAAI,CAACE,IAAI;gBAEhC,MAAM,EAAEC,IAAI,CAAA,EAAEC,UAAU,CAAA,EAAE,GAAGH,cAAc;gBAC3C,IAAI,CAAC,CAACE,IAAI,IAAIA,IAAI,CAACE,IAAI,KAAK,eAAe,CAAC,EAAE;oBAC5C,OAAM;iBACP;gBAED,IAAI,CAACF,IAAI,CAACA,IAAI,CAACG,UAAU,CAAC,MAAM,CAAC,EAAE;oBACjC,OAAM;iBACP;gBAED,KAAK,MAAMC,SAAS,IAAIH,UAAU,CAAE;oBAClC,IAAIG,SAAS,CAACF,IAAI,KAAK,cAAc,EAAE;wBACrC,SAAQ;qBACT;oBAED,IAAIE,SAAS,CAACJ,IAAI,CAACA,IAAI,KAAK,WAAW,EAAE;wBACvCI,SAAS,CAACJ,IAAI,CAACA,IAAI,GAAG,OAAO;qBAC9B;iBACF;aACF;SACF;KACF,CAAA;CACF,CAAA"}

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":["../../../../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,cAAc,MAAM,4DAA4D,CAAA;AAEvF,qCAAqC;AACrC,eAAe,SAASC,oBAAoB,CAAC,GAAGC,IAAI,AAAK,EAAa;IACpE,MAAMC,QAAQ,GAAGH,cAAc,IAAIE,IAAI,CAAC;IACxC,OAAO;QACLE,OAAO,EAAE;YACPC,OAAO,EAAE;gBACPC,IAAI,EAACC,IAA6B,EAAEC,KAAK,EAAE;oBACzC,IAAIC,kBAAkB,GAAG,KAAK;oBAC9BF,IAAI,CAACG,QAAQ,CAAC;wBACZC,gBAAgB,EAACC,cAAmB,EAAE;4BACpC,IAAIA,cAAc,CAACC,IAAI,CAACC,MAAM,CAACC,IAAI,KAAK,QAAQ,EAAE,OAAM;4BACxD,IAAIH,cAAc,CAACC,IAAI,CAACG,QAAQ,CAACD,IAAI,KAAK,SAAS,EAAE,OAAM;4BAC3DN,kBAAkB,GAAG,IAAI;yBAC1B;qBACF,CAAC;oBAEF,IAAI,CAACA,kBAAkB,EAAE;wBACvB,OAAM;qBACP;oBAEDN,QAAQ,CAACC,OAAO,CAACC,OAAO,CAACC,IAAI,CAACW,IAAI,CAAC,IAAI,EAAEV,IAAI,EAAEC,KAAK,CAAC;iBACtD;aACF;SACF;KACF,CAAA;CACF,CAAA"}

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":["../../../../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"],"mappings":"AAKA,OAAOA,GAAG,MAAM,4CAA4C,CAAA;AAE5D,eAAe,SAAU,EACvBC,KAAK,EAAEC,CAAC,CAAA,EAGT,EAAkB;IACjB,OAAO;QACLC,QAAQ,EAAEH,GAAG;QACbI,OAAO,EAAE;YACPC,UAAU,EAACC,KAAK,EAAEC,KAAK,EAAE;gBACvBA,KAAK,CAACC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC;aACvB;YAED,qEAAqE;YACrE,sCAAsC;YACtCC,WAAW,EAACH,KAAK,EAAEC,KAAK,EAAE;gBACxBA,KAAK,CAACC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC;aACvB;YAEDE,OAAO,EAAE;gBACPC,IAAI,EAACC,IAAkC,EAAEL,KAAK,EAAE;oBAC9C,IAAIA,KAAK,CAACM,GAAG,CAAC,KAAK,CAAC,EAAE;wBACpB,MAAMC,MAAM,GAAGZ,CAAC,CAACa,UAAU,CAACR,KAAK,CAACS,IAAI,CAACF,MAAM,CAAC;wBAC9C,IAAIG,QAAQ,GAAGH,MAAM;wBAErB,4EAA4E;wBAC5E,MAAMI,eAAe,GACnBX,KAAK,CAACS,IAAI,CAACG,WAAW,KAAK,KAAK,IAChCZ,KAAK,CAACS,IAAI,CAACC,QAAQ,IACnBL,IAAI,CAACQ,KAAK,CAACC,UAAU,CAACd,KAAK,CAACS,IAAI,CAACC,QAAQ,CAAC;wBAE5C,oCAAoC;wBACpC,IAAIV,KAAK,CAACS,IAAI,CAACM,QAAQ,EAAE;4BACvB,IAAIf,KAAK,CAACS,IAAI,CAACC,QAAQ,EAAE;gCACvBA,QAAQ,GAAGf,CAAC,CAACa,UAAU,CAACR,KAAK,CAACS,IAAI,CAACC,QAAQ,CAAC;6BAC7C,MAAM;gCACLA,QAAQ,GAAGL,IAAI,CAACQ,KAAK,CAACG,qBAAqB,CAAC,QAAQ,CAAC;6BACtD;4BAED,MAAM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C,CAACa,UAAU,CAACR,KAAK,CAACS,IAAI,CAAC4B,MAAM,CAAC,CAChC,GACDrC,KAAK,CAACS,IAAI,CAAC6B,eAAe,GAC1B3C,CAAC,CAAC4C,wBAAwB,CAAC7B,QAAQ,CAAC,GAEpCf,CAAC,CAAC6C,sBAAsB,CAAC9B,QAAQ,CAAC;6BACvC,EACDf,CAAC,CAAC8C,aAAa,CAACzC,KAAK,CAACS,IAAI,CAACiC,MAAM,IAAI,OAAO,CAAC,CAC9C;4BAED,MAAM,CAACrB,OAAO,CAAC,GAAGhB,IAAI,CAAC0B,gBAAgB,CAAC,MAAM,EAAEI,eAAe,CAAC;4BAChE,KAAK,MAAMQ,SAAS,IAAItB,OAAO,CAACf,GAAG,CAAC,YAAY,CAAC,CAAE;gCACjDD,IAAI,CAACQ,KAAK,CAACoB,eAAe,CACxB,QAAQ,EACRU,SAAS,CACV;6BACF;yBACF;qBACF;iBACF;aACF;SACF;KACF,CAAA;CACF,CAAA"}

View File

@@ -0,0 +1,20 @@
export default function NextPageDisallowReExportAllExports() {
return {
visitor: {
ImportDeclaration (path) {
if ([
"@next/font/local",
"@next/font/google"
].includes(path.node.source.value)) {
var ref, ref1;
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 = (((ref = path.node.loc) == null ? void 0 : ref.start) ?? ((ref1 = path.node.loc) == null ? void 0 : ref1.end)) ?? path.node.loc;
throw err;
}
}
}
};
};
//# sourceMappingURL=next-font-unsupported.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../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,kCAAkC,GAAmB;IAC3E,OAAO;QACLC,OAAO,EAAE;YACPC,iBAAiB,EAACC,IAAuC,EAAE;gBACzD,IACE;oBAAC,kBAAkB;oBAAE,mBAAmB;iBAAC,CAACC,QAAQ,CAChDD,IAAI,CAACE,IAAI,CAACC,MAAM,CAACC,KAAK,CACvB,EACD;wBAMEJ,GAAa,EAAWA,IAAa;oBALvC,MAAMK,GAAG,GAAG,IAAIC,WAAW,CACzB,CAAC,0KAA0K,CAAC,CAC7K,AACA;oBAAA,AAACD,GAAG,CAASE,IAAI,GAAG,mBAAmB,CACvC;oBAAA,AAACF,GAAG,CAASG,GAAG,GACfR,CAAAA,CAAAA,CAAAA,GAAa,GAAbA,IAAI,CAACE,IAAI,CAACM,GAAG,SAAO,GAApBR,KAAAA,CAAoB,GAApBA,GAAa,CAAES,KAAK,CAAA,IAAIT,CAAAA,CAAAA,IAAa,GAAbA,IAAI,CAACE,IAAI,CAACM,GAAG,SAAK,GAAlBR,KAAAA,CAAkB,GAAlBA,IAAa,CAAEU,GAAG,CAAA,CAAA,IAAIV,IAAI,CAACE,IAAI,CAACM,GAAG;oBAC7D,MAAMH,GAAG,CAAA;iBACV;aACF;SACF;KACF,CAAA;CACF,CAAA"}

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 ref;
if (BabelTypes.isExportNamedDeclaration(exportPath) && ((ref = exportPath.node.specifiers) == null ? void 0 : ref.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 ref, ref1;
if (exportState.bundleDropped || !exportPath.node.declaration && exportPath.node.specifiers.length === 0) {
return;
}
const config = {};
const declarations = [
...((ref = exportPath.node.declaration) == null ? void 0 : ref.declarations) || [],
(ref1 = exportPath.scope.getBinding(CONFIG_KEY)) == null ? void 0 : ref1.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 ref2;
if (BabelTypes.isImportSpecifier((ref2 = exportPath.scope.getBinding(specifier.local.name)) == null ? void 0 : ref2.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 ref3, ref4;
if (!((ref3 = exportState.file) == null ? void 0 : (ref4 = ref3.opts) == null ? void 0 : ref4.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

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
export default function NextPageDisallowReExportAllExports() {
return {
visitor: {
ExportAllDeclaration (path) {
var ref, ref1;
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 = (((ref = path.node.loc) == null ? void 0 : ref.start) ?? ((ref1 = path.node.loc) == null ? void 0 : ref1.end)) ?? path.node.loc;
throw err;
}
}
};
};
//# sourceMappingURL=next-page-disallow-re-export-all-exports.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../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,kCAAkC,GAAmB;IAC3E,OAAO;QACLC,OAAO,EAAE;YACPC,oBAAoB,EAACC,IAA0C,EAAE;oBAO7DA,GAAa,EAAWA,IAAa;gBANvC,MAAMC,GAAG,GAAG,IAAIC,WAAW,CACzB,CAAC,8GAA8G,CAAC,GAC9G,CAAC,8DAA8D,CAAC,CACnE,AACA;gBAAA,AAACD,GAAG,CAASE,IAAI,GAAG,mBAAmB,CACvC;gBAAA,AAACF,GAAG,CAASG,GAAG,GACfJ,CAAAA,CAAAA,CAAAA,GAAa,GAAbA,IAAI,CAACK,IAAI,CAACD,GAAG,SAAO,GAApBJ,KAAAA,CAAoB,GAApBA,GAAa,CAAEM,KAAK,CAAA,IAAIN,CAAAA,CAAAA,IAAa,GAAbA,IAAI,CAACK,IAAI,CAACD,GAAG,SAAK,GAAlBJ,KAAAA,CAAkB,GAAlBA,IAAa,CAAEO,GAAG,CAAA,CAAA,IAAIP,IAAI,CAACK,IAAI,CAACD,GAAG;gBAC7D,MAAMH,GAAG,CAAA;aACV;SACF;KACF,CAAA;CACF,CAAA"}

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 ref, ref1;
let local;
if (((ref = e.node) == null ? void 0 : ref.type) === "Identifier") {
local = e;
} else if (((ref1 = e.node) == null ? void 0 : ref1.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 ref, ref2;
let local;
if (((ref = e.node) == null ? void 0 : ref.type) === "Identifier") {
local = e;
} else if (((ref2 = e.node) == null ? void 0 : ref2.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":["../../../../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,MAAM,cAAc;AAE1B,sDAAsD;AACtD,MAAMC,aAAa,mGAC+E;AAElG,eAAe,SAAU,EACvBC,KAAK,EAAEC,CAAC,CAAA,EAGT,EAAkB;IACjB,MAAMC,OAAO,GAAG;QACdC,cAAc,EAAC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AAI,CAACQ,MAAM,CAACE,EAAE,CAACe,QAAQ,CAACC,MAAM,CAC5B,CAACC,QAAQ,EAAEC,OAAO,EAAEC,CAAC,GAAK;gBACxB,IAAID,OAAO,KAAK,IAAI,EAAE;oBACpB,OAAOD,QAAQ,CAAA;iBAChB;gBAED,OAAOA,QAAQ,CAACrB,MAAM,CACpBT,CAAC,CAACiC,cAAc,CAACjC,CAAC,CAACkC,cAAc,CAACF,CAAC,CAAC,EAAED,OAAO,CAAC,CAC/C,CAAA;aACF,EACD,EAAE,CACH,CACF;SACF;KACF;IAED,OAAO;QACLd,IAAI,EAAE,6BAA6B;QACnChB,OAAO,EAAE;YACP,kFAAkF;YAClFkC,OAAO,EAAChC,IAAI,EAAEC,KAAK,EAAE;gBACnBD,IAAI,CAACiC,QAAQ,CAACnC,OAAO,EAAEG,KAAK,CAAC;aAC9B;SACF;KACF,CAAA;CACF,CAAA"}

View File

@@ -0,0 +1,105 @@
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 ref2, ref1;
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 = [];
loader.traverse({
Import (importPath) {
var ref;
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((((ref = state.file.opts.caller) == null ? void 0 : ref.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(((ref2 = state.file.opts.caller) == null ? void 0 : ref2.isDev) || ((ref1 = state.file.opts.caller) == null ? void 0 : ref1.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

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,154 @@
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 ref, ref1;
const supportsESM = api.caller(supportsStaticESM);
const isServer = api.caller((caller)=>!!caller && caller.isServer);
const isCallerDevelopment = api.caller((caller)=>{
return 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 = ((ref = options["preset-react"]) == null ? void 0 : ref.runtime) === "automatic" || Boolean(api.caller((caller)=>!!caller && caller.hasJsxRuntime)) && ((ref1 = options["preset-react"]) == null ? void 0 : ref1.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

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,58 @@
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 }) {
return new Promise((resolve, reject)=>{
const compiler = webpack(config);
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
});
}
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);
});
});
});
}
//# sourceMappingURL=compiler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../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","run","stats","webpackCloseSpan","traceChild","name","traceAsyncFn","then","reason","stack","toString","message","details","Error","traceFn"],"mappings":"AAAA,SAASA,OAAO,QAAQ,oCAAoC,CAAA;AAS5D,SAASC,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AC,CAC3Ce,IAAI,CAAC,IAAM;gBACV,IAAIV,GAAG,EAAE;oBACP,MAAMW,MAAM,GAAGX,GAAG,CAACY,KAAK,IAAIZ,GAAG,CAACa,QAAQ,EAAE;oBAC1C,IAAIF,MAAM,EAAE;wBACV,OAAOd,OAAO,CAAC;4BACbV,MAAM,EAAE;gCAAC;oCAAE2B,OAAO,EAAEH,MAAM;oCAAEI,OAAO,EAAE,AAACf,GAAG,CAASe,OAAO;iCAAE;6BAAC;4BAC5D3B,QAAQ,EAAE,EAAE;4BACZiB,KAAK;yBACN,CAAC,CAAA;qBACH;oBACD,OAAOP,MAAM,CAACE,GAAG,CAAC,CAAA;iBACnB,MAAM,IAAI,CAACK,KAAK,EAAE,MAAM,IAAIW,KAAK,CAAC,uBAAuB,CAAC,CAAA;gBAE3D,MAAM/B,MAAM,GAAGqB,gBAAgB,CAC5BC,UAAU,CAAC,8BAA8B,CAAC,CAC1CU,OAAO,CAAC,IACPjC,aAAa,CAAC;wBAAEG,MAAM,EAAE,EAAE;wBAAEC,QAAQ,EAAE,EAAE;wBAAEiB,KAAK;qBAAE,EAAEA,KAAK,CAAC,CAC1D;gBACH,OAAOR,OAAO,CAACZ,MAAM,CAAC,CAAA;aACvB,CAAC;SACL,CAAC;KACH,CAAC,CAAA;CACH"}

View File

@@ -0,0 +1,3 @@
module.exports = require("next/dist/compiled/cssnano-simple")(require("postcss"));
//# sourceMappingURL=cssnano-simple.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../build/cssnano-simple.js"],"names":["module","exports","require"],"mappings":"AAAAA,MAAM,CAACC,OAAO,GAAGC,OAAO,CAAC,mCAAmC,CAAC,CAC3DA,OAAO,CAAC,SAAS,CAAC,CACnB"}

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

@@ -0,0 +1,352 @@
import chalk from "next/dist/compiled/chalk";
import { posix, join } from "path";
import { stringify } from "querystring";
import { PAGES_DIR_ALIAS, ROOT_DIR_ALIAS, APP_DIR_ALIAS, WEBPACK_LAYERS } 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, NestedMiddlewareError } 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";
/**
* 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 createPagesMapping({ isDev , pageExtensions , pagePaths , pagesType , pagesDir }) {
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;
}
const pageKey = getPageFromPath(pagePath, pageExtensions);
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;
}
result[pageKey] = normalizePathSep(join(pagesType === "pages" ? PAGES_DIR_ALIAS : pagesType === "app" ? APP_DIR_ALIAS : ROOT_DIR_ALIAS, pagePath));
return result;
}, {});
if (pagesType !== "pages") {
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 ref;
if (isMiddlewareFile(opts.page)) {
var ref1;
const loaderParams = {
absolutePagePath: opts.absolutePagePath,
page: opts.page,
rootDir: opts.rootDir,
matchers: ((ref1 = opts.middleware) == null ? void 0 : ref1.matchers) ? encodeMatchers(opts.middleware.matchers) : ""
};
return `next-middleware-loader?${stringify(loaderParams)}!`;
}
if (isAPIRoute(opts.page)) {
const loaderParams = {
absolutePagePath: opts.absolutePagePath,
page: opts.page,
rootDir: opts.rootDir
};
return `next-edge-function-loader?${stringify(loaderParams)}!`;
}
const loaderParams = {
absolute500Path: opts.pages["/500"] || "",
absoluteAppPath: opts.pages["/_app"],
absoluteDocumentPath: opts.pages["/_document"],
absoluteErrorPath: opts.pages["/_error"],
absolutePagePath: opts.absolutePagePath,
buildId: opts.buildId,
dev: opts.isDev,
isServerComponent: opts.isServerComponent,
page: opts.page,
stringifiedConfig: JSON.stringify(opts.config),
pagesType: opts.pagesType,
appDirLoader: Buffer.from(opts.appDirLoader || "").toString("base64"),
sriEnabled: !opts.isDev && !!((ref = opts.config.experimental.sri) == null ? void 0 : ref.algorithm),
hasFontLoaders: !!opts.config.experimental.fontLoaders
};
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.client : undefined
};
}
export function getAppEntry(opts) {
return {
import: `next-app-loader?${stringify(opts)}!`,
layer: WEBPACK_LAYERS.server
};
}
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 async function runDependingOnPageType(params) {
if (isMiddlewareFile(params.page)) {
await params.onEdgeServer();
return;
}
if (isAPIRoute(params.page)) {
if (isEdgeRuntime(params.pageRuntime)) {
await params.onEdgeServer();
return;
}
await params.onServer();
return;
}
if (params.page === "/_document") {
await params.onServer();
return;
}
if (params.page === "/_app" || params.page === "/_error" || params.page === "/404" || params.page === "/500") {
await Promise.all([
params.onClient(),
params.onServer()
]);
return;
}
if (isEdgeRuntime(params.pageRuntime)) {
await Promise.all([
params.onClient(),
params.onEdgeServer()
]);
return;
}
await Promise.all([
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 = {};
const nestedMiddleware = [];
let middlewareMatchers = undefined;
let appPathsPerRoute = {};
if (appDir && appPaths) {
for(const pathname in appPaths){
const normalizedPath = normalizeAppPath(pathname) || "/";
if (!appPathsPerRoute[normalizedPath]) {
appPathsPerRoute[normalizedPath] = [];
}
appPathsPerRoute[normalizedPath].push(pathname);
}
// 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)=>{
return 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 = (()=>{
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);
})();
/**
* When we find a middleware file that is not in the ROOT_DIR we fail.
* There is no need to check on `dev` as this should only happen when
* building for production.
*/ if (!absolutePagePath.startsWith(ROOT_DIR_ALIAS) && /[\\\\/]_middleware$/.test(page)) {
nestedMiddleware.push(page);
}
const isInsideAppDir = !!appDir && (absolutePagePath.startsWith(APP_DIR_ALIAS) || absolutePagePath.startsWith(appDir));
const staticInfo = await getPageStaticInfo({
nextConfig: config,
pageFilePath,
isDev,
page,
pageType: isInsideAppDir ? "app" : "pages"
});
const isServerComponent = isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client;
if (isMiddlewareFile(page)) {
var ref;
middlewareMatchers = ((ref = staticInfo.middleware) == null ? void 0 : ref.matchers) ?? [
{
regexp: ".*"
},
];
}
await runDependingOnPageType({
page,
pageRuntime: staticInfo.runtime,
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: mappings[page],
page
});
}
},
onServer: ()=>{
if (pagesType === "app" && appDir) {
const matchedAppPaths = appPathsPerRoute[normalizeAppPath(page) || "/"];
server[serverBundlePath] = getAppEntry({
name: serverBundlePath,
pagePath: mappings[page],
appDir,
appPaths: matchedAppPaths,
pageExtensions
});
} else {
server[serverBundlePath] = [
mappings[page]
];
}
},
onEdgeServer: ()=>{
let appDirLoader = "";
if (pagesType === "app") {
const matchedAppPaths = appPathsPerRoute[normalizeAppPath(page) || "/"];
appDirLoader = getAppEntry({
name: serverBundlePath,
pagePath: mappings[page],
appDir: appDir,
appPaths: matchedAppPaths,
pageExtensions
}).import;
}
edgeServer[serverBundlePath] = getEdgeServerEntry({
...params,
rootDir,
absolutePagePath: mappings[page],
bundlePath: clientBundlePath,
isDev: false,
isServerComponent,
page,
middleware: staticInfo == null ? void 0 : staticInfo.middleware,
pagesType,
appDirLoader
});
}
});
};
};
if (appDir && appPaths) {
const entryHandler = getEntryHandler(appPaths, "app");
await Promise.all(Object.keys(appPaths).map(entryHandler));
}
if (rootPaths) {
await Promise.all(Object.keys(rootPaths).map(getEntryHandler(rootPaths, "root")));
}
await Promise.all(Object.keys(pages).map(getEntryHandler(pages, "pages")));
if (nestedMiddleware.length > 0) {
throw new NestedMiddlewareError(nestedMiddleware, rootDir, appDir || pagesDir);
}
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/");
if (compilerType === COMPILER_NAMES.server) {
return {
publicPath: isApi ? "" : undefined,
runtime: isApi ? "webpack-api-runtime" : "webpack-runtime",
layer: isApi ? WEBPACK_LAYERS.api : isServerComponent ? WEBPACK_LAYERS.server : undefined,
...entry
};
}
if (compilerType === 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
};
}
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.appClient,
...entry
};
}
return {
dependOn: name.startsWith("pages/") && name !== "pages/_app" ? "pages/_app" : CLIENT_STATIC_FILES_RUNTIME_MAIN,
...entry
};
}
if (isAppLayer) {
return {
layer: WEBPACK_LAYERS.appClient,
...entry
};
}
return entry;
}
//# sourceMappingURL=entries.js.map

File diff suppressed because one or more lines are too long

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":["../../build/generate-build-id.ts"],"names":["generateBuildId","generate","fallback","buildId","test","Error","trim"],"mappings":"AAAA,OAAO,eAAeA,eAAe,CACnCC,QAAsD,EACtDC,QAAsB,EACL;IACjB,IAAIC,OAAO,GAAG,MAAMF,QAAQ,EAAE;IAC9B,gDAAgD;IAChD,IAAIE,OAAO,KAAK,IAAI,EAAE;QACpB,2EAA2E;QAC3E,6BAA6B;QAC7B,MAAO,CAACA,OAAO,IAAI,MAAMC,IAAI,CAACD,OAAO,CAAC,CAAE;YACtCA,OAAO,GAAGD,QAAQ,EAAE;SACrB;KACF;IAED,IAAI,OAAOC,OAAO,KAAK,QAAQ,EAAE;QAC/B,MAAM,IAAIE,KAAK,CACb,wGAAwG,CACzG,CAAA;KACF;IAED,OAAOF,OAAO,CAACG,IAAI,EAAE,CAAA;CACtB"}

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

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../build/is-writeable.ts"],"names":["fs","isWriteable","directory","promises","access","constants","W_OK","err"],"mappings":"AAAA,OAAOA,EAAE,MAAM,IAAI,CAAA;AAEnB,OAAO,eAAeC,WAAW,CAACC,SAAiB,EAAoB;IACrE,IAAI;QACF,MAAMF,EAAE,CAACG,QAAQ,CAACC,MAAM,CAACF,SAAS,EAAE,CAACF,EAAE,CAACK,SAAS,IAAIL,EAAE,CAAC,CAACM,IAAI,CAAC;QAC9D,OAAO,IAAI,CAAA;KACZ,CAAC,OAAOC,GAAG,EAAE;QACZ,OAAO,KAAK,CAAA;KACb;CACF"}

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 ref;
if ((ref = jsConfig.compilerOptions) == null ? void 0 : ref.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":["../../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,IAAI,MAAM,MAAM,CAAA;AACvB,SAASC,UAAU,QAAQ,oBAAo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C,UAAU,CAACqD,YAAY,CAAC,AAAC,EAAE;QACtDT,QAAQ,GAAGrC,aAAa,CAAC8C,YAAY,CAAC;QACtCV,eAAe,GAAG5C,IAAI,CAACqD,OAAO,CAACC,YAAY,CAAC;KAC7C;IAED,IAAIC,eAAe;IACnB,IAAIV,QAAQ,EAAE;YACRA,GAAwB;QAA5B,IAAIA,CAAAA,GAAwB,GAAxBA,QAAQ,CAACM,eAAe,SAAS,GAAjCN,KAAAA,CAAiC,GAAjCA,GAAwB,CAAEW,OAAO,EAAE;YACrCD,eAAe,GAAGvD,IAAI,CAACiD,OAAO,CAACrB,GAAG,EAAEiB,QAAQ,CAACM,eAAe,CAACK,OAAO,CAAC;SACtE,MAAM;YACLD,eAAe,GAAGX,eAAe;SAClC;KACF;IAED,OAAO;QACLF,aAAa;QACbG,QAAQ;QACRU,eAAe;KAChB,CAAA;CACF,CAAA"}

View File

@@ -0,0 +1,243 @@
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 page1 in amp){
let { errors , warnings } = amp[page1];
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(page1, errors[0]);
for(let index = 1; index < errors.length; ++index){
ampError("", errors[index]);
}
}
if (warnings.length) {
ampWarn(errors.length ? "" : page1, 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();
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,
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,
partial: clientWasLoading && (serverWasLoading || edgeServerWasLoading) ? "client and server" : undefined,
modules: (clientWasLoading ? client.modules : 0) + (serverWasLoading ? server.modules : 0) + (edgeServerWasLoading ? (edgeServer == null ? void 0 : edgeServer.modules) || 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,
modules: 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) {
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) {
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) {
buildStore.setState({
edgeServer: status,
trigger: undefined
});
} else {
buildStore.setState({
edgeServer: status
});
}
});
}
export function reportTrigger(trigger) {
buildStore.setState({
trigger
});
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,33 @@
import chalk from "../../lib/chalk";
export const prefixes = {
wait: chalk.cyan("wait") + " -",
error: chalk.red("error") + " -",
warn: chalk.yellow("warn") + " -",
ready: chalk.green("ready") + " -",
info: chalk.cyan("info") + " -",
event: chalk.magenta("event") + " -",
trace: chalk.magenta("trace") + " -"
};
export function wait(...message) {
console.log(prefixes.wait, ...message);
}
export function error(...message) {
console.error(prefixes.error, ...message);
}
export function warn(...message) {
console.warn(prefixes.warn, ...message);
}
export function ready(...message) {
console.log(prefixes.ready, ...message);
}
export function info(...message) {
console.log(prefixes.info, ...message);
}
export function event(...message) {
console.log(prefixes.event, ...message);
}
export function trace(...message) {
console.log(prefixes.trace, ...message);
}
//# sourceMappingURL=log.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../build/output/log.ts"],"names":["chalk","prefixes","wait","cyan","error","red","warn","yellow","ready","green","info","event","magenta","trace","message","console","log"],"mappings":"AAAA,OAAOA,KAAK,MAAM,iBAAiB,CAAA;AAEnC,OAAO,MAAMC,QAAQ,GAAG;IACtBC,IAAI,EAAEF,KAAK,CAACG,IAAI,CAAC,MAAM,CAAC,GAAG,KAAK;IAChCC,KAAK,EAAEJ,KAAK,CAACK,GAAG,CAAC,OAAO,CAAC,GAAG,IAAI;IAChCC,IAAI,EAAEN,KAAK,CAACO,MAAM,CAAC,MAAM,CAAC,GAAG,KAAK;IAClCC,KAAK,EAAER,KAAK,CAACS,KAAK,CAAC,OAAO,CAAC,GAAG,IAAI;IAClCC,IAAI,EAAEV,KAAK,CAACG,IAAI,CAAC,MAAM,CAAC,GAAG,KAAK;IAChCQ,KAAK,EAAEX,KAAK,CAACY,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI;IACpCC,KAAK,EAAEb,KAAK,CAACY,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI;CACrC,CAAA;AAED,OAAO,SAASV,IAAI,CAAC,GAAGY,OAAO,AAAO,EAAE;IACtCC,OAAO,CAACC,GAAG,CAACf,QAAQ,CAACC,IAAI,KAAKY,OAAO,CAAC;CACvC;AAED,OAAO,SAASV,KAAK,CAAC,GAAGU,OAAO,AAAO,EAAE;IACvCC,OAAO,CAACX,KAAK,CAACH,QAAQ,CAACG,KAAK,KAAKU,OAAO,CAAC;CAC1C;AAED,OAAO,SAASR,IAAI,CAAC,GAAGQ,OAAO,AAAO,EAAE;IACtCC,OAAO,CAACT,IAAI,CAACL,QAAQ,CAACK,IAAI,KAAKQ,OAAO,CAAC;CACxC;AAED,OAAO,SAASN,KAAK,CAAC,GAAGM,OAAO,AAAO,EAAE;IACvCC,OAAO,CAACC,GAAG,CAACf,QAAQ,CAACO,KAAK,KAAKM,OAAO,CAAC;CACxC;AAED,OAAO,SAASJ,IAAI,CAAC,GAAGI,OAAO,AAAO,EAAE;IACtCC,OAAO,CAACC,GAAG,CAACf,QAAQ,CAACS,IAAI,KAAKI,OAAO,CAAC;CACvC;AAED,OAAO,SAASH,KAAK,CAAC,GAAGG,OAAO,AAAO,EAAE;IACvCC,OAAO,CAACC,GAAG,CAACf,QAAQ,CAACU,KAAK,KAAKG,OAAO,CAAC;CACxC;AAED,OAAO,SAASD,KAAK,CAAC,GAAGC,OAAO,AAAO,EAAE;IACvCC,OAAO,CAACC,GAAG,CAACf,QAAQ,CAACY,KAAK,KAAKC,OAAO,CAAC;CACxC"}

View File

@@ -0,0 +1,105 @@
import createStore from "next/dist/compiled/unistore";
import stripAnsi from "next/dist/compiled/strip-ansi";
import { flushAllTraces } from "../../trace";
import { teardownCrashReporter, teardownTraceSubscriber } from "../swc";
import * as Log from "./log";
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;
store.subscribe((state)=>{
if (!hasStoreChanged(state)) {
return;
}
if (state.bootstrap) {
if (state.appUrl) {
Log.ready(`started server on ${state.bindAddr}, url: ${state.appUrl}`);
}
return;
}
if (state.loading) {
if (state.trigger) {
if (state.trigger !== "initial") {
Log.wait(`compiling ${state.trigger}...`);
}
} else {
Log.wait("compiling...");
}
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();
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.modules) {
modulesMessage = ` (${state.modules} modules)`;
}
let partialMessage = "";
if (state.partial) {
partialMessage = ` ${state.partial}`;
}
if (state.warnings) {
Log.warn(state.warnings.join("\n\n"));
// Ensure traces are flushed after each compile in development mode
flushAllTraces();
teardownTraceSubscriber();
teardownCrashReporter();
return;
}
if (state.typeChecking) {
Log.info(`bundled${partialMessage} successfully${timeMessage}${modulesMessage}, waiting for typecheck results...`);
return;
}
Log.event(`compiled${partialMessage} successfully${timeMessage}${modulesMessage}`);
// Ensure traces are flushed after each compile in development mode
flushAllTraces();
teardownTraceSubscriber();
teardownCrashReporter();
});
//# sourceMappingURL=store.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../build/output/store.ts"],"names":["createStore","stripAnsi","flushAllTraces","teardownCrashReporter","teardownTraceSubscriber","Log","store","appUrl","bindAddr","bootstrap","lastStore","hasStoreChanged","nextStore","Set","Object","keys","every","key","is","startTime","subscribe","state","ready","loading","trigger","wait","Date","now","errors","error","cleanError","indexOf","matches","match","prop","split","shift","slice","console","log","timeMessage","time","Math","round","modulesMessage","modules","partialMessage","partial","warnings","warn","join","typeChecking","info","event"],"mappings":"AAAA,OAAOA,WAAW,MAAM,6BAA6B,CAAA;AACrD,OAAOC,SAAS,MAAM,+BAA+B,CAAA;AACrD,SAASC,cAAc,QAAQ,aAAa,CAAA;AAC5C,SAASC,qBAAqB,EAAEC,uBAAuB,QAAQ,QAAQ,CAAA;AACvE,YAAYC,GAAG,MAAM,OAAO,CAAA;AAoB5B,OAAO,MAAMC,KAAK,GAAGN,WAAW,CAAc;IAC5CO,MAAM,EAAE,IAAI;IACZC,QAAQ,EAAE,IAAI;IACdC,SAAS,EAAE,IAAI;CAChB,CAAC,CAAA;AAEF,IAAIC,SAAS,GAAgB;IAAEH,MAAM,EAAE,IAAI;IAAEC,QAAQ,EAAE,IAAI;IAAEC,SAAS,EAAE,IAAI;CAAE;AAC9E,SAASE,eAAe,CAACC,SAAsB,EAAE;IAC/C,IACE,AACE;WACK,IAAIC,GAAG,CAAC;eAAIC,MAAM,CAACC,IAAI,CAACL,SAAS,CAAC;eAAKI,MAAM,CAACC,IAAI,CAACH,SAAS,CAAC;SAAC,CAAC;KACnE,CACDI,KAAK,CAAC,CAACC,GAAG,GAAKH,MAAM,CAACI,EAAE,CAACR,SAAS,CAACO,GAAG,CAAC,EAAEL,SAAS,CAACK,GAAG,CAAC,CAAC,CAAC,EAC3D;QACA,OAAO,KAAK,CAAA;KACb;IAEDP,SAAS,GAAGE,SAAS;IACrB,OAAO,IAAI,CAAA;CACZ;AAED,IAAIO,SAAS,GAAG,CAAC;AAEjBb,KAAK,CAACc,SAAS,CAAC,CAACC,KAAK,GAAK;IACzB,IAAI,CAACV,eAAe,CAACU,KAAK,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C,CAAC,CACzG;QACD,OAAM;KACP;IAEDvC,GAAG,CAACgD,KAAK,CACP,CAAC,QAAQ,EAAEP,cAAc,CAAC,aAAa,EAAEN,WAAW,CAAC,EAAEI,cAAc,CAAC,CAAC,CACxE;IACD,mEAAmE;IACnE1C,cAAc,EAAE;IAChBE,uBAAuB,EAAE;IACzBD,qBAAqB,EAAE;CACxB,CAAC"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/polyfills/fetch/index.js"],"names":["fetch","self","bind","module","exports","default"],"mappings":"AAAA,kBAAkB,CAClB,IAAIA,KAAK,GAAGC,IAAI,CAACD,KAAK,CAACE,IAAI,CAACD,IAAI,CAAC;AACjCE,MAAM,CAACC,OAAO,GAAGJ,KAAK;AACtBG,MAAM,CAACC,OAAO,CAACC,OAAO,GAAGF,MAAM,CAACC,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":["../../../../build/polyfills/fetch/whatwg-fetch.js"],"names":["exports","Headers","self","Request","Response","fetch"],"mappings":"AAAA,kBAAkB,CAClBA,OAAO,CAACC,OAAO,GAAGC,IAAI,CAACD,OAAO;AAC9BD,OAAO,CAACG,OAAO,GAAGD,IAAI,CAACC,OAAO;AAC9BH,OAAO,CAACI,QAAQ,GAAGF,IAAI,CAACE,QAAQ;AAChCJ,OAAO,CAACK,KAAK,GAAGH,IAAI,CAACG,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":["../../../build/polyfills/object-assign.js"],"names":["assign","Object","bind","module","exports","default"],"mappings":"AAAA,IAAIA,MAAM,GAAGC,MAAM,CAACD,MAAM,CAACE,IAAI,CAACD,MAAM,CAAC;AACvCE,MAAM,CAACC,OAAO,GAAGJ,MAAM;AACvBG,MAAM,CAACC,OAAO,CAACC,OAAO,GAAGF,MAAM,CAACC,OAAO"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"names":[],"mappings":""}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/polyfills/object.assign/implementation.js"],"names":["module","exports","Object","assign"],"mappings":"AAAAA,MAAM,CAACC,OAAO,GAAGC,MAAM,CAACC,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":["../../../../build/polyfills/object.assign/index.js"],"names":["assign","Object","bind","g","defineProperties","implementation","get","shim","value","getPolyfill","module","exports"],"mappings":"AAAA,IAAIA,MAAM,GAAGC,MAAM,CAACD,MAAM,CAACE,IAAI,CAACD,MAAM,CAAC;AACvC,SAASE,CAAC,GAAG;IACX,OAAOH,MAAM,CAAA;CACd;AACDC,MAAM,CAACG,gBAAgB,CAACD,CAAC,EAAE,EAAE;IAC3BE,cAAc,EAAE;QAAEC,GAAG,EAAEH,CAAC;KAAE;IAC1BI,IAAI,EAAE;QAAEC,KAAK,EAAEL,CAAC;KAAE;IAClBM,WAAW,EAAE;QAAED,KAAK,EAAEL,CAAC;KAAE;CAC1B,CAAC;AACFO,MAAM,CAACC,OAAO,GAAGR,CAAC,EAAE"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/polyfills/object.assign/polyfill.js"],"names":["module","exports","Object","assign"],"mappings":"AAAAA,MAAM,CAACC,OAAO,GAAG,WAAY;IAC3B,OAAOC,MAAM,CAACC,MAAM,CAAA;CACrB"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/polyfills/object.assign/shim.js"],"names":["module","exports","Object","assign"],"mappings":"AAAAA,MAAM,CAACC,OAAO,GAAG,WAAY;IAC3B,OAAOC,MAAM,CAACC,MAAM,CAAA;CACrB"}

View File

@@ -0,0 +1,4 @@
var ref, ref1;
module.exports = ((ref = global.process) == null ? void 0 : ref.env) && typeof ((ref1 = global.process) == null ? void 0 : ref1.env) === "object" ? global.process : require("../../compiled/process");
//# sourceMappingURL=process.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../build/polyfills/process.js"],"names":["module","global","exports","process","env","require"],"mappings":"AAAAA,IACEC,GAAc,EAAgBA,IAAc;AAD9CD,MAAM,CAACE,OAAO,GACZD,CAAAA,CAAAA,GAAc,GAAdA,MAAM,CAACE,OAAO,SAAK,GAAnBF,KAAAA,CAAmB,GAAnBA,GAAc,CAAEG,GAAG,CAAA,IAAI,OAAOH,CAAAA,CAAAA,IAAc,GAAdA,MAAM,CAACE,OAAO,SAAK,GAAnBF,KAAAA,CAAmB,GAAnBA,IAAc,CAAEG,GAAG,CAAA,KAAK,QAAQ,GAC1DH,MAAM,CAACE,OAAO,GACdE,OAAO,CAAC,wBAAwB,CAAC"}

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

@@ -0,0 +1,57 @@
import ora from "next/dist/compiled/ora";
const dotsSpinner = {
frames: [
".",
"..",
"..."
],
interval: 200
};
export default function createSpinner(text, options = {}, logFn = console.log) {
let spinner;
let prefixText = text && typeof text === "object" && text.prefixText;
if (process.stdout.isTTY) {
spinner = ora({
text: typeof text === "string" ? text : undefined,
prefixText: typeof prefixText === "string" ? prefixText : undefined,
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 = ()=>{
origStopAndPersist();
resetLog();
return spinner;
};
} else if (prefixText || text) {
logFn(prefixText ? prefixText + "..." : text);
}
return spinner;
};
//# sourceMappingURL=spinner.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../build/spinner.ts"],"names":["ora","dotsSpinner","frames","interval","createSpinner","text","options","logFn","console","log","spinner","prefixText","process","stdout","isTTY","undefined","stream","start","origLog","origWarn","warn","origError","error","origStop","stop","bind","origStopAndPersist","stopAndPersist","logHandle","method","args","resetLog"],"mappings":"AAAA,OAAOA,GAAG,MAAM,wBAAwB,CAAA;AAExC,MAAMC,WAAW,GAAG;IAClBC,MAAM,EAAE;QAAC,GAAG;QAAE,IAAI;QAAE,KAAK;KAAC;IAC1BC,QAAQ,EAAE,GAAG;CACd;AAED,eAAe,SAASC,aAAa,CACnCC,IAAqC,EACrCC,OAAoB,GAAG,EAAE,EACzBC,KAA+B,GAAGC,OAAO,CAACC,GAAG,EAC7C;IACA,IAAIC,OAAO,AAAqB;IAChC,IAAIC,UAAU,GAAGN,IAAI,IAAI,OAAOA,IAAI,KAAK,QAAQ,IAAIA,IAAI,CAACM,UAAU;IAEpE,IAAIC,OAAO,CAACC,MAAM,CAACC,KAA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SAAS;SAC1B;QACDX,OAAO,CAACc,IAAI,GAAG,IAAe;YAC5BD,QAAQ,EAAE;YACVQ,QAAQ,EAAE;YACV,OAAOrB,OAAO,CAAC;SAChB;QACDA,OAAO,CAACiB,cAAc,GAAG,IAAe;YACtCD,kBAAkB,EAAE;YACpBK,QAAQ,EAAE;YACV,OAAOrB,OAAO,CAAC;SAChB;KACF,MAAM,IAAIC,UAAU,IAAIN,IAAI,EAAE;QAC7BE,KAAK,CAACI,UAAU,GAAGA,UAAU,GAAG,KAAK,GAAGN,IAAI,CAAC;KAC9C;IAED,OAAOK,OAAO,CAAA;CACf,CAAA"}

View File

@@ -0,0 +1,13 @@
export function isWasm(): Promise<boolean>
export function transform(src: string, options?: any): Promise<any>
export function transformSync(src: string, options?: any): any
export function minify(src: string, options: any): Promise<string>
export function minifySync(src: string, options: any): string
export function parse(src: string, options: any): any
export const lockfilePatchPromise: { cur?: Promise<void> }
export function initCustomTraceSubscriber(traceFileName?: string): void
export function teardownTraceSubscriber(): void
export function teardownCrashReporter(): void
export function loadBindings(): Promise<void>
export function __isCustomTurbopackBinary(): Promise<boolean>

View File

@@ -0,0 +1,454 @@
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 } from "../../lib/download-wasm-swc";
import { version as nextVersion } from "next/package.json";
const ArchName = arch();
const PlatformName = platform();
const triples = platformArchTriples[PlatformName][ArchName] || [];
// 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 gaurentee.
const __INTERNAL_CUSTOM_TURBOPACK_BINARY = process.env.__INTERNAL_CUSTOM_TURBOPACK_BINARY;
const __INTERNAL_CUSTOM_TURBOPACK_BINDINGS = process.env.__INTERNAL_CUSTOM_TURBOPACK_BINDINGS;
export const __isCustomTurbopackBinary = async ()=>{
if (!!__INTERNAL_CUSTOM_TURBOPACK_BINARY && !!__INTERNAL_CUSTOM_TURBOPACK_BINDINGS) {
throw new Error("Cannot use TURBOPACK_BINARY and TURBOPACK_BINDINGS both");
}
return !!__INTERNAL_CUSTOM_TURBOPACK_BINARY || !!__INTERNAL_CUSTOM_TURBOPACK_BINDINGS;
};
// 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 = [
"aarch64-linux-android",
"x86_64-unknown-freebsd",
"aarch64-pc-windows-msvc",
"arm-linux-androideabi",
"armv7-unknown-linux-gnueabihf",
"i686-pc-windows-msvc",
];
let nativeBindings;
let wasmBindings;
let downloadWasmPromise;
let pendingBindings;
let swcTraceFlushGuard;
let swcCrashReporterFlushGuard;
export const lockfilePatchPromise = {};
export async function loadBindings() {
if (pendingBindings) {
return pendingBindings;
}
const isCustomTurbopack = await __isCustomTurbopackBinary();
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 shouldLoadWasmFallbackFirst = triples.some((triple)=>{
return !!(triple == null ? void 0 : triple.raw) && knownDefaultWasmFallbackTriples.includes(triple.raw);
});
if (shouldLoadWasmFallbackFirst) {
const fallbackBindings = await tryLoadWasmWithFallback(attempts);
if (fallbackBindings) {
return resolve(fallbackBindings);
}
}
try {
return resolve(loadNative(isCustomTurbopack));
} catch (a) {
attempts = attempts.concat(a);
}
// For these platforms we already tried to load wasm and failed, skip reattempt
if (!shouldLoadWasmFallbackFirst) {
const fallbackBindings = await tryLoadWasmWithFallback(attempts);
if (fallbackBindings) {
return resolve(fallbackBindings);
}
}
logLoadFailure(attempts, true);
});
return pendingBindings;
}
async function tryLoadWasmWithFallback(attempts) {
try {
let bindings = await loadWasm();
eventSwcLoadFailure({
wasm: "enabled"
});
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);
eventSwcLoadFailure({
wasm: "fallback"
});
// 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 (a1) {
attempts = attempts.concat(a1);
}
}
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);
}
eventSwcLoadFailure({
wasm: triedWasm ? "failed" : undefined
}).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);
});
}
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();
}
Log.info("Using wasm build of next-swc");
// 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: {
startDev: ()=>{
Log.error("Wasm binding does not support --turbo yet");
},
startTrace: ()=>{
Log.error("Wasm binding does not support trace yet");
}
},
mdx: {
compile: (src, options)=>bindings.mdxCompile(src, options),
compileSync: (src, options)=>bindings.mdxCompileSync(src, 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(isCustomTurbopack = false) {
if (nativeBindings) {
return nativeBindings;
}
let bindings;
let attempts = [];
for (const triple of triples){
try {
bindings = require(`@next/swc/native/next-swc.${triple.platformArchABI}.node`);
Log.info("Using locally built binary of @next/swc");
break;
} catch (e) {}
}
if (!bindings) {
for (const triple of triples){
let pkg = `@next/swc-${triple.platformArchABI}`;
try {
bindings = require(pkg);
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}`);
}
}
}
}
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 ref;
const isModule = typeof src !== undefined && typeof src !== "string" && !Buffer.isBuffer(src);
options = options || {};
if (options == null ? void 0 : (ref = options.jsc) == null ? void 0 : ref.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 ref;
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 : (ref = options.jsc) == null ? void 0 : ref.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,
teardownCrashReporter: bindings.teardownCrashReporter,
turbo: {
startDev: (options)=>{
const devOptions = {
...options,
noOpen: options.noOpen ?? true
};
if (!isCustomTurbopack) {
bindings.startTurboDev(toBuffer(devOptions));
} else if (!!__INTERNAL_CUSTOM_TURBOPACK_BINARY) {
console.warn(`Loading custom turbopack binary from ${__INTERNAL_CUSTOM_TURBOPACK_BINARY}`);
return new Promise((resolve, reject)=>{
const spawn = require("next/dist/compiled/cross-spawn");
const args = [];
Object.entries(devOptions).forEach(([key, value])=>{
let cli_key = `--${key.replace(/[A-Z]/g, (m)=>"-" + m.toLowerCase())}`;
if (key === "dir") {
args.push(value);
} else if (typeof value === "boolean" && value === true) {
args.push(cli_key);
} else if (typeof value !== "boolean" && !!value) {
args.push(cli_key, value);
}
});
console.warn(`Running turbopack with args: [${args.join(" ")}]`);
const child = spawn(__INTERNAL_CUSTOM_TURBOPACK_BINARY, args, {
stdio: "inherit",
env: {
...process.env
}
});
child.on("message", (message)=>{
console.log(message);
});
child.on("close", (code)=>{
if (code !== 0) {
reject({
command: `${__INTERNAL_CUSTOM_TURBOPACK_BINARY} ${args.join(" ")}`
});
return;
}
resolve(0);
});
});
} else if (!!__INTERNAL_CUSTOM_TURBOPACK_BINDINGS) {
console.warn(`Loading custom turbopack bindings from ${__INTERNAL_CUSTOM_TURBOPACK_BINARY}`);
console.warn(`Running turbopack with args: `, devOptions);
require(__INTERNAL_CUSTOM_TURBOPACK_BINDINGS).startDev(devOptions);
}
},
startTrace: (options = {})=>bindings.runTurboTracing(toBuffer({
exact: true,
...options
}))
},
mdx: {
compile: (src, options)=>bindings.mdxCompile(src, toBuffer(options ?? {})),
compileSync: (src, options)=>bindings.mdxCompileSync(src, toBuffer(options ?? {}))
}
};
return nativeBindings;
}
throw attempts;
}
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() {
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 == null ? void 0 : bindings.getTargetTriple()
};
}
/**
* Initialize trace subscriber to emit traces.
*
*/ export const initCustomTraceSubscriber = (()=>{
return (filename)=>{
if (!swcTraceFlushGuard) {
// Wasm binary doesn't support trace emission
let bindings = loadNative();
swcTraceFlushGuard = bindings.initCustomTraceSubscriber(filename);
}
};
})();
/**
* 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

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,63 @@
/*
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;
module.exports = {
createTransformer: (inputOptions)=>({
process (src, filename, jestOptions) {
const jestConfig = getJestConfig(jestOptions);
let swcTransformOpts = getJestSWCOptions({
// When target is node it's similar to the server option set in SWC.
isServer: jestConfig.testEnvironment && jestConfig.testEnvironment === "node",
filename,
nextConfig: inputOptions.nextConfig,
jsConfig: inputOptions.jsConfig,
resolvedBaseUrl: inputOptions.resolvedBaseUrl,
pagesDir: inputOptions.pagesDir,
hasServerComponents: inputOptions.hasServerComponents,
esm: isSupportEsm && isEsm(Boolean(inputOptions.isEsmProject), filename, jestConfig)
});
return transformSync(src, {
...swcTransformOpts,
filename
});
}
})
};
function getJestConfig(jestConfig) {
return "config" in jestConfig ? jestConfig.config : jestConfig;
}
function isEsm(isEsmProject, filename, jestConfig) {
var ref;
return /\.jsx?$/.test(filename) && isEsmProject || ((ref = jestConfig.extensionsToTreatAsEsm) == null ? void 0 : ref.find((ext)=>filename.endsWith(ext)));
}
//# sourceMappingURL=jest-transformer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../build/swc/jest-transformer.js"],"names":["vm","transformSync","getJestSWCOptions","isSupportEsm","module","exports","createTransformer","inputOptions","process","src","filename","jestOptions","jestConfig","getJestConfig","swcTransformOpts","isServer","testEnvironment","nextConfig","jsConfig","resolvedBaseUrl","pagesDir","hasServerComponents","esm","isEsm","Boolean","isEsmProject","config","test","extensionsToTreatAsEsm","find","ext","endsWith"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;EA0BE,CAEF,OAAOA,EAAE,MAAM,IAAI,CAAA;AACnB,SAASC,aAAa,QAAQ,SAAS,CAAA;AACvC,SAASC,iBAAiB,QAAQ,WAAW,CAAA;AAE7C,6FAA6F;AAC7F,mDAAmD;AACnD,MAAMC,YAAY,GAAG,QAAQ,IAAIH,EAAE;AAEnCI,MAAM,CAACC,OAAO,GAAG;IACfC,iBAAiB,EAAE,CAACC,YAAY,GAAK,CAAC;YACpCC,OAAO,EAACC,GAAG,EAAEC,QAAQ,EAAEC,WAAW,EAAE;gBAClC,MAAMC,UAAU,GAAGC,aAAa,CAACF,WAAW,CAAC;gBAE7C,IAAIG,gBAAgB,GAAGZ,iBAAiB,CAAC;oBACvC,oEAAoE;oBACpEa,QAAQ,EACNH,UAAU,CAACI,eAAe,IAAIJ,UAAU,CAACI,eAAe,KAAK,MAAM;oBACrEN,QAAQ;oBACRO,UAAU,EAAEV,YAAY,CAACU,UAAU;oBACnCC,QAAQ,EAAEX,YAAY,CAACW,QAAQ;oBAC/BC,eAAe,EAAEZ,YAAY,CAACY,eAAe;oBAC7CC,QAAQ,EAAEb,YAAY,CAACa,QAAQ;oBAC/BC,mBAAmB,EAAEd,YAAY,CAACc,mBAAmB;oBACrDC,GAAG,EACDnB,YAAY,IACZoB,KAAK,CAACC,OAAO,CAACjB,YAAY,CAACkB,YAAY,CAAC,EAAEf,QAAQ,EAAEE,UAAU,CAAC;iBAClE,CAAC;gBAEF,OAAOX,aAAa,CAACQ,GAAG,EAAE;oBAAE,GAAGK,gBAAgB;oBAAEJ,QAAQ;iBAAE,CAAC,CAAA;aAC7D;SACF,CAAC;CACH;AAED,SAASG,aAAa,CAACD,UAAU,EAAE;IACjC,OAAO,QAAQ,IAAIA,UAAU,GAEzBA,UAAU,CAACc,MAAM,GAEjBd,UAAU,CAAA;CACf;AAED,SAASW,KAAK,CAACE,YAAY,EAAEf,QAAQ,EAAEE,UAAU,EAAE;QAG/CA,GAAiC;IAFnC,OACE,AAAC,UAAUe,IAAI,CAACjB,QAAQ,CAAC,IAAIe,YAAY,KACzCb,CAAAA,GAAiC,GAAjCA,UAAU,CAACgB,sBAAsB,SAAM,GAAvChB,KAAAA,CAAuC,GAAvCA,GAAiC,CAAEiB,IAAI,CAAC,CAACC,GAAG,GAAKpB,QAAQ,CAACqB,QAAQ,CAACD,GAAG,CAAC,CAAC,CAAA,CACzE;CACF"}

View File

@@ -0,0 +1,7 @@
export function getParserOptions(options: {
filename: string
jsConfig?: any
[key: string]: any
}): any
export function getJestSWCOptions(...args: any[]): any
export function getLoaderSWCOptions(...args: any[]): any

View File

@@ -0,0 +1,229 @@
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 ref;
const isTSFile = filename.endsWith(".ts");
const isTypeScript = isTSFile || filename.endsWith(".tsx");
const enableDecorators = Boolean(jsConfig == null ? void 0 : (ref = jsConfig.compilerOptions) == null ? void 0 : ref.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 , nextConfig , resolvedBaseUrl , jsConfig , swcCacheDir , isServerLayer , hasServerComponents , }) {
var ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9;
const parserConfig = getParserOptions({
filename,
jsConfig
});
const paths = jsConfig == null ? void 0 : (ref = jsConfig.compilerOptions) == null ? void 0 : ref.paths;
const enableDecorators = Boolean(jsConfig == null ? void 0 : (ref1 = jsConfig.compilerOptions) == null ? void 0 : ref1.experimentalDecorators);
const emitDecoratorMetadata = Boolean(jsConfig == null ? void 0 : (ref2 = jsConfig.compilerOptions) == null ? void 0 : ref2.emitDecoratorMetadata);
const useDefineForClassFields = Boolean(jsConfig == null ? void 0 : (ref3 = jsConfig.compilerOptions) == null ? void 0 : ref3.useDefineForClassFields);
const plugins = ((nextConfig == null ? void 0 : (ref4 = nextConfig.experimental) == null ? void 0 : ref4.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: {
keepImportAssertions: 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 : (ref5 = jsConfig.compilerOptions) == null ? void 0 : ref5.jsxImportSource) ?? ((nextConfig == null ? void 0 : (ref6 = nextConfig.compiler) == null ? void 0 : ref6.emotion) ? "@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: nextConfig == null ? void 0 : (ref7 = nextConfig.compiler) == null ? void 0 : ref7.removeConsole,
// disable "reactRemoveProperties" when "jest" is true
// otherwise the setting from next.config.js will be used
reactRemoveProperties: jest ? false : nextConfig == null ? void 0 : (ref8 = nextConfig.compiler) == null ? void 0 : ref8.reactRemoveProperties,
modularizeImports: nextConfig == null ? void 0 : nextConfig.modularizeImports,
relay: nextConfig == null ? void 0 : (ref9 = nextConfig.compiler) == null ? void 0 : ref9.relay,
// Always transform styled-jsx and error when `client-only` condition is triggered
styledJsx: true,
// Disable css-in-js libs (without client-only integration) transform on server layer for server components
...!isServerLayer && {
emotion: getEmotionOptions(nextConfig, development),
styledComponents: getStyledComponentsOptions(nextConfig, development)
},
serverComponents: hasServerComponents ? {
isServer: !!isServerLayer
} : undefined
};
}
function getStyledComponentsOptions(nextConfig, development) {
var ref;
let styledComponentsOptions = nextConfig == null ? void 0 : (ref = nextConfig.compiler) == null ? void 0 : ref.styledComponents;
if (!styledComponentsOptions) {
return null;
}
return {
...styledComponentsOptions,
displayName: styledComponentsOptions.displayName ?? Boolean(development)
};
}
function getEmotionOptions(nextConfig, development) {
var ref, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17;
if (!(nextConfig == null ? void 0 : (ref = nextConfig.compiler) == null ? void 0 : ref.emotion)) {
return null;
}
let autoLabel = false;
switch(nextConfig == null ? void 0 : (ref10 = nextConfig.compiler) == null ? void 0 : (ref11 = ref10.emotion) == null ? void 0 : ref11.autoLabel){
case "never":
autoLabel = false;
break;
case "always":
autoLabel = true;
break;
case "dev-only":
default:
autoLabel = !!development;
break;
}
return {
enabled: true,
autoLabel,
importMap: nextConfig == null ? void 0 : (ref12 = nextConfig.compiler) == null ? void 0 : (ref13 = ref12.emotion) == null ? void 0 : ref13.importMap,
labelFormat: nextConfig == null ? void 0 : (ref14 = nextConfig.compiler) == null ? void 0 : (ref15 = ref14.emotion) == null ? void 0 : ref15.labelFormat,
sourcemap: development ? (nextConfig == null ? void 0 : (ref16 = nextConfig.compiler) == null ? void 0 : (ref17 = ref16.emotion) == null ? void 0 : ref17.sourceMap) ?? true : false
};
}
export function getJestSWCOptions({ isServer , filename , esm , nextConfig , jsConfig , pagesDir , hasServerComponents , }) {
let baseOptions = getBaseSWCOptions({
filename,
jest: true,
development: false,
hasReactRefresh: false,
globalWindow: !isServer,
nextConfig,
jsConfig,
hasServerComponents
});
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 , isServerLayer , pagesDir , isPageFile , hasReactRefresh , nextConfig , jsConfig , supportedBrowsers , swcCacheDir , relativeFilePathFromRoot , hasServerComponents , }) {
var ref;
let baseOptions = getBaseSWCOptions({
filename,
development,
globalWindow: !isServer,
hasReactRefresh,
nextConfig,
jsConfig,
// resolvedBaseUrl,
swcCacheDir,
isServerLayer,
relativeFilePathFromRoot,
hasServerComponents
});
if ((nextConfig == null ? void 0 : (ref = nextConfig.experimental) == null ? void 0 : ref.fontLoaders) && relativeFilePathFromRoot) {
baseOptions.fontLoaders = {
fontLoaders: nextConfig.experimental.fontLoaders.map(({ loader })=>loader),
relativeFilePathFromRoot
};
}
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,
isPageFile,
env: {
targets: {
// Targets the current version of Node.js
node: process.versions.node
}
}
};
} else {
// Matches default @babel/preset-env behavior
baseOptions.jsc.target = "es5";
return {
...baseOptions,
// Ensure Next.js internals are output as commonjs modules
...isNextDist ? {
module: {
type: "commonjs"
}
} : {},
disableNextSsg: !isPageFile,
isDevelopment: development,
isServer,
pagesDir,
isPageFile,
...supportedBrowsers && supportedBrowsers.length > 0 ? {
env: {
targets: supportedBrowsers
}
} : {}
};
}
}
//# sourceMappingURL=options.js.map

File diff suppressed because one or more lines are too long

1174
kitabcitab/node_modules/next/dist/esm/build/utils.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/config/blocks/base.ts"],"names":["curry","COMPILER_NAMES","base","ctx","config","mode","isDevelopment","name","isServer","isEdgeRuntime","edgeServer","server","client","target","targetWeb","process","env","__NEXT_TEST_MODE","__NEXT_TEST_WITH_DEVTOOL","devtool","productionBrowserSourceMaps","isClient","module","rules"],"mappings":"AAAA,OAAOA,KAAK,MAAM,iCAAiC,CAAA;AAEnD,SAASC,cAAc,QAAQ,kCAAkC,CAAA;AAGjE,OAAO,MAAMC,IAAI,GAAGF,KAAK,CAAC,SAASE,IAAI,CACrCC,GAAyB,EACzBC,MAA6B,EAC7B;IACAA,MAAM,CAACC,IAAI,GAAGF,GAAG,CAACG,aAAa,GAAG,aAAa,GAAG,YAAY;IAC9DF,MAAM,CAACG,IAAI,GAAGJ,GAAG,CAACK,QAAQ,GACtBL,GAAG,CAACM,aAAa,GACfR,cAAc,CAACS,UAAU,GACzBT,cAAc,CAACU,MAAM,GACvBV,cAAc,CAACW,MAAM;IAEzB,oCAAoC;IACpCR,MAAM,CAACS,MAAM,GAAG,CAACV,GAAG,CAACW,SAAS,GAC1B,WAAW,GACXX,GAAG,CAACM,aAAa,GACjB;QAAC,KAAK;QAAE,KAAK;KAAC,GACd;QAAC,KAAK;QAAE,KAAK;KAAC;IAElB,4DAA4D;IAC5D,IAAIN,GAAG,CAACG,aAAa,EAAE;QACrB,IAAIS,OAAO,CAACC,GAAG,CAACC,gBAAgB,IAAI,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB,EAAE;YACzEd,MAAM,CAACe,OAAO,GAAG,KAAK;SACvB,MAAM;YACL,+DAA+D;YAC/D,kEAAkE;YAClE,mEAAmE;YACnE,uDAAuD;YACvDf,MAAM,CAACe,OAAO,GAAG,iBAAiB;SACnC;KACF,MAAM;QACL,IACEhB,GAAG,CAACM,aAAa,IACjB,6BAA6B;QAC7B,CAACN,GAAG,CAACiB,2BAA2B,IAAIjB,GAAG,CAACkB,QAAQ,CAAC,EACjD;YACAjB,MAAM,CAACe,OAAO,GAAG,YAAY;SAC9B,MAAM;YACLf,MAAM,CAACe,OAAO,GAAG,KAAK;SACvB;KACF;IAED,IAAI,CAACf,MAAM,CAACkB,MAAM,EAAE;QAClBlB,MAAM,CAACkB,MAAM,GAAG;YAAEC,KAAK,EAAE,EAAE;SAAE;KAC9B;IAED,6EAA6E;IAC7E,mDAAmD;IAEnD,OAAOnB,MAAM,CAAA;CACd,CAAC,CAAA"}

View File

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

File diff suppressed because one or more lines are too long

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/client.ts"],"names":["getClientStyleLoader","hasAppDir","isDevelopment","assetPrefix","loader","options","insert","element","anchorElement","document","querySelector","parentNode","insertBefore","MiniCssExtractPlugin","require","default","publicPath","esModule"],"mappings":"AAEA,OAAO,SAASA,oBAAoB,CAAC,EACnCC,SAAS,CAAA,EACTC,aAAa,CAAA,EACbC,WAAW,CAAA,EAKZ,EAA0B;IACzB,0DAA0D;IAC1D,IAAID,aAAa,IAAI,CAACD,SAAS,EAAE;QAC/B,OAAO;YACLG,MAAM,EAAE,mBAAmB;YAC3BC,OAAO,EAAE;gBACPC,MAAM,EAAE,SAAUC,OAAa,EAAE;oBAC/B,uDAAuD;oBACvD,uDAAuD;oBACvD,uDAAuD;oBACvD,sDAAsD;oBACtD,sDAAsD;oBAEtD,sDAAsD;oBACtD,yBAAyB;oBACzB,IAAIC,aAAa,GAAGC,QAAQ,CAACC,aAAa,CACxC,2BAA2B,CAC5B,AAAC;oBACF,IAAIC,UAAU,GAAGH,aAAa,CAACG,UAAU,AAAC,AAAC,kBAAkB;oBAAnB;oBAE1C,mDAAmD;oBACnD,uDAAuD;oBACvD,2CAA2C;oBAC3CA,UAAU,CAACC,YAAY,CAACL,OAAO,EAAEC,aAAa,CAAC;iBAChD;aACF;SACF,CAAA;KACF;IAED,MAAMK,oBAAoB,GACxBC,OAAO,CAAC,6CAA6C,CAAC,CAACC,OAAO;IAChE,OAAO;QACLX,MAAM,EAAES,oBAAoB,CAACT,MAAM;QACnCC,OAAO,EAAE;YACPW,UAAU,EAAE,CAAC,EAAEb,WAAW,CAAC,OAAO,CAAC;YACnCc,QAAQ,EAAE,KAAK;SAChB;KACF,CAAA;CACF"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/file-resolve.ts"],"names":["cssFileResolve","url","_resourcePath","urlImports","startsWith","test"],"mappings":"AAAA,OAAO,SAASA,cAAc,CAC5BC,GAAW,EACXC,aAAqB,EACrBC,UAAe,EACf;IACA,IAAIF,GAAG,CAACG,UAAU,CAAC,GAAG,CAAC,EAAE;QACvB,OAAO,KAAK,CAAA;KACb;IACD,IAAI,CAACD,UAAU,IAAI,uBAAuBE,IAAI,CAACJ,GAAG,CAAC,EAAE;QACnD,OAAO,KAAK,CAAA;KACb;IACD,OAAO,IAAI,CAAA;CACZ"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts"],"names":["loaderUtils","path","regexLikeIndexModule","getCssModuleLocalIdent","context","_","exportName","options","relativePath","relative","rootContext","resourcePath","replace","fileNameOrFolder","test","hash","getHashDigest","Buffer","from","interpolateName"],"mappings":"AAAA,OAAOA,WAAW,MAAM,kCAAkC,CAAA;AAC1D,OAAOC,IAAI,MAAM,MAAM,CAAA;AAGvB,MAAMC,oBAAoB,mDAAmD;AAE7E,OAAO,SAASC,sBAAsB,CACpCC,OAAkC,EAClCC,CAAM,EACNC,UAAkB,EAClBC,OAAe,EACf;IACA,MAAMC,YAAY,GAAGP,IAAI,CACtBQ,QAAQ,CAACL,OAAO,CAACM,WAAW,EAAEN,OAAO,CAACO,YAAY,CAAC,CACnDC,OAAO,SAAS,GAAG,CAAC;IAEvB,0EAA0E;IAC1E,2BAA2B;IAC3B,MAAMC,gBAAgB,GAAGX,oBAAoB,CAACY,IAAI,CAACN,YAAY,CAAC,GAC5D,UAAU,GACV,QAAQ;IAEZ,iDAAiD;IACjD,MAAMO,IAAI,GAAGf,WAAW,CAACgB,aAAa,CACpCC,MAAM,CAACC,IAAI,CAAC,CAAC,SAAS,EAAEV,YAAY,CAAC,WAAW,EAAEF,UAAU,CAAC,CAAC,CAAC,EAC/D,KAAK,EACL,QAAQ,EACR,CAAC,CACF;IAED,yEAAyE;IACzE,OACEN,WAAW,CACRmB,eAAe,CACdf,OAAO,EACPS,gBAAgB,GAAG,GAAG,GAAGP,UAAU,GAAG,IAAI,GAAGS,IAAI,EACjDR,OAAO,CACR,CACAK,OAAO,CACN,oEAAoE;IACpE,oEAAoE;IACpE,QAAQ;iBAER,GAAG,CACJ,AACD,+DAA+D;IAC/D,iEAAiE;KAChEA,OAAO,oBAAoB,GAAG,CAAC,AAChC,uFAAuF;IACvF,sDAAsD;KACrDA,OAAO,iBAAiB,MAAM,CAAC,CACnC;CACF"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/global.ts"],"names":["getClientStyleLoader","cssFileResolve","getGlobalCssLoader","ctx","postcss","preProcessors","loaders","isClient","push","hasAppDir","isDevelopment","assetPrefix","loader","require","resolve","options","importLoaders","length","modules","url","resourcePath","experimental","urlImports","import","_","slice","reverse"],"mappings":"AAGA,SAASA,oBAAoB,QAAQ,UAAU,CAAA;AAC/C,SAASC,cAAc,QAAQ,gBAAgB,CAAA;AAE/C,OAAO,SAASC,kBAAkB,CAChCC,GAAyB,EACzBC,OAAY,EACZC,aAAgD,GAAG,EAAE,EAC3B;IAC1B,MAAMC,OAAO,GAA6B,EAAE;IAE5C,IAAIH,GAAG,CAACI,QAAQ,EAAE;QAChB,4DAA4D;QAC5D,SAAS;QACTD,OAAO,CAACE,IAAI,CACVR,oBAAoB,CAAC;YACnBS,SAAS,EAAEN,GAAG,CAACM,SAAS;YACxBC,aAAa,EAAEP,GAAG,CAACO,aAAa;YAChCC,WAAW,EAAER,GAAG,CAACQ,WAAW;SAC7B,CAAC,CACH;KACF;IAED,sCAAsC;IACtCL,OAAO,CAACE,IAAI,CAAC;QACXI,MAAM,EAAEC,OAAO,CAACC,OAAO,CAAC,oCAAoC,CAAC;QAC7DC,OAAO,EAAE;YACPX,OAAO;YACPY,aAAa,EAAE,CAAC,GAAGX,aAAa,CAACY,MAAM;YACvC,4CAA4C;YAC5CC,OAAO,EAAE,KAAK;YACdC,GAAG,EAAE,CAACA,GAAW,EAAEC,YAAoB,GACrCnB,cAAc,CAACkB,GAAG,EAAEC,YAAY,EAAEjB,GAAG,CAACkB,YAAY,CAACC,UAAU,CAAC;YAChEC,MAAM,EAAE,CAACJ,GAAW,EAAEK,CAAM,EAAEJ,YAAoB,GAChDnB,cAAc,CAACkB,GAAG,EAAEC,YAAY,EAAEjB,GAAG,CAACkB,YAAY,CAACC,UAAU,CAAC;SACjE;KACF,CAAC;IAEF,cAAc;IACdhB,OAAO,CAACE,IAAI,CAAC;QACXI,MAAM,EAAEC,OAAO,CAACC,OAAO,CAAC,wCAAwC,CAAC;QACjEC,OAAO,EAAE;YACPX,OAAO;SACR;KACF,CAAC;IAEFE,OAAO,CAACE,IAAI,CACV,sEAAsE;IACtE,0BAA0B;OACvBH,aAAa,CAACoB,KAAK,EAAE,CAACC,OAAO,EAAE,CACnC;IAED,OAAOpB,OAAO,CAAA;CACf"}

View File

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

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