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

9
kitabcitab/node_modules/next/dist/esm/lib/chalk.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
let chalk;
if (process.env.NEXT_RUNTIME === "edge") {
chalk = require("./web/chalk").default;
} else {
chalk = require("next/dist/compiled/chalk");
}
export default chalk;
//# sourceMappingURL=chalk.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/chalk.ts"],"names":["chalk","process","env","NEXT_RUNTIME","require","default"],"mappings":"AAAA,IAAIA,KAAK,AAA2C;AAEpD,IAAIC,OAAO,CAACC,GAAG,CAACC,YAAY,KAAK,MAAM,EAAE;IACvCH,KAAK,GAAGI,OAAO,CAAC,aAAa,CAAC,CAACC,OAAO;CACvC,MAAM;IACLL,KAAK,GAAGI,OAAO,CAAC,0BAA0B,CAAC;CAC5C;AAED,eAAeJ,KAAK,CAAA"}

View File

@@ -0,0 +1,29 @@
const globalInvokeCache = new Map();
export function withCoalescedInvoke(func) {
return async function(key, args) {
const entry = globalInvokeCache.get(key);
if (entry) {
return entry.then((res)=>({
isOrigin: false,
value: res.value
}));
}
async function __wrapper() {
return await func.apply(undefined, args);
}
const future = __wrapper().then((res)=>{
globalInvokeCache.delete(key);
return {
isOrigin: true,
value: res
};
}).catch((err)=>{
globalInvokeCache.delete(key);
return Promise.reject(err);
});
globalInvokeCache.set(key, future);
return future;
};
}
//# sourceMappingURL=coalesced-function.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/coalesced-function.ts"],"names":["globalInvokeCache","Map","withCoalescedInvoke","func","key","args","entry","get","then","res","isOrigin","value","__wrapper","apply","undefined","future","delete","catch","err","Promise","reject","set"],"mappings":"AAOA,MAAMA,iBAAiB,GAAG,IAAIC,GAAG,EAA6C;AAE9E,OAAO,SAASC,mBAAmB,CACjCC,IAAO,EAImD;IAC1D,OAAO,eAAgBC,GAAW,EAAEC,IAAmB,EAAE;QACvD,MAAMC,KAAK,GAAGN,iBAAiB,CAACO,GAAG,CAACH,GAAG,CAAC;QACxC,IAAIE,KAAK,EAAE;YACT,OAAOA,KAAK,CAACE,IAAI,CAAC,CAACC,GAAG,GAAK,CAAC;oBAC1BC,QAAQ,EAAE,KAAK;oBACfC,KAAK,EAAEF,GAAG,CAACE,KAAK;iBACjB,CAAC,CAAC,CAAA;SACJ;QAED,eAAeC,SAAS,GAAG;YACzB,OAAO,MAAMT,IAAI,CAACU,KAAK,CAACC,SAAS,EAAET,IAAI,CAAC,CAAA;SACzC;QAED,MAAMU,MAAM,GAAGH,SAAS,EAAE,CACvBJ,IAAI,CAAC,CAACC,GAAG,GAAK;YACbT,iBAAiB,CAACgB,MAAM,CAACZ,GAAG,CAAC;YAC7B,OAAO;gBAAEM,QAAQ,EAAE,IAAI;gBAAEC,KAAK,EAAEF,GAAG;aAAkC,CAAA;SACtE,CAAC,CACDQ,KAAK,CAAC,CAACC,GAAG,GAAK;YACdlB,iBAAiB,CAACgB,MAAM,CAACZ,GAAG,CAAC;YAC7B,OAAOe,OAAO,CAACC,MAAM,CAACF,GAAG,CAAC,CAAA;SAC3B,CAAC;QACJlB,iBAAiB,CAACqB,GAAG,CAACjB,GAAG,EAAEW,MAAM,CAAC;QAClC,OAAOA,MAAM,CAAA;KACd,CAAA;CACF"}

11
kitabcitab/node_modules/next/dist/esm/lib/commands.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
export const commands = {
build: ()=>Promise.resolve(require("../cli/next-build").nextBuild),
start: ()=>Promise.resolve(require("../cli/next-start").nextStart),
export: ()=>Promise.resolve(require("../cli/next-export").nextExport),
dev: ()=>Promise.resolve(require("../cli/next-dev").nextDev),
lint: ()=>Promise.resolve(require("../cli/next-lint").nextLint),
telemetry: ()=>Promise.resolve(require("../cli/next-telemetry").nextTelemetry),
info: ()=>Promise.resolve(require("../cli/next-info").nextInfo)
};
//# sourceMappingURL=commands.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/commands.ts"],"names":["commands","build","Promise","resolve","require","nextBuild","start","nextStart","export","nextExport","dev","nextDev","lint","nextLint","telemetry","nextTelemetry","info","nextInfo"],"mappings":"AAEA,OAAO,MAAMA,QAAQ,GAAqD;IACxEC,KAAK,EAAE,IAAMC,OAAO,CAACC,OAAO,CAACC,OAAO,CAAC,mBAAmB,CAAC,CAACC,SAAS,CAAC;IACpEC,KAAK,EAAE,IAAMJ,OAAO,CAACC,OAAO,CAACC,OAAO,CAAC,mBAAmB,CAAC,CAACG,SAAS,CAAC;IACpEC,MAAM,EAAE,IAAMN,OAAO,CAACC,OAAO,CAACC,OAAO,CAAC,oBAAoB,CAAC,CAACK,UAAU,CAAC;IACvEC,GAAG,EAAE,IAAMR,OAAO,CAACC,OAAO,CAACC,OAAO,CAAC,iBAAiB,CAAC,CAACO,OAAO,CAAC;IAC9DC,IAAI,EAAE,IAAMV,OAAO,CAACC,OAAO,CAACC,OAAO,CAAC,kBAAkB,CAAC,CAACS,QAAQ,CAAC;IACjEC,SAAS,EAAE,IACTZ,OAAO,CAACC,OAAO,CAACC,OAAO,CAAC,uBAAuB,CAAC,CAACW,aAAa,CAAC;IACjEC,IAAI,EAAE,IAAMd,OAAO,CAACC,OAAO,CAACC,OAAO,CAAC,kBAAkB,CAAC,CAACa,QAAQ,CAAC;CAClE,CAAA"}

View File

@@ -0,0 +1,4 @@
export class CompileError extends Error {
}
//# sourceMappingURL=compile-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/compile-error.ts"],"names":["CompileError","Error"],"mappings":"AAAA,OAAO,MAAMA,YAAY,SAASC,KAAK;CAAG"}

63
kitabcitab/node_modules/next/dist/esm/lib/constants.js generated vendored Normal file
View File

@@ -0,0 +1,63 @@
// Patterns to detect middleware files
export const MIDDLEWARE_FILENAME = "middleware";
export const MIDDLEWARE_LOCATION_REGEXP = `(?:src/)?${MIDDLEWARE_FILENAME}`;
// Because on Windows absolute paths in the generated code can break because of numbers, eg 1 in the path,
// we have to use a private alias
export const PAGES_DIR_ALIAS = "private-next-pages";
export const DOT_NEXT_ALIAS = "private-dot-next";
export const ROOT_DIR_ALIAS = "private-next-root-dir";
export const APP_DIR_ALIAS = "private-next-app-dir";
export const RSC_MOD_REF_PROXY_ALIAS = "private-next-rsc-mod-ref-proxy";
export const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict`;
export const SSG_GET_INITIAL_PROPS_CONFLICT = `You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps`;
export const SERVER_PROPS_GET_INIT_PROPS_CONFLICT = `You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.`;
export const SERVER_PROPS_SSG_CONFLICT = `You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps`;
export const STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR = `can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props`;
export const SERVER_PROPS_EXPORT_ERROR = `pages with \`getServerSideProps\` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export`;
export const GSP_NO_RETURNED_VALUE = "Your `getStaticProps` function did not return an object. Did you forget to add a `return`?";
export const GSSP_NO_RETURNED_VALUE = "Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?";
export const UNSTABLE_REVALIDATE_RENAME_ERROR = "The `unstable_revalidate` property is available for general use.\n" + "Please use `revalidate` instead.";
export const GSSP_COMPONENT_MEMBER_ERROR = `can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member`;
export const NON_STANDARD_NODE_ENV = `You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env`;
export const SSG_FALLBACK_EXPORT_ERROR = `Pages with \`fallback\` enabled in \`getStaticPaths\` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export`;
export const ESLINT_DEFAULT_DIRS = [
"pages",
"components",
"lib",
"src"
];
export const ESLINT_PROMPT_VALUES = [
{
title: "Strict",
recommended: true,
config: {
extends: "next/core-web-vitals"
}
},
{
title: "Base",
config: {
extends: "next"
}
},
{
title: "Cancel",
config: null
},
];
export const SERVER_RUNTIME = {
edge: "edge",
experimentalEdge: "experimental-edge",
nodejs: "nodejs"
};
export const WEBPACK_LAYERS = {
shared: "sc_shared",
server: "sc_server",
client: "sc_client",
api: "api",
middleware: "middleware",
edgeAsset: "edge-asset",
appClient: "app-client"
};
//# sourceMappingURL=constants.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/constants.ts"],"names":["MIDDLEWARE_FILENAME","MIDDLEWARE_LOCATION_REGEXP","PAGES_DIR_ALIAS","DOT_NEXT_ALIAS","ROOT_DIR_ALIAS","APP_DIR_ALIAS","RSC_MOD_REF_PROXY_ALIAS","PUBLIC_DIR_MIDDLEWARE_CONFLICT","SSG_GET_INITIAL_PROPS_CONFLICT","SERVER_PROPS_GET_INIT_PROPS_CONFLICT","SERVER_PROPS_SSG_CONFLICT","STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR","SERVER_PROPS_EXPORT_ERROR","GSP_NO_RETURNED_VALUE","GSSP_NO_RETURNED_VALUE","UNSTABLE_REVALIDATE_RENAME_ERROR","GSSP_COMPONENT_MEMBER_ERROR","NON_STANDARD_NODE_ENV","SSG_FALLBACK_EXPORT_ERROR","ESLINT_DEFAULT_DIRS","ESLINT_PROMPT_VALUES","title","recommended","config","extends","SERVER_RUNTIME","edge","experimentalEdge","nodejs","WEBPACK_LAYERS","shared","server","client","api","middleware","edgeAsset","appClient"],"mappings":"AAEA,sCAAsC;AACtC,OAAO,MAAMA,mBAAmB,GAAG,YAAY,CAAA;AAC/C,OAAO,MAAMC,0BAA0B,GAAG,CAAC,SAAS,EAAED,mBAAmB,CAAC,CAAC,CAAA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K,EAAE,MAAM;QACbE,MAAM,EAAE;YACNC,OAAO,EAAE,MAAM;SAChB;KACF;IACD;QACEH,KAAK,EAAE,QAAQ;QACfE,MAAM,EAAE,IAAI;KACb;CACF,CAAA;AAED,OAAO,MAAME,cAAc,GAAkC;IAC3DC,IAAI,EAAE,MAAM;IACZC,gBAAgB,EAAE,mBAAmB;IACrCC,MAAM,EAAE,QAAQ;CACjB,CAAA;AAED,OAAO,MAAMC,cAAc,GAAG;IAC5BC,MAAM,EAAE,WAAW;IACnBC,MAAM,EAAE,WAAW;IACnBC,MAAM,EAAE,WAAW;IACnBC,GAAG,EAAE,KAAK;IACVC,UAAU,EAAE,YAAY;IACxBC,SAAS,EAAE,YAAY;IACvBC,SAAS,EAAE,YAAY;CACxB,CAAA"}

View File

@@ -0,0 +1,41 @@
// the minimum number of operations required to convert string a to string b.
function minDistance(a, b, threshold) {
const m = a.length;
const n = b.length;
if (m < n) {
return minDistance(b, a, threshold);
}
if (n === 0) {
return m;
}
let previousRow = Array.from({
length: n + 1
}, (_, i)=>i);
for(let i1 = 0; i1 < m; i1++){
const s1 = a[i1];
let currentRow = [
i1 + 1
];
for(let j = 0; j < n; j++){
const s2 = b[j];
const insertions = previousRow[j + 1] + 1;
const deletions = currentRow[j] + 1;
const substitutions = previousRow[j] + Number(s1 !== s2);
currentRow.push(Math.min(insertions, deletions, substitutions));
}
previousRow = currentRow;
}
return previousRow[previousRow.length - 1];
}
export function detectTypo(input, options, threshold = 2) {
const potentialTypos = options.map((o)=>({
option: o,
distance: minDistance(o, input, threshold)
})).filter(({ distance })=>distance <= threshold && distance > 0).sort((a, b)=>a.distance - b.distance);
if (potentialTypos.length) {
return potentialTypos[0].option;
}
return null;
}
//# sourceMappingURL=detect-typo.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/detect-typo.ts"],"names":["minDistance","a","b","threshold","m","length","n","previousRow","Array","from","_","i","s1","currentRow","j","s2","insertions","deletions","substitutions","Number","push","Math","min","detectTypo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ACzB;IACD,OAAON,WAAW,CAACA,WAAW,CAACF,MAAM,GAAG,CAAC,CAAC,CAAA;CAC3C;AAED,OAAO,SAASkB,UAAU,CAACC,KAAa,EAAEC,OAAiB,EAAEtB,SAAS,GAAG,CAAC,EAAE;IAC1E,MAAMuB,cAAc,GAAGD,OAAO,CAC3BE,GAAG,CAAC,CAACC,CAAC,GAAK,CAAC;YACXC,MAAM,EAAED,CAAC;YACTE,QAAQ,EAAE9B,WAAW,CAAC4B,CAAC,EAAEJ,KAAK,EAAErB,SAAS,CAAC;SAC3C,CAAC,CAAC,CACF4B,MAAM,CAAC,CAAC,EAAED,QAAQ,CAAA,EAAE,GAAKA,QAAQ,IAAI3B,SAAS,IAAI2B,QAAQ,GAAG,CAAC,CAAC,CAC/DE,IAAI,CAAC,CAAC/B,CAAC,EAAEC,CAAC,GAAKD,CAAC,CAAC6B,QAAQ,GAAG5B,CAAC,CAAC4B,QAAQ,CAAC;IAE1C,IAAIJ,cAAc,CAACrB,MAAM,EAAE;QACzB,OAAOqB,cAAc,CAAC,CAAC,CAAC,CAACG,MAAM,CAAA;KAChC;IACD,OAAO,IAAI,CAAA;CACZ"}

View File

@@ -0,0 +1,112 @@
import os from "os";
import fs from "fs";
import path from "path";
import * as Log from "../build/output/log";
import { execSync } from "child_process";
import tar from "next/dist/compiled/tar";
import fetch from "next/dist/compiled/node-fetch";
import { fileExists } from "./file-exists";
const MAX_VERSIONS_TO_CACHE = 5;
export async function downloadWasmSwc(version, wasmDirectory, variant = "nodejs") {
const pkgName = `@next/swc-wasm-${variant}`;
const tarFileName = `${pkgName.substring(6)}-${version}.tgz`;
const outputDirectory = path.join(wasmDirectory, pkgName);
if (await fileExists(outputDirectory)) {
// if the package is already downloaded a different
// failure occurred than not being present
return;
}
// get platform specific cache directory adapted from playwright's handling
// https://github.com/microsoft/playwright/blob/7d924470d397975a74a19184c136b3573a974e13/packages/playwright-core/src/utils/registry.ts#L141
const cacheDirectory = await (async ()=>{
let result;
const envDefined = process.env["NEXT_SWC_PATH"];
if (envDefined) {
result = envDefined;
} else {
let systemCacheDirectory;
if (process.platform === "linux") {
systemCacheDirectory = process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache");
} else if (process.platform === "darwin") {
systemCacheDirectory = path.join(os.homedir(), "Library", "Caches");
} else if (process.platform === "win32") {
systemCacheDirectory = process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local");
} else {
/// Attempt to use generic tmp location for these platforms
if (process.platform === "freebsd" || process.platform === "android") {
for (const dir of [
path.join(os.homedir(), ".cache"),
path.join(os.tmpdir()),
]){
if (await fileExists(dir)) {
systemCacheDirectory = dir;
break;
}
}
}
if (!systemCacheDirectory) {
console.error(new Error("Unsupported platform: " + process.platform));
process.exit(0);
}
}
result = path.join(systemCacheDirectory, "next-swc");
}
if (!path.isAbsolute(result)) {
// It is important to resolve to the absolute path:
// - for unzipping to work correctly;
// - so that registry directory matches between installation and execution.
// INIT_CWD points to the root of `npm/yarn install` and is probably what
// the user meant when typing the relative path.
result = path.resolve(process.env["INIT_CWD"] || process.cwd(), result);
}
return result;
})();
await fs.promises.mkdir(outputDirectory, {
recursive: true
});
const extractFromTar = async ()=>{
await tar.x({
file: path.join(cacheDirectory, tarFileName),
cwd: outputDirectory,
strip: 1
});
};
if (!await fileExists(path.join(cacheDirectory, tarFileName))) {
Log.info("Downloading WASM swc package...");
await fs.promises.mkdir(cacheDirectory, {
recursive: true
});
const tempFile = path.join(cacheDirectory, `${tarFileName}.temp-${Date.now()}`);
let registry = `https://registry.npmjs.org/`;
try {
const output = execSync("npm config get registry").toString().trim();
if (output.startsWith("http")) {
registry = output.endsWith("/") ? output : `${output}/`;
}
} catch (_) {}
await fetch(`${registry}${pkgName}/-/${tarFileName}`).then((res)=>{
if (!res.ok) {
throw new Error(`request failed with status ${res.status}`);
}
const cacheWriteStream = fs.createWriteStream(tempFile);
return new Promise((resolve, reject)=>{
res.body.pipe(cacheWriteStream).on("error", (err)=>reject(err)).on("finish", ()=>resolve());
}).finally(()=>cacheWriteStream.close());
});
await fs.promises.rename(tempFile, path.join(cacheDirectory, tarFileName));
}
await extractFromTar();
const cacheFiles = await fs.promises.readdir(cacheDirectory);
if (cacheFiles.length > MAX_VERSIONS_TO_CACHE) {
cacheFiles.sort((a, b)=>{
if (a.length < b.length) return -1;
return a.localeCompare(b);
});
// prune oldest versions in cache
for(let i = 0; i++; i < cacheFiles.length - MAX_VERSIONS_TO_CACHE){
await fs.promises.unlink(path.join(cacheDirectory, cacheFiles[i])).catch(()=>{});
}
}
}
//# sourceMappingURL=download-wasm-swc.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,72 @@
import chalk from "next/dist/compiled/chalk";
import path from "path";
export var MessageSeverity;
(function(MessageSeverity) {
MessageSeverity[MessageSeverity["Warning"] = 1] = "Warning";
MessageSeverity[MessageSeverity["Error"] = 2] = "Error";
})(MessageSeverity || (MessageSeverity = {}));
function pluginCount(messages) {
let nextPluginWarningCount = 0;
let nextPluginErrorCount = 0;
for(let i = 0; i < messages.length; i++){
const { severity , ruleId } = messages[i];
if (ruleId == null ? void 0 : ruleId.includes("@next/next")) {
if (severity === 1) {
nextPluginWarningCount += 1;
} else {
nextPluginErrorCount += 1;
}
}
}
return {
nextPluginErrorCount,
nextPluginWarningCount
};
}
function formatMessage(dir, messages, filePath) {
let fileName = path.posix.normalize(path.relative(dir, filePath).replace(/\\/g, "/"));
if (!fileName.startsWith(".")) {
fileName = "./" + fileName;
}
let output = "\n" + chalk.cyan(fileName);
for(let i = 0; i < messages.length; i++){
const { message , severity , line , column , ruleId } = messages[i];
output = output + "\n";
if (line && column) {
output = output + chalk.yellow(line.toString()) + ":" + chalk.yellow(column.toString()) + " ";
}
if (severity === 1) {
output += chalk.yellow.bold("Warning") + ": ";
} else {
output += chalk.red.bold("Error") + ": ";
}
output += message;
if (ruleId) {
output += " " + chalk.gray.bold(ruleId);
}
}
return output;
}
export function formatResults(baseDir, results, format) {
let totalNextPluginErrorCount = 0;
let totalNextPluginWarningCount = 0;
let resultsWithMessages = results.filter(({ messages })=>{
return messages == null ? void 0 : messages.length;
});
// Track number of Next.js plugin errors and warnings
resultsWithMessages.forEach(({ messages })=>{
const res = pluginCount(messages);
totalNextPluginErrorCount += res.nextPluginErrorCount;
totalNextPluginWarningCount += res.nextPluginWarningCount;
});
// Use user defined formatter or Next.js's built-in custom formatter
const output = format ? format(resultsWithMessages) : resultsWithMessages.map(({ messages , filePath })=>formatMessage(baseDir, messages, filePath)).join("\n");
return {
output: output,
outputWithMessages: resultsWithMessages.length > 0 ? output + `\n\n${chalk.cyan("info")} - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules` : "",
totalNextPluginErrorCount,
totalNextPluginWarningCount
};
}
//# sourceMappingURL=customFormatter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/eslint/customFormatter.ts"],"names":["chalk","path","MessageSeverity","Warning","Error","pluginCount","messages","nextPluginWarningCount","nextPluginErrorCount","i","length","severity","ruleId","includes","formatMessage","dir","filePath","fileName","posix","normalize","relative","replace","startsWith","output","cyan","message","line","column","yellow","toString","bold","red","gray","formatResults","baseDir","results","format","totalNextPluginErrorCount","totalNextPluginWarningCount","resultsWithMessages","filter","forEach","res","map","join","outputWithMessages"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,IAAI,MAAM,MAAM,CAAA;WAGhB,eAGN;UAHWC,eAAe;IAAfA,eAAe,CAAfA,eAAe,CACzBC,SAAO,IAAG,CAAC,IAAXA,SAAO;IADGD,eAAe,CAAfA,eAAe,CAEzBE,OAAK,IAAG,CAAC,IAATA,OAAK;GAFKF,eAAe,KAAfA,eAAe;AAsB3B,SAASG,WAAW,CAACC,QAAuB,EAG1C;IACA,IAAIC,sBAAsB,GAAG,CAAC;IAC9B,IAAIC,oBAAoB,GAAG,CAAC;IAE5B,IAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,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AAC,EAAErC,QAAQ,CAAA,EAAEU,QAAQ,CAAA,EAAE,GAC1BF,aAAa,CAACoB,OAAO,EAAE5B,QAAQ,EAAEU,QAAQ,CAAC,CAC3C,CACA4B,IAAI,CAAC,IAAI,CAAC;IAEjB,OAAO;QACLrB,MAAM,EAAEA,MAAM;QACdsB,kBAAkB,EAChBN,mBAAmB,CAAC7B,MAAM,GAAG,CAAC,GAC1Ba,MAAM,GACN,CAAC,IAAI,EAAEvB,KAAK,CAACwB,IAAI,CACf,MAAM,CACP,CAAC,qHAAqH,CAAC,GACxH,EAAE;QACRa,yBAAyB;QACzBC,2BAA2B;KAC5B,CAAA;CACF"}

View File

@@ -0,0 +1,37 @@
import { promises as fs } from "fs";
export async function hasEslintConfiguration(eslintrcFile, packageJsonConfig) {
const configObject = {
exists: false,
emptyEslintrc: false,
emptyPkgJsonConfig: false
};
if (eslintrcFile) {
const content = await fs.readFile(eslintrcFile, {
encoding: "utf8"
}).then((txt)=>txt.trim().replace(/\n/g, ""), ()=>null);
if (content === "" || content === "{}" || content === "---" || content === "module.exports = {}") {
return {
...configObject,
emptyEslintrc: true
};
}
return {
...configObject,
exists: true
};
} else if (packageJsonConfig == null ? void 0 : packageJsonConfig.eslintConfig) {
if (Object.keys(packageJsonConfig == null ? void 0 : packageJsonConfig.eslintConfig).length) {
return {
...configObject,
exists: true
};
}
return {
...configObject,
emptyPkgJsonConfig: true
};
}
return configObject;
}
//# sourceMappingURL=hasEslintConfiguration.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/eslint/hasEslintConfiguration.ts"],"names":["promises","fs","hasEslintConfiguration","eslintrcFile","packageJsonConfig","configObject","exists","emptyEslintrc","emptyPkgJsonConfig","content","readFile","encoding","then","txt","trim","replace","eslintConfig","Object","keys","length"],"mappings":"AAAA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AASnC,OAAO,eAAeC,sBAAsB,CAC1CC,YAA2B,EAC3BC,iBAA+C,EACrB;IAC1B,MAAMC,YAAY,GAAG;QACnBC,MAAM,EAAE,KAAK;QACbC,aAAa,EAAE,KAAK;QACpBC,kBAAkB,EAAE,KAAK;KAC1B;IAED,IAAIL,YAAY,EAAE;QAChB,MAAMM,OAAO,GAAG,MAAMR,EAAE,CAACS,QAAQ,CAACP,YAAY,EAAE;YAAEQ,QAAQ,EAAE,MAAM;SAAE,CAAC,CAACC,IAAI,CACxE,CAACC,GAAG,GAAKA,GAAG,CAACC,IAAI,EAAE,CAACC,OAAO,QAAQ,EAAE,CAAC,EACtC,IAAM,IAAI,CACX;QAED,IACEN,OAAO,KAAK,EAAE,IACdA,OAAO,KAAK,IAAI,IAChBA,OAAO,KAAK,KAAK,IACjBA,OAAO,KAAK,qBAAqB,EACjC;YACA,OAAO;gBAAE,GAAGJ,YAAY;gBAAEE,aAAa,EAAE,IAAI;aAAE,CAAA;SAChD;QACD,OAAO;YAAE,GAAGF,YAAY;YAAEC,MAAM,EAAE,IAAI;SAAE,CAAA;KACzC,MAAM,IAAIF,iBAAiB,QAAc,GAA/BA,KAAAA,CAA+B,GAA/BA,iBAAiB,CAAEY,YAAY,EAAE;QAC1C,IAAIC,MAAM,CAACC,IAAI,CAACd,iBAAiB,QAAc,GAA/BA,KAAAA,CAA+B,GAA/BA,iBAAiB,CAAEY,YAAY,CAAC,CAACG,MAAM,EAAE;YACvD,OAAO;gBAAE,GAAGd,YAAY;gBAAEC,MAAM,EAAE,IAAI;aAAE,CAAA;SACzC;QACD,OAAO;YAAE,GAAGD,YAAY;YAAEG,kBAAkB,EAAE,IAAI;SAAE,CAAA;KACrD;IACD,OAAOH,YAAY,CAAA;CACpB"}

View File

@@ -0,0 +1,246 @@
import { promises as fs } from "fs";
import chalk from "next/dist/compiled/chalk";
import path from "path";
import findUp from "next/dist/compiled/find-up";
import semver from "next/dist/compiled/semver";
import * as CommentJson from "next/dist/compiled/comment-json";
import { formatResults } from "./customFormatter";
import { writeDefaultConfig } from "./writeDefaultConfig";
import { hasEslintConfiguration } from "./hasEslintConfiguration";
import { writeOutputFile } from "./writeOutputFile";
import { ESLINT_PROMPT_VALUES } from "../constants";
import { existsSync, findPagesDir } from "../find-pages-dir";
import { installDependencies } from "../install-dependencies";
import { hasNecessaryDependencies } from "../has-necessary-dependencies";
import * as Log from "../../build/output/log";
import isError, { getProperError } from "../is-error";
import { getPkgManager } from "../helpers/get-pkg-manager";
// 0 is off, 1 is warn, 2 is error. See https://eslint.org/docs/user-guide/configuring/rules#configuring-rules
const VALID_SEVERITY = [
"off",
"warn",
"error"
];
function isValidSeverity(severity) {
return VALID_SEVERITY.includes(severity);
}
const requiredPackages = [
{
file: "eslint",
pkg: "eslint",
exportsRestrict: false
},
{
file: "eslint-config-next",
pkg: "eslint-config-next",
exportsRestrict: false
},
];
async function cliPrompt() {
console.log(chalk.bold(`${chalk.cyan("?")} How would you like to configure ESLint? https://nextjs.org/docs/basic-features/eslint`));
try {
const cliSelect = (await Promise.resolve(require("next/dist/compiled/cli-select"))).default;
const { value } = await cliSelect({
values: ESLINT_PROMPT_VALUES,
valueRenderer: ({ title , recommended }, selected)=>{
const name = selected ? chalk.bold.underline.cyan(title) : title;
return name + (recommended ? chalk.bold.yellow(" (recommended)") : "");
},
selected: chalk.cyan("\u276F "),
unselected: " "
});
return {
config: value == null ? void 0 : value.config
};
} catch {
return {
config: null
};
}
}
async function lint(baseDir, lintDirs, eslintrcFile, pkgJsonPath, hasAppDir, { lintDuringBuild =false , eslintOptions =null , reportErrorsOnly =false , maxWarnings =-1 , formatter =null , outputFile =null }) {
try {
var ref, ref1;
// Load ESLint after we're sure it exists:
const deps = await hasNecessaryDependencies(baseDir, requiredPackages);
const packageManager = getPkgManager(baseDir);
if (deps.missing.some((dep)=>dep.pkg === "eslint")) {
Log.error(`ESLint must be installed${lintDuringBuild ? " in order to run during builds:" : ":"} ${chalk.bold.cyan((packageManager === "yarn" ? "yarn add --dev" : packageManager === "pnpm" ? "pnpm install --save-dev" : "npm install --save-dev") + " eslint")}`);
return null;
}
const mod = await Promise.resolve(require(deps.resolved.get("eslint")));
const { ESLint } = mod;
let eslintVersion = (ESLint == null ? void 0 : ESLint.version) ?? (mod == null ? void 0 : (ref = mod.CLIEngine) == null ? void 0 : ref.version);
if (!eslintVersion || semver.lt(eslintVersion, "7.0.0")) {
return `${chalk.red("error")} - Your project has an older version of ESLint installed${eslintVersion ? " (" + eslintVersion + ")" : ""}. Please upgrade to ESLint version 7 or above`;
}
let options = {
useEslintrc: true,
baseConfig: {},
errorOnUnmatchedPattern: false,
extensions: [
".js",
".jsx",
".ts",
".tsx"
],
cache: true,
...eslintOptions
};
let eslint = new ESLint(options);
let nextEslintPluginIsEnabled = false;
const nextRulesEnabled = new Map();
for (const configFile of [
eslintrcFile,
pkgJsonPath
]){
var ref2;
if (!configFile) continue;
const completeConfig = await eslint.calculateConfigForFile(configFile);
if ((ref2 = completeConfig.plugins) == null ? void 0 : ref2.includes("@next/next")) {
nextEslintPluginIsEnabled = true;
for (const [name, [severity]] of Object.entries(completeConfig.rules)){
if (!name.startsWith("@next/next/")) {
continue;
}
if (typeof severity === "number" && severity >= 0 && severity < VALID_SEVERITY.length) {
nextRulesEnabled.set(name, VALID_SEVERITY[severity]);
} else if (typeof severity === "string" && isValidSeverity(severity)) {
nextRulesEnabled.set(name, severity);
}
}
break;
}
}
const pagesDir = findPagesDir(baseDir, hasAppDir).pagesDir;
const pagesDirRules = pagesDir ? [
"@next/next/no-html-link-for-pages"
] : [];
if (nextEslintPluginIsEnabled) {
let updatedPagesDir = false;
for (const rule of pagesDirRules){
var ref3, ref4;
if (!((ref3 = options.baseConfig.rules) == null ? void 0 : ref3[rule]) && !((ref4 = options.baseConfig.rules) == null ? void 0 : ref4[rule.replace("@next/next", "@next/babel-plugin-next")])) {
if (!options.baseConfig.rules) {
options.baseConfig.rules = {};
}
options.baseConfig.rules[rule] = [
1,
pagesDir
];
updatedPagesDir = true;
}
}
if (updatedPagesDir) {
eslint = new ESLint(options);
}
} else {
Log.warn("The Next.js plugin was not detected in your ESLint configuration. See https://nextjs.org/docs/basic-features/eslint#migrating-existing-config");
}
const lintStart = process.hrtime();
let results = await eslint.lintFiles(lintDirs);
let selectedFormatter = null;
if (options.fix) await ESLint.outputFixes(results);
if (reportErrorsOnly) results = await ESLint.getErrorResults(results) // Only return errors if --quiet flag is used
;
if (formatter) selectedFormatter = await eslint.loadFormatter(formatter);
const formattedResult = formatResults(baseDir, results, selectedFormatter == null ? void 0 : selectedFormatter.format);
const lintEnd = process.hrtime(lintStart);
const totalWarnings = results.reduce((sum, file)=>sum + file.warningCount, 0);
if (outputFile) await writeOutputFile(outputFile, formattedResult.output);
return {
output: formattedResult.outputWithMessages,
isError: ((ref1 = ESLint.getErrorResults(results)) == null ? void 0 : ref1.length) > 0 || maxWarnings >= 0 && totalWarnings > maxWarnings,
eventInfo: {
durationInSeconds: lintEnd[0],
eslintVersion: eslintVersion,
lintedFilesCount: results.length,
lintFix: !!options.fix,
nextEslintPluginVersion: nextEslintPluginIsEnabled && deps.resolved.has("eslint-config-next") ? require(path.join(path.dirname(deps.resolved.get("eslint-config-next")), "package.json")).version : null,
nextEslintPluginErrorsCount: formattedResult.totalNextPluginErrorCount,
nextEslintPluginWarningsCount: formattedResult.totalNextPluginWarningCount,
nextRulesEnabled: Object.fromEntries(nextRulesEnabled)
}
};
} catch (err) {
if (lintDuringBuild) {
Log.error(`ESLint: ${isError(err) && err.message ? err.message.replace(/\n/g, " ") : err}`);
return null;
} else {
throw getProperError(err);
}
}
}
export async function runLintCheck(baseDir, lintDirs, hasAppDir, opts) {
const { lintDuringBuild =false , eslintOptions =null , reportErrorsOnly =false , maxWarnings =-1 , formatter =null , outputFile =null , strict =false , } = opts;
try {
// Find user's .eslintrc file
// See: https://eslint.org/docs/user-guide/configuring/configuration-files#configuration-file-formats
const eslintrcFile = await findUp([
".eslintrc.js",
".eslintrc.cjs",
".eslintrc.yaml",
".eslintrc.yml",
".eslintrc.json",
".eslintrc",
], {
cwd: baseDir
}) ?? null;
const pkgJsonPath = await findUp("package.json", {
cwd: baseDir
}) ?? null;
let packageJsonConfig = null;
if (pkgJsonPath) {
const pkgJsonContent = await fs.readFile(pkgJsonPath, {
encoding: "utf8"
});
packageJsonConfig = CommentJson.parse(pkgJsonContent);
}
const config = await hasEslintConfiguration(eslintrcFile, packageJsonConfig);
let deps;
if (config.exists) {
// Run if ESLint config exists
return await lint(baseDir, lintDirs, eslintrcFile, pkgJsonPath, hasAppDir, {
lintDuringBuild,
eslintOptions,
reportErrorsOnly,
maxWarnings,
formatter,
outputFile
});
} else {
// Display warning if no ESLint configuration is present inside
// config file during "next build", no warning is shown when
// no eslintrc file is present
if (lintDuringBuild) {
if (config.emptyPkgJsonConfig || config.emptyEslintrc) {
Log.warn(`No ESLint configuration detected. Run ${chalk.bold.cyan("next lint")} to begin setup`);
}
return null;
} else {
// Ask user what config they would like to start with for first time "next lint" setup
const { config: selectedConfig } = strict ? ESLINT_PROMPT_VALUES.find((opt)=>opt.title === "Strict") : await cliPrompt();
if (selectedConfig == null) {
// Show a warning if no option is selected in prompt
Log.warn("If you set up ESLint yourself, we recommend adding the Next.js ESLint plugin. See https://nextjs.org/docs/basic-features/eslint#migrating-existing-config");
return null;
} else {
// Check if necessary deps installed, and install any that are missing
deps = await hasNecessaryDependencies(baseDir, requiredPackages);
if (deps.missing.length > 0) await installDependencies(baseDir, deps.missing, true);
// Write default ESLint config.
// Check for /pages and src/pages is to make sure this happens in Next.js folder
if (existsSync(path.join(baseDir, "pages")) || existsSync(path.join(baseDir, "src/pages"))) {
await writeDefaultConfig(baseDir, config, selectedConfig, eslintrcFile, pkgJsonPath, packageJsonConfig);
}
}
Log.ready(`ESLint has successfully been configured. Run ${chalk.bold.cyan("next lint")} again to view warnings and errors.`);
return null;
}
}
} catch (err) {
throw err;
}
}
//# sourceMappingURL=runLintCheck.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,31 @@
import { promises as fs } from "fs";
import chalk from "next/dist/compiled/chalk";
import os from "os";
import path from "path";
import * as CommentJson from "next/dist/compiled/comment-json";
import * as Log from "../../build/output/log";
export async function writeDefaultConfig(baseDir, { exists , emptyEslintrc , emptyPkgJsonConfig }, selectedConfig, eslintrcFile, pkgJsonPath, packageJsonConfig) {
if (!exists && emptyEslintrc && eslintrcFile) {
const ext = path.extname(eslintrcFile);
let newFileContent;
if (ext === ".yaml" || ext === ".yml") {
newFileContent = "extends: 'next'";
} else {
newFileContent = CommentJson.stringify(selectedConfig, null, 2);
if (ext === ".js") {
newFileContent = "module.exports = " + newFileContent;
}
}
await fs.writeFile(eslintrcFile, newFileContent + os.EOL);
Log.info(`We detected an empty ESLint configuration file (${chalk.bold(path.basename(eslintrcFile))}) and updated it for you!`);
} else if (!exists && emptyPkgJsonConfig && packageJsonConfig) {
packageJsonConfig.eslintConfig = selectedConfig;
if (pkgJsonPath) await fs.writeFile(pkgJsonPath, CommentJson.stringify(packageJsonConfig, null, 2) + os.EOL);
Log.info(`We detected an empty ${chalk.bold("eslintConfig")} field in package.json and updated it for you!`);
} else if (!exists) {
await fs.writeFile(path.join(baseDir, ".eslintrc.json"), CommentJson.stringify(selectedConfig, null, 2) + os.EOL);
console.log(chalk.green(`We created the ${chalk.bold(".eslintrc.json")} file for you and included your selected configuration.`));
}
}
//# sourceMappingURL=writeDefaultConfig.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/eslint/writeDefaultConfig.ts"],"names":["promises","fs","chalk","os","path","CommentJson","Log","writeDefaultConfig","baseDir","exists","emptyEslintrc","emptyPkgJsonConfig","selectedConfig","eslintrcFile","pkgJsonPath","packageJsonConfig","ext","extname","newFileContent","stringify","writeFile","EOL","info","bold","basename","eslintConfig","join","console","log","green"],"mappings":"AAAA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AACnC,OAAOC,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,EAAE,MAAM,IAAI,CAAA;AACnB,OAAOC,IAAI,MAAM,MAAM,CA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I,CACN,CAAC,qBAAqB,EAAEpB,KAAK,CAACqB,IAAI,CAChC,cAAc,CACf,CAAC,8CAA8C,CAAC,CAClD;KACF,MAAM,IAAI,CAACd,MAAM,EAAE;QAClB,MAAMR,EAAE,CAACmB,SAAS,CAChBhB,IAAI,CAACsB,IAAI,CAAClB,OAAO,EAAE,gBAAgB,CAAC,EACpCH,WAAW,CAACc,SAAS,CAACP,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC,GAAGT,EAAE,CAACkB,GAAG,CACxD;QAEDM,OAAO,CAACC,GAAG,CACT1B,KAAK,CAAC2B,KAAK,CACT,CAAC,eAAe,EAAE3B,KAAK,CAACqB,IAAI,CAC1B,gBAAgB,CACjB,CAAC,uDAAuD,CAAC,CAC3D,CACF;KACF;CACF"}

View File

@@ -0,0 +1,38 @@
import { promises as fs } from "fs";
import path from "path";
import * as Log from "../../build/output/log";
import isError from "../../lib/is-error";
/**
* Check if a given file path is a directory or not.
* Returns `true` if the path is a directory.
*/ async function isDirectory(/** The path to a file to check. */ filePath) {
try {
return (await fs.stat(filePath)).isDirectory();
} catch (error) {
if (isError(error) && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
return false;
}
throw error;
}
}
/**
* Create a file with eslint output data
*/ export async function writeOutputFile(/** The name file that needs to be created */ outputFile, /** The data that needs to be inserted into the file */ outputData) {
const filePath = path.resolve(process.cwd(), outputFile);
if (await isDirectory(filePath)) {
Log.error(`Cannot write to output file path, it is a directory: ${filePath}`);
} else {
try {
await fs.mkdir(path.dirname(filePath), {
recursive: true
});
await fs.writeFile(filePath, outputData);
Log.info(`The output file has been created: ${filePath}`);
} catch (err) {
Log.error(`There was a problem writing the output file: ${filePath}`);
console.error(err);
}
}
}
//# sourceMappingURL=writeOutputFile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/eslint/writeOutputFile.ts"],"names":["promises","fs","path","Log","isError","isDirectory","filePath","stat","error","code","writeOutputFile","outputFile","outputData","resolve","process","cwd","mkd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AE;YACZlB,GAAG,CAACK,KAAK,CAAC,CAAC,6CAA6C,EAAEF,QAAQ,CAAC,CAAC,CAAC;YACrEgB,OAAO,CAACd,KAAK,CAACa,GAAG,CAAC;SACnB;KACF;CACF"}

View File

@@ -0,0 +1,4 @@
export class FatalError extends Error {
}
//# sourceMappingURL=fatal-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/fatal-error.ts"],"names":["FatalError","Error"],"mappings":"AAAA,OAAO,MAAMA,UAAU,SAASC,KAAK;CAAG"}

View File

@@ -0,0 +1,23 @@
import { constants, promises } from "fs";
import isError from "./is-error";
export async function fileExists(fileName, type) {
try {
if (type === "file") {
const stats = await promises.stat(fileName);
return stats.isFile();
} else if (type === "directory") {
const stats = await promises.stat(fileName);
return stats.isDirectory();
} else {
await promises.access(fileName, constants.F_OK);
}
return true;
} catch (err) {
if (isError(err) && (err.code === "ENOENT" || err.code === "ENAMETOOLONG")) {
return false;
}
throw err;
}
}
//# sourceMappingURL=file-exists.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/file-exists.ts"],"names":["constants","promises","isError","fileExists","fileName","type","stats","stat","isFile","isDirectory","access","F_OK","err","code"],"mappings":"AAAA,SAASA,SAAS,EAAEC,QAAQ,QAAQ,IAAI,CAAA;AACxC,OAAOC,OAAO,MAAM,YAAY,CAAA;AAEhC,OAAO,eAAeC,UAAU,CAC9BC,QAAgB,EAChBC,IAA2B,EACT;IAClB,IAAI;QACF,IAAIA,IAAI,KAAK,MAAM,EAAE;YACnB,MAAMC,KAAK,GAAG,MAAML,QAAQ,CAACM,IAAI,CAACH,QAAQ,CAAC;YAC3C,OAAOE,KAAK,CAACE,MAAM,EAAE,CAAA;SACtB,MAAM,IAAIH,IAAI,KAAK,WAAW,EAAE;YAC/B,MAAMC,KAAK,GAAG,MAAML,QAAQ,CAACM,IAAI,CAACH,QAAQ,CAAC;YAC3C,OAAOE,KAAK,CAACG,WAAW,EAAE,CAAA;SAC3B,MAAM;YACL,MAAMR,QAAQ,CAACS,MAAM,CAACN,QAAQ,EAAEJ,SAAS,CAACW,IAAI,CAAC;SAChD;QACD,OAAO,IAAI,CAAA;KACZ,CAAC,OAAOC,GAAG,EAAE;QACZ,IACEV,OAAO,CAACU,GAAG,CAAC,IACZ,CAACA,GAAG,CAACC,IAAI,KAAK,QAAQ,IAAID,GAAG,CAACC,IAAI,KAAK,cAAc,CAAC,EACtD;YACA,OAAO,KAAK,CAAA;SACb;QACD,MAAMD,GAAG,CAAA;KACV;CACF"}

View File

@@ -0,0 +1,44 @@
import findUp from "next/dist/compiled/find-up";
import fs from "fs";
import JSON5 from "next/dist/compiled/json5";
export function findConfigPath(dir, key) {
// If we didn't find the configuration in `package.json`, we should look for
// known filenames.
return findUp([
`.${key}rc.json`,
`${key}.config.json`,
`.${key}rc.js`,
`${key}.config.js`,
`${key}.config.cjs`,
], {
cwd: dir
});
}
// We'll allow configuration to be typed, but we force everything provided to
// become optional. We do not perform any schema validation. We should maybe
// force all the types to be `unknown` as well.
export async function findConfig(directory, key, _returnFile) {
// `package.json` configuration always wins. Let's check that first.
const packageJsonPath = await findUp("package.json", {
cwd: directory
});
if (packageJsonPath) {
const packageJson = require(packageJsonPath);
if (packageJson[key] != null && typeof packageJson[key] === "object") {
return packageJson[key];
}
}
const filePath = await findConfigPath(directory, key);
if (filePath) {
if (filePath.endsWith(".js") || filePath.endsWith(".cjs")) {
return require(filePath);
}
// We load JSON contents with JSON5 to allow users to comment in their
// configuration file. This pattern was popularized by TypeScript.
const fileContents = fs.readFileSync(filePath, "utf8");
return JSON5.parse(fileContents);
}
return null;
}
//# sourceMappingURL=find-config.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/find-config.ts"],"names":["findUp","fs","JSON5","findConfigPath","dir","key","cwd","findConfig","directory","_returnFile","packageJsonPath","packageJson","require","filePath","endsWith","fileContents","readFileSync","parse"],"mappings":"AAAA,OAAOA,MAAM,MAAM,4BAA4B,CAAA;AAC/C,O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Gd,EAAE,CAACe,YAAY,CAACH,QAAQ,EAAE,MAAM,CAAC;QACtD,OAAOX,KAAK,CAACe,KAAK,CAACF,YAAY,CAAC,CAAA;KACjC;IAED,OAAO,IAAI,CAAA;CACZ"}

View File

@@ -0,0 +1,43 @@
import fs from "fs";
import path from "path";
import * as Log from "../build/output/log";
export const existsSync = (f)=>{
try {
fs.accessSync(f, fs.constants.F_OK);
return true;
} catch (_) {
return false;
}
};
export function findDir(dir, name) {
// prioritize ./${name} over ./src/${name}
let curDir = path.join(dir, name);
if (existsSync(curDir)) return curDir;
curDir = path.join(dir, "src", name);
if (existsSync(curDir)) return curDir;
return null;
}
export function findPagesDir(dir, isAppDirEnabled) {
const pagesDir = findDir(dir, "pages") || undefined;
const appDir = findDir(dir, "app") || undefined;
if (isAppDirEnabled && appDir == null && pagesDir == null) {
throw new Error("> Couldn't find any `pages` or `app` directory. Please create one under the project root");
}
if (!isAppDirEnabled) {
if (appDir != null && pagesDir == null) {
throw new Error("> The `app` directory is experimental. To enable, add `appDir: true` to your `next.config.js` configuration under `experimental`. See https://nextjs.org/docs/messages/experimental-app-dir-config");
}
if (appDir != null && pagesDir != null) {
Log.warn("The `app` directory is experimental. To enable, add `appDir: true` to your `next.config.js` configuration under `experimental`. See https://nextjs.org/docs/messages/experimental-app-dir-config");
}
if (pagesDir == null) {
throw new Error("> Couldn't find a `pages` directory. Please create one under the project root");
}
}
return {
pagesDir,
appDir: isAppDirEnabled ? appDir : undefined
};
}
//# sourceMappingURL=find-pages-dir.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/find-pages-dir.ts"],"names":["fs","path","Log","existsSync","f","accessSync","constants","F_OK","_","findDir","dir","name","curDir","join","findPagesDir","isAppDirEnabled","pagesDir","undefined","appDir","Error","warn"],"mappings":"AAAA,OAAOA,EAAE,MAAM,IAAI,CAAA;AACnB,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,YAAYC,GAAG,MAAM,qBAAqB,CAAA;AAE1C,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J,QAAQ,IAAI,IAAI,EAAE;YACpB,MAAM,IAAIG,KAAK,CACb,+EAA+E,CAChF,CAAA;SACF;KACF;IAED,OAAO;QACLH,QAAQ;QACRE,MAAM,EAAEH,eAAe,GAAGG,MAAM,GAAGD,SAAS;KAC7C,CAAA;CACF"}

View File

@@ -0,0 +1,24 @@
import { join } from "path";
import { nonNullable } from "./non-nullable";
import { promises } from "fs";
export async function flatReaddir(dir, include) {
const dirents = await promises.readdir(dir, {
withFileTypes: true
});
const result = await Promise.all(dirents.map(async (part)=>{
const absolutePath = join(dir, part.name);
if (part.isSymbolicLink()) {
const stats = await promises.stat(absolutePath);
if (stats.isDirectory()) {
return null;
}
}
if (part.isDirectory() || !include.test(part.name)) {
return null;
}
return absolutePath;
}));
return result.filter(nonNullable);
}
//# sourceMappingURL=flat-readdir.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/flat-readdir.ts"],"names":["join","nonNullable","promises","flatReaddir","dir","include","dirents","readdir","withFileTypes","result","Promise","all","map","part","absolutePath","name","isSymbolicLink","stats","stat","isDirectory","test","filter"],"mappings":"AAAA,SAASA,IAAI,QAAQ,MAAM,CAAA;AAC3B,SAASC,WAAW,QAAQ,gBAAgB,CAAA;AAC5C,SAASC,QAAQ,QAAQ,IAAI,CAAA;AAE7B,OAAO,eAAeC,WAAW,CAACC,GAAW,EAAEC,OAAe,EAAE;IAC9D,MAAMC,OAAO,GAAG,MAAMJ,QAAQ,CAACK,OAAO,CAACH,GAAG,EAAE;QAAEI,aAAa,EAAE,IAAI;KAAE,CAAC;IACpE,MAAMC,MAAM,GAAG,MAAMC,OAAO,CAACC,GAAG,CAC9BL,OAAO,CAACM,GAAG,CAAC,OAAOC,IAAI,GAAK;QAC1B,MAAMC,YAAY,GAAGd,IAAI,CAACI,GAAG,EAAES,IAAI,CAACE,IAAI,CAAC;QACzC,IAAIF,IAAI,CAACG,cAAc,EAAE,EAAE;YACzB,MAAMC,KAAK,GAAG,MAAMf,QAAQ,CAACgB,IAAI,CAACJ,YAAY,CAAC;YAC/C,IAAIG,KAAK,CAACE,WAAW,EAAE,EAAE;gBACvB,OAAO,IAAI,CAAA;aACZ;SACF;QAED,IAAIN,IAAI,CAACM,WAAW,EAAE,IAAI,CAACd,OAAO,CAACe,IAAI,CAACP,IAAI,CAACE,IAAI,CAAC,EAAE;YAClD,OAAO,IAAI,CAAA;SACZ;QAED,OAAOD,YAAY,CAAA;KACpB,CAAC,CACH;IAED,OAAOL,MAAM,CAACY,MAAM,CAACpB,WAAW,CAAC,CAAA;CAClC"}

View File

@@ -0,0 +1,13 @@
export function formatServerError(error) {
if (error.message.includes("createContext is not a function")) {
const message = 'createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component';
error.message = message;
if (error.stack) {
const lines = error.stack.split("\n");
lines[0] = message;
error.stack = lines.join("\n");
}
}
}
//# sourceMappingURL=format-server-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/format-server-error.ts"],"names":["formatServerError","error","message","includes","stack","lines","split","join"],"mappings":"AAAA,OAAO,SAASA,iBAAiB,CAACC,KAAY,EAAQ;IACpD,IAAIA,KAAK,CAACC,OAAO,CAACC,QAAQ,CAAC,iCAAiC,CAAC,EAAE;QAC7D,MAAMD,OAAO,GACX,yLAAyL;QAC3LD,KAAK,CAACC,OAAO,GAAGA,OAAO;QACvB,IAAID,KAAK,CAACG,KAAK,EAAE;YACf,MAAMC,KAAK,GAAGJ,KAAK,CAACG,KAAK,CAACE,KAAK,CAAC,IAAI,CAAC;YACrCD,KAAK,CAAC,CAAC,CAAC,GAAGH,OAAO;YAClBD,KAAK,CAACG,KAAK,GAAGC,KAAK,CAACE,IAAI,CAAC,IAAI,CAAC;SAC/B;KACF;CACF"}

View File

@@ -0,0 +1,50 @@
import { promises as fs } from "fs";
import findUp from "next/dist/compiled/find-up";
import JSON5 from "next/dist/compiled/json5";
import * as path from "path";
let cachedDeps;
export function getDependencies({ cwd }) {
if (cachedDeps) {
return cachedDeps;
}
return cachedDeps = (async ()=>{
const configurationPath = await findUp("package.json", {
cwd
});
if (!configurationPath) {
return {
dependencies: {},
devDependencies: {}
};
}
const content = await fs.readFile(configurationPath, "utf-8");
const packageJson = JSON5.parse(content);
const { dependencies ={} , devDependencies ={} } = packageJson || {};
return {
dependencies,
devDependencies
};
})();
}
export async function getPackageVersion({ cwd , name }) {
const { dependencies , devDependencies } = await getDependencies({
cwd
});
if (!(dependencies[name] || devDependencies[name])) {
return null;
}
const cwd2 = cwd.endsWith(path.posix.sep) || cwd.endsWith(path.win32.sep) ? cwd : `${cwd}/`;
try {
const targetPath = require.resolve(`${name}/package.json`, {
paths: [
cwd2
]
});
const targetContent = await fs.readFile(targetPath, "utf-8");
return JSON5.parse(targetContent).version ?? null;
} catch {
return null;
}
}
//# sourceMappingURL=get-package-version.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/get-package-version.ts"],"names":["promises","fs","findUp","JSON5","path","cachedDeps","getDependencies","cwd","configurationPath","dependencies","devDependencies","content","readFile","packageJson","parse","getPackageVersion","name","cwd2","endsWith","posix","sep","win32","targetPath","require","resolve","paths","targetContent","version"],"mappings":"AAAA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AACnC,OAAOC,MAAM,MAAM,4BAA4B,CAAA;AAC/C,OAAOC,KAAK,MAAM,0BAA0B,CAAA;AAC5C,YAAYC,IAAI,MAAM,MAAM,CAAA;AAO5B,IAAIC,UAAU,AAAkC;AAEhD,OAAO,SAASC,eAAe,CAAC,EAC9BC,GAAG,CAAA,EAGJ,EAAoC;IACnC,IAAIF,UAAU,EAAE;QACd,OAAOA,UAAU,CAAA;KAClB;IAED,OAAQA,UAAU,GAAG,CAAC,UAAY;QAChC,MAAMG,iBAAiB,GAAuB,MAAMN,MAAM,CAAC,cAAc,EAAE;YACzEK,GAAG;SACJ,CAAC;QACF,IAAI,CAACC,iBAAiB,EAAE;YACtB,OAAO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AI,IAAI,CAAA;KAClD,CAAC,OAAM;QACN,OAAO,IAAI,CAAA;KACZ;CACF"}

View File

@@ -0,0 +1,30 @@
import fs from "fs";
import path from "path";
import { commands } from "./commands";
import * as Log from "../build/output/log";
import { detectTypo } from "./detect-typo";
export function getProjectDir(dir) {
try {
const resolvedDir = path.resolve(dir || ".");
const realDir = fs.realpathSync.native(resolvedDir);
if (resolvedDir !== realDir && resolvedDir.toLowerCase() === realDir.toLowerCase()) {
Log.warn(`Invalid casing detected for project dir, received ${resolvedDir} actual path ${realDir}, see more info here https://nextjs.org/docs/messages/invalid-project-dir-casing`);
}
return realDir;
} catch (err) {
if (err.code === "ENOENT") {
if (typeof dir === "string") {
const detectedTypo = detectTypo(dir, Object.keys(commands));
if (detectedTypo) {
Log.error(`"next ${dir}" does not exist. Did you mean "next ${detectedTypo}"?`);
process.exit(1);
}
}
Log.error(`Invalid project directory provided, no such directory: ${path.resolve(dir || ".")}`);
process.exit(1);
}
throw err;
}
}
//# sourceMappingURL=get-project-dir.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/get-project-dir.ts"],"names":["fs","path","commands","Log","detectTypo","getProjectDir","dir","resolvedDir","resolve","realDir","realpathSync","native","toLowerCase","warn","err","code","detectedTypo","Object","keys","error","process","exit"],"mappings":"AAAA,OAAOA,EAAE,MAAM,IAAI,CAAA;AACnB,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,SAASC,QAAQ,QAAQ,YAAY,CAAA;AACrC,YAAYC,GAAG,MAAM,qBAAqB,CAAA;AAC1C,SAASC,UAAU,QAAQ,eAAe,CAAA;AAE1C,OAAO,SAASC,aAAa,CAACC,GAAY,EAAE;IAC1C,IAAI;QACF,MAAMC,WAAW,GAAGN,IAAI,CAACO,OAAO,CAACF,GAAG,IAAI,GAAG,CAAC;QAC5C,MAAMG,OAAO,GAAGT,EAAE,CAACU,YAAY,CAACC,MAAM,CAACJ,WAAW,CAAC;QAEnD,IACEA,WAAW,KAAKE,OAAO,IACvBF,WAAW,CAACK,WAAW,EAAE,KAAKH,OAAO,CAACG,WAAW,EAAE,EACnD;YACAT,GAAG,CAACU,IAAI,CACN,CAAC,kDAAkD,EAAEN,WAAW,CAAC,aAAa,EAAEE,OAAO,CAAC,gFAAgF,CAAC,CAC1K;SACF;QAED,OAAOA,OAAO,CAAA;KACf,CAAC,OAAOK,GAAG,EAAO;QACjB,IAAIA,GAAG,CAACC,IAAI,KAAK,QAAQ,EAAE;YACzB,IAAI,OAAOT,GAAG,KAAK,QAAQ,EAAE;gBAC3B,MAAMU,YAAY,GAAGZ,UAAU,CAACE,GAAG,EAAEW,MAAM,CAACC,IAAI,CAAChB,QAAQ,CAAC,CAAC;gBAE3D,IAAIc,YAAY,EAAE;oBAChBb,GAAG,CAACgB,KAAK,CACP,CAAC,MAAM,EAAEb,GAAG,CAAC,qCAAqC,EAAEU,YAAY,CAAC,EAAE,CAAC,CACrE;oBACDI,OAAO,CAACC,IAAI,CAAC,CAAC,CAAC;iBAChB;aACF;YAEDlB,GAAG,CAACgB,KAAK,CACP,CAAC,uDAAuD,EAAElB,IAAI,CAACO,OAAO,CACpEF,GAAG,IAAI,GAAG,CACX,CAAC,CAAC,CACJ;YACDc,OAAO,CAACC,IAAI,CAAC,CAAC,CAAC;SAChB;QACD,MAAMP,GAAG,CAAA;KACV;CACF"}

View File

@@ -0,0 +1,37 @@
import { promises as fs } from "fs";
import { fileExists } from "./file-exists";
import { resolveFrom } from "./resolve-from";
import { dirname, join, relative } from "path";
export async function hasNecessaryDependencies(baseDir, requiredPackages) {
let resolutions = new Map();
const missingPackages = [];
await Promise.all(requiredPackages.map(async (p)=>{
try {
const pkgPath = await fs.realpath(resolveFrom(baseDir, `${p.pkg}/package.json`));
const pkgDir = dirname(pkgPath);
if (p.exportsRestrict) {
const fileNameToVerify = relative(p.pkg, p.file);
if (fileNameToVerify) {
const fileToVerify = join(pkgDir, fileNameToVerify);
if (await fileExists(fileToVerify)) {
resolutions.set(p.pkg, fileToVerify);
} else {
return missingPackages.push(p);
}
} else {
resolutions.set(p.pkg, pkgPath);
}
} else {
resolutions.set(p.pkg, resolveFrom(baseDir, p.file));
}
} catch (_) {
return missingPackages.push(p);
}
}));
return {
resolved: resolutions,
missing: missingPackages
};
}
//# sourceMappingURL=has-necessary-dependencies.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/has-necessary-dependencies.ts"],"names":["promises","fs","fileExists","resolveFrom","dirname","join","relative","hasNecessaryDependencies","baseDir","requiredPackages","resolutions","Map","missingPackages","Promise","all","map","p","pkgPath","realpath","pkg","pkgDir","exportsRestrict","fileNameToVerify","file","fileToVerify","set","push","_","resolved","missing"],"mappings":"AAAA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AACnC,SAASC,UAAU,QAAQ,eAAe,CAAA;AAC1C,SAASC,WAAW,QAAQ,gBAAgB,CAAA;AAC5C,SAASC,OAAO,EAAEC,IAAI,EAAEC,QAAQ,QAAQ,MAAM,CAAA;AAa9C,OAAO,eAAeC,wBAAwB,CAC5CC,OAAe,EACfC,gBAAqC,EACL;IAChC,IAAIC,WAAW,GAAG,IAAIC,GAAG,EAAkB;IAC3C,MAAMC,eAAe,GAAwB,EAAE;IAE/C,MAAMC,OAAO,CAACC,GAAG,CACfL,gBAAgB,CAACM,GAAG,CAAC,OAAOC,CAAC,GAAK;QAChC,IAAI;YACF,MAAMC,OAAO,GAAG,MAAMhB,EAAE,CAACiB,QAAQ,CAC/Bf,WAAW,CAACK,OAAO,EAAE,CAAC,EAAEQ,CAAC,CAACG,GAAG,CAAC,aAAa,CAAC,CAAC,CAC9C;YACD,MAAMC,MAAM,GAAGhB,OAAO,CAACa,OAAO,CAAC;YAE/B,IAAID,CAAC,CAACK,eAAe,EAAE;gBACrB,MAAMC,gBAAgB,GAAGhB,QAAQ,CAACU,CAAC,CAACG,GAAG,EAAEH,CAAC,CAACO,IAAI,CAAC;gBAChD,IAAID,gBAAgB,EAAE;oBACpB,MAAME,YAAY,GAAGnB,IAAI,CAACe,MAAM,EAAEE,gBAAgB,CAAC;oBACnD,IAAI,MAAMpB,UAAU,CAACsB,YAAY,CAAC,EAAE;wBAClCd,WAAW,CAACe,GAAG,CAACT,CAAC,CAACG,GAAG,EAAEK,YAAY,CAAC;qBACrC,MAAM;wBACL,OAAOZ,eAAe,CAACc,IAAI,CAACV,CAAC,CAAC,CAAA;qBAC/B;iBACF,MAAM;oBACLN,WAAW,CAACe,GAAG,CAACT,CAAC,CAACG,GAAG,EAAEF,OAAO,CAAC;iBAChC;aACF,MAAM;gBACLP,WAAW,CAACe,GAAG,CAACT,CAAC,CAACG,GAAG,EAAEhB,WAAW,CAACK,OAAO,EAAEQ,CAAC,CAACO,IAAI,CAAC,CAAC;aACrD;SACF,CAAC,OAAOI,CAAC,EAAE;YACV,OAAOf,eAAe,CAACc,IAAI,CAACV,CAAC,CAAC,CAAA;SAC/B;KACF,CAAC,CACH;IAED,OAAO;QACLY,QAAQ,EAAElB,WAAW;QACrBmB,OAAO,EAAEjB,eAAe;KACzB,CAAA;CACF"}

View File

@@ -0,0 +1,36 @@
import { execSync } from "child_process";
import dns from "dns";
import url from "url";
function getProxy() {
if (process.env.https_proxy) {
return process.env.https_proxy;
}
try {
const httpsProxy = execSync("npm config get https-proxy").toString().trim();
return httpsProxy !== "null" ? httpsProxy : undefined;
} catch (e) {
return;
}
}
export function getOnline() {
return new Promise((resolve)=>{
dns.lookup("registry.yarnpkg.com", (registryErr)=>{
if (!registryErr) {
return resolve(true);
}
const proxy = getProxy();
if (!proxy) {
return resolve(false);
}
const { hostname } = url.parse(proxy);
if (!hostname) {
return resolve(false);
}
dns.lookup(hostname, (proxyErr)=>{
resolve(proxyErr == null);
});
});
});
}
//# sourceMappingURL=get-online.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/helpers/get-online.ts"],"names":["execSync","dns","url","getProxy","process","env","https_proxy","httpsProxy","toString","trim","undefined","e","getOnline","Promise","resolve","lookup","registryErr","proxy","hostname","parse","proxyErr"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,eAAe,CAAA;AACxC,OAAOC,GAAG,MAAM,KAAK,CAAA;AACrB,OAAOC,GAAG,MAAM,KAAK,CAAA;AAErB,SAASC,QAAQ,GAAuB;IACtC,IAAIC,OAAO,CAACC,GAAG,CAACC,WAAW,EAAE;QAC3B,OAAOF,OAAO,CAACC,GAAG,CAACC,WAAW,CAAA;KAC/B;IAED,IAAI;QACF,MAAMC,UAAU,GAAGP,QAAQ,CAAC,4BAA4B,CAAC,CAACQ,QAAQ,EAAE,CAACC,IAAI,EAAE;QAC3E,OAAOF,UAAU,KAAK,MAAM,GAAGA,UAAU,GAAGG,SAAS,CAAA;KACtD,CAAC,OAAOC,CAAC,EAAE;QACV,OAAM;KACP;CACF;AAED,OAAO,SAASC,SAAS,GAAqB;IAC5C,OAAO,IAAIC,OAAO,CAAC,CAACC,OAAO,GAAK;QAC9Bb,GAAG,CAACc,MAAM,CAAC,sBAAsB,EAAE,CAACC,WAAW,GAAK;YAClD,IAAI,CAACA,WAAW,EAAE;gBAChB,OAAOF,OAAO,CAAC,IAAI,CAAC,CAAA;aACrB;YAED,MAAMG,KAAK,GAAGd,QAAQ,EAAE;YACxB,IAAI,CAACc,KAAK,EAAE;gBACV,OAAOH,OAAO,CAAC,KAAK,CAAC,CAAA;aACtB;YAED,MAAM,EAAEI,QAAQ,CAAA,EAAE,GAAGhB,GAAG,CAACiB,KAAK,CAACF,KAAK,CAAC;YACrC,IAAI,CAACC,QAAQ,EAAE;gBACb,OAAOJ,OAAO,CAAC,KAAK,CAAC,CAAA;aACtB;YAEDb,GAAG,CAACc,MAAM,CAACG,QAAQ,EAAE,CAACE,QAAQ,GAAK;gBACjCN,OAAO,CAACM,QAAQ,IAAI,IAAI,CAAC;aAC1B,CAAC;SACH,CAAC;KACH,CAAC,CAAA;CACH"}

View File

@@ -0,0 +1,48 @@
import fs from "fs";
import path from "path";
import { execSync } from "child_process";
export function getPkgManager(baseDir) {
try {
for (const { lockFile , packageManager } of [
{
lockFile: "yarn.lock",
packageManager: "yarn"
},
{
lockFile: "pnpm-lock.yaml",
packageManager: "pnpm"
},
{
lockFile: "package-lock.json",
packageManager: "npm"
},
]){
if (fs.existsSync(path.join(baseDir, lockFile))) {
return packageManager;
}
}
const userAgent = process.env.npm_config_user_agent;
if (userAgent) {
if (userAgent.startsWith("yarn")) {
return "yarn";
} else if (userAgent.startsWith("pnpm")) {
return "pnpm";
}
}
try {
execSync("yarn --version", {
stdio: "ignore"
});
return "yarn";
} catch {
execSync("pnpm --version", {
stdio: "ignore"
});
return "pnpm";
}
} catch {
return "npm";
}
}
//# sourceMappingURL=get-pkg-manager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/helpers/get-pkg-manager.ts"],"names":["fs","path","execSync","getPkgManager","baseDir","lockFile","packageManager","existsSync","join","userAgent","process","env","npm_config_user_agent","startsWith","stdio"],"mappings":"AAAA,OAAOA,EAAE,MAAM,IAAI,CAAA;AACnB,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,SAASC,QAAQ,QAAQ,eAAe,CAAA;AAIxC,OAAO,SAASC,aAAa,CAACC,OAAe,EAAkB;IAC7D,IAAI;QACF,KAAK,MAAM,EAAEC,QAAQ,CAAA,EAAEC,cAAc,CAAA,EAAE,IAAI;YACzC;gBAAED,QAAQ,EAAE,WAAW;gBAAEC,cAAc,EAAE,MAAM;aAAE;YACjD;gBAAED,QAAQ,EAAE,gBAAgB;gBAAEC,cAAc,EAAE,MAAM;aAAE;YACtD;gBAAED,QAAQ,EAAE,mBAAmB;gBAAEC,cAAc,EAAE,KAAK;aAAE;SACzD,CAAE;YACD,IAAIN,EAAE,CAACO,UAAU,CAACN,IAAI,CAACO,IAAI,CAACJ,OAAO,EAAEC,QAAQ,CAAC,CAAC,EAAE;gBAC/C,OAAOC,cAAc,CAAkB;aACxC;SACF;QACD,MAAMG,SAAS,GAAGC,OAAO,CAACC,GAAG,CAACC,qBAAqB;QACnD,IAAIH,SAAS,EAAE;YACb,IAAIA,SAAS,CAACI,UAAU,CAAC,MAAM,CAAC,EAAE;gBAChC,OAAO,MAAM,CAAA;aACd,MAAM,IAAIJ,SAAS,CAACI,UAAU,CAAC,MAAM,CAAC,EAAE;gBACvC,OAAO,MAAM,CAAA;aACd;SACF;QACD,IAAI;YACFX,QAAQ,CAAC,gBAAgB,EAAE;gBAAEY,KAAK,EAAE,QAAQ;aAAE,CAAC;YAC/C,OAAO,MAAM,CAAA;SACd,CAAC,OAAM;YACNZ,QAAQ,CAAC,gBAAgB,EAAE;gBAAEY,KAAK,EAAE,QAAQ;aAAE,CAAC;YAC/C,OAAO,MAAM,CAAA;SACd;KACF,CAAC,OAAM;QACN,OAAO,KAAK,CAAA;KACb;CACF"}

View File

@@ -0,0 +1,94 @@
import chalk from "next/dist/compiled/chalk";
import spawn from "next/dist/compiled/cross-spawn";
/**
* Spawn a package manager installation with either Yarn or NPM.
*
* @returns A Promise that resolves once the installation is finished.
*/ export function install(root, dependencies, { packageManager , isOnline , devDependencies }) {
/**
* (p)npm-specific command-line flags.
*/ const npmFlags = [];
/**
* Yarn-specific command-line flags.
*/ const yarnFlags = [];
/**
* Return a Promise that resolves once the installation is finished.
*/ return new Promise((resolve, reject)=>{
let args;
let command = packageManager;
const useYarn = packageManager === "yarn";
if (dependencies && dependencies.length) {
/**
* If there are dependencies, run a variation of `{packageManager} add`.
*/ if (useYarn) {
/**
* Call `yarn add --exact (--offline)? (-D)? ...`.
*/ args = [
"add",
"--exact"
];
if (!isOnline) args.push("--offline");
args.push("--cwd", root);
if (devDependencies) args.push("--dev");
args.push(...dependencies);
} else {
/**
* Call `(p)npm install [--save|--save-dev] ...`.
*/ args = [
"install",
"--save-exact"
];
args.push(devDependencies ? "--save-dev" : "--save");
args.push(...dependencies);
}
} else {
/**
* If there are no dependencies, run a variation of `{packageManager}
* install`.
*/ args = [
"install"
];
if (!isOnline) {
console.log(chalk.yellow("You appear to be offline."));
if (useYarn) {
console.log(chalk.yellow("Falling back to the local Yarn cache."));
console.log();
args.push("--offline");
} else {
console.log();
}
}
}
/**
* Add any package manager-specific flags.
*/ if (useYarn) {
args.push(...yarnFlags);
} else {
args.push(...npmFlags);
}
/**
* Spawn the installation process.
*/ const child = spawn(command, args, {
stdio: "inherit",
env: {
...process.env,
ADBLOCK: "1",
// we set NODE_ENV to development as pnpm skips dev
// dependencies when production
NODE_ENV: "development",
DISABLE_OPENCOLLECTIVE: "1"
}
});
child.on("close", (code)=>{
if (code !== 0) {
reject({
command: `${command} ${args.join(" ")}`
});
return;
}
resolve();
});
});
}
//# sourceMappingURL=install.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/helpers/install.ts"],"names":["chalk","spawn","install","root","dependencies","packageManager","isOnline","devDependencies","npmFlags","yarnFlags","Promise","resolve","reject","args","command","useYarn","length","push","console","log","yellow","child","stdio","env","process","ADBLOCK","NODE_ENV","DISABLE_OPENCOLLECTIVE","on","code","join"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,KAAK,MAAM,gCAAgC,CAAA;AAmBlD;;;;GAIG,CACH,OAAO,SAASC,OAAO,CACrBC,IAAY,EACZC,YAA6B,EAC7B,EAAEC,cAAc,CAAA,EAAEC,QAAQ,CAAA,EAAEC,eAAe,CAAA,EAAe,EAC3C;IACf;;KAEG,CACH,MAAMC,QAAQ,GAAa,EAAE;IAC7B;;KAEG,CACH,MAAMC,SAAS,GAAa,EAAE;IAC9B;;KAEG,CACH,OAAO,IAAIC,OAAO,CAAC,CAACC,OAAO,EAAEC,MAAM,GAAK;QACtC,IAAIC,IAAI,AAAU;QAClB,IAAIC,OAAO,GAAGT,cAAc;QAC5B,MAAMU,OAAO,GAAGV,cAAc,KAAK,MAAM;QAEzC,IAAID,YAAY,IAAIA,YAAY,CAACY,MAAM,EAAE;YACvC;;SAEG,CACH,IAAID,OAAO,EAAE;gBACX;;WAEG,CACHF,IAA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D,+BAA+B;gBAC/BC,QAAQ,EAAE,aAAa;gBACvBC,sBAAsB,EAAE,GAAG;aAC5B;SACF,CAAC;QACFN,KAAK,CAACO,EAAE,CAAC,OAAO,EAAE,CAACC,IAAI,GAAK;YAC1B,IAAIA,IAAI,KAAK,CAAC,EAAE;gBACdjB,MAAM,CAAC;oBAAEE,OAAO,EAAE,CAAC,EAAEA,OAAO,CAAC,CAAC,EAAED,IAAI,CAACiB,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;iBAAE,CAAC;gBACnD,OAAM;aACP;YACDnB,OAAO,EAAE;SACV,CAAC;KACH,CAAC,CAAA;CACH"}

View File

@@ -0,0 +1,5 @@
var ref;
import * as Log from "../build/output/log";
Log.warn(`"next" should not be imported directly, imported in ${(ref = module.parent) == null ? void 0 : ref.filename}\nSee more info here: https://nextjs.org/docs/messages/import-next`);
//# sourceMappingURL=import-next-warning.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/import-next-warning.ts"],"names":["module","Log","warn","parent","filename"],"mappings":"AAAA,IAGyDA,GAAa;AAHtE,YAAYC,GAAG,MAAM,qBAAqB,CAAA;AAE1CA,GAAG,CAACC,IAAI,CACN,CAAC,oDAAoD,EAAEF,CAAAA,GAAa,GAAbA,MAAM,CAACG,MAAM,SAAU,GAAvBH,KAAAA,CAAuB,GAAvBA,GAAa,CAAEI,QAAQ,CAAC,kEAAkE,CAAC,CACnJ"}

View File

@@ -0,0 +1,25 @@
import chalk from "next/dist/compiled/chalk";
import path from "path";
import { getPkgManager } from "./helpers/get-pkg-manager";
import { install } from "./helpers/install";
import { getOnline } from "./helpers/get-online";
export async function installDependencies(baseDir, deps, dev = false) {
const packageManager = getPkgManager(baseDir);
const isOnline = await getOnline();
if (deps.length) {
console.log();
console.log(`Installing ${dev ? "devDependencies" : "dependencies"} (${packageManager}):`);
for (const dep1 of deps){
console.log(`- ${chalk.cyan(dep1.pkg)}`);
}
console.log();
await install(path.resolve(baseDir), deps.map((dep)=>dep.pkg), {
devDependencies: dev,
isOnline,
packageManager
});
console.log();
}
}
//# sourceMappingURL=install-dependencies.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/install-dependencies.ts"],"names":["chalk","path","getPkgManager","install","getOnline","installDependencies","baseDir","deps","dev","packageManager","isOnline","length","console","log","dep","cyan","pkg","resolve","map","devDependencies"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,IAAI,MAAM,MAAM,CAAA;AAGvB,SAASC,aAAa,QAAQ,2BAA2B,CAAA;AACzD,SAASC,OAAO,QAAQ,mBAAmB,CAAA;AAC3C,SAASC,SAAS,QAAQ,sBAAsB,CAAA;AAMhD,OAAO,eAAeC,mBAAmB,CACvCC,OAAe,EACfC,IAAS,EACTC,GAAY,GAAG,KAAK,EACpB;IACA,MAAMC,cAAc,GAAGP,aAAa,CAACI,OAAO,CAAC;IAC7C,MAAMI,QAAQ,GAAG,MAAMN,SAAS,EAAE;IAElC,IAAIG,IAAI,CAACI,MAAM,EAAE;QACfC,OAAO,CAACC,GAAG,EAAE;QACbD,OAAO,CAACC,GAAG,CACT,CAAC,WAAW,EACVL,GAAG,GAAG,iBAAiB,GAAG,cAAc,CACzC,EAAE,EAAEC,cAAc,CAAC,EAAE,CAAC,CACxB;QACD,KAAK,MAAMK,IAAG,IAAIP,IAAI,CAAE;YACtBK,OAAO,CAACC,GAAG,CAAC,CAAC,EAAE,EAAEb,KAAK,CAACe,IAAI,CAACD,IAAG,CAACE,GAAG,CAAC,CAAC,CAAC,CAAC;SACxC;QACDJ,OAAO,CAACC,GAAG,EAAE;QAEb,MAAMV,OAAO,CACXF,IAAI,CAACgB,OAAO,CAACX,OAAO,CAAC,EACrBC,IAAI,CAACW,GAAG,CAAC,CAACJ,GAAsB,GAAKA,GAAG,CAACE,GAAG,CAAC,EAC7C;YAAEG,eAAe,EAAEX,GAAG;YAAEE,QAAQ;YAAED,cAAc;SAAE,CACnD;QACDG,OAAO,CAACC,GAAG,EAAE;KACd;CACF"}

View File

@@ -0,0 +1,5 @@
export function interopDefault(mod) {
return mod.default || mod;
}
//# sourceMappingURL=interop-default.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/interop-default.ts"],"names":["interopDefault","mod","default"],"mappings":"AAAA,OAAO,SAASA,cAAc,CAACC,GAAQ,EAAE;IACvC,OAAOA,GAAG,CAACC,OAAO,IAAID,GAAG,CAAA;CAC1B"}

View File

@@ -0,0 +1,5 @@
export function isAPIRoute(value) {
return value === "/api" || Boolean(value == null ? void 0 : value.startsWith("/api/"));
}
//# sourceMappingURL=is-api-route.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/is-api-route.ts"],"names":["isAPIRoute","value","Boolean","startsWith"],"mappings":"AAAA,OAAO,SAASA,UAAU,CAACC,KAAc,EAAE;IACzC,OAAOA,KAAK,KAAK,MAAM,IAAIC,OAAO,CAACD,KAAK,QAAY,GAAjBA,KAAAA,CAAiB,GAAjBA,KAAK,CAAEE,UAAU,CAAC,OAAO,CAAC,CAAC,CAAA;CAC/D"}

View File

@@ -0,0 +1,6 @@
import { SERVER_RUNTIME } from "./constants";
export function isEdgeRuntime(value) {
return value === SERVER_RUNTIME.experimentalEdge || value === SERVER_RUNTIME.edge;
}
//# sourceMappingURL=is-edge-runtime.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/is-edge-runtime.ts"],"names":["SERVER_RUNTIME","isEdgeRuntime","value","experimentalEdge","edge"],"mappings":"AACA,SAASA,cAAc,QAAQ,aAAa,CAAA;AAE5C,OAAO,SAASC,aAAa,CAACC,KAAc,EAA0B;IACpE,OACEA,KAAK,KAAKF,cAAc,CAACG,gBAAgB,IAAID,KAAK,KAAKF,cAAc,CAACI,IAAI,CAC3E;CACF"}

22
kitabcitab/node_modules/next/dist/esm/lib/is-error.js generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import { isPlainObject } from "../shared/lib/is-plain-object";
export default function isError(err) {
return typeof err === "object" && err !== null && "name" in err && "message" in err;
};
export function getProperError(err) {
if (isError(err)) {
return err;
}
if (process.env.NODE_ENV === "development") {
// provide better error for case where `throw undefined`
// is called in development
if (typeof err === "undefined") {
return new Error("An undefined error was thrown, " + "see here for more info: https://nextjs.org/docs/messages/threw-undefined");
}
if (err === null) {
return new Error("A null error was thrown, " + "see here for more info: https://nextjs.org/docs/messages/threw-undefined");
}
}
return new Error(isPlainObject(err) ? JSON.stringify(err) : err + "");
}
//# sourceMappingURL=is-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/is-error.ts"],"names":["isPlainObject","isError","err","getProperError","process","env","NODE_ENV","Error","JSON","stringify"],"mappings":"AAAA,SAASA,aAAa,QAAQ,+BAA+B,CAAA;AAU7D,eAAe,SAASC,OAAO,CAACC,GAAY,EAAoB;IAC9D,OACE,OAAOA,GAAG,KAAK,QAAQ,IAAIA,GAAG,KAAK,IAAI,IAAI,MAAM,IAAIA,GAAG,IAAI,SAAS,IAAIA,GAAG,CAC7E;CACF,CAAA;AAED,OAAO,SAASC,cAAc,CAACD,GAAY,EAAS;IAClD,IAAID,OAAO,CAACC,GAAG,CAAC,EAAE;QAChB,OAAOA,GAAG,CAAA;KACX;IAED,IAAIE,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,aAAa,EAAE;QAC1C,wDAAwD;QACxD,2BAA2B;QAC3B,IAAI,OAAOJ,GAAG,KAAK,WAAW,EAAE;YAC9B,OAAO,IAAIK,KAAK,CACd,iCAAiC,GAC/B,0EAA0E,CAC7E,CAAA;SACF;QAED,IAAIL,GAAG,KAAK,IAAI,EAAE;YAChB,OAAO,IAAIK,KAAK,CACd,2BAA2B,GACzB,0EAA0E,CAC7E,CAAA;SACF;KACF;IAED,OAAO,IAAIA,KAAK,CAACP,aAAa,CAACE,GAAG,CAAC,GAAGM,IAAI,CAACC,SAAS,CAACP,GAAG,CAAC,GAAGA,GAAG,GAAG,EAAE,CAAC,CAAA;CACtE"}

View File

@@ -0,0 +1,60 @@
import { isPlainObject, getObjectClassLabel } from "../shared/lib/is-plain-object";
const regexpPlainIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
export class SerializableError extends Error {
constructor(page, method, path, message){
super(path ? `Error serializing \`${path}\` returned from \`${method}\` in "${page}".\nReason: ${message}` : `Error serializing props returned from \`${method}\` in "${page}".\nReason: ${message}`);
}
}
export function isSerializableProps(page, method, input) {
if (!isPlainObject(input)) {
throw new SerializableError(page, method, "", `Props must be returned as a plain object from ${method}: \`{ props: { ... } }\` (received: \`${getObjectClassLabel(input)}\`).`);
}
function visit(visited, value, path) {
if (visited.has(value)) {
throw new SerializableError(page, method, path, `Circular references cannot be expressed in JSON (references: \`${visited.get(value) || "(self)"}\`).`);
}
visited.set(value, path);
}
function isSerializable(refs, value, path) {
const type = typeof value;
if (// `null` can be serialized, but not `undefined`.
value === null || // n.b. `bigint`, `function`, `symbol`, and `undefined` cannot be
// serialized.
//
// `object` is special-cased below, as it may represent `null`, an Array,
// a plain object, a class, et al.
type === "boolean" || type === "number" || type === "string") {
return true;
}
if (type === "undefined") {
throw new SerializableError(page, method, path, "`undefined` cannot be serialized as JSON. Please use `null` or omit this value.");
}
if (isPlainObject(value)) {
visit(refs, value, path);
if (Object.entries(value).every(([key, nestedValue])=>{
const nextPath = regexpPlainIdentifier.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`;
const newRefs = new Map(refs);
return isSerializable(newRefs, key, nextPath) && isSerializable(newRefs, nestedValue, nextPath);
})) {
return true;
}
throw new SerializableError(page, method, path, `invariant: Unknown error encountered in Object.`);
}
if (Array.isArray(value)) {
visit(refs, value, path);
if (value.every((nestedValue, index)=>{
const newRefs = new Map(refs);
return isSerializable(newRefs, nestedValue, `${path}[${index}]`);
})) {
return true;
}
throw new SerializableError(page, method, path, `invariant: Unknown error encountered in Array.`);
}
// None of these can be expressed as JSON:
// const type: "bigint" | "symbol" | "object" | "function"
throw new SerializableError(page, method, path, "`" + type + "`" + (type === "object" ? ` ("${Object.prototype.toString.call(value)}")` : "") + " cannot be serialized as JSON. Please only return JSON serializable data types.");
}
return isSerializable(new Map(), input, "");
}
//# sourceMappingURL=is-serializable-props.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/is-serializable-props.ts"],"names":["isPlainObject","getObjectClassLabel","regexpPlainIdentifier","SerializableError","Error","constructor","page","method","path","message","isSerializableProps","input","visit","visited","value","has","get","set","isSerializable","refs","type","Object","entries","every","key","nestedValue","nextPath","test","JSON","stringify","newRefs","Map","Array","isArray","index","prototype","toString","call"],"mappings":"AAAA,SACEA,aAAa,EACbC,mBAAmB,QACd,+BAA+B,CAAA;AAEtC,MAAMC,qBAAqB,+BAA+B;AAE1D,OAAO,MAAMC,iBAAiB,SAASC,KAAK;IAC1CC,YAAYC,IAAY,EAAEC,MAAc,EAAEC,IAAY,EAAEC,OAAe,CAAE;QACvE,KAAK,CACHD,IAAI,GACA,CAAC,oBAAoB,EAAEA,IAAI,CAAC,mBAAmB,EAAED,MAAM,CAAC,OAAO,EAAED,IAAI,CAAC,YAAY,EAAEG,OAAO,CAAC,CAAC,GAC7F,CAAC,wCAAwC,EAAEF,MAAM,CAAC,OAAO,EAAED,IAAI,CAAC,YAAY,EAAEG,OAAO,CAAC,CAAC,CAC5F;KACF;CACF;AAED,OAAO,SAASC,mBAAmB,CACjCJ,IAAY,EACZC,MAAc,EACdI,KAAU,EACJ;IACN,IAAI,CAACX,aAAa,CAACW,KAAK,CAAC,EAAE;QACzB,MAAM,IAAIR,iBAAiB,CACzBG,IAAI,EACJC,MAAM,EACN,EAAE,EACF,CAAC,8CAA8C,EAAEA,MAAM,CAAC,sCAAsC,EAAEN,mBAAmB,CACjHU,KAAK,CACN,CAAC,IAAI,CAAC,CACR,CAAA;KACF;IAED,SAASC,KAAK,CAACC,OAAyB,EAAEC,KAAU,EAAEN,IAAY,EAAE;QAClE,IAAIK,OAAO,CAACE,GAAG,CAACD,KAAK,CAAC,EAAE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egexp } from "../shared/lib/escape-regexp";
import { tryToParsePath } from "./try-to-parse-path";
import { allowedStatusCodes } from "./redirect-status";
const allowedHasTypes = new Set([
"header",
"cookie",
"query",
"host"
]);
const namedGroupsRegex = /\(\?<([a-zA-Z][a-zA-Z0-9]*)>/g;
export function normalizeRouteRegex(regex) {
// clean up un-necessary escaping from regex.source which turns / into \\/
return regex.replace(/\\\//g, "/");
}
function checkRedirect(route) {
const invalidParts = [];
let hadInvalidStatus = false;
if (route.statusCode && !allowedStatusCodes.has(route.statusCode)) {
hadInvalidStatus = true;
invalidParts.push(`\`statusCode\` is not undefined or valid statusCode`);
}
if (typeof route.permanent !== "boolean" && !route.statusCode) {
invalidParts.push(`\`permanent\` is not set to \`true\` or \`false\``);
}
return {
invalidParts,
hadInvalidStatus
};
}
function checkHeader(route) {
const invalidParts = [];
if (!Array.isArray(route.headers)) {
invalidParts.push("`headers` field must be an array");
} else if (route.headers.length === 0) {
invalidParts.push("`headers` field cannot be empty");
} else {
for (const header of route.headers){
if (!header || typeof header !== "object") {
invalidParts.push("`headers` items must be object with { key: '', value: '' }");
break;
}
if (typeof header.key !== "string") {
invalidParts.push("`key` in header item must be string");
break;
}
if (typeof header.value !== "string") {
invalidParts.push("`value` in header item must be string");
break;
}
}
}
return invalidParts;
}
export function checkCustomRoutes(routes, type) {
if (!Array.isArray(routes)) {
console.error(`Error: ${type}s must return an array, received ${typeof routes}.\n` + `See here for more info: https://nextjs.org/docs/messages/routes-must-be-array`);
process.exit(1);
}
let numInvalidRoutes = 0;
let hadInvalidStatus = false;
let hadInvalidHas = false;
let hadInvalidMissing = false;
const allowedKeys = new Set([
"source",
"locale",
"has",
"missing"
]);
if (type === "rewrite") {
allowedKeys.add("basePath");
allowedKeys.add("destination");
}
if (type === "redirect") {
allowedKeys.add("basePath");
allowedKeys.add("statusCode");
allowedKeys.add("permanent");
allowedKeys.add("destination");
}
if (type === "header") {
allowedKeys.add("basePath");
allowedKeys.add("headers");
}
for (const route of routes){
if (!route || typeof route !== "object") {
console.error(`The route ${JSON.stringify(route)} is not a valid object with \`source\`${type !== "middleware" ? ` and \`${type === "header" ? "headers" : "destination"}\`` : ""}`);
numInvalidRoutes++;
continue;
}
if (type === "rewrite" && route.basePath === false && !(route.destination.startsWith("http://") || route.destination.startsWith("https://"))) {
console.error(`The route ${route.source} rewrites urls outside of the basePath. Please use a destination that starts with \`http://\` or \`https://\` https://nextjs.org/docs/messages/invalid-external-rewrite`);
numInvalidRoutes++;
continue;
}
const keys = Object.keys(route);
const invalidKeys = keys.filter((key)=>!allowedKeys.has(key));
const invalidParts = [];
if ("basePath" in route && typeof route.basePath !== "undefined" && route.basePath !== false) {
invalidParts.push("`basePath` must be undefined or false");
}
if (typeof route.locale !== "undefined" && route.locale !== false) {
invalidParts.push("`locale` must be undefined or false");
}
const checkInvalidHasMissing = (items, fieldName)=>{
let hadInvalidItem = false;
if (typeof items !== "undefined" && !Array.isArray(items)) {
invalidParts.push(`\`${fieldName}\` must be undefined or valid has object`);
hadInvalidItem = true;
} else if (items) {
const invalidHasItems = [];
for (const hasItem of items){
let invalidHasParts = [];
if (!allowedHasTypes.has(hasItem.type)) {
invalidHasParts.push(`invalid type "${hasItem.type}"`);
}
if (typeof hasItem.key !== "string" && hasItem.type !== "host") {
invalidHasParts.push(`invalid key "${hasItem.key}"`);
}
if (typeof hasItem.value !== "undefined" && typeof hasItem.value !== "string") {
invalidHasParts.push(`invalid value "${hasItem.value}"`);
}
if (typeof hasItem.value === "undefined" && hasItem.type === "host") {
invalidHasParts.push(`value is required for "host" type`);
}
if (invalidHasParts.length > 0) {
invalidHasItems.push(`${invalidHasParts.join(", ")} for ${JSON.stringify(hasItem)}`);
}
}
if (invalidHasItems.length > 0) {
hadInvalidItem = true;
const itemStr = `item${invalidHasItems.length === 1 ? "" : "s"}`;
console.error(`Invalid \`${fieldName}\` ${itemStr}:\n` + invalidHasItems.join("\n"));
console.error();
invalidParts.push(`invalid \`${fieldName}\` ${itemStr} found`);
}
}
return hadInvalidItem;
};
if (checkInvalidHasMissing(route.has, "has")) {
hadInvalidHas = true;
}
if (checkInvalidHasMissing(route.missing, "missing")) {
hadInvalidMissing = true;
}
if (!route.source) {
invalidParts.push("`source` is missing");
} else if (typeof route.source !== "string") {
invalidParts.push("`source` is not a string");
} else if (!route.source.startsWith("/")) {
invalidParts.push("`source` does not start with /");
}
if (type === "header") {
invalidParts.push(...checkHeader(route));
} else if (type !== "middleware") {
let _route = route;
if (!_route.destination) {
invalidParts.push("`destination` is missing");
} else if (typeof _route.destination !== "string") {
invalidParts.push("`destination` is not a string");
} else if (type === "rewrite" && !_route.destination.match(/^(\/|https:\/\/|http:\/\/)/)) {
invalidParts.push("`destination` does not start with `/`, `http://`, or `https://`");
}
}
if (type === "redirect") {
const result = checkRedirect(route);
hadInvalidStatus = hadInvalidStatus || result.hadInvalidStatus;
invalidParts.push(...result.invalidParts);
}
let sourceTokens;
if (typeof route.source === "string" && route.source.startsWith("/")) {
// only show parse error if we didn't already show error
// for not being a string
const { tokens , error , regexStr } = tryToParsePath(route.source);
if (error) {
invalidParts.push("`source` parse failed");
}
if (regexStr && regexStr.length > 4096) {
invalidParts.push("`source` exceeds max built length of 4096");
}
sourceTokens = tokens;
}
const hasSegments = new Set();
if (route.has) {
for (const hasItem of route.has){
if (!hasItem.value && hasItem.key) {
hasSegments.add(hasItem.key);
}
if (hasItem.value) {
for (const match of hasItem.value.matchAll(namedGroupsRegex)){
if (match[1]) {
hasSegments.add(match[1]);
}
}
if (hasItem.type === "host") {
hasSegments.add("host");
}
}
}
}
// make sure no unnamed patterns are attempted to be used in the
// destination as this can cause confusion and is not allowed
if (typeof route.destination === "string") {
if (route.destination.startsWith("/") && Array.isArray(sourceTokens)) {
const unnamedInDest = new Set();
for (const token of sourceTokens){
if (typeof token === "object" && typeof token.name === "number") {
const unnamedIndex = new RegExp(`:${token.name}(?!\\d)`);
if (route.destination.match(unnamedIndex)) {
unnamedInDest.add(`:${token.name}`);
}
}
}
if (unnamedInDest.size > 0) {
invalidParts.push(`\`destination\` has unnamed params ${[
...unnamedInDest
].join(", ")}`);
} else {
const { tokens: destTokens , regexStr: destRegexStr , error: destinationParseFailed , } = tryToParsePath(route.destination, {
handleUrl: true
});
if (destRegexStr && destRegexStr.length > 4096) {
invalidParts.push("`destination` exceeds max built length of 4096");
}
if (destinationParseFailed) {
invalidParts.push("`destination` parse failed");
} else {
const sourceSegments = new Set(sourceTokens.map((item)=>typeof item === "object" && item.name).filter(Boolean));
const invalidDestSegments = new Set();
for (const token of destTokens){
if (typeof token === "object" && !sourceSegments.has(token.name) && !hasSegments.has(token.name)) {
invalidDestSegments.add(token.name);
}
}
if (invalidDestSegments.size) {
invalidParts.push(`\`destination\` has segments not in \`source\` or \`has\` (${[
...invalidDestSegments,
].join(", ")})`);
}
}
}
}
}
const hasInvalidKeys = invalidKeys.length > 0;
const hasInvalidParts = invalidParts.length > 0;
if (hasInvalidKeys || hasInvalidParts) {
console.error(`${invalidParts.join(", ")}${invalidKeys.length ? (hasInvalidParts ? "," : "") + ` invalid field${invalidKeys.length === 1 ? "" : "s"}: ` + invalidKeys.join(",") : ""} for route ${JSON.stringify(route)}`);
console.error();
numInvalidRoutes++;
}
}
if (numInvalidRoutes > 0) {
if (hadInvalidStatus) {
console.error(`\nValid redirect statusCode values are ${[
...allowedStatusCodes
].join(", ")}`);
}
if (hadInvalidHas) {
console.error(`\nValid \`has\` object shape is ${JSON.stringify({
type: [
...allowedHasTypes
].join(", "),
key: "the key to check for",
value: "undefined or a value string to match against"
}, null, 2)}`);
}
if (hadInvalidMissing) {
console.error(`\nValid \`missing\` object shape is ${JSON.stringify({
type: [
...allowedHasTypes
].join(", "),
key: "the key to check for",
value: "undefined or a value string to match against"
}, null, 2)}`);
}
console.error();
console.error(`Error: Invalid ${type}${numInvalidRoutes === 1 ? "" : "s"} found`);
process.exit(1);
}
}
function processRoutes(routes, config, type) {
const _routes = routes;
const newRoutes = [];
const defaultLocales = [];
if (config.i18n && type === "redirect") {
var ref;
for (const item of ((ref = config.i18n) == null ? void 0 : ref.domains) || []){
defaultLocales.push({
locale: item.defaultLocale,
base: `http${item.http ? "" : "s"}://${item.domain}`
});
}
defaultLocales.push({
locale: config.i18n.defaultLocale,
base: ""
});
}
for (const r of _routes){
var ref1;
const srcBasePath = config.basePath && r.basePath !== false ? config.basePath : "";
const isExternal = !((ref1 = r.destination) == null ? void 0 : ref1.startsWith("/"));
const destBasePath = srcBasePath && !isExternal ? srcBasePath : "";
if (config.i18n && r.locale !== false) {
var ref2;
if (!isExternal) {
defaultLocales.forEach((item)=>{
let destination;
if (r.destination) {
destination = item.base ? `${item.base}${destBasePath}${r.destination}` : `${destBasePath}${r.destination}`;
}
newRoutes.push({
...r,
destination,
source: `${srcBasePath}/${item.locale}${r.source}`
});
});
}
r.source = `/:nextInternalLocale(${config.i18n.locales.map((locale)=>escapeStringRegexp(locale)).join("|")})${r.source === "/" && !config.trailingSlash ? "" : r.source}`;
if (r.destination && ((ref2 = r.destination) == null ? void 0 : ref2.startsWith("/"))) {
r.destination = `/:nextInternalLocale${r.destination === "/" && !config.trailingSlash ? "" : r.destination}`;
}
}
r.source = `${srcBasePath}${r.source === "/" && srcBasePath ? "" : r.source}`;
if (r.destination) {
r.destination = `${destBasePath}${r.destination === "/" && destBasePath ? "" : r.destination}`;
}
newRoutes.push(r);
}
return newRoutes;
}
async function loadRedirects(config) {
if (typeof config.redirects !== "function") {
return [];
}
let redirects = await config.redirects();
// check before we process the routes and after to ensure
// they are still valid
checkCustomRoutes(redirects, "redirect");
redirects = processRoutes(redirects, config, "redirect");
checkCustomRoutes(redirects, "redirect");
return redirects;
}
async function loadRewrites(config) {
if (typeof config.rewrites !== "function") {
return {
beforeFiles: [],
afterFiles: [],
fallback: []
};
}
const _rewrites = await config.rewrites();
let beforeFiles = [];
let afterFiles = [];
let fallback = [];
if (!Array.isArray(_rewrites) && typeof _rewrites === "object" && Object.keys(_rewrites).every((key)=>key === "beforeFiles" || key === "afterFiles" || key === "fallback")) {
beforeFiles = _rewrites.beforeFiles || [];
afterFiles = _rewrites.afterFiles || [];
fallback = _rewrites.fallback || [];
} else {
afterFiles = _rewrites;
}
// check before we process the routes and after to ensure
// they are still valid
checkCustomRoutes(beforeFiles, "rewrite");
checkCustomRoutes(afterFiles, "rewrite");
checkCustomRoutes(fallback, "rewrite");
beforeFiles = processRoutes(beforeFiles, config, "rewrite");
afterFiles = processRoutes(afterFiles, config, "rewrite");
fallback = processRoutes(fallback, config, "rewrite");
checkCustomRoutes(beforeFiles, "rewrite");
checkCustomRoutes(afterFiles, "rewrite");
checkCustomRoutes(fallback, "rewrite");
return {
beforeFiles,
afterFiles,
fallback
};
}
async function loadHeaders(config) {
if (typeof config.headers !== "function") {
return [];
}
let headers = await config.headers();
// check before we process the routes and after to ensure
// they are still valid
checkCustomRoutes(headers, "header");
headers = processRoutes(headers, config, "header");
checkCustomRoutes(headers, "header");
return headers;
}
export default async function loadCustomRoutes(config) {
const [headers, rewrites, redirects] = await Promise.all([
loadHeaders(config),
loadRewrites(config),
loadRedirects(config),
]);
const totalRewrites = rewrites.beforeFiles.length + rewrites.afterFiles.length + rewrites.fallback.length;
const totalRoutes = headers.length + redirects.length + totalRewrites;
if (totalRoutes > 1000) {
console.warn(chalk.bold.yellow(`Warning: `) + `total number of custom routes exceeds 1000, this can reduce performance. Route counts:\n` + `headers: ${headers.length}\n` + `rewrites: ${totalRewrites}\n` + `redirects: ${redirects.length}\n` + `See more info: https://nextjs.org/docs/messages/max-custom-routes-reached`);
}
if (!config.skipTrailingSlashRedirect) {
if (config.trailingSlash) {
redirects.unshift({
source: "/:file((?!\\.well-known(?:/.*)?)(?:[^/]+/)*[^/]+\\.\\w+)/",
destination: "/:file",
permanent: true,
locale: config.i18n ? false : undefined,
internal: true
}, {
source: "/:notfile((?!\\.well-known(?:/.*)?)(?:[^/]+/)*[^/\\.]+)",
destination: "/:notfile/",
permanent: true,
locale: config.i18n ? false : undefined,
internal: true
});
if (config.basePath) {
redirects.unshift({
source: config.basePath,
destination: config.basePath + "/",
permanent: true,
basePath: false,
locale: config.i18n ? false : undefined,
internal: true
});
}
} else {
redirects.unshift({
source: "/:path+/",
destination: "/:path+",
permanent: true,
locale: config.i18n ? false : undefined,
internal: true
});
if (config.basePath) {
redirects.unshift({
source: config.basePath + "/",
destination: config.basePath,
permanent: true,
basePath: false,
locale: config.i18n ? false : undefined,
internal: true
});
}
}
}
return {
headers,
rewrites,
redirects
};
};
//# sourceMappingURL=load-custom-routes.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
export function nonNullable(value) {
return value !== null && value !== undefined;
}
//# sourceMappingURL=non-nullable.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/non-nullable.ts"],"names":["nonNullable","value","undefined"],"mappings":"AAAA,OAAO,SAASA,WAAW,CAAIC,KAAQ,EAA2B;IAChE,OAAOA,KAAK,KAAK,IAAI,IAAIA,KAAK,KAAKC,SAAS,CAAA;CAC7C"}

View File

@@ -0,0 +1,5 @@
export function getOxfordCommaList(items) {
return items.map((v, index, { length })=>(index > 0 ? index === length - 1 ? length > 2 ? ", and " : " and " : ", " : "") + v).join("");
}
//# sourceMappingURL=oxford-comma-list.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/oxford-comma-list.ts"],"names":["getOxfordCommaList","items","map","v","index","length","join"],"mappings":"AAAA,OAAO,SAASA,kBAAkB,CAACC,KAAe,EAAU;IAC1D,OAAOA,KAAK,CACTC,GAAG,CACF,CAACC,CAAC,EAAEC,KAAK,EAAE,EAAEC,MAAM,CAAA,EAAE,GACnB,CAACD,KAAK,GAAG,CAAC,GACNA,KAAK,KAAKC,MAAM,GAAG,CAAC,GAClBA,MAAM,GAAG,CAAC,GACR,QAAQ,GACR,OAAO,GACT,IAAI,GACN,EAAE,CAAC,GAAGF,CAAC,CACd,CACAG,IAAI,CAAC,EAAE,CAAC,CAAA;CACZ"}

View File

@@ -0,0 +1,144 @@
import { promises } from "fs";
import "../server/node-polyfill-fetch";
import * as Log from "../build/output/log";
import findUp from "next/dist/compiled/find-up";
import { execSync } from "child_process";
// @ts-ignore no-json types
import nextPkgJson from "next/package.json";
import { isCI } from "../telemetry/ci-info";
let registry;
async function fetchPkgInfo(pkg) {
if (!registry) {
try {
const output = execSync("npm config get registry").toString().trim();
if (output.startsWith("http")) {
registry = output;
if (!registry.endsWith("/")) {
registry += "/";
}
}
} catch (_) {
registry = `https://registry.npmjs.org/`;
}
}
const res = await fetch(`${registry}${pkg}`);
if (!res.ok) {
throw new Error(`Failed to fetch registry info for ${pkg}, got status ${res.status}`);
}
const data = await res.json();
const versionData = data.versions[nextPkgJson.version];
return {
os: versionData.os,
cpu: versionData.cpu,
engines: versionData.engines,
tarball: versionData.dist.tarball,
integrity: versionData.dist.integrity
};
}
/**
* Attempts to patch npm package-lock.json when it
* fails to include optionalDependencies for other platforms
* this can occur when the package-lock is rebuilt from a current
* node_modules install instead of pulling fresh package data
*/ export async function patchIncorrectLockfile(dir) {
if (process.env.NEXT_IGNORE_INCORRECT_LOCKFILE) {
return;
}
const lockfilePath = await findUp("package-lock.json", {
cwd: dir
});
if (!lockfilePath) {
// if no lockfile present there is no action to take
return;
}
const content = await promises.readFile(lockfilePath, "utf8");
// maintain current line ending
const endingNewline = content.endsWith("\r\n") ? "\r\n" : content.endsWith("\n") ? "\n" : "";
const lockfileParsed = JSON.parse(content);
const lockfileVersion = parseInt(lockfileParsed == null ? void 0 : lockfileParsed.lockfileVersion, 10);
const expectedSwcPkgs = Object.keys(nextPkgJson.optionalDependencies || {});
const patchDependency = (pkg, pkgData)=>{
lockfileParsed.dependencies[pkg] = {
version: nextPkgJson.version,
resolved: pkgData.tarball,
integrity: pkgData.integrity,
optional: true
};
};
const patchPackage = (pkg, pkgData)=>{
lockfileParsed.packages[pkg] = {
version: nextPkgJson.version,
resolved: pkgData.tarball,
integrity: pkgData.integrity,
cpu: pkgData.cpu,
optional: true,
os: pkgData.os,
engines: pkgData.engines
};
};
try {
const supportedVersions = [
1,
2,
3
];
if (!supportedVersions.includes(lockfileVersion)) {
// bail on unsupported version
return;
}
// v1 only uses dependencies
// v2 uses dependencies and packages
// v3 only uses packages
const shouldPatchDependencies = lockfileVersion === 1 || lockfileVersion === 2;
const shouldPatchPackages = lockfileVersion === 2 || lockfileVersion === 3;
if (shouldPatchDependencies && !lockfileParsed.dependencies || shouldPatchPackages && !lockfileParsed.packages) {
// invalid lockfile so bail
return;
}
const missingSwcPkgs = [];
let pkgPrefix;
if (shouldPatchPackages) {
pkgPrefix = "";
for (const pkg of Object.keys(lockfileParsed.packages)){
if (pkg.endsWith("node_modules/next")) {
pkgPrefix = pkg.substring(0, pkg.length - 4);
}
}
if (!pkgPrefix) {
// unable to locate the next package so bail
return;
}
}
for (const pkg1 of expectedSwcPkgs){
if (shouldPatchDependencies && !lockfileParsed.dependencies[pkg1] || shouldPatchPackages && !lockfileParsed.packages[`${pkgPrefix}${pkg1}`]) {
missingSwcPkgs.push(pkg1);
}
}
if (missingSwcPkgs.length === 0) {
return;
}
Log.warn(`Found lockfile missing swc dependencies,`, isCI ? "run next locally to automatically patch" : "patching...");
if (isCI) {
// no point in updating in CI as the user can't save the patch
return;
}
const pkgsData = await Promise.all(missingSwcPkgs.map((pkg)=>fetchPkgInfo(pkg)));
for(let i = 0; i < pkgsData.length; i++){
const pkg = missingSwcPkgs[i];
const pkgData = pkgsData[i];
if (shouldPatchDependencies) {
patchDependency(pkg, pkgData);
}
if (shouldPatchPackages) {
patchPackage(`${pkgPrefix}${pkg}`, pkgData);
}
}
await promises.writeFile(lockfilePath, JSON.stringify(lockfileParsed, null, 2) + endingNewline);
Log.warn('Lockfile was successfully patched, please run "npm install" to ensure @next/swc dependencies are downloaded');
} catch (err) {
Log.error(`Failed to patch lockfile, please try uninstalling and reinstalling next in this workspace`);
console.error(err);
}
}
//# sourceMappingURL=patch-incorrect-lockfile.js.map

File diff suppressed because one or more lines are too long

9
kitabcitab/node_modules/next/dist/esm/lib/pick.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
export function pick(obj, keys) {
const newObj = {};
for (const key of keys){
newObj[key] = obj[key];
}
return newObj;
}
//# sourceMappingURL=pick.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/pick.ts"],"names":["pick","obj","keys","newObj","key"],"mappings":"AAAA,OAAO,SAASA,IAAI,CAAuBC,GAAM,EAAEC,IAAS,EAAc;IACxE,MAAMC,MAAM,GAAG,EAAE,AAAc;IAC/B,KAAK,MAAMC,GAAG,IAAIF,IAAI,CAAE;QACtBC,MAAM,CAACC,GAAG,CAAC,GAAGH,GAAG,CAACG,GAAG,CAAC;KACvB;IACD,OAAOD,MAAM,CAAA;CACd"}

View File

@@ -0,0 +1,60 @@
/*
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ const UNITS = [
"B",
"kB",
"MB",
"GB",
"TB",
"PB",
"EB",
"ZB",
"YB"
];
/*
Formats the given number using `Number#toLocaleString`.
- If locale is a string, the value is expected to be a locale-key (for example: `de`).
- If locale is true, the system default locale is used for translation.
- If no value for locale is specified, the number is returned unmodified.
*/ const toLocaleString = (number, locale)=>{
let result = number;
if (typeof locale === "string") {
result = number.toLocaleString(locale);
} else if (locale === true) {
result = number.toLocaleString();
}
return result;
};
export default function prettyBytes(number, options) {
if (!Number.isFinite(number)) {
throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
}
options = Object.assign({}, options);
if (options.signed && number === 0) {
return " 0 B";
}
const isNegative = number < 0;
const prefix = isNegative ? "-" : options.signed ? "+" : "";
if (isNegative) {
number = -number;
}
if (number < 1) {
const numberString = toLocaleString(number, options.locale);
return prefix + numberString + " B";
}
const exponent = Math.min(Math.floor(Math.log10(number) / 3), UNITS.length - 1);
number = Number((number / Math.pow(1000, exponent)).toPrecision(3));
const numberString = toLocaleString(number, options.locale);
const unit = UNITS[exponent];
return prefix + numberString + " " + unit;
};
//# sourceMappingURL=pretty-bytes.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/pretty-bytes.ts"],"names":["UNITS","toLocaleString","number","locale","result","prettyBytes","options","Number","isFinite","TypeError","Object","assign","signed","isNegative","prefix","numberString","exponent","Math","min","floor","log10","length","pow","toPrecision","unit"],"mappings":"AAAA;;;;;;;;;;EAUE,CAEF,MAAMA,KAAK,GAAG;IAAC,GAAG;IAAE,IAAI;IAAE,IAAI;IAAE,IAAI;IAAE,IAAI;IAAE,IAAI;IAAE,IAAI;IAAE,IAAI;IAAE,IAAI;CAAC;AAEnE;;;;;EAKE,CACF,MAAMC,cAAc,GAAG,CAACC,MAAc,EAAEC,MAAW,GAAK;IACtD,IAAIC,MAAM,GAAQF,MAAM;IACxB,IAAI,OAAOC,MAAM,KAAK,QAAQ,EAAE;QAC9BC,MAAM,GAAGF,MAAM,CAACD,cAAc,CAACE,MAAM,CAAC;KACvC,MAAM,IAAIA,MAAM,KAAK,IAAI,EAAE;QAC1BC,MAAM,GAAGF,MAAM,CAACD,cAAc,EAAE;KACjC;IAED,OAAOG,MAAM,CA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AE5B,OAAOF,MAAM,GAAGC,YAAY,GAAG,GAAG,GAAGS,IAAI,CAAA;CAC1C,CAAA"}

View File

@@ -0,0 +1,56 @@
import path from "path";
import { promises, constants } from "fs";
import { Sema } from "next/dist/compiled/async-sema";
import isError from "./is-error";
const COPYFILE_EXCL = constants.COPYFILE_EXCL;
export async function recursiveCopy(source, dest, { concurrency =32 , overwrite =false , filter =()=>true } = {}) {
const cwdPath = process.cwd();
const from = path.resolve(cwdPath, source);
const to = path.resolve(cwdPath, dest);
const sema = new Sema(concurrency);
// deep copy the file/directory
async function _copy(item, lstats) {
const target = item.replace(from, to);
await sema.acquire();
if (!lstats) {
// after lock on first run
lstats = await promises.lstat(from);
}
// readdir & lstat do not follow symbolic links
// if part is a symbolic link, follow it with stat
let isFile = lstats.isFile();
let isDirectory = lstats.isDirectory();
if (lstats.isSymbolicLink()) {
const stats = await promises.stat(item);
isFile = stats.isFile();
isDirectory = stats.isDirectory();
}
if (isDirectory) {
try {
await promises.mkdir(target, {
recursive: true
});
} catch (err) {
// do not throw `folder already exists` errors
if (isError(err) && err.code !== "EEXIST") {
throw err;
}
}
sema.release();
const files = await promises.readdir(item, {
withFileTypes: true
});
await Promise.all(files.map((file)=>_copy(path.join(item, file.name), file)));
} else if (isFile && // before we send the path to filter
// we remove the base path (from) and replace \ by / (windows)
filter(item.replace(from, "").replace(/\\/g, "/"))) {
await promises.copyFile(item, target, overwrite ? undefined : COPYFILE_EXCL);
sema.release();
} else {
sema.release();
}
}
await _copy(from);
}
//# sourceMappingURL=recursive-copy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/recursive-copy.ts"],"names":["path","promises","constants","Sema","isError","COPYFILE_EXCL","recursiveCopy","source","dest","concurrency","overwrite","filter","cwdPath","process","cwd","from","resolve","to","sema","_copy","item","lstats","target","replace","acquire","lstat","isFile","isDirectory","isSymbolicLink","stats","stat","mkdir","recursive","err","code","release","files","readdir","withFileTypes","Promise","all","map","file","join","name","copyFile","undefined"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AAGG,KAAK,CAACH,MAAM,EAAE;YACvBC,WAAW,GAAGE,KAAK,CAACF,WAAW,EAAE;SAClC;QAED,IAAIA,WAAW,EAAE;YACf,IAAI;gBACF,MAAM1B,QAAQ,CAAC8B,KAAK,CAACT,MAAM,EAAE;oBAAEU,SAAS,EAAE,IAAI;iBAAE,CAAC;aAClD,CAAC,OAAOC,GAAG,EAAE;gBACZ,8CAA8C;gBAC9C,IAAI7B,OAAO,CAAC6B,GAAG,CAAC,IAAIA,GAAG,CAACC,IAAI,KAAK,QAAQ,EAAE;oBACzC,MAAMD,GAAG,CAAA;iBACV;aACF;YACDf,IAAI,CAACiB,OAAO,EAAE;YACd,MAAMC,KAAK,GAAG,MAAMnC,QAAQ,CAACoC,OAAO,CAACjB,IAAI,EAAE;gBAAEkB,aAAa,EAAE,IAAI;aAAE,CAAC;YACnE,MAAMC,OAAO,CAACC,GAAG,CACfJ,KAAK,CAACK,GAAG,CAAC,CAACC,IAAI,GAAKvB,KAAK,CAACnB,IAAI,CAAC2C,IAAI,CAACvB,IAAI,EAAEsB,IAAI,CAACE,IAAI,CAAC,EAAEF,IAAI,CAAC,CAAC,CAC7D;SACF,MAAM,IACLhB,MAAM,IACN,oCAAoC;QACpC,8DAA8D;QAC9Df,MAAM,CAACS,IAAI,CAACG,OAAO,CAACR,IAAI,EAAE,EAAE,CAAC,CAACQ,OAAO,QAAQ,GAAG,CAAC,CAAC,EAClD;YACA,MAAMtB,QAAQ,CAAC4C,QAAQ,CACrBzB,IAAI,EACJE,MAAM,EACNZ,SAAS,GAAGoC,SAAS,GAAGzC,aAAa,CACtC;YACDa,IAAI,CAACiB,OAAO,EAAE;SACf,MAAM;YACLjB,IAAI,CAACiB,OAAO,EAAE;SACf;KACF;IAED,MAAMhB,KAAK,CAACJ,IAAI,CAAC;CAClB"}

View File

@@ -0,0 +1,62 @@
import { promises } from "fs";
import { join, isAbsolute, dirname } from "path";
import isError from "./is-error";
const sleep = (timeout)=>new Promise((resolve)=>setTimeout(resolve, timeout));
const unlinkPath = async (p, isDir = false, t = 1)=>{
try {
if (isDir) {
await promises.rmdir(p);
} else {
await promises.unlink(p);
}
} catch (e) {
const code = isError(e) && e.code;
if ((code === "EBUSY" || code === "ENOTEMPTY" || code === "EPERM" || code === "EMFILE") && t < 3) {
await sleep(t * 100);
return unlinkPath(p, isDir, t++);
}
if (code === "ENOENT") {
return;
}
throw e;
}
};
/**
* Recursively delete directory contents
*/ export async function recursiveDelete(/** Directory to delete the contents of */ dir, /** Exclude based on relative file path */ exclude, /** Ensures that parameter dir exists, this is not passed recursively */ previousPath = "") {
let result;
try {
result = await promises.readdir(dir, {
withFileTypes: true
});
} catch (e) {
if (isError(e) && e.code === "ENOENT") {
return;
}
throw e;
}
await Promise.all(result.map(async (part)=>{
const absolutePath = join(dir, part.name);
// readdir does not follow symbolic links
// if part is a symbolic link, follow it using stat
let isDirectory = part.isDirectory();
const isSymlink = part.isSymbolicLink();
if (isSymlink) {
const linkPath = await promises.readlink(absolutePath);
try {
const stats = await promises.stat(isAbsolute(linkPath) ? linkPath : join(dirname(absolutePath), linkPath));
isDirectory = stats.isDirectory();
} catch (_) {}
}
const pp = join(previousPath, part.name);
const isNotExcluded = !exclude || !exclude.test(pp);
if (isNotExcluded) {
if (isDirectory) {
await recursiveDelete(absolutePath, exclude, pp);
}
return unlinkPath(absolutePath, !isSymlink && isDirectory);
}
}));
}
//# sourceMappingURL=recursive-delete.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/recursive-delete.ts"],"names":["promises","join","isAbsolute","dirname","isError","sleep","timeout","Promise","resolve","setTimeout","unlinkPath","p","isDir","t","rmdir","unlink","e","code","recursiveDelete","dir","exclude","previousPath","result","readdir","withFileTypes","all","map","part","absolutePath","name","isDirectory","isSymlink","isSymbolicLink","linkPath","readlink","stats","stat","_","pp","isNotExcluded","test"],"mappings":"AAAA,SAAiBA,QAAQ,QAAQ,IAAI,CAAA;AACrC,SAASC,IAAI,EAAEC,UAAU,EA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ively read directory
* Returns array holding all relative paths
*/ export async function recursiveReadDir(/** Directory to read */ dir, /** Filter for the file name, only the name part is considered, not the full path */ filter, /** Filter for the file name, only the name part is considered, not the full path */ ignore, /** This doesn't have to be provided, it's used for the recursion */ arr = [], /** Used to replace the initial path, only the relative path is left, it's faster than path.relative. */ rootDir = dir) {
const result = await promises.readdir(dir, {
withFileTypes: true
});
await Promise.all(result.map(async (part)=>{
const absolutePath = join(dir, part.name);
if (ignore && ignore.test(part.name)) return;
// readdir does not follow symbolic links
// if part is a symbolic link, follow it using stat
let isDirectory = part.isDirectory();
if (part.isSymbolicLink()) {
const stats = await promises.stat(absolutePath);
isDirectory = stats.isDirectory();
}
if (isDirectory) {
await recursiveReadDir(absolutePath, filter, ignore, arr, rootDir);
return;
}
if (!filter.test(part.name)) {
return;
}
arr.push(absolutePath.replace(rootDir, ""));
}));
return arr.sort();
}
//# sourceMappingURL=recursive-readdir.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/recursive-readdir.ts"],"names":["promises","join","recursiveReadDir","dir","filter","ignore","arr","rootDir","result","readdir","withFileTypes","Promise","all","map","part","absolutePath","name","test","isDirectory","isSymbolicLink","stats","stat","push","replace","sort"],"mappings":"AAAA,SAAiBA,QAAQ,QAAQ,IAAI,CAAA;AACrC,SAASC,IAAI,QAAQ,MAAM,CAAA;AAE3B;;;GAGG,CACH,OAAO,eAAeC,gBAAgB,CACpC,wBAAwB,CACxBC,GAAW,EACX,oFAAoF,CACpFC,MAAc,EACd,oFAAoF,CACpFC,MAAe,EACf,oEAAoE,CACpEC,GAAa,GAAG,EAAE,EAClB,wGAAwG,CACxGC,OAAe,GAAGJ,GAAG,EACF;IACnB,MAAMK,MAAM,GAAG,MAAMR,QAAQ,CAACS,OAAO,CAACN,GAAG,EAAE;QAAEO,aAAa,EAAE,IAAI;KAAE,CAAC;IAEnE,MAAMC,OAAO,CAACC,GAAG,CACfJ,MAAM,CAACK,GAAG,CAAC,OAAOC,IAAY,GAAK;QACjC,MAAMC,YAAY,GAAGd,IAAI,CAACE,GAAG,EAAEW,IAAI,CAACE,IAAI,CAAC;QACzC,IAAIX,MAAM,IAAIA,MAAM,CAACY,IAAI,CAACH,IAAI,CAACE,IAAI,CAAC,EAAE,OAAM;QAE5C,yCAAyC;QACzC,mDAAmD;QACnD,IAAIE,WAAW,GAAGJ,IAAI,CAACI,WAAW,EAAE;QACpC,IAAIJ,IAAI,CAACK,cAAc,EAAE,EAAE;YACzB,MAAMC,KAAK,GAAG,MAAMpB,QAAQ,CAACqB,IAAI,CAACN,YAAY,CAAC;YAC/CG,WAAW,GAAGE,KAAK,CAACF,WAAW,EAAE;SAClC;QAED,IAAIA,WAAW,EAAE;YACf,MAAMhB,gBAAgB,CAACa,YAAY,EAAEX,MAAM,EAAEC,MAAM,EAAEC,GAAG,EAAEC,OAAO,CAAC;YAClE,OAAM;SACP;QAED,IAAI,CAACH,MAAM,CAACa,IAAI,CAACH,IAAI,CAACE,IAAI,CAAC,EAAE;YAC3B,OAAM;SACP;QAEDV,GAAG,CAACgB,IAAI,CAACP,YAAY,CAACQ,OAAO,CAAChB,OAAO,EAAE,EAAE,CAAC,CAAC;KAC5C,CAAC,CACH;IAED,OAAOD,GAAG,CAACkB,IAAI,EAAE,CAAA;CAClB"}

View File

@@ -0,0 +1,23 @@
import { PERMANENT_REDIRECT_STATUS, TEMPORARY_REDIRECT_STATUS } from "../shared/lib/constants";
export const allowedStatusCodes = new Set([
301,
302,
303,
307,
308
]);
export function getRedirectStatus(route) {
return route.statusCode || (route.permanent ? PERMANENT_REDIRECT_STATUS : TEMPORARY_REDIRECT_STATUS);
}
// for redirects we restrict matching /_next and for all routes
// we add an optional trailing slash at the end for easier
// configuring between trailingSlash: true/false
export function modifyRouteRegex(regex, restrictedPaths) {
if (restrictedPaths) {
regex = regex.replace(/\^/, `^(?!${restrictedPaths.map((path)=>path.replace(/\//g, "\\/")).join("|")})`);
}
regex = regex.replace(/\$$/, "(?:\\/)?$");
return regex;
}
//# sourceMappingURL=redirect-status.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/redirect-status.ts"],"names":["PERMANENT_REDIRECT_STATUS","TEMPORARY_REDIRECT_STATUS","allowedStatusCodes","Set","getRedirectStatus","route","statusCode","permanent","modifyRouteRegex","regex","restrictedPaths","replace","map","path","join"],"mappings":"AAAA,SACEA,yBAAyB,EACzBC,yBAAyB,QACpB,yBAAyB,CAAA;AAEhC,OAAO,MAAMC,kBAAkB,GAAG,IAAIC,GAAG,CAAC;AAAC,OAAG;AAAE,OAAG;AAAE,OAAG;AAAE,OAAG;AAAE,OAAG;CAAC,CAAC,CAAA;AAEpE,OAAO,SAASC,iBAAiB,CAACC,KAGjC,EAAU;IACT,OACEA,KAAK,CAACC,UAAU,IAChB,CAACD,KAAK,CAACE,SAAS,GAAGP,yBAAyB,GAAGC,yBAAyB,CAAC,CAC1E;CACF;AAED,+DAA+D;AAC/D,0DAA0D;AAC1D,gDAAgD;AAChD,OAAO,SAASO,gBAAgB,CAACC,KAAa,EAAEC,eAA0B,EAAE;IAC1E,IAAIA,eAAe,EAAE;QACnBD,KAAK,GAAGA,KAAK,CAACE,OAAO,OAEnB,CAAC,IAAI,EAAED,eAAe,CACnBE,GAAG,CAAC,CAACC,IAAI,GAAKA,IAAI,CAACF,OAAO,QAAQ,KAAK,CAAC,CAAC,CACzCG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAChB;KACF;IACDL,KAAK,GAAGA,KAAK,CAACE,OAAO,QAAQ,WAAW,CAAC;IACzC,OAAOF,KAAK,CAAA;CACb"}

View File

@@ -0,0 +1,40 @@
// source: https://github.com/sindresorhus/resolve-from
import fs from "fs";
import path from "path";
import isError from "./is-error";
const Module = require("module");
export const resolveFrom = (fromDirectory, moduleId, silent)=>{
if (typeof fromDirectory !== "string") {
throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``);
}
if (typeof moduleId !== "string") {
throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
}
try {
fromDirectory = fs.realpathSync(fromDirectory);
} catch (error) {
if (isError(error) && error.code === "ENOENT") {
fromDirectory = path.resolve(fromDirectory);
} else if (silent) {
return;
} else {
throw error;
}
}
const fromFile = path.join(fromDirectory, "noop.js");
const resolveFileName = ()=>Module._resolveFilename(moduleId, {
id: fromFile,
filename: fromFile,
paths: Module._nodeModulePaths(fromDirectory)
});
if (silent) {
try {
return resolveFileName();
} catch (error) {
return;
}
}
return resolveFileName();
};
//# sourceMappingURL=resolve-from.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/resolve-from.ts"],"names":["fs","path","isError","Module","require","resolveFrom","fromDirectory","moduleId","silent","TypeError","realpathSync","error","code","resolve","fromFile","join","resolveFileName","_resolveFilename","id","filename","paths","_nodeModulePaths"],"mappings":"AAAA,uDAAuD;AACvD,OAAOA,EAAE,MAAM,IAAI,CAAA;AACnB,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,OAAOC,OAAO,MAAM,YAAY,CAAA;AAEhC,MAAMC,MAAM,GAAGC,OAAO,CAAC,QAAQ,CAAC;AAEhC,OAAO,MAAMC,WAAW,GAAG,CACzBC,aAAqB,EACrBC,QAAgB,EAChBC,MAAgB,GACb;IACH,IAAI,OAAOF,aAAa,KAAK,QAAQ,EAAE;QACrC,MAAM,IAAIG,SAAS,CACjB,CAAC,qDAAqD,EAAE,OAAOH,aAAa,CAAC,EAAE,CAAC,CACjF,CAAA;KACF;IAED,IAAI,OAAOC,QAAQ,KAAK,QAAQ,EAAE;QAChC,MAAM,IAAIE,SAAS,CACjB,CAAC,sDAAsD,EAAE,OAAOF,QAAQ,CAAC,EAAE,CAAC,CAC7E,CAAA;KACF;IAED,IAAI;QACFD,aAAa,GAAGN,EAAE,CAACU,YAAY,CAACJ,aAAa,CAAC;KAC/C,CAAC,OAAOK,KAAK,EAAW;QACvB,IAAIT,OAAO,CAACS,KAAK,CAAC,IAAIA,KAAK,CAACC,IAAI,KAAK,QAAQ,EAAE;YAC7CN,aAAa,GAAGL,IAAI,CAACY,OAAO,CAACP,aAAa,CAAC;SAC5C,MAAM,IAAIE,MAAM,EAAE;YACjB,OAAM;SACP,MAAM;YACL,MAAMG,KAAK,CAAA;SACZ;KACF;IAED,MAAMG,QAAQ,GAAGb,IAAI,CAACc,IAAI,CAACT,aAAa,EAAE,SAAS,CAAC;IAEpD,MAAMU,eAAe,GAAG,IACtBb,MAAM,CAACc,gBAAgB,CAACV,QAAQ,EAAE;YAChCW,EAAE,EAAEJ,QAAQ;YACZK,QAAQ,EAAEL,QAAQ;YAClBM,KAAK,EAAEjB,MAAM,CAACkB,gBAAgB,CAACf,aAAa,CAAC;SAC9C,CAAC;IAEJ,IAAIE,MAAM,EAAE;QACV,IAAI;YACF,OAAOQ,eAAe,EAAE,CAAA;SACzB,CAAC,OAAOL,KAAK,EAAE;YACd,OAAM;SACP;KACF;IAED,OAAOK,eAAe,EAAE,CAAA;CACzB,CAAA"}

View File

@@ -0,0 +1,28 @@
// A list of popular packages that cannot be bundled on the server.
export const EXTERNAL_PACKAGES = [
"@prisma/client",
"@sentry/nextjs",
"@sentry/node",
"autoprefixer",
"cypress",
"eslint",
"express",
"firebase-admin",
"jest",
"lodash",
"mongodb",
"next-mdx-remote",
"next-seo",
"postcss",
"prettier",
"prisma",
"rimraf",
"sharp",
"sqlite3",
"tailwindcss",
"ts-node",
"typescript",
"webpack",
];
//# sourceMappingURL=server-external-packages.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/server-external-packages.ts"],"names":["EXTERNAL_PACKAGES"],"mappings":"AAAA,mEAAmE;AACnE,OAAO,MAAMA,iBAAiB,GAAG;IAC/B,gBAAgB;IAChB,gBAAgB;IAChB,cAAc;IACd,cAAc;IACd,SAAS;IACT,QAAQ;IACR,SAAS;IACT,gBAAgB;IAChB,MAAM;IACN,QAAQ;IACR,SAAS;IACT,iBAAiB;IACjB,UAAU;IACV,SAAS;IACT,UAAU;IACV,QAAQ;IACR,QAAQ;IACR,OAAO;IACP,SAAS;IACT,aAAa;IACb,SAAS;IACT,YAAY;IACZ,SAAS;CACV,CAAA"}

View File

@@ -0,0 +1,41 @@
import { parse, tokensToRegexp } from "next/dist/compiled/path-to-regexp";
import { parse as parseURL } from "url";
import isError from "./is-error";
/**
* If there is an error show our error link but still show original error or
* a formatted one if we can
*/ function reportError({ route , parsedPath }, err) {
let errMatches;
if (isError(err) && (errMatches = err.message.match(/at (\d{0,})/))) {
const position = parseInt(errMatches[1], 10);
console.error(`\nError parsing \`${route}\` ` + `https://nextjs.org/docs/messages/invalid-route-source\n` + `Reason: ${err.message}\n\n` + ` ${parsedPath}\n` + ` ${new Array(position).fill(" ").join("")}^\n`);
} else {
console.error(`\nError parsing ${route} https://nextjs.org/docs/messages/invalid-route-source`, err);
}
}
/**
* Attempts to parse a given route with `path-to-regexp` and returns an object
* with the result. Whenever an error happens on parse, it will print an error
* attempting to find the error position and showing a link to the docs. When
* `handleUrl` is set to `true` it will also attempt to parse the route
* and use the resulting pathname to parse with `path-to-regexp`.
*/ export function tryToParsePath(route, options) {
const result = {
route,
parsedPath: route
};
try {
if (options == null ? void 0 : options.handleUrl) {
const parsed = parseURL(route, true);
result.parsedPath = `${parsed.pathname}${parsed.hash || ""}`;
}
result.tokens = parse(result.parsedPath);
result.regexStr = tokensToRegexp(result.tokens).source;
} catch (err) {
reportError(result, err);
result.error = err;
}
return result;
}
//# sourceMappingURL=try-to-parse-path.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../lib/try-to-parse-path.ts"],"names":["parse","tokensToRegexp","parseURL","isError","reportError","route","parsedPath","err","errMatches","message","match","position","parseInt","console","error","Array","fill","join","tryToParsePath","options","result","handleUrl","parsed","pathname","hash","tokens","regexStr","source"],"mappings":"AACA,SAASA,KAAK,EAAEC,cAAc,QAAQ,mCAAmC,CAAA;AACzE,SAASD,KAAK,IAAIE,QAAQ,QAAQ,KAAK,CAAA;A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E,CAAC,CAAC;SAC9D;QAEDJ,MAAM,CAACK,MAAM,GAAGzB,KAAK,CAACoB,MAAM,CAACd,UAAU,CAAC;QACxCc,MAAM,CAACM,QAAQ,GAAGzB,cAAc,CAACmB,MAAM,CAACK,MAAM,CAAC,CAACE,MAAM;KACvD,CAAC,OAAOpB,GAAG,EAAE;QACZH,WAAW,CAACgB,MAAM,EAAEb,GAAG,CAAC;QACxBa,MAAM,CAACN,KAAK,GAAGP,GAAG;KACnB;IAED,OAAOa,MAAM,CAAA;CACd"}

View File

@@ -0,0 +1,152 @@
import { codeFrameColumns } from "next/dist/compiled/babel/code-frame";
import chalk from "next/dist/compiled/chalk";
import path from "path";
export var DiagnosticCategory;
(function(DiagnosticCategory) {
DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
})(DiagnosticCategory || (DiagnosticCategory = {}));
function getFormattedLayoutAndPageDiagnosticMessageText(baseDir, diagnostic) {
var ref, ref1;
const message = diagnostic.messageText;
const sourceFilepath = ((ref1 = (ref = diagnostic.file) == null ? void 0 : ref.text.trim().match(/^\/\/ File: (.+)\n/)) == null ? void 0 : ref1[1]) || "";
if (sourceFilepath && typeof message !== "string") {
const relativeSourceFile = path.relative(baseDir, sourceFilepath);
const type = /'typeof import\(".+page"\)'/.test(message.messageText) ? "Page" : "Layout";
// Reference of error codes:
// https://github.com/Microsoft/TypeScript/blob/main/src/compiler/diagnosticMessages.json
switch(message.code){
case 2344:
const filepathAndType = message.messageText.match(/'typeof import\("(.+)"\)'.+'(.+)'/);
if (filepathAndType) {
let main = `${type} "${chalk.bold(relativeSourceFile)}" does not match the required types of a Next.js ${type}.`;
function processNext(indent, next) {
if (!next) return;
for (const item of next){
switch(item.code){
case 2200:
const mismatchedField = item.messageText.match(/The types of '(.+)'/);
if (mismatchedField) {
main += "\n" + " ".repeat(indent * 2);
main += `"${chalk.bold(mismatchedField[1])}" has the wrong type:`;
}
break;
case 2322:
const types = item.messageText.match(/Type '(.+)' is not assignable to type '(.+)'./);
if (types) {
main += "\n" + " ".repeat(indent * 2);
if (types[2] === "PageComponent" || types[2] === "LayoutComponent") {
main += `The exported ${type} component isn't correctly typed.`;
} else {
main += `Expected "${chalk.bold(types[2].replace('"__invalid_negative_number__"', "number (>= 0)"))}", got "${chalk.bold(types[1])}".`;
}
}
break;
case 2326:
main += "\n" + " ".repeat(indent * 2);
main += `Invalid configuration:`;
break;
case 2739:
const invalidProp = item.messageText.match(/Type '(.+)' is missing the following properties from type '(.+)'/);
if (invalidProp) {
if (invalidProp[1] === "LayoutProps" || invalidProp[1] === "PageProps") {
main += "\n" + " ".repeat(indent * 2);
main += `Prop "${invalidProp[2]}" is incompatible with the ${type}.`;
}
}
break;
case 2559:
const invalid = item.messageText.match(/Type '(.+)' has/);
if (invalid) {
main += "\n" + " ".repeat(indent * 2);
main += `Type "${chalk.bold(invalid[1])}" isn't allowed.`;
}
break;
case 2741:
const incompatPageProp = item.messageText.match(/Property '(.+)' is missing in type 'PageProps'/);
if (incompatPageProp) {
main += "\n" + " ".repeat(indent * 2);
main += `Prop "${chalk.bold(incompatPageProp[1])}" will never be passed. Remove it from the component's props.`;
} else {
const extraLayoutProp = item.messageText.match(/Property '(.+)' is missing in type 'LayoutProps' but required in type '(.+)'/);
if (extraLayoutProp) {
main += "\n" + " ".repeat(indent * 2);
main += `Prop "${chalk.bold(extraLayoutProp[1])}" is not valid for this Layout, remove it to fix.`;
}
}
break;
default:
}
processNext(indent + 1, item.next);
}
}
processNext(1, message.next);
return main;
}
break;
case 2345:
const filepathAndInvalidExport = message.messageText.match(/'typeof import\("(.+)"\)'.+Impossible<"(.+)">/);
if (filepathAndInvalidExport) {
const main = `${type} "${chalk.bold(relativeSourceFile)}" exports an invalid "${chalk.bold(filepathAndInvalidExport[2])}" field. ${type} should only export a default React component and configuration options. Learn more: https://nextjs.org/docs/messages/invalid-segment-export`;
return main;
}
break;
default:
}
}
}
export async function getFormattedDiagnostic(ts, baseDir, distDir, diagnostic, isAppDirEnabled) {
var ref;
// If the error comes from .next/types/, we handle it specially.
const isLayoutOrPageError = isAppDirEnabled && ((ref = diagnostic.file) == null ? void 0 : ref.fileName.startsWith(path.join(baseDir, distDir, "types")));
let message = "";
const layoutReason = isLayoutOrPageError ? getFormattedLayoutAndPageDiagnosticMessageText(baseDir, diagnostic) : null;
const reason = layoutReason || ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
const category = diagnostic.category;
switch(category){
// Warning
case 0:
{
message += chalk.yellow.bold("Type warning") + ": ";
break;
}
// Error
case 1:
{
message += chalk.red.bold("Type error") + ": ";
break;
}
// 2 = Suggestion, 3 = Message
case 2:
case 3:
default:
{
message += chalk.cyan.bold(category === 2 ? "Suggestion" : "Info") + ": ";
break;
}
}
message += reason + "\n";
if (!isLayoutOrPageError && diagnostic.file) {
const pos = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
const line = pos.line + 1;
const character = pos.character + 1;
let fileName = path.posix.normalize(path.relative(baseDir, diagnostic.file.fileName).replace(/\\/g, "/"));
if (!fileName.startsWith(".")) {
fileName = "./" + fileName;
}
message = chalk.cyan(fileName) + ":" + chalk.yellow(line.toString()) + ":" + chalk.yellow(character.toString()) + "\n" + message;
message += "\n" + codeFrameColumns(diagnostic.file.getFullText(diagnostic.file.getSourceFile()), {
start: {
line: line,
column: character
}
}, {
forceColor: true
});
}
return message;
}
//# sourceMappingURL=diagnosticFormatter.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,46 @@
import chalk from "next/dist/compiled/chalk";
import os from "os";
import path from "path";
import { FatalError } from "../fatal-error";
import isError from "../is-error";
export async function getTypeScriptConfiguration(ts, tsConfigPath, metaOnly) {
try {
var ref;
const formatDiagnosticsHost = {
getCanonicalFileName: (fileName)=>fileName,
getCurrentDirectory: ts.sys.getCurrentDirectory,
getNewLine: ()=>os.EOL
};
const { config , error } = ts.readConfigFile(tsConfigPath, ts.sys.readFile);
if (error) {
throw new FatalError(ts.formatDiagnostic(error, formatDiagnosticsHost));
}
let configToParse = config;
const result = ts.parseJsonConfigFileContent(configToParse, // When only interested in meta info,
// avoid enumerating all files (for performance reasons)
metaOnly ? {
...ts.sys,
readDirectory (_path, extensions, _excludes, _includes, _depth) {
return [
extensions ? `file${extensions[0]}` : `file.ts`
];
}
} : ts.sys, path.dirname(tsConfigPath));
if (result.errors) {
result.errors = result.errors.filter(({ code })=>// No inputs were found in config file
code !== 18003);
}
if ((ref = result.errors) == null ? void 0 : ref.length) {
throw new FatalError(ts.formatDiagnostic(result.errors[0], formatDiagnosticsHost));
}
return result;
} catch (err) {
if (isError(err) && err.name === "SyntaxError") {
const reason = "\n" + (err.message ?? "");
throw new FatalError(chalk.red.bold("Could not parse", chalk.cyan("tsconfig.json") + "." + " Please make sure it contains syntactically correct JSON.") + reason);
}
throw err;
}
}
//# sourceMappingURL=getTypeScriptConfiguration.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/typescript/getTypeScriptConfiguration.ts"],"names":["chalk","os","path","FatalError","isError","getTypeScriptConfiguration","ts","tsConfigPath","metaOnly","result","formatDiagnosticsHost","getCanonicalFileName","fileName","getCurrentDirectory","sys","getNewLine","EOL","config","error","readConfigFile","readFile","formatDiagnostic","configToParse","parseJsonConfigFileContent","readDirectory","_path","extensions","_excludes","_includes","_depth","dirname","errors","filter","code","length","err","name","reason","message","red","bold","cyan"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,EAAE,MAAM,IAAI,CAAA;AACnB,OAAOC,IAAI,MAAM,MAAM,CAAA;AAEvB,SAASC,UAAU,QAAQ,gBAAgB,CAAA;AAC3C,OAAOC,OAAO,MAAM,aAAa,CAAA;AAEjC,OAAO,eAAeC,0BAA0B,CAC9CC,EAA+B,EAC/BC,YAAo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,GAArBtB,KAAAA,CAAqB,GAArBA,GAAa,CAAEyB,MAAM,EAAE;YACzB,MAAM,IAAI/B,UAAU,CAClBG,EAAE,CAACe,gBAAgB,CAACZ,MAAM,CAACsB,MAAM,CAAC,CAAC,CAAC,EAAErB,qBAAqB,CAAC,CAC7D,CAAA;SACF;QAED,OAAOD,MAAM,CAAA;KACd,CAAC,OAAO0B,GAAG,EAAE;QACZ,IAAI/B,OAAO,CAAC+B,GAAG,CAAC,IAAIA,GAAG,CAACC,IAAI,KAAK,aAAa,EAAE;YAC9C,MAAMC,MAAM,GAAG,IAAI,GAAG,CAACF,GAAG,CAACG,OAAO,IAAI,EAAE,CAAC;YACzC,MAAM,IAAInC,UAAU,CAClBH,KAAK,CAACuC,GAAG,CAACC,IAAI,CACZ,iBAAiB,EACjBxC,KAAK,CAACyC,IAAI,CAAC,eAAe,CAAC,GACzB,GAAG,GACH,2DAA2D,CAC9D,GAAGJ,MAAM,CACX,CAAA;SACF;QACD,MAAMF,GAAG,CAAA;KACV;CACF"}

View File

@@ -0,0 +1,33 @@
import { promises as fs } from "fs";
import path from "path";
import { fileExists } from "../file-exists";
import { recursiveReadDir } from "../recursive-readdir";
export async function getTypeScriptIntent(baseDir, intentDirs, tsconfigPath) {
const resolvedTsConfigPath = path.join(baseDir, tsconfigPath);
// The integration turns on if we find a `tsconfig.json` in the user's
// project.
const hasTypeScriptConfiguration = await fileExists(resolvedTsConfigPath);
if (hasTypeScriptConfiguration) {
const content = await fs.readFile(resolvedTsConfigPath, {
encoding: "utf8"
}).then((txt)=>txt.trim(), ()=>null);
return {
firstTimeSetup: content === "" || content === "{}"
};
}
// Next.js also offers a friendly setup mode that bootstraps a TypeScript
// project for the user when we detect TypeScript files. So, we need to check
// the `pages/` directory for a TypeScript file.
// Checking all directories is too slow, so this is a happy medium.
for (const dir of intentDirs){
const typescriptFiles = await recursiveReadDir(dir, /.*\.(ts|tsx)$/, /(node_modules|.*\.d\.ts)/);
if (typescriptFiles.length) {
return {
firstTimeSetup: true
};
}
}
return false;
}
//# sourceMappingURL=getTypeScriptIntent.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/typescript/getTypeScriptIntent.ts"],"names":["promises","fs","path","fileExists","recursiveReadDir","getTypeScriptIntent","baseDir","intentDirs","tsconfigPath","resolvedTsConfigPath","join","hasTypeScriptConfiguration","content","readFile","encoding","then","txt","trim","firstTimeSetup","dir","typescriptFiles","length"],"mappings":"AAAA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AACnC,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,SAASC,UAAU,QAAQ,gBAAgB,CAAA;AAC3C,SAASC,gBAAgB,QAAQ,sBAAsB,CAAA;AAIvD,OAAO,eAAeC,mBAAmB,CACvCC,OAAe,EACfC,UAAoB,EACpBC,YAAoB,EACe;IACnC,MAAMC,oBAAoB,GAAGP,IAAI,CAACQ,IAAI,CAACJ,OAAO,EAAEE,YAAY,CAAC;IAE7D,sEAAsE;IACtE,WAAW;IACX,MAAMG,0BAA0B,GAAG,MAAMR,UAAU,CAACM,oBAAoB,CAAC;IACzE,IAAIE,0BAA0B,EAAE;QAC9B,MAAMC,OAAO,GAAG,MAAMX,EAAE,CACrBY,QAAQ,CAACJ,oBAAoB,EAAE;YAAEK,QAAQ,EAAE,MAAM;SAAE,CAAC,CACpDC,IAAI,CACH,CAACC,GAAG,GAAKA,GAAG,CAACC,IAAI,EAAE,EACnB,IAAM,IAAI,CACX;QACH,OAAO;YAAEC,cAAc,EAAEN,OAAO,KAAK,EAAE,IAAIA,OAAO,KAAK,IAAI;SAAE,CAAA;KAC9D;IAED,yEAAyE;IACzE,6EAA6E;IAC7E,gDAAgD;IAChD,mEAAmE;IACnE,KAAK,MAAMO,GAAG,IAAIZ,UAAU,CAAE;QAC5B,MAAMa,eAAe,GAAG,MAAMhB,gBAAgB,CAC5Ce,GAAG,8CAGJ;QACD,IAAIC,eAAe,CAACC,MAAM,EAAE;YAC1B,OAAO;gBAAEH,cAAc,EAAE,IAAI;aAAE,CAAA;SAChC;KACF;IAED,OAAO,KAAK,CAAA;CACb"}

View File

@@ -0,0 +1,13 @@
import chalk from "next/dist/compiled/chalk";
import { getOxfordCommaList } from "../oxford-comma-list";
import { FatalError } from "../fatal-error";
import { getPkgManager } from "../helpers/get-pkg-manager";
export async function missingDepsError(dir, missingPackages) {
const packagesHuman = getOxfordCommaList(missingPackages.map((p)=>p.pkg));
const packagesCli = missingPackages.map((p)=>p.pkg).join(" ");
const packageManager = getPkgManager(dir);
const removalMsg = "\n\n" + chalk.bold("If you are not trying to use TypeScript, please remove the " + chalk.cyan("tsconfig.json") + " file from your package root (and any TypeScript files in your pages directory).");
throw new FatalError(chalk.bold.red(`It looks like you're trying to use TypeScript but do not have the required package(s) installed.`) + "\n\n" + chalk.bold(`Please install ${chalk.bold(packagesHuman)} by running:`) + "\n\n" + `\t${chalk.bold.cyan((packageManager === "yarn" ? "yarn add --dev" : packageManager === "pnpm" ? "pnpm install --save-dev" : "npm install --save-dev") + " " + packagesCli)}` + removalMsg + "\n");
}
//# sourceMappingURL=missingDependencyError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/typescript/missingDependencyError.ts"],"names":["chalk","getOxfordCommaList","FatalError","getPkgManager","missingDepsError","dir","missingPackages","packagesHuman","map","p","pkg","packagesCli","join","packageManager","removalMsg","bold","cyan","red"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAE5C,SAASC,kBAAkB,QAAQ,sBAAsB,CAAA;AAEzD,SAASC,UAAU,QAAQ,gBAAgB,CAAA;AAC3C,SAASC,aAAa,QAAQ,4BAA4B,CAAA;AAE1D,OAAO,eAAeC,gBAAgB,CACpCC,GAAW,EACXC,eAAoC,EACpC;IACA,MAAMC,aAAa,GAAGN,kBAAkB,CAACK,eAAe,CAACE,GAAG,CAAC,CAACC,CAAC,GAAKA,CAAC,CAACC,GAAG,CAAC,CAAC;IAC3E,MAAMC,WAAW,GAAGL,eAAe,CAACE,GAAG,CAAC,CAACC,CAAC,GAAKA,CAAC,CAACC,GAAG,CAAC,CAACE,IAAI,CAAC,GAAG,CAAC;IAC/D,MAAMC,cAAc,GAAGV,aAAa,CAACE,GAAG,CAAC;IAEzC,MAAMS,UAAU,GACd,MAAM,GACNd,KAAK,CAACe,IAAI,CACR,6DAA6D,GAC3Df,KAAK,CAACgB,IAAI,CAAC,eAAe,CAAC,GAC3B,kFAAkF,CACrF;IAEH,MAAM,IAAId,UAAU,CAClBF,KAAK,CAACe,IAAI,CAACE,GAAG,CACZ,CAAC,gGAAgG,CAAC,CACnG,GACC,MAAM,GACNjB,KAAK,CAACe,IAAI,CAAC,CAAC,eAAe,EAAEf,KAAK,CAACe,IAAI,CAACR,aAAa,CAAC,CAAC,YAAY,CAAC,CAAC,GACrE,MAAM,GACN,CAAC,EAAE,EAAEP,KAAK,CAACe,IAAI,CAACC,IAAI,CAClB,CAACH,cAAc,KAAK,MAAM,GACtB,gBAAgB,GAChBA,cAAc,KAAK,MAAM,GACzB,yBAAyB,GACzB,wBAAwB,CAAC,GAC3B,GAAG,GACHF,WAAW,CACd,CAAC,CAAC,GACHG,UAAU,GACV,IAAI,CACP,CAAA;CACF"}

View File

@@ -0,0 +1,71 @@
import path from "path";
import { DiagnosticCategory, getFormattedDiagnostic } from "./diagnosticFormatter";
import { getTypeScriptConfiguration } from "./getTypeScriptConfiguration";
import { getRequiredConfiguration } from "./writeConfigurationDefaults";
import { CompileError } from "../compile-error";
import { warn } from "../../build/output/log";
export async function runTypeCheck(ts, baseDir, distDir, tsConfigPath, cacheDir, isAppDirEnabled) {
const effectiveConfiguration = await getTypeScriptConfiguration(ts, tsConfigPath);
if (effectiveConfiguration.fileNames.length < 1) {
return {
hasWarnings: false,
inputFilesCount: 0,
totalFilesCount: 0,
incremental: false
};
}
const requiredConfig = getRequiredConfiguration(ts);
const options = {
...effectiveConfiguration.options,
...requiredConfig,
declarationMap: false,
emitDeclarationOnly: false,
noEmit: true
};
let program;
let incremental = false;
if ((options.incremental || options.composite) && cacheDir) {
if (options.composite) {
warn("TypeScript project references are not fully supported. Attempting to build in incremental mode.");
}
incremental = true;
program = ts.createIncrementalProgram({
rootNames: effectiveConfiguration.fileNames,
options: {
...options,
composite: false,
incremental: true,
tsBuildInfoFile: path.join(cacheDir, ".tsbuildinfo")
}
});
} else {
program = ts.createProgram(effectiveConfiguration.fileNames, options);
}
const result = program.emit();
// Intended to match:
// - pages/test.js
// - pages/apples.test.js
// - pages/__tests__/a.js
//
// But not:
// - pages/contest.js
// - pages/other.js
// - pages/test/a.js
//
const regexIgnoredFile = /[\\/]__(?:tests|mocks)__[\\/]|(?<=[\\/.])(?:spec|test)\.[^\\/]+$/;
const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(result.diagnostics).filter((d)=>!(d.file && regexIgnoredFile.test(d.file.fileName)));
const firstError = allDiagnostics.find((d)=>d.category === DiagnosticCategory.Error && Boolean(d.file)) ?? allDiagnostics.find((d)=>d.category === DiagnosticCategory.Error);
if (firstError) {
throw new CompileError(await getFormattedDiagnostic(ts, baseDir, distDir, firstError, isAppDirEnabled));
}
const warnings = await Promise.all(allDiagnostics.filter((d)=>d.category === DiagnosticCategory.Warning).map((d)=>getFormattedDiagnostic(ts, baseDir, distDir, d, isAppDirEnabled)));
return {
hasWarnings: true,
warnings,
inputFilesCount: effectiveConfiguration.fileNames.length,
totalFilesCount: program.getSourceFiles().length,
incremental
};
}
//# sourceMappingURL=runTypeCheck.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/typescript/runTypeCheck.ts"],"names":["path","DiagnosticCategory","getFormattedDiagnostic","getTypeScriptConfiguration","getRequiredConfiguration","CompileError","warn","runTypeCheck","ts","baseDir","distDir","tsConfigPath","cacheDir","isAppDirEnabled","effectiveConfiguration","fileNames","length","hasWarnings","inputFilesCount","totalFilesCount","incremental","requiredConfig","options","declarationMap","emitDeclarationOnly","noEmit","program","composite","createIncrementalProgram","rootNames","tsBuildInfoFile","join","createProgram","result","emit","regexIgnoredFile","allDiagnostics","getPreEmitDiagnostics","concat","diagnostics","filter","d","file","test","fileName","firstError","find","category","Error","Boolean","warnings","Promise","all","Warning","map","getSourceFiles"],"mappings":"AAAA,OAAOA,IAAI,MAAM,MAAM,CAAA;AACvB,SACEC,kBAAkB,EAClBC,sBAAsB,QACjB,uBAAuB,CAAA;AAC9B,SAASC,0BAA0B,QAAQ,8BAA8B,CAAA;AACzE,SAASC,wBAAwB,QAAQ,8BAA8B,CAAA;AAEvE,SAASC,YAAY,QAAQ,kBAAkB,CAAA;AAC/C,SAASC,IAAI,QAAQ,wBAAwB,CAAA;AAU7C,OAAO,eAAeC,YAAY,CAChCC,EAA+B,EAC/BC,OAAe,EACfC,OAAe,EACfC,YAAoB,EACpBC,QAAiB,EACjBC,eAAyB,EACC;IAC1B,MAAMC,sBAAsB,GAAG,MAAMX,0BAA0B,CAC7DK,EAAE,EACFG,YAAY,CACb;IAED,IAAIG,sBAAsB,CAACC,SAAS,CAACC,MAAM,GAAG,CAAC,EAAE;QAC/C,OAAO;YACLC,WAAW,EAAE,KAAK;YAClBC,eAAe,EAAE,CAAC;YAClBC,eAAe,EAAE,CAAC;YAClBC,WAAW,EAAE,KAAK;SACnB,CAAA;KACF;IACD,MAAMC,cAAc,GAAGjB,wBAAwB,CAACI,EAAE,CAAC;IAEnD,MAAMc,OAAO,GAAG;QACd,GAAGR,sBAAsB,CAACQ,OAAO;QACjC,GAAGD,cAAc;QACjBE,cAAc,EAAE,KAAK;QACrBC,mBAAmB,EAAE,KAAK;QAC1BC,MAAM,EAAE,IAAI;KACb;IAED,IAAIC,OAAO,AAE4B;IACvC,IAAIN,WAAW,GAAG,KAAK;IACvB,IAAI,CAACE,OAAO,CAACF,WAAW,IAAIE,OAAO,CAACK,SAAS,CAAC,IAAIf,QAAQ,EAAE;QAC1D,IAAIU,OAAO,CAACK,SAAS,EAAE;YACrBrB,IAAI,CACF,iGAAiG,CAClG;SACF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B,CAC1BM,EAAE,EACFC,OAAO,EACPC,OAAO,EACPmC,UAAU,EACVhC,eAAe,CAChB,CACF,CAAA;KACF;IAED,MAAMqC,QAAQ,GAAG,MAAMC,OAAO,CAACC,GAAG,CAChChB,cAAc,CACXI,MAAM,CAAC,CAACC,CAAC,GAAKA,CAAC,CAACM,QAAQ,KAAK9C,kBAAkB,CAACoD,OAAO,CAAC,CACxDC,GAAG,CAAC,CAACb,CAAC,GACLvC,sBAAsB,CAACM,EAAE,EAAEC,OAAO,EAAEC,OAAO,EAAE+B,CAAC,EAAE5B,eAAe,CAAC,CACjE,CACJ;IACD,OAAO;QACLI,WAAW,EAAE,IAAI;QACjBiC,QAAQ;QACRhC,eAAe,EAAEJ,sBAAsB,CAACC,SAAS,CAACC,MAAM;QACxDG,eAAe,EAAEO,OAAO,CAAC6B,cAAc,EAAE,CAACvC,MAAM;QAChDI,WAAW;KACZ,CAAA;CACF"}

View File

@@ -0,0 +1,30 @@
import os from "os";
import path from "path";
import { promises as fs } from "fs";
export async function writeAppTypeDeclarations(baseDir, imageImportsEnabled) {
// Reference `next` types
const appTypeDeclarations = path.join(baseDir, "next-env.d.ts");
// Defaults EOL to system default
let eol = os.EOL;
let currentContent;
try {
currentContent = await fs.readFile(appTypeDeclarations, "utf8");
// If file already exists then preserve its line ending
const lf = currentContent.indexOf("\n", /* skip first so we can lf - 1 */ 1);
if (lf !== -1) {
if (currentContent[lf - 1] === "\r") {
eol = "\r\n";
} else {
eol = "\n";
}
}
} catch (err) {}
const content = '/// <reference types="next" />' + eol + (imageImportsEnabled ? '/// <reference types="next/image-types/global" />' + eol : "") + eol + "// NOTE: This file should not be edited" + eol + "// see https://nextjs.org/docs/basic-features/typescript for more information." + eol;
// Avoids an un-necessary write on read-only fs
if (currentContent === content) {
return;
}
await fs.writeFile(appTypeDeclarations, content);
}
//# sourceMappingURL=writeAppTypeDeclarations.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../lib/typescript/writeAppTypeDeclarations.ts"],"names":["os","path","promises","fs","writeAppTypeDeclarations","baseDir","imageImportsEnabled","appTypeDeclarations","join","eol","EOL","currentContent","readFile","lf","indexOf","err","content","writeFile"],"mappings":"AAAA,OAAOA,EAAE,MAAM,IAAI,CAAA;AACnB,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,SAASC,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AAEnC,OAAO,eAAeC,wBAAwB,CAC5CC,OAAe,EACfC,mBAA4B,EACb;IACf,yBAAyB;IACzB,MAAMC,mBAAmB,GAAGN,IAAI,CAACO,IAAI,CAACH,OAAO,EAAE,eAAe,CAAC;IAE/D,iCAAiC;IACjC,IAAII,GAAG,GAAGT,EAAE,CAACU,GAAG;IAChB,IAAIC,cAAc,AAAoB;IAEtC,IAAI;QACFA,cAAc,GAAG,MAAMR,EAAE,CAACS,QAAQ,CAACL,mBAAmB,EAAE,MAAM,CAAC;QAC/D,uDAAuD;QACvD,MAAMM,EAAE,GAAGF,cAAc,CAACG,OAAO,CAAC,IAAI,EAAE,iCAAiC,CAAC,CAAC,CAAC;QAE5E,IAAID,EAAE,KAAK,CAAC,CAAC,EAAE;YACb,IAAIF,cAAc,CAACE,EAAE,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE;gBACnCJ,GAAG,GAAG,MAAM;aACb,MAAM;gBACLA,GAAG,GAAG,IAAI;aACX;SACF;KACF,CAAC,OAAOM,GAAG,EAAE,EAAE;IAEhB,MAAMC,OAAO,GACX,gCAAgC,GAChCP,GAAG,GACH,CAACH,mBAAmB,GAChB,mDAAmD,GAAGG,GAAG,GACzD,EAAE,CAAC,GACPA,GAAG,GACH,yCAAyC,GACzCA,GAAG,GACH,gFAAgF,GAChFA,GAAG;IAEL,+CAA+C;IAC/C,IAAIE,cAAc,KAAKK,OAAO,EAAE;QAC9B,OAAM;KACP;IACD,MAAMb,EAAE,CAACc,SAAS,CAACV,mBAAmB,EAAES,OAAO,CAAC;CACjD"}

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