main repo

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

View File

@@ -0,0 +1,31 @@
export async function getLayoutOrPageModule(loaderTree) {
const { layout, page, defaultPage } = loaderTree[2];
const isLayout = typeof layout !== "undefined";
const isPage = typeof page !== "undefined";
const isDefaultPage = typeof defaultPage !== "undefined" && loaderTree[0] === "__DEFAULT__";
let value = undefined;
let modType = undefined;
if (isLayout) {
value = await layout[0]();
modType = "layout";
} else if (isPage) {
value = await page[0]();
modType = "page";
} else if (isDefaultPage) {
value = await defaultPage[0]();
modType = "page";
}
return [
value,
modType
];
}
export async function getComponentTypeModule(loaderTree, componentType) {
const { [componentType]: component } = loaderTree[2];
if (typeof component !== "undefined") {
return await component[0]();
}
return undefined;
}
//# sourceMappingURL=app-dir-module.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/app-dir-module.ts"],"names":["getLayoutOrPageModule","loaderTree","layout","page","defaultPage","isLayout","isPage","isDefaultPage","value","undefined","modType","getComponentTypeModule","componentType","component"],"mappings":"AAWA,OAAO,eAAeA,sBAAsBC,UAAsB;IAChE,MAAM,EAAEC,MAAM,EAAEC,IAAI,EAAEC,WAAW,EAAE,GAAGH,UAAU,CAAC,EAAE;IACnD,MAAMI,WAAW,OAAOH,WAAW;IACnC,MAAMI,SAAS,OAAOH,SAAS;IAC/B,MAAMI,gBACJ,OAAOH,gBAAgB,eAAeH,UAAU,CAAC,EAAE,KAAK;IAE1D,IAAIO,QAAQC;IACZ,IAAIC,UAAyCD;IAE7C,IAAIJ,UAAU;QACZG,QAAQ,MAAMN,MAAM,CAAC,EAAE;QACvBQ,UAAU;IACZ,OAAO,IAAIJ,QAAQ;QACjBE,QAAQ,MAAML,IAAI,CAAC,EAAE;QACrBO,UAAU;IACZ,OAAO,IAAIH,eAAe;QACxBC,QAAQ,MAAMJ,WAAW,CAAC,EAAE;QAC5BM,UAAU;IACZ;IAEA,OAAO;QAACF;QAAOE;KAAQ;AACzB;AAEA,OAAO,eAAeC,uBACpBV,UAAsB,EACtBW,aAAqC;IAErC,MAAM,EAAE,CAACA,cAAc,EAAEC,SAAS,EAAE,GAAGZ,UAAU,CAAC,EAAE;IACpD,IAAI,OAAOY,cAAc,aAAa;QACpC,OAAO,MAAMA,SAAS,CAAC,EAAE;IAC3B;IACA,OAAOJ;AACT"}

27
node_modules/next/dist/esm/server/lib/cpu-profile.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
const privateCpuProfileName = process.env.__NEXT_PRIVATE_CPU_PROFILE;
const isCpuProfileEnabled = process.env.NEXT_CPU_PROF || privateCpuProfileName;
if (isCpuProfileEnabled) {
const { Session } = require("inspector");
const fs = require("fs");
const session = new Session();
session.connect();
session.post("Profiler.enable");
session.post("Profiler.start");
function saveProfile() {
session.post("Profiler.stop", (error, param)=>{
if (error) {
console.error("Cannot generate CPU profiling:", error);
return;
}
// Write profile to disk
const filename = `${privateCpuProfileName || "CPU.main"}.${Date.now()}.cpuprofile`;
fs.writeFileSync(`./${filename}`, JSON.stringify(param.profile));
process.exit(0);
});
}
process.on("SIGINT", saveProfile);
process.on("SIGTERM", saveProfile);
process.on("exit", saveProfile);
}
//# sourceMappingURL=cpu-profile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/cpu-profile.ts"],"names":["privateCpuProfileName","process","env","__NEXT_PRIVATE_CPU_PROFILE","isCpuProfileEnabled","NEXT_CPU_PROF","Session","require","fs","session","connect","post","saveProfile","error","param","console","filename","Date","now","writeFileSync","JSON","stringify","profile","exit","on"],"mappings":"AAAA,MAAMA,wBAAwBC,QAAQC,GAAG,CAACC,0BAA0B;AACpE,MAAMC,sBAAsBH,QAAQC,GAAG,CAACG,aAAa,IAAIL;AAEzD,IAAII,qBAAqB;IACvB,MAAM,EAAEE,OAAO,EAAE,GAAGC,QAAQ;IAC5B,MAAMC,KAAKD,QAAQ;IAEnB,MAAME,UAAU,IAAIH;IACpBG,QAAQC,OAAO;IAEfD,QAAQE,IAAI,CAAC;IACbF,QAAQE,IAAI,CAAC;IAEb,SAASC;QACPH,QAAQE,IAAI,CAAC,iBAAiB,CAACE,OAAOC;YACpC,IAAID,OAAO;gBACTE,QAAQF,KAAK,CAAC,kCAAkCA;gBAChD;YACF;YAEA,wBAAwB;YACxB,MAAMG,WAAW,CAAC,EAChBhB,yBAAyB,WAC1B,CAAC,EAAEiB,KAAKC,GAAG,GAAG,WAAW,CAAC;YAC3BV,GAAGW,aAAa,CAAC,CAAC,EAAE,EAAEH,SAAS,CAAC,EAAEI,KAAKC,SAAS,CAACP,MAAMQ,OAAO;YAC9DrB,QAAQsB,IAAI,CAAC;QACf;IACF;IACAtB,QAAQuB,EAAE,CAAC,UAAUZ;IACrBX,QAAQuB,EAAE,CAAC,WAAWZ;IACtBX,QAAQuB,EAAE,CAAC,QAAQZ;AACrB"}

34
node_modules/next/dist/esm/server/lib/etag.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
/**
* FNV-1a Hash implementation
* @author Travis Webb (tjwebb) <me@traviswebb.com>
*
* Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js
*
* Simplified, optimized and add modified for 52 bit, which provides a larger hash space
* and still making use of Javascript's 53-bit integer space.
*/ export const fnv1a52 = (str)=>{
const len = str.length;
let i = 0, t0 = 0, v0 = 0x2325, t1 = 0, v1 = 0x8422, t2 = 0, v2 = 0x9ce4, t3 = 0, v3 = 0xcbf2;
while(i < len){
v0 ^= str.charCodeAt(i++);
t0 = v0 * 435;
t1 = v1 * 435;
t2 = v2 * 435;
t3 = v3 * 435;
t2 += v0 << 8;
t3 += v1 << 8;
t1 += t0 >>> 16;
v0 = t0 & 65535;
t2 += t1 >>> 16;
v1 = t1 & 65535;
v3 = t3 + (t2 >>> 16) & 65535;
v2 = t2 & 65535;
}
return (v3 & 15) * 281474976710656 + v2 * 4294967296 + v1 * 65536 + (v0 ^ v3 >> 4);
};
export const generateETag = (payload, weak = false)=>{
const prefix = weak ? 'W/"' : '"';
return prefix + fnv1a52(payload).toString(36) + payload.length.toString(36) + '"';
};
//# sourceMappingURL=etag.js.map

1
node_modules/next/dist/esm/server/lib/etag.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/etag.ts"],"names":["fnv1a52","str","len","length","i","t0","v0","t1","v1","t2","v2","t3","v3","charCodeAt","generateETag","payload","weak","prefix","toString"],"mappings":"AAAA;;;;;;;;CAQC,GACD,OAAO,MAAMA,UAAU,CAACC;IACtB,MAAMC,MAAMD,IAAIE,MAAM;IACtB,IAAIC,IAAI,GACNC,KAAK,GACLC,KAAK,QACLC,KAAK,GACLC,KAAK,QACLC,KAAK,GACLC,KAAK,QACLC,KAAK,GACLC,KAAK;IAEP,MAAOR,IAAIF,IAAK;QACdI,MAAML,IAAIY,UAAU,CAACT;QACrBC,KAAKC,KAAK;QACVC,KAAKC,KAAK;QACVC,KAAKC,KAAK;QACVC,KAAKC,KAAK;QACVH,MAAMH,MAAM;QACZK,MAAMH,MAAM;QACZD,MAAMF,OAAO;QACbC,KAAKD,KAAK;QACVI,MAAMF,OAAO;QACbC,KAAKD,KAAK;QACVK,KAAK,AAACD,KAAMF,CAAAA,OAAO,EAAC,IAAM;QAC1BC,KAAKD,KAAK;IACZ;IAEA,OACE,AAACG,CAAAA,KAAK,EAAC,IAAK,kBACZF,KAAK,aACLF,KAAK,QACJF,CAAAA,KAAMM,MAAM,CAAC;AAElB,EAAC;AAED,OAAO,MAAME,eAAe,CAACC,SAAiBC,OAAO,KAAK;IACxD,MAAMC,SAASD,OAAO,QAAQ;IAC9B,OACEC,SAASjB,QAAQe,SAASG,QAAQ,CAAC,MAAMH,QAAQZ,MAAM,CAACe,QAAQ,CAAC,MAAM;AAE3E,EAAC"}

103
node_modules/next/dist/esm/server/lib/find-page-file.js generated vendored Normal file
View File

@@ -0,0 +1,103 @@
import { fileExists } from "../../lib/file-exists";
import { getPagePaths } from "../../shared/lib/page-path/get-page-paths";
import { nonNullable } from "../../lib/non-nullable";
import { join, sep, normalize } from "path";
import { promises as fsPromises } from "fs";
import { warn } from "../../build/output/log";
import chalk from "../../lib/chalk";
import { isMetadataRouteFile } from "../../lib/metadata/is-metadata-route";
async function isTrueCasePagePath(pagePath, pagesDir) {
const pageSegments = normalize(pagePath).split(sep).filter(Boolean);
const segmentExistsPromises = pageSegments.map(async (segment, i)=>{
const segmentParentDir = join(pagesDir, ...pageSegments.slice(0, i));
const parentDirEntries = await fsPromises.readdir(segmentParentDir);
return parentDirEntries.includes(segment);
});
return (await Promise.all(segmentExistsPromises)).every(Boolean);
}
/**
* Finds a page file with the given parameters. If the page is duplicated with
* multiple extensions it will throw, otherwise it will return the *relative*
* path to the page file or null if it is not found.
*
* @param pagesDir Absolute path to the pages folder with trailing `/pages`.
* @param normalizedPagePath The page normalized (it will be denormalized).
* @param pageExtensions Array of page extensions.
*/ export async function findPageFile(pagesDir, normalizedPagePath, pageExtensions, isAppDir) {
const pagePaths = getPagePaths(normalizedPagePath, pageExtensions, isAppDir);
const [existingPath, ...others] = (await Promise.all(pagePaths.map(async (path)=>{
const filePath = join(pagesDir, path);
try {
return await fileExists(filePath) ? path : null;
} catch (err) {
var _err_code;
if (!(err == null ? void 0 : (_err_code = err.code) == null ? void 0 : _err_code.includes("ENOTDIR"))) throw err;
}
return null;
}))).filter(nonNullable);
if (!existingPath) {
return null;
}
if (!await isTrueCasePagePath(existingPath, pagesDir)) {
return null;
}
if (others.length > 0) {
warn(`Duplicate page detected. ${chalk.cyan(join("pages", existingPath))} and ${chalk.cyan(join("pages", others[0]))} both resolve to ${chalk.cyan(normalizedPagePath)}.`);
}
return existingPath;
}
/**
*
* createValidFileMatcher receives configured page extensions and return helpers to determine:
* `isLayoutsLeafPage`: if a file is a valid page file or routes file under app directory
* `isTrackedFiles`: if it's a tracked file for webpack watcher
*
*/ export function createValidFileMatcher(pageExtensions, appDirPath) {
const getExtensionRegexString = (extensions)=>`(?:${extensions.join("|")})`;
const validExtensionFileRegex = new RegExp("\\." + getExtensionRegexString(pageExtensions) + "$");
const leafOnlyPageFileRegex = new RegExp(`(^(page|route)|[\\\\/](page|route))\\.${getExtensionRegexString(pageExtensions)}$`);
const rootNotFoundFileRegex = new RegExp(`^not-found\\.${getExtensionRegexString(pageExtensions)}$`);
/** TODO-METADATA: support other metadata routes
* regex for:
*
* /robots.txt|<ext>
* /sitemap.xml|<ext>
* /favicon.ico
* /manifest.json|<ext>
* <route>/icon.png|jpg|<ext>
* <route>/apple-touch-icon.png|jpg|<ext>
*
*/ /**
* Match the file if it's a metadata route file, static: if the file is a static metadata file.
* It needs to be a file which doesn't match the custom metadata routes e.g. `app/robots.txt/route.js`
*/ function isMetadataFile(filePath) {
const appDirRelativePath = appDirPath ? filePath.replace(appDirPath, "") : filePath;
return isMetadataRouteFile(appDirRelativePath, pageExtensions, true);
}
// Determine if the file is leaf node page file or route file under layouts,
// 'page.<extension>' | 'route.<extension>'
function isAppRouterPage(filePath) {
return leafOnlyPageFileRegex.test(filePath) || isMetadataFile(filePath);
}
function isPageFile(filePath) {
return validExtensionFileRegex.test(filePath) || isMetadataFile(filePath);
}
function isRootNotFound(filePath) {
if (!appDirPath) {
return false;
}
if (!filePath.startsWith(appDirPath + sep)) {
return false;
}
const rest = filePath.slice(appDirPath.length + 1);
return rootNotFoundFileRegex.test(rest);
}
return {
isPageFile,
isAppRouterPage,
isMetadataFile,
isRootNotFound
};
}
//# sourceMappingURL=find-page-file.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/find-page-file.ts"],"names":["fileExists","getPagePaths","nonNullable","join","sep","normalize","promises","fsPromises","warn","chalk","isMetadataRouteFile","isTrueCasePagePath","pagePath","pagesDir","pageSegments","split","filter","Boolean","segmentExistsPromises","map","segment","i","segmentParentDir","slice","parentDirEntries","readdir","includes","Promise","all","every","findPageFile","normalizedPagePath","pageExtensions","isAppDir","pagePaths","existingPath","others","path","filePath","err","code","length","cyan","createValidFileMatcher","appDirPath","getExtensionRegexString","extensions","validExtensionFileRegex","RegExp","leafOnlyPageFileRegex","rootNotFoundFileRegex","isMetadataFile","appDirRelativePath","replace","isAppRouterPage","test","isPageFile","isRootNotFound","startsWith","rest"],"mappings":"AAAA,SAASA,UAAU,QAAQ,wBAAuB;AAClD,SAASC,YAAY,QAAQ,4CAA2C;AACxE,SAASC,WAAW,QAAQ,yBAAwB;AACpD,SAASC,IAAI,EAAEC,GAAG,EAAEC,SAAS,QAAQ,OAAM;AAC3C,SAASC,YAAYC,UAAU,QAAQ,KAAI;AAC3C,SAASC,IAAI,QAAQ,yBAAwB;AAC7C,OAAOC,WAAW,kBAAiB;AACnC,SAASC,mBAAmB,QAAQ,uCAAsC;AAE1E,eAAeC,mBAAmBC,QAAgB,EAAEC,QAAgB;IAClE,MAAMC,eAAeT,UAAUO,UAAUG,KAAK,CAACX,KAAKY,MAAM,CAACC;IAC3D,MAAMC,wBAAwBJ,aAAaK,GAAG,CAAC,OAAOC,SAASC;QAC7D,MAAMC,mBAAmBnB,KAAKU,aAAaC,aAAaS,KAAK,CAAC,GAAGF;QACjE,MAAMG,mBAAmB,MAAMjB,WAAWkB,OAAO,CAACH;QAClD,OAAOE,iBAAiBE,QAAQ,CAACN;IACnC;IAEA,OAAO,AAAC,CAAA,MAAMO,QAAQC,GAAG,CAACV,sBAAqB,EAAGW,KAAK,CAACZ;AAC1D;AAEA;;;;;;;;CAQC,GACD,OAAO,eAAea,aACpBjB,QAAgB,EAChBkB,kBAA0B,EAC1BC,cAAwB,EACxBC,QAAiB;IAEjB,MAAMC,YAAYjC,aAAa8B,oBAAoBC,gBAAgBC;IACnE,MAAM,CAACE,cAAc,GAAGC,OAAO,GAAG,AAChC,CAAA,MAAMT,QAAQC,GAAG,CACfM,UAAUf,GAAG,CAAC,OAAOkB;QACnB,MAAMC,WAAWnC,KAAKU,UAAUwB;QAChC,IAAI;YACF,OAAO,AAAC,MAAMrC,WAAWsC,YAAaD,OAA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;IAChE;IAEA,SAASkB,WAAWlB,QAAgB;QAClC,OAAOS,wBAAwBQ,IAAI,CAACjB,aAAaa,eAAeb;IAClE;IAEA,SAASmB,eAAenB,QAAgB;QACtC,IAAI,CAACM,YAAY;YACf,OAAO;QACT;QACA,IAAI,CAACN,SAASoB,UAAU,CAACd,aAAaxC,MAAM;YAC1C,OAAO;QACT;QACA,MAAMuD,OAAOrB,SAASf,KAAK,CAACqB,WAAWH,MAAM,GAAG;QAChD,OAAOS,sBAAsBK,IAAI,CAACI;IACpC;IAEA,OAAO;QACLH;QACAF;QACAH;QACAM;IACF;AACF"}

View File

@@ -0,0 +1,11 @@
import { isIPv6 } from "./is-ipv6";
/**
* Formats a hostname so that it is a valid host that can be fetched by wrapping
* IPv6 hosts with brackets.
* @param hostname
* @returns
*/ export function formatHostname(hostname) {
return isIPv6(hostname) ? `[${hostname}]` : hostname;
}
//# sourceMappingURL=format-hostname.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/format-hostname.ts"],"names":["isIPv6","formatHostname","hostname"],"mappings":"AAAA,SAASA,MAAM,QAAQ,YAAW;AAElC;;;;;CAKC,GACD,OAAO,SAASC,eAAeC,QAAgB;IAC7C,OAAOF,OAAOE,YAAY,CAAC,CAAC,EAAEA,SAAS,CAAC,CAAC,GAAGA;AAC9C"}

View File

@@ -0,0 +1,29 @@
import { createIpcServer } from "./server-ipc";
import { IncrementalCache } from "./incremental-cache";
let initializeResult;
export async function initialize(...constructorArgs) {
const incrementalCache = new IncrementalCache(...constructorArgs);
const { ipcPort, ipcValidationKey } = await createIpcServer({
async revalidateTag (...args) {
return incrementalCache.revalidateTag(...args);
},
async get (...args) {
return incrementalCache.get(...args);
},
async set (...args) {
return incrementalCache.set(...args);
},
async lock (...args) {
return incrementalCache.lock(...args);
},
async unlock (...args) {
return incrementalCache.unlock(...args);
}
});
return {
ipcPort,
ipcValidationKey
};
}
//# sourceMappingURL=incremental-cache-server.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/incremental-cache-server.ts"],"names":["createIpcServer","IncrementalCache","initializeResult","initialize","constructorArgs","incrementalCache","ipcPort","ipcValidationKey","revalidateTag","args","get","set","lock","unlock"],"mappings":"AAAA,SAASA,eAAe,QAAQ,eAAc;AAC9C,SAASC,gBAAgB,QAAQ,sBAAqB;AAEtD,IAAIC;AAOJ,OAAO,eAAeC,WACpB,GAAGC,eAA+D;IAElE,MAAMC,mBAAmB,IAAIJ,oBAAoBG;IAEjD,MAAM,EAAEE,OAAO,EAAEC,gBAAgB,EAAE,GAAG,MAAMP,gBAAgB;QAC1D,MAAMQ,eACJ,GAAGC,IAAmD;YAEtD,OAAOJ,iBAAiBG,aAAa,IAAIC;QAC3C;QAEA,MAAMC,KAAI,GAAGD,IAAyC;YACpD,OAAOJ,iBAAiBK,GAAG,IAAID;QACjC;QAEA,MAAME,KAAI,GAAGF,IAAyC;YACpD,OAAOJ,iBAAiBM,GAAG,IAAIF;QACjC;QAEA,MAAMG,MAAK,GAAGH,IAA0C;YACtD,OAAOJ,iBAAiBO,IAAI,IAAIH;QAClC;QAEA,MAAMI,QAAO,GAAGJ,IAA4C;YAC1D,OAAOJ,iBAAiBQ,MAAM,IAAIJ;QACpC;IACF;IAEA,OAAO;QACLH;QACAC;IACF;AACF"}

View File

@@ -0,0 +1,247 @@
import LRUCache from "next/dist/compiled/lru-cache";
import { CACHE_ONE_YEAR, NEXT_CACHE_SOFT_TAGS_HEADER } from "../../../lib/constants";
let rateLimitedUntil = 0;
let memoryCache;
const CACHE_TAGS_HEADER = "x-vercel-cache-tags";
const CACHE_HEADERS_HEADER = "x-vercel-sc-headers";
const CACHE_STATE_HEADER = "x-vercel-cache-state";
const CACHE_REVALIDATE_HEADER = "x-vercel-revalidate";
const CACHE_FETCH_URL_HEADER = "x-vercel-cache-item-name";
const CACHE_CONTROL_VALUE_HEADER = "x-vercel-cache-control";
export default class FetchCache {
static isAvailable(ctx) {
return !!(ctx._requestHeaders["x-vercel-sc-host"] || process.env.SUSPENSE_CACHE_URL);
}
constructor(ctx){
this.debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE;
this.headers = {};
this.headers["Content-Type"] = "application/json";
if (CACHE_HEADERS_HEADER in ctx._requestHeaders) {
const newHeaders = JSON.parse(ctx._requestHeaders[CACHE_HEADERS_HEADER]);
for(const k in newHeaders){
this.headers[k] = newHeaders[k];
}
delete ctx._requestHeaders[CACHE_HEADERS_HEADER];
}
const scHost = ctx._requestHeaders["x-vercel-sc-host"] || process.env.SUSPENSE_CACHE_URL;
const scBasePath = ctx._requestHeaders["x-vercel-sc-basepath"] || process.env.SUSPENSE_CACHE_BASEPATH;
if (process.env.SUSPENSE_CACHE_AUTH_TOKEN) {
this.headers["Authorization"] = `Bearer ${process.env.SUSPENSE_CACHE_AUTH_TOKEN}`;
}
if (scHost) {
this.cacheEndpoint = `https://${scHost}${scBasePath || ""}`;
if (this.debug) {
console.log("using cache endpoint", this.cacheEndpoint);
}
} else if (this.debug) {
console.log("no cache endpoint available");
}
if (ctx.maxMemoryCacheSize) {
if (!memoryCache) {
if (this.debug) {
console.log("using memory store for fetch cache");
}
memoryCache = new LRUCache({
max: ctx.maxMemoryCacheSize,
length ({ value }) {
var _JSON_stringify;
if (!value) {
return 25;
} else if (value.kind === "REDIRECT") {
return JSON.stringify(value.props).length;
} else if (value.kind === "IMAGE") {
throw new Error("invariant image should not be incremental-cache");
} else if (value.kind === "FETCH") {
return JSON.stringify(value.data || "").length;
} else if (value.kind === "ROUTE") {
return value.body.length;
}
// rough estimate of size of cache value
return value.html.length + (((_JSON_stringify = JSON.stringify(value.pageData)) == null ? void 0 : _JSON_stringify.length) || 0);
}
});
}
} else {
if (this.debug) {
console.log("not using memory store for fetch cache");
}
}
}
async revalidateTag(tag) {
if (this.debug) {
console.log("revalidateTag", tag);
}
if (Date.now() < rateLimitedUntil) {
if (this.debug) {
console.log("rate limited ", rateLimitedUntil);
}
return;
}
try {
const res = await fetch(`${this.cacheEndpoint}/v1/suspense-cache/revalidate?tags=${tag}`, {
method: "POST",
headers: this.headers,
// @ts-expect-error not on public type
next: {
internal: true
}
});
if (res.status === 429) {
const retryAfter = res.headers.get("retry-after") || "60000";
rateLimitedUntil = Date.now() + parseInt(retryAfter);
}
if (!res.ok) {
throw new Error(`Request failed with status ${res.status}.`);
}
} catch (err) {
console.warn(`Failed to revalidate tag ${tag}`, err);
}
}
async get(key, ctx) {
const { tags, softTags, fetchCache, fetchIdx, fetchUrl } = ctx;
if (!fetchCache) return null;
if (Date.now() < rateLimitedUntil) {
if (this.debug) {
console.log("rate limited");
}
return null;
}
let data = memoryCache == null ? void 0 : memoryCache.get(key);
// memory cache data is only leveraged for up to 1 seconds
// so that revalidation events can be pulled from source
if (Date.now() - ((data == null ? void 0 : data.lastModified) || 0) > 2000) {
data = undefined;
}
// get data from fetch cache
if (!data && this.cacheEndpoint) {
try {
const start = Date.now();
const fetchParams = {
internal: true,
fetchType: "cache-get",
fetchUrl: fetchUrl,
fetchIdx
};
const res = await fetch(`${this.cacheEndpoint}/v1/suspense-cache/${key}`, {
method: "GET",
headers: {
...this.headers,
[CACHE_FETCH_URL_HEADER]: fetchUrl,
[CACHE_TAGS_HEADER]: (tags == null ? void 0 : tags.join(",")) || "",
[NEXT_CACHE_SOFT_TAGS_HEADER]: (softTags == null ? void 0 : softTags.join(",")) || ""
},
next: fetchParams
});
if (res.status === 429) {
const retryAfter = res.headers.get("retry-after") || "60000";
rateLimitedUntil = Date.now() + parseInt(retryAfter);
}
if (res.status === 404) {
if (this.debug) {
console.log(`no fetch cache entry for ${key}, duration: ${Date.now() - start}ms`);
}
return null;
}
if (!res.ok) {
console.error(await res.text());
throw new Error(`invalid response from cache ${res.status}`);
}
const cached = await res.json();
if (!cached || cached.kind !== "FETCH") {
this.debug && console.log({
cached
});
throw new Error(`invalid cache value`);
}
const cacheState = res.headers.get(CACHE_STATE_HEADER);
const age = res.headers.get("age");
data = {
value: cached,
// if it's already stale set it to a time in the past
// if not derive last modified from age
lastModified: cacheState !== "fresh" ? Date.now() - CACHE_ONE_YEAR : Date.now() - parseInt(age || "0", 10) * 1000
};
if (this.debug) {
console.log(`got fetch cache entry for ${key}, duration: ${Date.now() - start}ms, size: ${Object.keys(cached).length}, cache-state: ${cacheState} tags: ${tags == null ? void 0 : tags.join(",")} softTags: ${softTags == null ? void 0 : softTags.join(",")}`);
}
if (data) {
memoryCache == null ? void 0 : memoryCache.set(key, data);
}
} catch (err) {
// unable to get data from fetch-cache
if (this.debug) {
console.error(`Failed to get from fetch-cache`, err);
}
}
}
return data || null;
}
async set(key, data, { fetchCache, fetchIdx, fetchUrl, tags }) {
if (!fetchCache) return;
if (Date.now() < rateLimitedUntil) {
if (this.debug) {
console.log("rate limited");
}
return;
}
memoryCache == null ? void 0 : memoryCache.set(key, {
value: data,
lastModified: Date.now()
});
if (this.cacheEndpoint) {
try {
const start = Date.now();
if (data !== null && "revalidate" in data) {
this.headers[CACHE_REVALIDATE_HEADER] = data.revalidate.toString();
}
if (!this.headers[CACHE_REVALIDATE_HEADER] && data !== null && "data" in data) {
this.headers[CACHE_CONTROL_VALUE_HEADER] = data.data.headers["cache-control"];
}
const body = JSON.stringify({
...data,
// we send the tags in the header instead
// of in the body here
tags: undefined
});
if (this.debug) {
console.log("set cache", key);
}
const fetchParams = {
internal: true,
fetchType: "cache-set",
fetchUrl,
fetchIdx
};
const res = await fetch(`${this.cacheEndpoint}/v1/suspense-cache/${key}`, {
method: "POST",
headers: {
...this.headers,
[CACHE_FETCH_URL_HEADER]: fetchUrl || "",
[CACHE_TAGS_HEADER]: (tags == null ? void 0 : tags.join(",")) || ""
},
body: body,
next: fetchParams
});
if (res.status === 429) {
const retryAfter = res.headers.get("retry-after") || "60000";
rateLimitedUntil = Date.now() + parseInt(retryAfter);
}
if (!res.ok) {
this.debug && console.log(await res.text());
throw new Error(`invalid response ${res.status}`);
}
if (this.debug) {
console.log(`successfully set to fetch-cache for ${key}, duration: ${Date.now() - start}ms, size: ${body.length}`);
}
} catch (err) {
// unable to set to fetch-cache
if (this.debug) {
console.error(`Failed to update fetch cache`, err);
}
}
}
return;
}
}
//# sourceMappingURL=fetch-cache.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,274 @@
import LRUCache from "next/dist/compiled/lru-cache";
import path from "../../../shared/lib/isomorphic/path";
import { NEXT_CACHE_TAGS_HEADER } from "../../../lib/constants";
let memoryCache;
let tagsManifest;
export default class FileSystemCache {
constructor(ctx){
this.fs = ctx.fs;
this.flushToDisk = ctx.flushToDisk;
this.serverDistDir = ctx.serverDistDir;
this.appDir = !!ctx._appDir;
this.revalidatedTags = ctx.revalidatedTags;
if (ctx.maxMemoryCacheSize && !memoryCache) {
memoryCache = new LRUCache({
max: ctx.maxMemoryCacheSize,
length ({ value }) {
var _JSON_stringify;
if (!value) {
return 25;
} else if (value.kind === "REDIRECT") {
return JSON.stringify(value.props).length;
} else if (value.kind === "IMAGE") {
throw new Error("invariant image should not be incremental-cache");
} else if (value.kind === "FETCH") {
return JSON.stringify(value.data || "").length;
} else if (value.kind === "ROUTE") {
return value.body.length;
}
// rough estimate of size of cache value
return value.html.length + (((_JSON_stringify = JSON.stringify(value.pageData)) == null ? void 0 : _JSON_stringify.length) || 0);
}
});
}
if (this.serverDistDir && this.fs) {
this.tagsManifestPath = path.join(this.serverDistDir, "..", "cache", "fetch-cache", "tags-manifest.json");
this.loadTagsManifest();
}
}
loadTagsManifest() {
if (!this.tagsManifestPath || !this.fs || tagsManifest) return;
try {
tagsManifest = JSON.parse(this.fs.readFileSync(this.tagsManifestPath).toString("utf8"));
} catch (err) {
tagsManifest = {
version: 1,
items: {}
};
}
}
async revalidateTag(tag) {
// we need to ensure the tagsManifest is refreshed
// since separate workers can be updating it at the same
// time and we can't flush out of sync data
this.loadTagsManifest();
if (!tagsManifest || !this.tagsManifestPath) {
return;
}
const data = tagsManifest.items[tag] || {};
data.revalidatedAt = Date.now();
tagsManifest.items[tag] = data;
try {
await this.fs.mkdir(path.dirname(this.tagsManifestPath));
await this.fs.writeFile(this.tagsManifestPath, JSON.stringify(tagsManifest || {}));
} catch (err) {
console.warn("Failed to update tags manifest.", err);
}
}
async get(key, { tags, softTags, fetchCache } = {}) {
var _data_value, _data_value1;
let data = memoryCache == null ? void 0 : memoryCache.get(key);
// let's check the disk for seed data
if (!data && process.env.NEXT_RUNTIME !== "edge") {
try {
const { filePath } = await this.getFsPath({
pathname: `${key}.body`,
appDir: true
});
const fileData = await this.fs.readFile(filePath);
const { mtime } = await this.fs.stat(filePath);
const meta = JSON.parse((await this.fs.readFile(filePath.replace(/\.body$/, ".meta"))).toString("utf8"));
const cacheEntry = {
lastModified: mtime.getTime(),
value: {
kind: "ROUTE",
body: fileData,
headers: meta.headers,
status: meta.status
}
};
return cacheEntry;
} catch (_) {
// no .meta data for the related key
}
try {
const { filePath, isAppPath } = await this.getFsPath({
pathname: fetchCache ? key : `${key}.html`,
fetchCache
});
const fileData = (await this.fs.readFile(filePath)).toString("utf-8");
const { mtime } = await this.fs.stat(filePath);
if (fetchCache) {
var _data_value2;
const lastModified = mtime.getTime();
const parsedData = JSON.parse(fileData);
data = {
lastModified,
value: parsedData
};
if (((_data_value2 = data.value) == null ? void 0 : _data_value2.kind) === "FETCH") {
var _data_value_data, _data_value3;
const storedTags = (_data_value3 = data.value) == null ? void 0 : (_data_value_data = _data_value3.data) == null ? void 0 : _data_value_data.tags;
// update stored tags if a new one is being added
// TODO: remove this when we can send the tags
// via header on GET same as SET
if (!(tags == null ? void 0 : tags.every((tag)=>storedTags == null ? void 0 : storedTags.includes(tag)))) {
await this.set(key, data.value, {
tags
});
}
}
} else {
const pageData = isAppPath ? (await this.fs.readFile((await this.getFsPath({
pathname: `${key}.rsc`,
appDir: true
})).filePath)).toString("utf8") : JSON.parse((await this.fs.readFile((await this.getFsPath({
pathname: `${key}.json`,
appDir: false
})).filePath)).toString("utf8"));
let meta = {};
if (isAppPath) {
try {
meta = JSON.parse((await this.fs.readFile(filePath.replace(/\.html$/, ".meta"))).toString("utf-8"));
} catch {}
}
data = {
lastModified: mtime.getTime(),
value: {
kind: "PAGE",
html: fileData,
pageData,
headers: meta.headers,
status: meta.status
}
};
}
if (data) {
memoryCache == null ? void 0 : memoryCache.set(key, data);
}
} catch (_) {
// unable to get data from disk
}
}
if ((data == null ? void 0 : (_data_value = data.value) == null ? void 0 : _data_value.kind) === "PAGE") {
var _data_value_headers;
let cacheTags;
const tagsHeader = (_data_value_headers = data.value.headers) == null ? void 0 : _data_value_headers[NEXT_CACHE_TAGS_HEADER];
if (typeof tagsHeader === "string") {
cacheTags = tagsHeader.split(",");
}
if (cacheTags == null ? void 0 : cacheTags.length) {
this.loadTagsManifest();
const isStale = cacheTags.some((tag)=>{
var _tagsManifest_items_tag;
return (tagsManifest == null ? void 0 : (_tagsManifest_items_tag = tagsManifest.items[tag]) == null ? void 0 : _tagsManifest_items_tag.revalidatedAt) && (tagsManifest == null ? void 0 : tagsManifest.items[tag].revalidatedAt) >= ((data == null ? void 0 : data.lastModified) || Date.now());
});
// we trigger a blocking validation if an ISR page
// had a tag revalidated, if we want to be a background
// revalidation instead we return data.lastModified = -1
if (isStale) {
data = undefined;
}
}
}
if (data && (data == null ? void 0 : (_data_value1 = data.value) == null ? void 0 : _data_value1.kind) === "FETCH") {
this.loadTagsManifest();
const combinedTags = [
...tags || [],
...softTags || []
];
const wasRevalidated = combinedTags.some((tag)=>{
var _tagsManifest_items_tag;
if (this.revalidatedTags.includes(tag)) {
return true;
}
return (tagsManifest == null ? void 0 : (_tagsManifest_items_tag = tagsManifest.items[tag]) == null ? void 0 : _tagsManifest_items_tag.revalidatedAt) && (tagsManifest == null ? void 0 : tagsManifest.items[tag].revalidatedAt) >= ((data == null ? void 0 : data.lastModified) || Date.now());
});
// When revalidate tag is called we don't return
// stale data so it's updated right away
if (wasRevalidated) {
data = undefined;
}
}
return data || null;
}
async set(key, data, ctx) {
memoryCache == null ? void 0 : memoryCache.set(key, {
value: data,
lastModified: Date.now()
});
if (!this.flushToDisk) return;
if ((data == null ? void 0 : data.kind) === "ROUTE") {
const { filePath } = await this.getFsPath({
pathname: `${key}.body`,
appDir: true
});
await this.fs.mkdir(path.dirname(filePath));
await this.fs.writeFile(filePath, data.body);
await this.fs.writeFile(filePath.replace(/\.body$/, ".meta"), JSON.stringify({
headers: data.headers,
status: data.status
}));
return;
}
if ((data == null ? void 0 : data.kind) === "PAGE") {
const isAppPath = typeof data.pageData === "string";
const { filePath: htmlPath } = await this.getFsPath({
pathname: `${key}.html`,
appDir: isAppPath
});
await this.fs.mkdir(path.dirname(htmlPath));
await this.fs.writeFile(htmlPath, data.html);
await this.fs.writeFile((await this.getFsPath({
pathname: `${key}.${isAppPath ? "rsc" : "json"}`,
appDir: isAppPath
})).filePath, isAppPath ? data.pageData : JSON.stringify(data.pageData));
if (data.headers || data.status) {
await this.fs.writeFile(htmlPath.replace(/\.html$/, ".meta"), JSON.stringify({
headers: data.headers,
status: data.status
}));
}
} else if ((data == null ? void 0 : data.kind) === "FETCH") {
const { filePath } = await this.getFsPath({
pathname: key,
fetchCache: true
});
await this.fs.mkdir(path.dirname(filePath));
await this.fs.writeFile(filePath, JSON.stringify({
...data,
tags: ctx.tags
}));
}
}
async getFsPath({ pathname, appDir, fetchCache }) {
if (fetchCache) {
// we store in .next/cache/fetch-cache so it can be persisted
// across deploys
return {
filePath: path.join(this.serverDistDir, "..", "cache", "fetch-cache", pathname),
isAppPath: false
};
}
let isAppPath = false;
let filePath = path.join(this.serverDistDir, "pages", pathname);
if (!this.appDir || appDir === false) return {
filePath,
isAppPath
};
try {
await this.fs.readFile(filePath);
return {
filePath,
isAppPath
};
} catch (err) {
return {
filePath: path.join(this.serverDistDir, "app", pathname),
isAppPath: true
};
}
}
}
//# sourceMappingURL=file-system-cache.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,368 @@
import FetchCache from "./fetch-cache";
import FileSystemCache from "./file-system-cache";
import path from "../../../shared/lib/isomorphic/path";
import { encodeText } from "../../stream-utils/encode-decode";
import { encode } from "../../../shared/lib/base64-arraybuffer";
import { normalizePagePath } from "../../../shared/lib/page-path/normalize-page-path";
import { CACHE_ONE_YEAR, NEXT_CACHE_REVALIDATED_TAGS_HEADER, NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, PRERENDER_REVALIDATE_HEADER } from "../../../lib/constants";
function toRoute(pathname) {
return pathname.replace(/\/$/, "").replace(/\/index$/, "") || "/";
}
export class CacheHandler {
// eslint-disable-next-line
constructor(_ctx){}
async get(..._args) {
return {};
}
async set(..._args) {}
async revalidateTag(_tag) {}
}
export class IncrementalCache {
constructor({ fs, dev, appDir, flushToDisk, fetchCache, minimalMode, serverDistDir, requestHeaders, requestProtocol, maxMemoryCacheSize, getPrerenderManifest, fetchCacheKeyPrefix, CurCacheHandler, allowedRevalidateHeaderKeys }){
var _this_prerenderManifest_preview, _this_prerenderManifest, _this_prerenderManifest_preview1, _this_prerenderManifest1;
this.locks = new Map();
this.unlocks = new Map();
const debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE;
if (!CurCacheHandler) {
if (fs && serverDistDir) {
if (debug) {
console.log("using filesystem cache handler");
}
CurCacheHandler = FileSystemCache;
}
if (FetchCache.isAvailable({
_requestHeaders: requestHeaders
}) && minimalMode && fetchCache) {
if (debug) {
console.log("using fetch cache handler");
}
CurCacheHandler = FetchCache;
}
} else if (debug) {
console.log("using custom cache handler", CurCacheHandler.name);
}
if (process.env.__NEXT_TEST_MAX_ISR_CACHE) {
// Allow cache size to be overridden for testing purposes
maxMemoryCacheSize = parseInt(process.env.__NEXT_TEST_MAX_ISR_CACHE, 10);
}
this.dev = dev;
// this is a hack to avoid Webpack knowing this is equal to this.minimalMode
// because we replace this.minimalMode to true in production bundles.
const minimalModeKey = "minimalMode";
this[minimalModeKey] = minimalMode;
this.requestHeaders = requestHeaders;
this.requestProtocol = requestProtocol;
this.allowedRevalidateHeaderKeys = allowedRevalidateHeaderKeys;
this.prerenderManifest = getPrerenderManifest();
this.fetchCacheKeyPrefix = fetchCacheKeyPrefix;
let revalidatedTags = [];
if (requestHeaders[PRERENDER_REVALIDATE_HEADER] === ((_this_prerenderManifest = this.prerenderManifest) == null ? void 0 : (_this_prerenderManifest_preview = _this_prerenderManifest.preview) == null ? void 0 : _this_prerenderManifest_preview.previewModeId)) {
this.isOnDemandRevalidate = true;
}
if (minimalMode && typeof requestHeaders[NEXT_CACHE_REVALIDATED_TAGS_HEADER] === "string" && requestHeaders[NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER] === ((_this_prerenderManifest1 = this.prerenderManifest) == null ? void 0 : (_this_prerenderManifest_preview1 = _this_prerenderManifest1.preview) == null ? void 0 : _this_prerenderManifest_preview1.previewModeId)) {
revalidatedTags = requestHeaders[NEXT_CACHE_REVALIDATED_TAGS_HEADER].split(",");
}
if (CurCacheHandler) {
this.cacheHandler = new CurCacheHandler({
dev,
fs,
flushToDisk,
serverDistDir,
revalidatedTags,
maxMemoryCacheSize,
_appDir: !!appDir,
_requestHeaders: requestHeaders,
fetchCacheKeyPrefix
});
}
}
calculateRevalidate(pathname, fromTime, dev) {
// in development we don't have a prerender-manifest
// and default to always revalidating to allow easier debugging
if (dev) return new Date().getTime() - 1000;
// if an entry isn't present in routes we fallback to a default
// of revalidating after 1 second
const { initialRevalidateSeconds } = this.prerenderManifest.routes[toRoute(pathname)] || {
initialRevalidateSeconds: 1
};
const revalidateAfter = typeof initialRevalidateSeconds === "number" ? initialRevalidateSeconds * 1000 + fromTime : initialRevalidateSeconds;
return revalidateAfter;
}
_getPathname(pathname, fetchCache) {
return fetchCache ? pathname : normalizePagePath(pathname);
}
async unlock(cacheKey) {
const unlock = this.unlocks.get(cacheKey);
if (unlock) {
unlock();
this.locks.delete(cacheKey);
this.unlocks.delete(cacheKey);
}
}
async lock(cacheKey) {
if (process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT && process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY && process.env.NEXT_RUNTIME !== "edge") {
const invokeIpcMethod = require("../server-ipc/request-utils").invokeIpcMethod;
await invokeIpcMethod({
method: "lock",
ipcPort: process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT,
ipcKey: process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY,
args: [
cacheKey
]
});
return async ()=>{
await invokeIpcMethod({
method: "unlock",
ipcPort: process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT,
ipcKey: process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY,
args: [
cacheKey
]
});
};
}
let unlockNext = ()=>Promise.resolve();
const existingLock = this.locks.get(cacheKey);
if (existingLock) {
await existingLock;
} else {
const newLock = new Promise((resolve)=>{
unlockNext = async ()=>{
resolve();
};
});
this.locks.set(cacheKey, newLock);
this.unlocks.set(cacheKey, unlockNext);
}
return unlockNext;
}
async revalidateTag(tag) {
var _this_cacheHandler_revalidateTag, _this_cacheHandler;
if (process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT && process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY && process.env.NEXT_RUNTIME !== "edge") {
const invokeIpcMethod = require("../server-ipc/request-utils").invokeIpcMethod;
return invokeIpcMethod({
method: "revalidateTag",
ipcPort: process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT,
ipcKey: process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY,
args: [
...arguments
]
});
}
return (_this_cacheHandler = this.cacheHandler) == null ? void 0 : (_this_cacheHandler_revalidateTag = _this_cacheHandler.revalidateTag) == null ? void 0 : _this_cacheHandler_revalidateTag.call(_this_cacheHandler, tag);
}
// x-ref: https://github.com/facebook/react/blob/2655c9354d8e1c54ba888444220f63e836925caa/packages/react/src/ReactFetch.js#L23
async fetchCacheKey(url, init = {}) {
// this should be bumped anytime a fix is made to cache entries
// that should bust the cache
const MAIN_KEY_PREFIX = "v3";
let cacheKey;
const bodyChunks = [];
if (init.body) {
// handle ReadableStream body
if (typeof init.body.getReader === "function") {
const readableBody = init.body;
const reader = readableBody.getReader();
let arrayBuffer = new Uint8Array();
function processValue({ done, value }) {
if (done) {
return;
}
if (value) {
try {
bodyChunks.push(typeof value === "string" ? value : encode(value));
const curBuffer = typeof value === "string" ? encodeText(value) : new Uint8Array(value);
const prevBuffer = arrayBuffer;
arrayBuffer = new Uint8Array(prevBuffer.byteLength + curBuffer.byteLength);
arrayBuffer.set(prevBuffer);
arrayBuffer.set(curBuffer, prevBuffer.byteLength);
} catch (err) {
console.error(err);
}
}
reader.read().then(processValue);
}
await reader.read().then(processValue);
init._ogBody = arrayBuffer;
} else if (typeof init.body.keys === "function") {
const formData = init.body;
init._ogBody = init.body;
for (const key of new Set([
...formData.keys()
])){
const values = formData.getAll(key);
bodyChunks.push(`${key}=${(await Promise.all(values.map(async (val)=>{
if (typeof val === "string") {
return val;
} else {
return await val.text();
}
}))).join(",")}`);
}
// handle blob body
} else if (typeof init.body.arrayBuffer === "function") {
const blob = init.body;
const arrayBuffer = await blob.arrayBuffer();
bodyChunks.push(encode(await init.body.arrayBuffer()));
init._ogBody = new Blob([
arrayBuffer
], {
type: blob.type
});
} else if (typeof init.body === "string") {
bodyChunks.push(init.body);
init._ogBody = init.body;
}
}
const cacheString = JSON.stringify([
MAIN_KEY_PREFIX,
this.fetchCacheKeyPrefix || "",
url,
init.method,
typeof (init.headers || {}).keys === "function" ? Object.fromEntries(init.headers) : init.headers,
init.mode,
init.redirect,
init.credentials,
init.referrer,
init.referrerPolicy,
init.integrity,
init.cache,
bodyChunks
]);
if (process.env.NEXT_RUNTIME === "edge") {
function bufferToHex(buffer) {
return Array.prototype.map.call(new Uint8Array(buffer), (b)=>b.toString(16).padStart(2, "0")).join("");
}
const buffer = encodeText(cacheString);
cacheKey = bufferToHex(await crypto.subtle.digest("SHA-256", buffer));
} else {
const crypto1 = require("crypto");
cacheKey = crypto1.createHash("sha256").update(cacheString).digest("hex");
}
return cacheKey;
}
// get data from cache if available
async get(cacheKey, ctx = {}) {
var _this_cacheHandler, _cacheData_value, _this_prerenderManifest_routes_toRoute;
if (process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT && process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY && process.env.NEXT_RUNTIME !== "edge") {
const invokeIpcMethod = require("../server-ipc/request-utils").invokeIpcMethod;
return invokeIpcMethod({
method: "get",
ipcPort: process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT,
ipcKey: process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY,
args: [
...arguments
]
});
}
// we don't leverage the prerender cache in dev mode
// so that getStaticProps is always called for easier debugging
if (this.dev && (!ctx.fetchCache || this.requestHeaders["cache-control"] === "no-cache")) {
return null;
}
cacheKey = this._getPathname(cacheKey, ctx.fetchCache);
let entry = null;
let revalidate = ctx.revalidate;
const cacheData = await ((_this_cacheHandler = this.cacheHandler) == null ? void 0 : _this_cacheHandler.get(cacheKey, ctx));
if ((cacheData == null ? void 0 : (_cacheData_value = cacheData.value) == null ? void 0 : _cacheData_value.kind) === "FETCH") {
const combinedTags = [
...ctx.tags || [],
...ctx.softTags || []
];
// if a tag was revalidated we don't return stale data
if (combinedTags.some((tag)=>{
var _this_revalidatedTags;
return (_this_revalidatedTags = this.revalidatedTags) == null ? void 0 : _this_revalidatedTags.includes(tag);
})) {
return null;
}
revalidate = revalidate || cacheData.value.revalidate;
const age = Math.round((Date.now() - (cacheData.lastModified || 0)) / 1000);
const isStale = age > revalidate;
const data = cacheData.value.data;
return {
isStale: isStale,
value: {
kind: "FETCH",
data,
revalidate: revalidate
},
revalidateAfter: Date.now() + revalidate * 1000
};
}
const curRevalidate = (_this_prerenderManifest_routes_toRoute = this.prerenderManifest.routes[toRoute(cacheKey)]) == null ? void 0 : _this_prerenderManifest_routes_toRoute.initialRevalidateSeconds;
let isStale;
let revalidateAfter;
if ((cacheData == null ? void 0 : cacheData.lastModified) === -1) {
isStale = -1;
revalidateAfter = -1 * CACHE_ONE_YEAR;
} else {
revalidateAfter = this.calculateRevalidate(cacheKey, (cacheData == null ? void 0 : cacheData.lastModified) || Date.now(), this.dev && !ctx.fetchCache);
isStale = revalidateAfter !== false && revalidateAfter < Date.now() ? true : undefined;
}
if (cacheData) {
entry = {
isStale,
curRevalidate,
revalidateAfter,
value: cacheData.value
};
}
if (!cacheData && this.prerenderManifest.notFoundRoutes.includes(cacheKey)) {
// for the first hit after starting the server the cache
// may not have a way to save notFound: true so if
// the prerender-manifest marks this as notFound then we
// return that entry and trigger a cache set to give it a
// chance to update in-memory entries
entry = {
isStale,
value: null,
curRevalidate,
revalidateAfter
};
this.set(cacheKey, entry.value, ctx);
}
return entry;
}
// populate the incremental cache with new data
async set(pathname, data, ctx) {
if (process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT && process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY && process.env.NEXT_RUNTIME !== "edge") {
const invokeIpcMethod = require("../server-ipc/request-utils").invokeIpcMethod;
return invokeIpcMethod({
method: "set",
ipcPort: process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT,
ipcKey: process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY,
args: [
...arguments
]
});
}
if (this.dev && !ctx.fetchCache) return;
// fetchCache has upper limit of 2MB per-entry currently
if (ctx.fetchCache && JSON.stringify(data).length > 2 * 1024 * 1024) {
if (this.dev) {
throw new Error(`fetch for over 2MB of data can not be cached`);
}
return;
}
pathname = this._getPathname(pathname, ctx.fetchCache);
try {
var _this_cacheHandler;
// we use the prerender manifest memory instance
// to store revalidate timings for calculating
// revalidateAfter values so we update this on set
if (typeof ctx.revalidate !== "undefined" && !ctx.fetchCache) {
this.prerenderManifest.routes[pathname] = {
dataRoute: path.posix.join("/_next/data", `${normalizePagePath(pathname)}.json`),
srcRoute: null,
initialRevalidateSeconds: ctx.revalidate
};
}
await ((_this_cacheHandler = this.cacheHandler) == null ? void 0 : _this_cacheHandler.set(pathname, data, ctx));
} catch (error) {
console.warn("Failed to update prerender cache for", pathname, error);
}
}
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

31
node_modules/next/dist/esm/server/lib/is-ipv6.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
// Regex from `node/lib/internal/net.js`: https://github.com/nodejs/node/blob/9fc57006c27564ed7f75eee090eca86786508f51/lib/internal/net.js#L19-L29
// License included below:
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
const v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`;
const v6Seg = "(?:[0-9a-fA-F]{1,4})";
const IPv6Reg = new RegExp("^(" + `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` + `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` + `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` + `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` + `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` + `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` + `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` + `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + ")(%[0-9a-zA-Z-.:]{1,})?$");
export function isIPv6(s) {
return IPv6Reg.test(s);
}
//# sourceMappingURL=is-ipv6.js.map

1
node_modules/next/dist/esm/server/lib/is-ipv6.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/is-ipv6.ts"],"names":["v4Seg","v4Str","v6Seg","IPv6Reg","RegExp","isIPv6","s","test"],"mappings":"AAAA,kJAAkJ;AAClJ,0BAA0B;AAC1B,sDAAsD;AACtD,EAAE;AACF,0EAA0E;AAC1E,gEAAgE;AAChE,sEAAsE;AACtE,sEAAsE;AACtE,4EAA4E;AAC5E,qEAAqE;AACrE,wBAAwB;AACxB,EAAE;AACF,0EAA0E;AAC1E,yDAAyD;AACzD,EAAE;AACF,0EAA0E;AAC1E,6DAA6D;AAC7D,4EAA4E;AAC5E,2EAA2E;AAC3E,wEAAwE;AACxE,4EAA4E;AAC5E,yCAAyC;AAEzC,MAAMA,QAAQ;AACd,MAAMC,QAAQ,CAAC,CAAC,EAAED,MAAM,OAAO,EAAEA,MAAM,CAAC;AACxC,MAAME,QAAQ;AACd,MAAMC,UAAU,IAAIC,OAClB,OACE,CAAC,GAAG,EAAEF,MAAM,QAAQ,EAAEA,MAAM,IAAI,CAAC,GACjC,CAAC,GAAG,EAAEA,MAAM,QAAQ,EAAED,MAAM,EAAE,EAAEC,MAAM,IAAI,CAAC,GAC3C,CAAC,GAAG,EAAEA,MAAM,SAAS,EAAED,MAAM,GAAG,EAAEC,MAAM,UAAU,CAAC,GACnD,CAAC,GAAG,EAAEA,MAAM,UAAU,EAAEA,MAAM,OAAO,EAAED,MAAM,GAAG,EAAEC,MAAM,UAAU,CAAC,GACnE,CAAC,GAAG,EAAEA,MAAM,UAAU,EAAEA,MAAM,OAAO,EAAED,MAAM,GAAG,EAAEC,MAAM,UAAU,CAAC,GACnE,CAAC,GAAG,EAAEA,MAAM,UAAU,EAAEA,MAAM,OAAO,EAAED,MAAM,GAAG,EAAEC,MAAM,UAAU,CAAC,GACnE,CAAC,GAAG,EAAEA,MAAM,UAAU,EAAEA,MAAM,OAAO,EAAED,MAAM,GAAG,EAAEC,MAAM,UAAU,CAAC,GACnE,CAAC,SAAS,EAAEA,MAAM,OAAO,EAAED,MAAM,KAAK,EAAEC,MAAM,UAAU,CAAC,GACzD;AAGJ,OAAO,SAASG,OAAOC,CAAS;IAC9B,OAAOH,QAAQI,IAAI,CAACD;AACtB"}

View File

@@ -0,0 +1,10 @@
export function checkIsNodeDebugging() {
var _process_env_NODE_OPTIONS_match, _process_env_NODE_OPTIONS, _process_env_NODE_OPTIONS_match1, _process_env_NODE_OPTIONS1;
let isNodeDebugging = !!(process.execArgv.some((localArg)=>localArg.startsWith("--inspect")) || ((_process_env_NODE_OPTIONS = process.env.NODE_OPTIONS) == null ? void 0 : (_process_env_NODE_OPTIONS_match = _process_env_NODE_OPTIONS.match) == null ? void 0 : _process_env_NODE_OPTIONS_match.call(_process_env_NODE_OPTIONS, /--inspect(=\S+)?( |$)/)));
if (process.execArgv.some((localArg)=>localArg.startsWith("--inspect-brk")) || ((_process_env_NODE_OPTIONS1 = process.env.NODE_OPTIONS) == null ? void 0 : (_process_env_NODE_OPTIONS_match1 = _process_env_NODE_OPTIONS1.match) == null ? void 0 : _process_env_NODE_OPTIONS_match1.call(_process_env_NODE_OPTIONS1, /--inspect-brk(=\S+)?( |$)/))) {
isNodeDebugging = "brk";
}
return isNodeDebugging;
}
//# sourceMappingURL=is-node-debugging.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/is-node-debugging.ts"],"names":["checkIsNodeDebugging","process","isNodeDebugging","execArgv","some","localArg","startsWith","env","NODE_OPTIONS","match"],"mappings":"AAAA,OAAO,SAASA;QAGZC,iCAAAA,2BAKAA,kCAAAA;IAPF,IAAIC,kBAAmC,CAAC,CACtCD,CAAAA,QAAQE,QAAQ,CAACC,IAAI,CAAC,CAACC,WAAaA,SAASC,UAAU,CAAC,mBACxDL,4BAAAA,QAAQM,GAAG,CAACC,YAAY,sBAAxBP,kCAAAA,0BAA0BQ,KAAK,qBAA/BR,qCAAAA,2BAAkC,yBAAuB;IAG3D,IACEA,QAAQE,QAAQ,CAACC,IAAI,CAAC,CAACC,WAAaA,SAASC,UAAU,CAAC,uBACxDL,6BAAAA,QAAQM,GAAG,CAACC,YAAY,sBAAxBP,mCAAAA,2BAA0BQ,KAAK,qBAA/BR,sCAAAA,4BAAkC,+BAClC;QACAC,kBAAkB;IACpB;IACA,OAAOA;AACT"}

View File

@@ -0,0 +1,8 @@
import { getPathMatch } from "../../shared/lib/router/utils/path-match";
const matcher = getPathMatch("/_next/data/:path*");
export function matchNextDataPathname(pathname) {
if (typeof pathname !== "string") return false;
return matcher(pathname);
}
//# sourceMappingURL=match-next-data-pathname.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/match-next-data-pathname.ts"],"names":["getPathMatch","matcher","matchNextDataPathname","pathname"],"mappings":"AAAA,SAASA,YAAY,QAAQ,2CAA0C;AAEvE,MAAMC,UAAUD,aAAa;AAE7B,OAAO,SAASE,sBAAsBC,QAAmC;IACvE,IAAI,OAAOA,aAAa,UAAU,OAAO;IAEzC,OAAOF,QAAQE;AACjB"}

297
node_modules/next/dist/esm/server/lib/mock-request.js generated vendored Normal file
View File

@@ -0,0 +1,297 @@
import Stream from "stream";
import { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from "../web/utils";
export class MockedRequest extends Stream.Readable {
constructor({ url, headers, method, socket = null, readable }){
super();
// This is hardcoded for now, but can be updated to be configurable if needed.
this.httpVersion = "1.0";
this.httpVersionMajor = 1;
this.httpVersionMinor = 0;
// If we don't actually have a socket, we'll just use a mock one that
// always returns false for the `encrypted` property.
this.socket = new Proxy({}, {
get: (_target, prop)=>{
if (prop !== "encrypted") {
throw new Error("Method not implemented");
}
// For this mock request, always ensure we just respond with the encrypted
// set to false to ensure there's no odd leakages.
return false;
}
});
this.url = url;
this.headers = headers;
this.method = method;
if (readable) {
this.bodyReadable = readable;
this.bodyReadable.on("end", ()=>this.emit("end"));
this.bodyReadable.on("close", ()=>this.emit("close"));
}
if (socket) {
this.socket = socket;
}
}
get headersDistinct() {
const headers = {};
for (const [key, value] of Object.entries(this.headers)){
if (!value) continue;
headers[key] = Array.isArray(value) ? value : [
value
];
}
return headers;
}
_read(size) {
if (this.bodyReadable) {
return this.bodyReadable._read(size);
} else {
this.emit("end");
this.emit("close");
}
}
/**
* The `connection` property is just an alias for the `socket` property.
*
* @deprecated — since v13.0.0 - Use socket instead.
*/ get connection() {
return this.socket;
}
// The following methods are not implemented as they are not used in the
// Next.js codebase.
get aborted() {
throw new Error("Method not implemented");
}
get complete() {
throw new Error("Method not implemented");
}
get trailers() {
throw new Error("Method not implemented");
}
get trailersDistinct() {
throw new Error("Method not implemented");
}
get rawTrailers() {
throw new Error("Method not implemented");
}
get rawHeaders() {
throw new Error("Method not implemented.");
}
setTimeout() {
throw new Error("Method not implemented.");
}
}
export class MockedResponse extends Stream.Writable {
constructor(res = {}){
super();
this.statusMessage = "";
this.finished = false;
this.headersSent = false;
/**
* A list of buffers that have been written to the response.
*
* @internal - used internally by Next.js
*/ this.buffers = [];
this.statusCode = res.statusCode ?? 200;
this.socket = res.socket ?? null;
this.headers = res.headers ? fromNodeOutgoingHttpHeaders(res.headers) : new Headers();
this.headPromise = new Promise((resolve)=>{
this.headPromiseResolve = resolve;
});
// Attach listeners for the `finish`, `end`, and `error` events to the
// `MockedResponse` instance.
this.hasStreamed = new Promise((resolve, reject)=>{
this.on("finish", ()=>resolve(true));
this.on("end", ()=>resolve(true));
this.on("error", (err)=>reject(err));
}).then((val)=>{
var _this_headPromiseResolve, _this;
(_this_headPromiseResolve = (_this = this).headPromiseResolve) == null ? void 0 : _this_headPromiseResolve.call(_this);
return val;
});
if (res.resWriter) {
this.resWriter = res.resWriter;
}
}
appendHeader(name, value) {
const values = Array.isArray(value) ? value : [
value
];
for (const v of values){
this.headers.append(name, v);
}
return this;
}
/**
* Returns true if the response has been sent, false otherwise.
*
* @internal - used internally by Next.js
*/ get isSent() {
return this.finished || this.headersSent;
}
/**
* The `connection` property is just an alias for the `socket` property.
*
* @deprecated — since v13.0.0 - Use socket instead.
*/ get connection() {
return this.socket;
}
write(chunk) {
if (this.resWriter) {
return this.resWriter(chunk);
}
this.buffers.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
return true;
}
end() {
this.finished = true;
return super.end(...arguments);
}
/**
* This method is a no-op because the `MockedResponse` instance is not
* actually connected to a socket. This method is not specified on the
* interface type for `ServerResponse` but is called by Node.js.
*
* @see https://github.com/nodejs/node/pull/7949
*/ _implicitHeader() {}
_write(chunk, _encoding, callback) {
this.write(chunk);
// According to Node.js documentation, the callback MUST be invoked to
// signal that the write completed successfully. If this callback is not
// invoked, the 'finish' event will not be emitted.
//
// https://nodejs.org/docs/latest-v16.x/api/stream.html#writable_writechunk-encoding-callback
callback();
}
writeHead(statusCode, statusMessage, headers) {
var _this_headPromiseResolve, _this;
if (!headers && typeof statusMessage !== "string") {
headers = statusMessage;
} else if (typeof statusMessage === "string" && statusMessage.length > 0) {
this.statusMessage = statusMessage;
}
if (headers) {
// When headers have been set with response.setHeader(), they will be
// merged with any headers passed to response.writeHead(), with the
// headers passed to response.writeHead() given precedence.
//
// https://nodejs.org/api/http.html#responsewriteheadstatuscode-statusmessage-headers
//
// For this reason, we need to only call `set` to ensure that this will
// overwrite any existing headers.
if (Array.isArray(headers)) {
// headers may be an Array where the keys and values are in the same list.
// It is not a list of tuples. So, the even-numbered offsets are key
// values, and the odd-numbered offsets are the associated values. The
// array is in the same format as request.rawHeaders.
for(let i = 0; i < headers.length; i += 2){
// The header key is always a string according to the spec.
this.setHeader(headers[i], headers[i + 1]);
}
} else {
for (const [key, value] of Object.entries(headers)){
// Skip undefined values
if (typeof value === "undefined") continue;
this.setHeader(key, value);
}
}
}
this.statusCode = statusCode;
this.headersSent = true;
(_this_headPromiseResolve = (_this = this).headPromiseResolve) == null ? void 0 : _this_headPromiseResolve.call(_this);
return this;
}
hasHeader(name) {
return this.headers.has(name);
}
getHeader(name) {
return this.headers.get(name) ?? undefined;
}
getHeaders() {
return toNodeOutgoingHttpHeaders(this.headers);
}
getHeaderNames() {
return Array.from(this.headers.keys());
}
setHeader(name, value) {
if (Array.isArray(value)) {
// Because `set` here should override any existing values, we need to
// delete the existing values before setting the new ones via `append`.
this.headers.delete(name);
for (const v of value){
this.headers.append(name, v);
}
} else if (typeof value === "number") {
this.headers.set(name, value.toString());
} else {
this.headers.set(name, value);
}
return this;
}
removeHeader(name) {
this.headers.delete(name);
}
// The following methods are not implemented as they are not used in the
// Next.js codebase.
get strictContentLength() {
throw new Error("Method not implemented.");
}
writeEarlyHints() {
throw new Error("Method not implemented.");
}
get req() {
throw new Error("Method not implemented.");
}
assignSocket() {
throw new Error("Method not implemented.");
}
detachSocket() {
throw new Error("Method not implemented.");
}
writeContinue() {
throw new Error("Method not implemented.");
}
writeProcessing() {
throw new Error("Method not implemented.");
}
get upgrading() {
throw new Error("Method not implemented.");
}
get chunkedEncoding() {
throw new Error("Method not implemented.");
}
get shouldKeepAlive() {
throw new Error("Method not implemented.");
}
get useChunkedEncodingByDefault() {
throw new Error("Method not implemented.");
}
get sendDate() {
throw new Error("Method not implemented.");
}
setTimeout() {
throw new Error("Method not implemented.");
}
addTrailers() {
throw new Error("Method not implemented.");
}
flushHeaders() {
throw new Error("Method not implemented.");
}
}
export function createRequestResponseMocks({ url, headers = {}, method = "GET", bodyReadable, resWriter, socket = null }) {
return {
req: new MockedRequest({
url,
headers,
method,
socket,
readable: bodyReadable
}),
res: new MockedResponse({
socket,
resWriter
})
};
}
//# sourceMappingURL=mock-request.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
import _fs from "fs";
export const nodeFs = {
readFile: (f)=>_fs.promises.readFile(f),
readFileSync: (f)=>_fs.readFileSync(f),
writeFile: (f, d)=>_fs.promises.writeFile(f, d),
mkdir: (dir)=>_fs.promises.mkdir(dir, {
recursive: true
}),
stat: (f)=>_fs.promises.stat(f)
};
//# sourceMappingURL=node-fs-methods.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/node-fs-methods.ts"],"names":["_fs","nodeFs","readFile","f","promises","readFileSync","writeFile","d","mkdir","dir","recursive","stat"],"mappings":"AAAA,OAAOA,SAAS,KAAI;AAGpB,OAAO,MAAMC,SAAkB;IAC7BC,UAAU,CAACC,IAAMH,IAAII,QAAQ,CAACF,QAAQ,CAACC;IACvCE,cAAc,CAACF,IAAMH,IAAIK,YAAY,CAACF;IACtCG,WAAW,CAACH,GAAGI,IAAMP,IAAII,QAAQ,CAACE,SAAS,CAACH,GAAGI;IAC/CC,OAAO,CAACC,MAAQT,IAAII,QAAQ,CAACI,KAAK,CAACC,KAAK;YAAEC,WAAW;QAAK;IAC1DC,MAAM,CAACR,IAAMH,IAAII,QAAQ,CAACO,IAAI,CAACR;AACjC,EAAC"}

461
node_modules/next/dist/esm/server/lib/patch-fetch.js generated vendored Normal file
View File

@@ -0,0 +1,461 @@
import { AppRenderSpan, NextNodeServerSpan } from "./trace/constants";
import { getTracer, SpanKind } from "./trace/tracer";
import { CACHE_ONE_YEAR, NEXT_CACHE_IMPLICIT_TAG_ID, NEXT_CACHE_TAG_MAX_LENGTH } from "../../lib/constants";
import * as Log from "../../build/output/log";
const isEdgeRuntime = process.env.NEXT_RUNTIME === "edge";
export function validateTags(tags, description) {
const validTags = [];
const invalidTags = [];
for (const tag of tags){
if (typeof tag !== "string") {
invalidTags.push({
tag,
reason: "invalid type, must be a string"
});
} else if (tag.length > NEXT_CACHE_TAG_MAX_LENGTH) {
invalidTags.push({
tag,
reason: `exceeded max length of ${NEXT_CACHE_TAG_MAX_LENGTH}`
});
} else {
validTags.push(tag);
}
}
if (invalidTags.length > 0) {
console.warn(`Warning: invalid tags passed to ${description}: `);
for (const { tag, reason } of invalidTags){
console.log(`tag: "${tag}" ${reason}`);
}
}
return validTags;
}
const getDerivedTags = (pathname)=>{
const derivedTags = [
`/layout`
];
// we automatically add the current path segments as tags
// for revalidatePath handling
if (pathname.startsWith("/")) {
const pathnameParts = pathname.split("/");
for(let i = 1; i < pathnameParts.length + 1; i++){
let curPathname = pathnameParts.slice(0, i).join("/");
if (curPathname) {
// all derived tags other than the page are layout tags
if (!curPathname.endsWith("/page") && !curPathname.endsWith("/route")) {
curPathname = `${curPathname}${!curPathname.endsWith("/") ? "/" : ""}layout`;
}
derivedTags.push(curPathname);
}
}
}
return derivedTags;
};
export function addImplicitTags(staticGenerationStore) {
const newTags = [];
if (!staticGenerationStore) {
return newTags;
}
const { pagePath, urlPathname } = staticGenerationStore;
if (!Array.isArray(staticGenerationStore.tags)) {
staticGenerationStore.tags = [];
}
if (pagePath) {
const derivedTags = getDerivedTags(pagePath);
for (let tag of derivedTags){
var _staticGenerationStore_tags;
tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`;
if (!((_staticGenerationStore_tags = staticGenerationStore.tags) == null ? void 0 : _staticGenerationStore_tags.includes(tag))) {
staticGenerationStore.tags.push(tag);
}
newTags.push(tag);
}
}
if (urlPathname) {
var _staticGenerationStore_tags1;
const tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${urlPathname}`;
if (!((_staticGenerationStore_tags1 = staticGenerationStore.tags) == null ? void 0 : _staticGenerationStore_tags1.includes(tag))) {
staticGenerationStore.tags.push(tag);
}
newTags.push(tag);
}
return newTags;
}
function trackFetchMetric(staticGenerationStore, ctx) {
if (!staticGenerationStore) return;
if (!staticGenerationStore.fetchMetrics) {
staticGenerationStore.fetchMetrics = [];
}
const dedupeFields = [
"url",
"status",
"method"
];
// don't add metric if one already exists for the fetch
if (staticGenerationStore.fetchMetrics.some((metric)=>{
return dedupeFields.every((field)=>metric[field] === ctx[field]);
})) {
return;
}
staticGenerationStore.fetchMetrics.push({
url: ctx.url,
cacheStatus: ctx.cacheStatus,
cacheReason: ctx.cacheReason,
status: ctx.status,
method: ctx.method,
start: ctx.start,
end: Date.now(),
idx: staticGenerationStore.nextFetchId || 0
});
}
// we patch fetch to collect cache information used for
// determining if a page is static or not
export function patchFetch({ serverHooks, staticGenerationAsyncStorage }) {
if (!globalThis._nextOriginalFetch) {
globalThis._nextOriginalFetch = globalThis.fetch;
}
if (globalThis.fetch.__nextPatched) return;
const { DynamicServerError } = serverHooks;
const originFetch = globalThis._nextOriginalFetch;
globalThis.fetch = async (input, init)=>{
var _init_method, _this;
let url;
try {
url = new URL(input instanceof Request ? input.url : input);
url.username = "";
url.password = "";
} catch {
// Error caused by malformed URL should be handled by native fetch
url = undefined;
}
const fetchUrl = (url == null ? void 0 : url.href) ?? "";
const fetchStart = Date.now();
const method = (init == null ? void 0 : (_init_method = init.method) == null ? void 0 : _init_method.toUpperCase()) || "GET";
// Do create a new span trace for internal fetches in the
// non-verbose mode.
const isInternal = ((_this = init == null ? void 0 : init.next) == null ? void 0 : _this.internal) === true;
return await getTracer().trace(isInternal ? NextNodeServerSpan.internalFetch : AppRenderSpan.fetch, {
kind: SpanKind.CLIENT,
spanName: [
"fetch",
method,
fetchUrl
].filter(Boolean).join(" "),
attributes: {
"http.url": fetchUrl,
"http.method": method,
"net.peer.name": url == null ? void 0 : url.hostname,
"net.peer.port": (url == null ? void 0 : url.port) || undefined
}
}, async ()=>{
var _getRequestMeta;
const staticGenerationStore = staticGenerationAsyncStorage.getStore() || (fetch.__nextGetStaticStore == null ? void 0 : fetch.__nextGetStaticStore.call(fetch));
const isRequestInput = input && typeof input === "object" && typeof input.method === "string";
const getRequestMeta = (field)=>{
let value = isRequestInput ? input[field] : null;
return value || (init == null ? void 0 : init[field]);
};
// If the staticGenerationStore is not available, we can't do any
// special treatment of fetch, therefore fallback to the original
// fetch implementation.
if (!staticGenerationStore || isInternal || staticGenerationStore.isDraftMode) {
return originFetch(input, init);
}
let revalidate = undefined;
const getNextField = (field)=>{
var _init_next, _init_next1, _input_next;
return typeof (init == null ? void 0 : (_init_next = init.next) == null ? void 0 : _init_next[field]) !== "undefined" ? init == null ? void 0 : (_init_next1 = init.next) == null ? void 0 : _init_next1[field] : isRequestInput ? (_input_next = input.next) == null ? void 0 : _input_next[field] : undefined;
};
// RequestInit doesn't keep extra fields e.g. next so it's
// only available if init is used separate
let curRevalidate = getNextField("revalidate");
const tags = validateTags(getNextField("tags") || [], `fetch ${input.toString()}`);
if (Array.isArray(tags)) {
if (!staticGenerationStore.tags) {
staticGenerationStore.tags = [];
}
for (const tag of tags){
if (!staticGenerationStore.tags.includes(tag)) {
staticGenerationStore.tags.push(tag);
}
}
}
const implicitTags = addImplicitTags(staticGenerationStore);
const isOnlyCache = staticGenerationStore.fetchCache === "only-cache";
const isForceCache = staticGenerationStore.fetchCache === "force-cache";
const isDefaultCache = staticGenerationStore.fetchCache === "default-cache";
const isDefaultNoStore = staticGenerationStore.fetchCache === "default-no-store";
const isOnlyNoStore = staticGenerationStore.fetchCache === "only-no-store";
const isForceNoStore = staticGenerationStore.fetchCache === "force-no-store";
let _cache = getRequestMeta("cache");
let cacheReason = "";
if (typeof _cache === "string" && typeof curRevalidate !== "undefined") {
Log.warn(`fetch for ${fetchUrl} on ${staticGenerationStore.urlPathname} specified "cache: ${_cache}" and "revalidate: ${curRevalidate}", only one should be specified.`);
_cache = undefined;
}
if (_cache === "force-cache") {
curRevalidate = false;
}
if ([
"no-cache",
"no-store"
].includes(_cache || "")) {
curRevalidate = 0;
cacheReason = `cache: ${_cache}`;
}
if (typeof curRevalidate === "number" || curRevalidate === false) {
revalidate = curRevalidate;
}
const _headers = getRequestMeta("headers");
const initHeaders = typeof (_headers == null ? void 0 : _headers.get) === "function" ? _headers : new Headers(_headers || {});
const hasUnCacheableHeader = initHeaders.get("authorization") || initHeaders.get("cookie");
const isUnCacheableMethod = ![
"get",
"head"
].includes(((_getRequestMeta = getRequestMeta("method")) == null ? void 0 : _getRequestMeta.toLowerCase()) || "get");
// if there are authorized headers or a POST method and
// dynamic data usage was present above the tree we bail
// e.g. if cookies() is used before an authed/POST fetch
const autoNoCache = (hasUnCacheableHeader || isUnCacheableMethod) && staticGenerationStore.revalidate === 0;
if (isForceNoStore) {
revalidate = 0;
cacheReason = "fetchCache = force-no-store";
}
if (isOnlyNoStore) {
if (_cache === "force-cache" || revalidate === 0) {
throw new Error(`cache: 'force-cache' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-no-store'`);
}
revalidate = 0;
cacheReason = "fetchCache = only-no-store";
}
if (isOnlyCache && _cache === "no-store") {
throw new Error(`cache: 'no-store' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-cache'`);
}
if (isForceCache && (typeof curRevalidate === "undefined" || curRevalidate === 0)) {
cacheReason = "fetchCache = force-cache";
revalidate = false;
}
if (typeof revalidate === "undefined") {
if (isDefaultCache) {
revalidate = false;
cacheReason = "fetchCache = default-cache";
} else if (autoNoCache) {
revalidate = 0;
cacheReason = "auto no cache";
} else if (isDefaultNoStore) {
revalidate = 0;
cacheReason = "fetchCache = default-no-store";
} else {
cacheReason = "auto cache";
revalidate = typeof staticGenerationStore.revalidate === "boolean" || typeof staticGenerationStore.revalidate === "undefined" ? false : staticGenerationStore.revalidate;
}
} else if (!cacheReason) {
cacheReason = `revalidate: ${revalidate}`;
}
if (// we don't consider autoNoCache to switch to dynamic during
// revalidate although if it occurs during build we do
!autoNoCache && (typeof staticGenerationStore.revalidate === "undefined" || typeof revalidate === "number" && (staticGenerationStore.revalidate === false || typeof staticGenerationStore.revalidate === "number" && revalidate < staticGenerationStore.revalidate))) {
staticGenerationStore.revalidate = revalidate;
}
const isCacheableRevalidate = typeof revalidate === "number" && revalidate > 0 || revalidate === false;
let cacheKey;
if (staticGenerationStore.incrementalCache && isCacheableRevalidate) {
try {
cacheKey = await staticGenerationStore.incrementalCache.fetchCacheKey(fetchUrl, isRequestInput ? input : init);
} catch (err) {
console.error(`Failed to generate cache key for`, input);
}
}
const fetchIdx = staticGenerationStore.nextFetchId ?? 1;
staticGenerationStore.nextFetchId = fetchIdx + 1;
const normalizedRevalidate = typeof revalidate !== "number" ? CACHE_ONE_YEAR : revalidate;
const doOriginalFetch = async (isStale, cacheReasonOverride)=>{
const requestInputFields = [
"cache",
"credentials",
"headers",
"integrity",
"keepalive",
"method",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"window",
"duplex",
// don't pass through signal when revalidating
...isStale ? [] : [
"signal"
]
];
if (isRequestInput) {
const reqInput = input;
const reqOptions = {
body: reqInput._ogBody || reqInput.body
};
for (const field of requestInputFields){
// @ts-expect-error custom fields
reqOptions[field] = reqInput[field];
}
input = new Request(reqInput.url, reqOptions);
} else if (init) {
const initialInit = init;
init = {
body: init._ogBody || init.body
};
for (const field of requestInputFields){
// @ts-expect-error custom fields
init[field] = initialInit[field];
}
}
// add metadata to init without editing the original
const clonedInit = {
...init,
next: {
...init == null ? void 0 : init.next,
fetchType: "origin",
fetchIdx
}
};
return originFetch(input, clonedInit).then(async (res)=>{
if (!isStale) {
trackFetchMetric(staticGenerationStore, {
start: fetchStart,
url: fetchUrl,
cacheReason: cacheReasonOverride || cacheReason,
cacheStatus: revalidate === 0 || cacheReasonOverride ? "skip" : "miss",
status: res.status,
method: clonedInit.method || "GET"
});
}
if (res.status === 200 && staticGenerationStore.incrementalCache && cacheKey && isCacheableRevalidate) {
const bodyBuffer = Buffer.from(await res.arrayBuffer());
try {
await staticGenerationStore.incrementalCache.set(cacheKey, {
kind: "FETCH",
data: {
headers: Object.fromEntries(res.headers.entries()),
body: bodyBuffer.toString("base64"),
status: res.status,
url: res.url
},
revalidate: normalizedRevalidate
}, {
fetchCache: true,
revalidate,
fetchUrl,
fetchIdx,
tags
});
} catch (err) {
console.warn(`Failed to set fetch cache`, input, err);
}
const response = new Response(bodyBuffer, {
headers: new Headers(res.headers),
status: res.status
});
Object.defineProperty(response, "url", {
value: res.url
});
return response;
}
return res;
});
};
let handleUnlock = ()=>Promise.resolve();
let cacheReasonOverride;
if (cacheKey && staticGenerationStore.incrementalCache) {
handleUnlock = await staticGenerationStore.incrementalCache.lock(cacheKey);
const entry = staticGenerationStore.isOnDemandRevalidate ? null : await staticGenerationStore.incrementalCache.get(cacheKey, {
fetchCache: true,
revalidate,
fetchUrl,
fetchIdx,
tags,
softTags: implicitTags
});
if (entry) {
await handleUnlock();
} else {
// in dev, incremental cache response will be null in case the browser adds `cache-control: no-cache` in the request headers
cacheReasonOverride = "cache-control: no-cache (hard refresh)";
}
if ((entry == null ? void 0 : entry.value) && entry.value.kind === "FETCH") {
// when stale and is revalidating we wait for fresh data
// so the revalidated entry has the updated data
if (!(staticGenerationStore.isRevalidate && entry.isStale)) {
if (entry.isStale) {
if (!staticGenerationStore.pendingRevalidates) {
staticGenerationStore.pendingRevalidates = [];
}
staticGenerationStore.pendingRevalidates.push(doOriginalFetch(true).catch(console.error));
}
const resData = entry.value.data;
let decodedBody;
if (process.env.NEXT_RUNTIME === "edge") {
const { decode } = require("../../shared/lib/base64-arraybuffer");
decodedBody = decode(resData.body);
} else {
decodedBody = Buffer.from(resData.body, "base64").subarray();
}
trackFetchMetric(staticGenerationStore, {
start: fetchStart,
url: fetchUrl,
cacheReason,
cacheStatus: "hit",
status: resData.status || 200,
method: (init == null ? void 0 : init.method) || "GET"
});
const response = new Response(decodedBody, {
headers: resData.headers,
status: resData.status
});
Object.defineProperty(response, "url", {
value: entry.value.data.url
});
return response;
}
}
}
if (staticGenerationStore.isStaticGeneration) {
if (init && typeof init === "object") {
const cache = init.cache;
// Delete `cache` property as Cloudflare Workers will throw an error
if (isEdgeRuntime) {
delete init.cache;
}
if (cache === "no-store") {
staticGenerationStore.revalidate = 0;
const dynamicUsageReason = `no-store fetch ${input}${staticGenerationStore.urlPathname ? ` ${staticGenerationStore.urlPathname}` : ""}`;
const err = new DynamicServerError(dynamicUsageReason);
staticGenerationStore.dynamicUsageErr = err;
staticGenerationStore.dynamicUsageStack = err.stack;
staticGenerationStore.dynamicUsageDescription = dynamicUsageReason;
}
const hasNextConfig = "next" in init;
const next = init.next || {};
if (typeof next.revalidate === "number" && (typeof staticGenerationStore.revalidate === "undefined" || typeof staticGenerationStore.revalidate === "number" && next.revalidate < staticGenerationStore.revalidate)) {
const forceDynamic = staticGenerationStore.forceDynamic;
if (!forceDynamic || next.revalidate !== 0) {
staticGenerationStore.revalidate = next.revalidate;
}
if (!forceDynamic && next.revalidate === 0) {
const dynamicUsageReason = `revalidate: ${next.revalidate} fetch ${input}${staticGenerationStore.urlPathname ? ` ${staticGenerationStore.urlPathname}` : ""}`;
const err = new DynamicServerError(dynamicUsageReason);
staticGenerationStore.dynamicUsageErr = err;
staticGenerationStore.dynamicUsageStack = err.stack;
staticGenerationStore.dynamicUsageDescription = dynamicUsageReason;
}
}
if (hasNextConfig) delete init.next;
}
}
return doOriginalFetch(false, cacheReasonOverride).finally(handleUnlock);
});
};
globalThis.fetch.__nextGetStaticStore = ()=>{
return staticGenerationAsyncStorage;
};
globalThis.fetch.__nextPatched = true;
}
//# sourceMappingURL=patch-fetch.js.map

File diff suppressed because one or more lines are too long

68
node_modules/next/dist/esm/server/lib/render-server.js generated vendored Normal file
View File

@@ -0,0 +1,68 @@
import next from "../next";
const result = {};
let apps = {};
let sandboxContext;
let requireCacheHotReloader;
if (process.env.NODE_ENV !== "production") {
sandboxContext = require("../web/sandbox/context");
requireCacheHotReloader = require("../../build/webpack/plugins/nextjs-require-cache-hot-reloader");
}
export function clearModuleContext(target) {
return sandboxContext == null ? void 0 : sandboxContext.clearModuleContext(target);
}
export function deleteAppClientCache() {
return requireCacheHotReloader == null ? void 0 : requireCacheHotReloader.deleteAppClientCache();
}
export function deleteCache(filePaths) {
for (const filePath of filePaths){
requireCacheHotReloader == null ? void 0 : requireCacheHotReloader.deleteCache(filePath);
}
}
export async function propagateServerField(dir, field, value) {
const app = apps[dir];
if (!app) {
throw new Error("Invariant cant propagate server field, no app initialized");
}
let appField = app.server;
if (appField) {
if (typeof appField[field] === "function") {
await appField[field].apply(app.server, Array.isArray(value) ? value : []);
} else {
appField[field] = value;
}
}
}
export async function initialize(opts) {
// if we already setup the server return as we only need to do
// this on first worker boot
if (result[opts.dir]) {
return result[opts.dir];
}
const type = process.env.__NEXT_PRIVATE_RENDER_WORKER;
if (type) {
process.title = "next-render-worker-" + type;
}
let requestHandler;
let upgradeHandler;
const app = next({
...opts,
_routerWorker: opts.workerType === "router",
_renderWorker: opts.workerType === "render",
hostname: opts.hostname || "localhost",
customServer: false,
httpServer: opts.server,
port: opts.port,
isNodeDebugging: opts.isNodeDebugging
});
apps[opts.dir] = app;
requestHandler = app.getRequestHandler();
upgradeHandler = app.getUpgradeHandler();
await app.prepare(opts.serverFields);
result[opts.dir] = {
requestHandler,
upgradeHandler
};
return result[opts.dir];
}
//# sourceMappingURL=render-server.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/render-server.ts"],"names":["next","result","apps","sandboxContext","requireCacheHotReloader","process","env","NODE_ENV","require","clearModuleContext","target","deleteAppClientCache","deleteCache","filePaths","filePath","propagateServerField","dir","field","value","app","Error","appField","server","apply","Array","isArray","initialize","opts","type","__NEXT_PRIVATE_RENDER_WORKER","title","requestHandler","upgradeHandler","_routerWorker","workerType","_renderWorker","hostname","customServer","httpServer","port","isNodeDebugging","getRequestHandler","getUpgradeHandler","prepare","serverFields"],"mappings":"AAEA,OAAOA,UAAU,UAAS;AAG1B,MAAMC,SAWF,CAAC;AAEL,IAAIC,OAA4D,CAAC;AAEjE,IAAIC;AACJ,IAAIC;AAIJ,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCJ,iBAAiBK,QAAQ;IACzBJ,0BAA0BI,QAAQ;AACpC;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AAI;QACfC,iBAAiBb,KAAKa,eAAe;IACvC;IACAtC,IAAI,CAACyB,KAAKX,GAAG,CAAC,GAAGG;IACjBY,iBAAiBZ,IAAIsB,iBAAiB;IACtCT,iBAAiBb,IAAIuB,iBAAiB;IAEtC,MAAMvB,IAAIwB,OAAO,CAAChB,KAAKiB,YAAY;IAEnC3C,MAAM,CAAC0B,KAAKX,GAAG,CAAC,GAAG;QACjBe;QACAC;IACF;IACA,OAAO/B,MAAM,CAAC0B,KAAKX,GAAG,CAAC;AACzB"}

170
node_modules/next/dist/esm/server/lib/route-resolver.js generated vendored Normal file
View File

@@ -0,0 +1,170 @@
import "../require-hook";
import "../node-polyfill-fetch";
import url from "url";
import path from "path";
import { findPageFile } from "./find-page-file";
import { getRequestMeta } from "../request-meta";
import setupDebug from "next/dist/compiled/debug";
import { getCloneableBody } from "../body-streams";
import { findPagesDir } from "../../lib/find-pages-dir";
import { setupFsCheck } from "./router-utils/filesystem";
import { proxyRequest } from "./router-utils/proxy-request";
import { getResolveRoutes } from "./router-utils/resolve-routes";
import { PERMANENT_REDIRECT_STATUS } from "../../shared/lib/constants";
import { formatHostname } from "./format-hostname";
import { signalFromNodeResponse } from "../web/spec-extension/adapters/next-request";
import { getMiddlewareRouteMatcher } from "../../shared/lib/router/utils/middleware-route-matcher";
import { pipeReadable } from "../pipe-readable";
const debug = setupDebug("next:router-server");
export async function makeResolver(dir, nextConfig, middleware, { hostname = "localhost", port = 3000 }) {
const fsChecker = await setupFsCheck({
dir,
dev: true,
minimalMode: false,
config: nextConfig
});
const { appDir, pagesDir } = findPagesDir(dir);
// we format the hostname so that it can be fetched
const fetchHostname = formatHostname(hostname);
fsChecker.ensureCallback(async (item)=>{
let result = null;
if (item.type === "appFile") {
if (!appDir) {
throw new Error("no app dir present");
}
result = await findPageFile(appDir, item.itemPath, nextConfig.pageExtensions, true);
} else if (item.type === "pageFile") {
if (!pagesDir) {
throw new Error("no pages dir present");
}
result = await findPageFile(pagesDir, item.itemPath, nextConfig.pageExtensions, false);
}
if (!result) {
throw new Error(`failed to find page file ${item.type} ${item.itemPath}`);
}
});
const distDir = path.join(dir, nextConfig.distDir);
const middlewareInfo = middleware ? {
name: "middleware",
paths: middleware.files.map((file)=>path.join(process.cwd(), file)),
wasm: [],
assets: []
} : {};
if (middleware == null ? void 0 : middleware.files.length) {
var _middleware_matcher;
fsChecker.middlewareMatcher = getMiddlewareRouteMatcher(((_middleware_matcher = middleware.matcher) == null ? void 0 : _middleware_matcher.map((item)=>({
regexp: item,
originalSource: item
}))) || [
{
regexp: ".*",
originalSource: "/:path*"
}
]);
}
const resolveRoutes = getResolveRoutes(fsChecker, nextConfig, {
dir,
port,
hostname,
isNodeDebugging: false,
dev: true,
workerType: "render"
}, {
pages: {
async initialize () {
return {
async requestHandler (req, res) {
if (!req.headers["x-middleware-invoke"]) {
throw new Error(`Invariant unexpected request handler call`);
}
const cloneableBody = getCloneableBody(req);
const { run } = require("../web/sandbox");
const result = await run({
distDir,
name: middlewareInfo.name || "/",
paths: middlewareInfo.paths || [],
edgeFunctionEntry: middlewareInfo,
request: {
headers: req.headers,
method: req.method || "GET",
nextConfig: {
i18n: nextConfig.i18n,
basePath: nextConfig.basePath,
trailingSlash: nextConfig.trailingSlash
},
url: `http://${fetchHostname}:${port}${req.url}`,
body: cloneableBody,
signal: signalFromNodeResponse(res)
},
useCache: true,
onWarning: console.warn
});
const err = new Error();
err.result = result;
throw err;
},
async upgradeHandler () {
throw new Error(`Invariant: unexpected upgrade handler call`);
}
};
},
deleteAppClientCache () {},
async deleteCache () {},
async clearModuleContext () {},
async propagateServerField () {}
}
}, {});
return async function resolveRoute(req, res) {
const routeResult = await resolveRoutes({
req,
res,
isUpgradeReq: false,
signal: signalFromNodeResponse(res)
});
const { matchedOutput, bodyStream, statusCode, parsedUrl, resHeaders, finished } = routeResult;
debug("requestHandler!", req.url, {
matchedOutput,
statusCode,
resHeaders,
bodyStream: !!bodyStream,
parsedUrl: {
pathname: parsedUrl.pathname,
query: parsedUrl.query
},
finished
});
for (const key of Object.keys(resHeaders || {})){
res.setHeader(key, resHeaders[key]);
}
if (!bodyStream && statusCode && statusCode > 300 && statusCode < 400) {
const destination = url.format(parsedUrl);
res.statusCode = statusCode;
res.setHeader("location", destination);
if (statusCode === PERMANENT_REDIRECT_STATUS) {
res.setHeader("Refresh", `0;url=${destination}`);
}
res.end(destination);
return;
}
// handle middleware body response
if (bodyStream) {
res.statusCode = statusCode || 200;
return await pipeReadable(bodyStream, res);
}
if (finished && parsedUrl.protocol) {
var _getRequestMeta;
await proxyRequest(req, res, parsedUrl, undefined, (_getRequestMeta = getRequestMeta(req, "__NEXT_CLONABLE_BODY")) == null ? void 0 : _getRequestMeta.cloneBodyStream(), nextConfig.experimental.proxyTimeout);
return;
}
res.setHeader("x-nextjs-route-result", "1");
res.end();
return {
type: "rewrite",
statusCode: 200,
headers: resHeaders,
url: url.format(parsedUrl)
};
};
}
//# sourceMappingURL=route-resolver.js.map

File diff suppressed because one or more lines are too long

476
node_modules/next/dist/esm/server/lib/router-server.js generated vendored Normal file
View File

@@ -0,0 +1,476 @@
// This is required before other imports to ensure the require hook is setup.
import "../node-polyfill-fetch";
import "../node-environment";
import "../require-hook";
import url from "url";
import path from "path";
import loadConfig from "../config";
import { serveStatic } from "../serve-static";
import setupDebug from "next/dist/compiled/debug";
import { Telemetry } from "../../telemetry/storage";
import { DecodeError } from "../../shared/lib/utils";
import { findPagesDir } from "../../lib/find-pages-dir";
import { setupFsCheck } from "./router-utils/filesystem";
import { proxyRequest } from "./router-utils/proxy-request";
import { isAbortError, pipeReadable } from "../pipe-readable";
import { createRequestResponseMocks } from "./mock-request";
import { getResolveRoutes } from "./router-utils/resolve-routes";
import { getRequestMeta } from "../request-meta";
import { pathHasPrefix } from "../../shared/lib/router/utils/path-has-prefix";
import { removePathPrefix } from "../../shared/lib/router/utils/remove-path-prefix";
import setupCompression from "next/dist/compiled/compression";
import { NoFallbackError } from "../base-server";
import { signalFromNodeResponse } from "../web/spec-extension/adapters/next-request";
import { PHASE_PRODUCTION_SERVER, PHASE_DEVELOPMENT_SERVER, PERMANENT_REDIRECT_STATUS } from "../../shared/lib/constants";
const debug = setupDebug("next:router-server:main");
const devInstances = {};
const requestHandlers = {};
export async function initialize(opts) {
var _renderWorkers_app;
process.title = "next-router-worker";
if (!process.env.NODE_ENV) {
// @ts-ignore not readonly
process.env.NODE_ENV = opts.dev ? "development" : "production";
}
const config = await loadConfig(opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER, opts.dir, {
silent: false
});
let compress;
if ((config == null ? void 0 : config.compress) !== false) {
compress = setupCompression();
}
const fsChecker = await setupFsCheck({
dev: opts.dev,
dir: opts.dir,
config,
minimalMode: opts.minimalMode
});
const renderWorkers = {};
let devInstance;
if (opts.dev) {
const telemetry = new Telemetry({
distDir: path.join(opts.dir, config.distDir)
});
const { pagesDir, appDir } = findPagesDir(opts.dir);
const { setupDev } = await require("./router-utils/setup-dev");
devInstance = await setupDev({
// Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.
renderWorkers,
appDir,
pagesDir,
telemetry,
fsChecker,
dir: opts.dir,
nextConfig: config,
isCustomServer: opts.customServer,
turbo: !!process.env.TURBOPACK,
port: opts.port
});
devInstances[opts.dir] = devInstance;
global._nextDevHandlers = {
async ensurePage (dir, match) {
const curDevInstance = devInstances[dir];
// TODO: remove after ensure is pulled out of server
return await (curDevInstance == null ? void 0 : curDevInstance.hotReloader.ensurePage(match));
},
async logErrorWithOriginalStack (dir, ...args) {
const curDevInstance = devInstances[dir];
// @ts-ignore
return await (curDevInstance == null ? void 0 : curDevInstance.logErrorWithOriginalStack(...args));
},
async getFallbackErrorComponents (dir) {
const curDevInstance = devInstances[dir];
await curDevInstance.hotReloader.buildFallbackError();
// Build the error page to ensure the fallback is built too.
// TODO: See if this can be moved into hotReloader or removed.
await curDevInstance.hotReloader.ensurePage({
page: "/_error",
clientOnly: false
});
},
async getCompilationError (dir, page) {
var _curDevInstance_hotReloader;
const curDevInstance = devInstances[dir];
const errors = await (curDevInstance == null ? void 0 : (_curDevInstance_hotReloader = curDevInstance.hotReloader) == null ? void 0 : _curDevInstance_hotReloader.getCompilationErrors(page));
if (!errors) return;
// Return the very first error we found.
return errors[0];
},
async revalidate (dir, { urlPath, revalidateHeaders, opts: revalidateOpts }) {
const mocked = createRequestResponseMocks({
url: urlPath,
headers: revalidateHeaders
});
const curRequestHandler = requestHandlers[dir];
// eslint-disable-next-line @typescript-eslint/no-use-before-define
await curRequestHandler(mocked.req, mocked.res);
await mocked.res.hasStreamed;
if (mocked.res.getHeader("x-nextjs-cache") !== "REVALIDATED" && !(mocked.res.statusCode === 404 && revalidateOpts.unstable_onlyGenerated)) {
throw new Error(`Invalid response ${mocked.res.statusCode}`);
}
return {};
}
};
}
renderWorkers.app = require("./render-server");
renderWorkers.pages = renderWorkers.app;
const renderWorkerOpts = {
port: opts.port,
dir: opts.dir,
workerType: "render",
hostname: opts.hostname,
minimalMode: opts.minimalMode,
dev: !!opts.dev,
server: opts.server,
isNodeDebugging: !!opts.isNodeDebugging,
serverFields: (devInstance == null ? void 0 : devInstance.serverFields) || {},
experimentalTestProxy: !!opts.experimentalTestProxy
};
// pre-initialize workers
const handlers = await ((_renderWorkers_app = renderWorkers.app) == null ? void 0 : _renderWorkers_app.initialize(renderWorkerOpts));
const initialized = {
app: handlers,
pages: handlers
};
const logError = async (type, err)=>{
await (devInstance == null ? void 0 : devInstance.logErrorWithOriginalStack(err, type));
};
const cleanup = ()=>{
var _renderWorkers_pages__workerPool, _renderWorkers_pages;
debug("router-server process cleanup");
for (const curWorker of [
...((_renderWorkers_pages = renderWorkers.pages) == null ? void 0 : (_renderWorkers_pages__workerPool = _renderWorkers_pages._workerPool) == null ? void 0 : _renderWorkers_pages__workerPool._workers) || []
]){
var _curWorker__child;
(_curWorker__child = curWorker._child) == null ? void 0 : _curWorker__child.kill("SIGINT");
}
if (!process.env.__NEXT_PRIVATE_CPU_PROFILE) {
process.exit(0);
}
};
process.on("exit", cleanup);
process.on("SIGINT", cleanup);
process.on("SIGTERM", cleanup);
process.on("uncaughtException", logError.bind(null, "uncaughtException"));
process.on("unhandledRejection", logError.bind(null, "unhandledRejection"));
const resolveRoutes = getResolveRoutes(fsChecker, config, opts, renderWorkers, renderWorkerOpts, devInstance == null ? void 0 : devInstance.ensureMiddleware);
const requestHandlerImpl = async (req, res)=>{
if (compress) {
// @ts-expect-error not express req/res
compress(req, res, ()=>{});
}
req.on("error", (_err)=>{
// TODO: log socket errors?
});
res.on("error", (_err)=>{
// TODO: log socket errors?
});
const invokedOutputs = new Set();
async function invokeRender(parsedUrl, type, invokePath, handleIndex, additionalInvokeHeaders = {}) {
var _fsChecker_getMiddlewareMatchers;
// invokeRender expects /api routes to not be locale prefixed
// so normalize here before continuing
if (config.i18n && removePathPrefix(invokePath, config.basePath).startsWith(`/${parsedUrl.query.__nextLocale}/api`)) {
invokePath = fsChecker.handleLocale(removePathPrefix(invokePath, config.basePath)).pathname;
}
if (req.headers["x-nextjs-data"] && ((_fsChecker_getMiddlewareMatchers = fsChecker.getMiddlewareMatchers()) == null ? void 0 : _fsChecker_getMiddlewareMatchers.length) && removePathPrefix(invokePath, config.basePath) === "/404") {
res.setHeader("x-nextjs-matched-path", parsedUrl.pathname || "");
res.statusCode = 200;
res.setHeader("content-type", "application/json");
res.end("{}");
return null;
}
const workerResult = initialized[type];
if (!workerResult) {
throw new Error(`Failed to initialize render worker ${type}`);
}
const invokeHeaders = {
...req.headers,
"x-middleware-invoke": "",
"x-invoke-path": invokePath,
"x-invoke-query": encodeURIComponent(JSON.stringify(parsedUrl.query)),
...additionalInvokeHeaders || {}
};
Object.assign(req.headers, invokeHeaders);
debug("invokeRender", req.url, invokeHeaders);
try {
var _renderWorkers_pages;
const initResult = await ((_renderWorkers_pages = renderWorkers.pages) == null ? void 0 : _renderWorkers_pages.initialize(renderWorkerOpts));
try {
await (initResult == null ? void 0 : initResult.requestHandler(req, res));
} catch (err) {
if (err instanceof NoFallbackError) {
// eslint-disable-next-line
await handleRequest(handleIndex + 1);
return;
}
throw err;
}
return;
} catch (e) {
// If the client aborts before we can receive a response object (when
// the headers are flushed), then we can early exit without further
// processing.
if (isAbortError(e)) {
return;
}
throw e;
}
}
const handleRequest = async (handleIndex)=>{
if (handleIndex > 5) {
throw new Error(`Attempted to handle request too many times ${req.url}`);
}
// handle hot-reloader first
if (devInstance) {
const origUrl = req.url || "/";
if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {
req.url = removePathPrefix(origUrl, config.basePath);
}
const parsedUrl = url.parse(req.url || "/");
const hotReloaderResult = await devInstance.hotReloader.run(req, res, parsedUrl);
if (hotReloaderResult.finished) {
return hotReloaderResult;
}
req.url = origUrl;
}
const { finished, parsedUrl, statusCode, resHeaders, bodyStream, matchedOutput } = await resolveRoutes({
req,
res,
isUpgradeReq: false,
signal: signalFromNodeResponse(res),
invokedOutputs
});
if (res.closed || res.finished) {
return;
}
if (devInstance && (matchedOutput == null ? void 0 : matchedOutput.type) === "devVirtualFsItem") {
const origUrl = req.url || "/";
if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {
req.url = removePathPrefix(origUrl, config.basePath);
}
if (resHeaders) {
for (const key of Object.keys(resHeaders)){
res.setHeader(key, resHeaders[key]);
}
}
const result = await devInstance.requestHandler(req, res);
if (result.finished) {
return;
}
// TODO: throw invariant if we resolved to this but it wasn't handled?
req.url = origUrl;
}
debug("requestHandler!", req.url, {
matchedOutput,
statusCode,
resHeaders,
bodyStream: !!bodyStream,
parsedUrl: {
pathname: parsedUrl.pathname,
query: parsedUrl.query
},
finished
});
// apply any response headers from routing
for (const key of Object.keys(resHeaders || {})){
res.setHeader(key, resHeaders[key]);
}
// handle redirect
if (!bodyStream && statusCode && statusCode > 300 && statusCode < 400) {
const destination = url.format(parsedUrl);
res.statusCode = statusCode;
res.setHeader("location", destination);
if (statusCode === PERMANENT_REDIRECT_STATUS) {
res.setHeader("Refresh", `0;url=${destination}`);
}
return res.end(destination);
}
// handle middleware body response
if (bodyStream) {
res.statusCode = statusCode || 200;
return await pipeReadable(bodyStream, res);
}
if (finished && parsedUrl.protocol) {
var _getRequestMeta;
return await proxyRequest(req, res, parsedUrl, undefined, (_getRequestMeta = getRequestMeta(req, "__NEXT_CLONABLE_BODY")) == null ? void 0 : _getRequestMeta.cloneBodyStream(), config.experimental.proxyTimeout);
}
if ((matchedOutput == null ? void 0 : matchedOutput.fsPath) && matchedOutput.itemPath) {
if (opts.dev && (fsChecker.appFiles.has(matchedOutput.itemPath) || fsChecker.pageFiles.has(matchedOutput.itemPath))) {
res.statusCode = 500;
await invokeRender(parsedUrl, "pages", "/_error", handleIndex, {
"x-invoke-status": "500",
"x-invoke-error": JSON.stringify({
message: `A conflicting public file and page file was found for path ${matchedOutput.itemPath} https://nextjs.org/docs/messages/conflicting-public-file-page`
})
});
return;
}
if (!res.getHeader("cache-control") && matchedOutput.type === "nextStaticFolder") {
if (opts.dev) {
res.setHeader("Cache-Control", "no-store, must-revalidate");
} else {
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
}
}
if (!(req.method === "GET" || req.method === "HEAD")) {
res.setHeader("Allow", [
"GET",
"HEAD"
]);
res.statusCode = 405;
return await invokeRender(url.parse("/405", true), "pages", "/405", handleIndex, {
"x-invoke-status": "405"
});
}
try {
return await serveStatic(req, res, matchedOutput.itemPath, {
root: matchedOutput.itemsRoot,
// Ensures that etags are not generated for static files when disabled.
etag: config.generateEtags
});
} catch (err) {
/**
* Hardcoded every possible error status code that could be thrown by "serveStatic" method
* This is done by searching "this.error" inside "send" module's source code:
* https://github.com/pillarjs/send/blob/master/index.js
* https://github.com/pillarjs/send/blob/develop/index.js
*/ const POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC = new Set([
// send module will throw 500 when header is already sent or fs.stat error happens
// https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L392
// Note: we will use Next.js built-in 500 page to handle 500 errors
// 500,
// send module will throw 404 when file is missing
// https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L421
// Note: we will use Next.js built-in 404 page to handle 404 errors
// 404,
// send module will throw 403 when redirecting to a directory without enabling directory listing
// https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L484
// Note: Next.js throws a different error (without status code) for directory listing
// 403,
// send module will throw 400 when fails to normalize the path
// https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L520
400,
// send module will throw 412 with conditional GET request
// https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L632
412,
// send module will throw 416 when range is not satisfiable
// https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L669
416
]);
let validErrorStatus = POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC.has(err.statusCode);
// normalize non-allowed status codes
if (!validErrorStatus) {
err.statusCode = 400;
}
if (typeof err.statusCode === "number") {
const invokePath = `/${err.statusCode}`;
const invokeStatus = `${err.statusCode}`;
res.statusCode = err.statusCode;
return await invokeRender(url.parse(invokePath, true), "pages", invokePath, handleIndex, {
"x-invoke-status": invokeStatus
});
}
throw err;
}
}
if (matchedOutput) {
invokedOutputs.add(matchedOutput.itemPath);
return await invokeRender(parsedUrl, matchedOutput.type === "appFile" ? "app" : "pages", parsedUrl.pathname || "/", handleIndex, {
"x-invoke-output": matchedOutput.itemPath
});
}
// 404 case
res.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
// Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route.
if (opts.dev && !matchedOutput && parsedUrl.pathname === "/favicon.ico") {
res.statusCode = 404;
res.end("");
return null;
}
const appNotFound = opts.dev ? devInstance == null ? void 0 : devInstance.serverFields.hasAppNotFound : await fsChecker.getItem("/_not-found");
res.statusCode = 404;
if (appNotFound) {
return await invokeRender(parsedUrl, "app", opts.dev ? "/not-found" : "/_not-found", handleIndex, {
"x-invoke-status": "404"
});
}
await invokeRender(parsedUrl, "pages", "/404", handleIndex, {
"x-invoke-status": "404"
});
};
try {
await handleRequest(0);
} catch (err) {
try {
let invokePath = "/500";
let invokeStatus = "500";
if (err instanceof DecodeError) {
invokePath = "/400";
invokeStatus = "400";
} else {
console.error(err);
}
res.statusCode = Number(invokeStatus);
return await invokeRender(url.parse(invokePath, true), "pages", invokePath, 0, {
"x-invoke-status": invokeStatus
});
} catch (err2) {
console.error(err2);
}
res.statusCode = 500;
res.end("Internal Server Error");
}
};
let requestHandler = requestHandlerImpl;
if (opts.experimentalTestProxy) {
// Intercept fetch and other testmode apis.
const { wrapRequestHandlerWorker, interceptTestApis } = require("../../experimental/testmode/server");
requestHandler = wrapRequestHandlerWorker(requestHandler);
interceptTestApis();
}
requestHandlers[opts.dir] = requestHandler;
const upgradeHandler = async (req, socket, head)=>{
try {
req.on("error", (_err)=>{
// TODO: log socket errors?
// console.error(_err);
});
socket.on("error", (_err)=>{
// TODO: log socket errors?
// console.error(_err);
});
if (opts.dev && devInstance) {
var _req_url;
if ((_req_url = req.url) == null ? void 0 : _req_url.includes(`/_next/webpack-hmr`)) {
return devInstance.hotReloader.onHMR(req, socket, head);
}
}
const { matchedOutput, parsedUrl } = await resolveRoutes({
req,
res: socket,
isUpgradeReq: true,
signal: signalFromNodeResponse(socket)
});
// TODO: allow upgrade requests to pages/app paths?
// this was not previously supported
if (matchedOutput) {
return socket.end();
}
if (parsedUrl.protocol) {
return await proxyRequest(req, socket, parsedUrl, head);
}
// no match close socket
socket.end();
} catch (err) {
console.error("Error handling upgrade request", err);
socket.end();
}
};
return [
requestHandler,
upgradeHandler
];
}
//# sourceMappingURL=router-server.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,29 @@
import path from "../../../shared/lib/isomorphic/path";
import { normalizePagePath } from "../../../shared/lib/page-path/normalize-page-path";
import { isDynamicRoute } from "../../../shared/lib/router/utils/is-dynamic";
import { getNamedRouteRegex } from "../../../shared/lib/router/utils/route-regex";
import { normalizeRouteRegex } from "../../../lib/load-custom-routes";
import { escapeStringRegexp } from "../../../shared/lib/escape-regexp";
export function buildDataRoute(page, buildId) {
const pagePath = normalizePagePath(page);
const dataRoute = path.posix.join("/_next/data", buildId, `${pagePath}.json`);
let dataRouteRegex;
let namedDataRouteRegex;
let routeKeys;
if (isDynamicRoute(page)) {
const routeRegex = getNamedRouteRegex(dataRoute.replace(/\.json$/, ""), true);
dataRouteRegex = normalizeRouteRegex(routeRegex.re.source.replace(/\(\?:\\\/\)\?\$$/, `\\.json$`));
namedDataRouteRegex = routeRegex.namedRegex.replace(/\(\?:\/\)\?\$$/, `\\.json$`);
routeKeys = routeRegex.routeKeys;
} else {
dataRouteRegex = normalizeRouteRegex(new RegExp(`^${path.posix.join("/_next/data", escapeStringRegexp(buildId), `${pagePath}.json`)}$`).source);
}
return {
page,
routeKeys,
dataRouteRegex,
namedDataRouteRegex
};
}
//# sourceMappingURL=build-data-route.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/router-utils/build-data-route.ts"],"names":["path","normalizePagePath","isDynamicRoute","getNamedRouteRegex","normalizeRouteRegex","escapeStringRegexp","buildDataRoute","page","buildId","pagePath","dataRoute","posix","join","dataRouteRegex","namedDataRouteRegex","routeKeys","routeRegex","replace","re","source","namedRegex","RegExp"],"mappings":"AAAA,OAAOA,UAAU,sCAAqC;AACtD,SAASC,iBAAiB,QAAQ,oDAAmD;AACrF,SAASC,cAAc,QAAQ,8CAA6C;AAC5E,SAASC,kBAAkB,QAAQ,+CAA8C;AACjF,SAASC,mBAAmB,QAAQ,kCAAiC;AACrE,SAASC,kBAAkB,QAAQ,oCAAmC;AAEtE,OAAO,SAASC,eAAeC,IAAY,EAAEC,OAAe;IAC1D,MAAMC,WAAWR,kBAAkBM;IACnC,MAAMG,YAAYV,KAAKW,KAAK,CAACC,IAAI,CAAC,eAAeJ,SAAS,CAAC,EAAEC,SAAS,KAAK,CAAC;IAE5E,IAAII;IACJ,IAAIC;IACJ,IAAIC;IAEJ,IAAIb,eAAeK,OAAO;QACxB,MAAMS,aAAab,mBACjBO,UAAUO,OAAO,CAAC,WAAW,KAC7B;QAGFJ,iBAAiBT,oBACfY,WAAWE,EAAE,CAACC,MAAM,CAACF,OAAO,CAAC,oBAAoB,CAAC,QAAQ,CAAC;QAE7DH,sBAAsBE,WAAWI,UAAU,CAAEH,OAAO,CAClD,kBACA,CAAC,QAAQ,CAAC;QAEZF,YAAYC,WAAWD,SAAS;IAClC,OAAO;QACLF,iBAAiBT,oBACf,IAAIiB,OACF,CAAC,CAAC,EAAErB,KAAKW,KAAK,CAACC,IAAI,CACjB,eACAP,mBAAmBG,UACnB,CAAC,EAAEC,SAAS,KAAK,CAAC,EAClB,CAAC,CAAC,EACJU,MAAM;IAEZ;IAEA,OAAO;QACLZ;QACAQ;QACAF;QACAC;IACF;AACF"}

View File

@@ -0,0 +1,423 @@
import path from "path";
import fs from "fs/promises";
import * as Log from "../../../build/output/log";
import setupDebug from "next/dist/compiled/debug";
import LRUCache from "next/dist/compiled/lru-cache";
import loadCustomRoutes from "../../../lib/load-custom-routes";
import { modifyRouteRegex } from "../../../lib/redirect-status";
import { FileType, fileExists } from "../../../lib/file-exists";
import { recursiveReadDir } from "../../../lib/recursive-readdir";
import { isDynamicRoute } from "../../../shared/lib/router/utils";
import { escapeStringRegexp } from "../../../shared/lib/escape-regexp";
import { getPathMatch } from "../../../shared/lib/router/utils/path-match";
import { getRouteRegex } from "../../../shared/lib/router/utils/route-regex";
import { getRouteMatcher } from "../../../shared/lib/router/utils/route-matcher";
import { pathHasPrefix } from "../../../shared/lib/router/utils/path-has-prefix";
import { normalizeLocalePath } from "../../../shared/lib/i18n/normalize-locale-path";
import { removePathPrefix } from "../../../shared/lib/router/utils/remove-path-prefix";
import { getMiddlewareRouteMatcher } from "../../../shared/lib/router/utils/middleware-route-matcher";
import { APP_PATH_ROUTES_MANIFEST, BUILD_ID_FILE, MIDDLEWARE_MANIFEST, PAGES_MANIFEST, PRERENDER_MANIFEST, ROUTES_MANIFEST } from "../../../shared/lib/constants";
import { normalizePathSep } from "../../../shared/lib/page-path/normalize-path-sep";
import { normalizeMetadataRoute } from "../../../lib/metadata/get-metadata-route";
const debug = setupDebug("next:router-server:filesystem");
export const buildCustomRoute = (type, item, basePath, caseSensitive)=>{
const restrictedRedirectPaths = [
"/_next"
].map((p)=>basePath ? `${basePath}${p}` : p);
const match = getPathMatch(item.source, {
strict: true,
removeUnnamedParams: true,
regexModifier: !item.internal ? (regex)=>modifyRouteRegex(regex, type === "redirect" ? restrictedRedirectPaths : undefined) : undefined,
sensitive: caseSensitive
});
return {
...item,
...type === "rewrite" ? {
check: true
} : {},
match
};
};
export async function setupFsCheck(opts) {
const getItemsLru = !opts.dev ? new LRUCache({
max: 1024 * 1024,
length (value, key) {
if (!value) return (key == null ? void 0 : key.length) || 0;
return (key || "").length + (value.fsPath || "").length + value.itemPath.length + value.type.length;
}
}) : undefined;
// routes that have _next/data endpoints (SSG/SSP)
const nextDataRoutes = new Set();
const publicFolderItems = new Set();
const nextStaticFolderItems = new Set();
const legacyStaticFolderItems = new Set();
const appFiles = new Set();
const pageFiles = new Set();
let dynamicRoutes = [];
let middlewareMatcher = ()=>false;
const distDir = path.join(opts.dir, opts.config.distDir);
const publicFolderPath = path.join(opts.dir, "public");
const nextStaticFolderPath = path.join(distDir, "static");
const legacyStaticFolderPath = path.join(opts.dir, "static");
let customRoutes = {
redirects: [],
rewrites: {
beforeFiles: [],
afterFiles: [],
fallback: []
},
headers: []
};
let buildId = "development";
let prerenderManifest;
if (!opts.dev) {
var _middlewareManifest_middleware_, _middlewareManifest_middleware;
const buildIdPath = path.join(opts.dir, opts.config.distDir, BUILD_ID_FILE);
buildId = await fs.readFile(buildIdPath, "utf8");
try {
for (const file of (await recursiveReadDir(publicFolderPath))){
// Ensure filename is encoded and normalized.
publicFolderItems.add(encodeURI(normalizePathSep(file)));
}
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
}
try {
for (const file of (await recursiveReadDir(legacyStaticFolderPath))){
// Ensure filename is encoded and normalized.
legacyStaticFolderItems.add(encodeURI(normalizePathSep(file)));
}
Log.warn(`The static directory has been deprecated in favor of the public directory. https://nextjs.org/docs/messages/static-dir-deprecated`);
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
}
try {
for (const file of (await recursiveReadDir(nextStaticFolderPath))){
// Ensure filename is encoded and normalized.
nextStaticFolderItems.add(path.posix.join("/_next/static", encodeURI(normalizePathSep(file))));
}
} catch (err) {
if (opts.config.output !== "standalone") throw err;
}
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST);
const prerenderManifestPath = path.join(distDir, PRERENDER_MANIFEST);
const middlewareManifestPath = path.join(distDir, "server", MIDDLEWARE_MANIFEST);
const pagesManifestPath = path.join(distDir, "server", PAGES_MANIFEST);
const appRoutesManifestPath = path.join(distDir, APP_PATH_ROUTES_MANIFEST);
const routesManifest = JSON.parse(await fs.readFile(routesManifestPath, "utf8"));
prerenderManifest = JSON.parse(await fs.readFile(prerenderManifestPath, "utf8"));
const middlewareManifest = JSON.parse(await fs.readFile(middlewareManifestPath, "utf8").catch(()=>"{}"));
const pagesManifest = JSON.parse(await fs.readFile(pagesManifestPath, "utf8"));
const appRoutesManifest = JSON.parse(await fs.readFile(appRoutesManifestPath, "utf8").catch(()=>"{}"));
for (const key of Object.keys(pagesManifest)){
// ensure the non-locale version is in the set
if (opts.config.i18n) {
pageFiles.add(normalizeLocalePath(key, opts.config.i18n.locales).pathname);
} else {
pageFiles.add(key);
}
}
for (const key of Object.keys(appRoutesManifest)){
appFiles.add(appRoutesManifest[key]);
}
const escapedBuildId = escapeStringRegexp(buildId);
for (const route of routesManifest.dataRoutes){
if (isDynamicRoute(route.page)) {
const routeRegex = getRouteRegex(route.page);
dynamicRoutes.push({
...route,
regex: routeRegex.re.toString(),
match: getRouteMatcher({
// TODO: fix this in the manifest itself, must also be fixed in
// upstream builder that relies on this
re: opts.config.i18n ? new RegExp(route.dataRouteRegex.replace(`/${escapedBuildId}/`, `/${escapedBuildId}/(?<nextLocale>[^/]+?)/`)) : new RegExp(route.dataRouteRegex),
groups: routeRegex.groups
})
});
}
nextDataRoutes.add(route.page);
}
for (const route of routesManifest.dynamicRoutes){
dynamicRoutes.push({
...route,
match: getRouteMatcher(getRouteRegex(route.page))
});
}
if ((_middlewareManifest_middleware = middlewareManifest.middleware) == null ? void 0 : (_middlewareManifest_middleware_ = _middlewareManifest_middleware["/"]) == null ? void 0 : _middlewareManifest_middleware_.matchers) {
var _middlewareManifest_middleware_1, _middlewareManifest_middleware1;
middlewareMatcher = getMiddlewareRouteMatcher((_middlewareManifest_middleware1 = middlewareManifest.middleware) == null ? void 0 : (_middlewareManifest_middleware_1 = _middlewareManifest_middleware1["/"]) == null ? void 0 : _middlewareManifest_middleware_1.matchers);
}
customRoutes = {
redirects: routesManifest.redirects,
rewrites: routesManifest.rewrites ? Array.isArray(routesManifest.rewrites) ? {
beforeFiles: [],
afterFiles: routesManifest.rewrites,
fallback: []
} : routesManifest.rewrites : {
beforeFiles: [],
afterFiles: [],
fallback: []
},
headers: routesManifest.headers
};
} else {
// dev handling
customRoutes = await loadCustomRoutes(opts.config);
prerenderManifest = {
version: 4,
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: {
previewModeId: require("crypto").randomBytes(16).toString("hex"),
previewModeSigningKey: require("crypto").randomBytes(32).toString("hex"),
previewModeEncryptionKey: require("crypto").randomBytes(32).toString("hex")
}
};
}
const headers = customRoutes.headers.map((item)=>buildCustomRoute("header", item, opts.config.basePath, opts.config.experimental.caseSensitiveRoutes));
const redirects = customRoutes.redirects.map((item)=>buildCustomRoute("redirect", item, opts.config.basePath, opts.config.experimental.caseSensitiveRoutes));
const rewrites = {
// TODO: add interception routes generateInterceptionRoutesRewrites()
beforeFiles: customRoutes.rewrites.beforeFiles.map((item)=>buildCustomRoute("before_files_rewrite", item)),
afterFiles: customRoutes.rewrites.afterFiles.map((item)=>buildCustomRoute("rewrite", item, opts.config.basePath, opts.config.experimental.caseSensitiveRoutes)),
fallback: customRoutes.rewrites.fallback.map((item)=>buildCustomRoute("rewrite", item, opts.config.basePath, opts.config.experimental.caseSensitiveRoutes))
};
const { i18n } = opts.config;
const handleLocale = (pathname, locales)=>{
let locale;
if (i18n) {
const i18nResult = normalizeLocalePath(pathname, locales || i18n.locales);
pathname = i18nResult.pathname;
locale = i18nResult.detectedLocale;
}
return {
locale,
pathname
};
};
debug("nextDataRoutes", nextDataRoutes);
debug("dynamicRoutes", dynamicRoutes);
debug("pageFiles", pageFiles);
debug("appFiles", appFiles);
let ensureFn;
return {
headers,
rewrites,
redirects,
buildId,
handleLocale,
appFiles,
pageFiles,
dynamicRoutes,
nextDataRoutes,
interceptionRoutes: undefined,
devVirtualFsItems: new Set(),
prerenderManifest,
middlewareMatcher: middlewareMatcher,
ensureCallback (fn) {
ensureFn = fn;
},
async getItem (itemPath) {
const originalItemPath = itemPath;
const itemKey = originalItemPath;
const lruResult = getItemsLru == null ? void 0 : getItemsLru.get(itemKey);
if (lruResult) {
return lruResult;
}
// handle minimal mode case with .rsc output path (this is
// mostly for testings)
if (opts.minimalMode && itemPath.endsWith(".rsc")) {
itemPath = itemPath.substring(0, itemPath.length - ".rsc".length);
}
const { basePath } = opts.config;
if (basePath && !pathHasPrefix(itemPath, basePath)) {
return null;
}
itemPath = removePathPrefix(itemPath, basePath) || "/";
if (itemPath !== "/" && itemPath.endsWith("/")) {
itemPath = itemPath.substring(0, itemPath.length - 1);
}
let decodedItemPath = itemPath;
try {
decodedItemPath = decodeURIComponent(itemPath);
} catch {}
if (itemPath === "/_next/image") {
return {
itemPath,
type: "nextImage"
};
}
const itemsToCheck = [
[
this.devVirtualFsItems,
"devVirtualFsItem"
],
[
nextStaticFolderItems,
"nextStaticFolder"
],
[
legacyStaticFolderItems,
"legacyStaticFolder"
],
[
publicFolderItems,
"publicFolder"
],
[
appFiles,
"appFile"
],
[
pageFiles,
"pageFile"
]
];
for (let [items, type] of itemsToCheck){
let locale;
let curItemPath = itemPath;
let curDecodedItemPath = decodedItemPath;
const isDynamicOutput = type === "pageFile" || type === "appFile";
if (i18n) {
const localeResult = handleLocale(itemPath, // legacy behavior allows visiting static assets under
// default locale but no other locale
isDynamicOutput ? undefined : [
i18n == null ? void 0 : i18n.defaultLocale
]);
if (localeResult.pathname !== curItemPath) {
curItemPath = localeResult.pathname;
locale = localeResult.locale;
try {
curDecodedItemPath = decodeURIComponent(curItemPath);
} catch {}
}
}
if (type === "legacyStaticFolder") {
if (!pathHasPrefix(curItemPath, "/static")) {
continue;
}
curItemPath = curItemPath.substring("/static".length);
try {
curDecodedItemPath = decodeURIComponent(curItemPath);
} catch {}
}
if (type === "nextStaticFolder" && !pathHasPrefix(curItemPath, "/_next/static")) {
continue;
}
const nextDataPrefix = `/_next/data/${buildId}/`;
if (type === "pageFile" && curItemPath.startsWith(nextDataPrefix) && curItemPath.endsWith(".json")) {
items = nextDataRoutes;
// remove _next/data/<build-id> prefix
curItemPath = curItemPath.substring(nextDataPrefix.length - 1);
// remove .json postfix
curItemPath = curItemPath.substring(0, curItemPath.length - ".json".length);
const curLocaleResult = handleLocale(curItemPath);
curItemPath = curLocaleResult.pathname === "/index" ? "/" : curLocaleResult.pathname;
locale = curLocaleResult.locale;
try {
curDecodedItemPath = decodeURIComponent(curItemPath);
} catch {}
}
// check decoded variant as well
if (!items.has(curItemPath) && !opts.dev) {
curItemPath = curDecodedItemPath;
}
const matchedItem = items.has(curItemPath);
if (matchedItem || opts.dev) {
let fsPath;
let itemsRoot;
switch(type){
case "nextStaticFolder":
{
itemsRoot = nextStaticFolderPath;
curItemPath = curItemPath.substring("/_next/static".length);
break;
}
case "legacyStaticFolder":
{
itemsRoot = legacyStaticFolderPath;
break;
}
case "publicFolder":
{
itemsRoot = publicFolderPath;
break;
}
default:
{
break;
}
}
if (itemsRoot && curItemPath) {
fsPath = path.posix.join(itemsRoot, curItemPath);
}
// dynamically check fs in development so we don't
// have to wait on the watcher
if (!matchedItem && opts.dev) {
const isStaticAsset = [
"nextStaticFolder",
"publicFolder",
"legacyStaticFolder"
].includes(type);
if (isStaticAsset && itemsRoot) {
let found = fsPath && await fileExists(fsPath, FileType.File);
if (!found) {
try {
// In dev, we ensure encoded paths match
// decoded paths on the filesystem so check
// that variation as well
const tempItemPath = decodeURIComponent(curItemPath);
fsPath = path.posix.join(itemsRoot, tempItemPath);
found = await fileExists(fsPath, FileType.File);
} catch {}
if (!found) {
continue;
}
}
} else if (type === "pageFile" || type === "appFile") {
var _ensureFn;
const isAppFile = type === "appFile";
if (ensureFn && await ((_ensureFn = ensureFn({
type,
itemPath: isAppFile ? normalizeMetadataRoute(curItemPath) : curItemPath
})) == null ? void 0 : _ensureFn.catch(()=>"ENSURE_FAILED")) === "ENSURE_FAILED") {
continue;
}
} else {
continue;
}
}
// i18n locales aren't matched for app dir
if (type === "appFile" && locale && locale !== (i18n == null ? void 0 : i18n.defaultLocale)) {
continue;
}
const itemResult = {
type,
fsPath,
locale,
itemsRoot,
itemPath: curItemPath
};
getItemsLru == null ? void 0 : getItemsLru.set(itemKey, itemResult);
return itemResult;
}
}
getItemsLru == null ? void 0 : getItemsLru.set(itemKey, null);
return null;
},
getDynamicRoutes () {
// this should include data routes
return this.dynamicRoutes;
},
getMiddlewareMatchers () {
return this.middlewareMatcher;
}
};
}
//# sourceMappingURL=filesystem.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,93 @@
import url from "url";
import { stringifyQuery } from "../../server-route-utils";
export async function proxyRequest(req, res, parsedUrl, upgradeHead, reqBody, proxyTimeout) {
const { query } = parsedUrl;
delete parsedUrl.query;
parsedUrl.search = stringifyQuery(req, query);
const target = url.format(parsedUrl);
const HttpProxy = require("next/dist/compiled/http-proxy");
const proxy = new HttpProxy({
target,
changeOrigin: true,
ignorePath: true,
xfwd: true,
ws: true,
// we limit proxy requests to 30s by default, in development
// we don't time out WebSocket requests to allow proxying
proxyTimeout: proxyTimeout === null ? undefined : proxyTimeout || 30000
});
await new Promise((proxyResolve, proxyReject)=>{
let finished = false;
// http-proxy does not properly detect a client disconnect in newer
// versions of Node.js. This is caused because it only listens for the
// `aborted` event on the our request object, but it also fully reads
// and closes the request object. Node **will not** fire `aborted` when
// the request is already closed. Listening for `close` on our response
// object will detect the disconnect, and we can abort the proxy's
// connection.
proxy.on("proxyReq", (proxyReq)=>{
res.on("close", ()=>proxyReq.destroy());
});
proxy.on("proxyRes", (proxyRes)=>{
if (res.destroyed) {
proxyRes.destroy();
} else {
res.on("close", ()=>proxyRes.destroy());
}
});
proxy.on("proxyRes", (proxyRes, innerReq, innerRes)=>{
const cleanup = (err)=>{
// cleanup event listeners to allow clean garbage collection
proxyRes.removeListener("error", cleanup);
proxyRes.removeListener("close", cleanup);
innerRes.removeListener("error", cleanup);
innerRes.removeListener("close", cleanup);
// destroy all source streams to propagate the caught event backward
innerReq.destroy(err);
proxyRes.destroy(err);
};
proxyRes.once("error", cleanup);
proxyRes.once("close", cleanup);
innerRes.once("error", cleanup);
innerRes.once("close", cleanup);
});
proxy.on("error", (err)=>{
console.error(`Failed to proxy ${target}`, err);
if (!finished) {
finished = true;
proxyReject(err);
if (!res.destroyed) {
res.statusCode = 500;
res.end("Internal Server Error");
}
}
});
// if upgrade head is present treat as WebSocket request
if (upgradeHead) {
proxy.on("proxyReqWs", (proxyReq)=>{
proxyReq.on("close", ()=>{
if (!finished) {
finished = true;
proxyResolve(true);
}
});
});
proxy.ws(req, res, upgradeHead);
proxyResolve(true);
} else {
proxy.on("proxyReq", (proxyReq)=>{
proxyReq.on("close", ()=>{
if (!finished) {
finished = true;
proxyResolve(true);
}
});
});
proxy.web(req, res, {
buffer: reqBody
});
}
});
}
//# sourceMappingURL=proxy-request.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/router-utils/proxy-request.ts"],"names":["url","stringifyQuery","proxyRequest","req","res","parsedUrl","upgradeHead","reqBody","proxyTimeout","query","search","target","format","HttpProxy","require","proxy","changeOrigin","ignorePath","xfwd","ws","undefined","Promise","proxyResolve","proxyReject","finished","on","proxyReq","destroy","proxyRes","destroyed","innerReq","innerRes","cleanup","err","removeListener","once","console","error","statusCode","end","web","buffer"],"mappings":"AAGA,OAAOA,SAAS,MAAK;AACrB,SAASC,cAAc,QAAQ,2BAA0B;AAEzD,OAAO,eAAeC,aACpBC,GAAoB,EACpBC,GAAmB,EACnBC,SAAiC,EACjCC,WAAiB,EACjBC,OAAa,EACbC,YAA4B;IAE5B,MAAM,EAAEC,KAAK,EAAE,GAAGJ;IAClB,OAAO,AAACA,UAAkBI,KAAK;IAC/BJ,UAAUK,MAAM,GAAGT,eAAeE,KAAYM;IAE9C,MAAME,SAASX,IAAIY,MAAM,CAACP;IAC1B,MAAMQ,YACJC,QAAQ;IAEV,MAAMC,QAAQ,IAAIF,UAAU;QAC1BF;QACAK,cAAc;QACdC,YAAY;QACZC,MAAM;QACNC,IAAI;QACJ,4DAA4D;QAC5D,yDAAyD;QACzDX,cAAcA,iBAAiB,OAAOY,YAAYZ,gBAAgB;IACpE;IAEA,MAAM,IAAIa,QAAQ,CAACC,cAAcC;QAC/B,IAAIC,WAAW;QAEf,mEAAmE;QACnE,sEAAsE;QACtE,qEAAqE;QACrE,uEAAuE;QACvE,uEAAuE;QACvE,kEAAkE;QAClE,cAAc;QACdT,MAAMU,EAAE,CAAC,YAAY,CAACC;YACpBtB,IAAIqB,EAAE,CAAC,SAAS,IAAMC,SAASC,OAAO;QACxC;QACAZ,MAAMU,EAAE,CAAC,YAAY,CAACG;YACpB,IAAIxB,IAAIyB,SAAS,EAAE;gBACjBD,SAASD,OAAO;YAClB,OAAO;gBACLvB,IAAIqB,EAAE,CAAC,SAAS,IAAMG,SAASD,OAAO;YACxC;QACF;QAEAZ,MAAMU,EAAE,CAAC,YAAY,CAACG,UAAUE,UAAUC;YACxC,MAAMC,UAAU,CAACC;gBACf,4DAA4D;gBAC5DL,SAASM,cAAc,CAAC,SAASF;gBACjCJ,SAASM,cAAc,CAAC,SAASF;gBACjCD,SAASG,cAAc,CAAC,SAASF;gBACjCD,SAASG,cAAc,CAAC,SAASF;gBAEjC,oEAAoE;gBACpEF,SAASH,OAAO,CAACM;gBACjBL,SAASD,OAAO,CAACM;YACnB;YAEAL,SAASO,IAAI,CAAC,SAASH;YACvBJ,SAASO,IAAI,CAAC,SAASH;YACvBD,SAASI,IAAI,CAAC,SAASH;YACvBD,SAASI,IAAI,CAAC,SAASH;QACzB;QAEAjB,MAAMU,EAAE,CAAC,SAAS,CAACQ;YACjBG,QAAQC,KAAK,CAAC,CAAC,gBAAgB,EAAE1B,OAAO,CAAC,EAAEsB;YAC3C,IAAI,CAACT,UAAU;gBACbA,WAAW;gBACXD,YAAYU;gBAEZ,IAAI,CAAC7B,IAAIyB,SAAS,EAAE;oBAClBzB,IAAIkC,UAAU,GAAG;oBACjBlC,IAAImC,GAAG,CAAC;gBACV;YACF;QACF;QAEA,wDAAwD;QACxD,IAAIjC,aAAa;YACfS,MAAMU,EAAE,CAAC,cAAc,CAACC;gBACtBA,SAASD,EAAE,CAAC,SAAS;oBACnB,IAAI,CAACD,UAAU;wBACbA,WAAW;wBACXF,aAAa;oBACf;gBACF;YACF;YACAP,MAAMI,EAAE,CAAChB,KAA+BC,KAAKE;YAC7CgB,aAAa;QACf,OAAO;YACLP,MAAMU,EAAE,CAAC,YAAY,CAACC;gBACpBA,SAASD,EAAE,CAAC,SAAS;oBACnB,IAAI,CAACD,UAAU;wBACbA,WAAW;wBACXF,aAAa;oBACf;gBACF;YACF;YACAP,MAAMyB,GAAG,CAACrC,KAAKC,KAAK;gBAClBqC,QAAQlC;YACV;QACF;IACF;AACF"}

View File

@@ -0,0 +1,515 @@
import url from "url";
import setupDebug from "next/dist/compiled/debug";
import { getCloneableBody } from "../../body-streams";
import { filterReqHeaders, ipcForbiddenHeaders } from "../server-ipc/utils";
import { stringifyQuery } from "../../server-route-utils";
import { formatHostname } from "../format-hostname";
import { toNodeOutgoingHttpHeaders } from "../../web/utils";
import { isAbortError } from "../../pipe-readable";
import { getHostname } from "../../../shared/lib/get-hostname";
import { getRedirectStatus } from "../../../lib/redirect-status";
import { normalizeRepeatedSlashes } from "../../../shared/lib/utils";
import { relativizeURL } from "../../../shared/lib/router/utils/relativize-url";
import { addPathPrefix } from "../../../shared/lib/router/utils/add-path-prefix";
import { pathHasPrefix } from "../../../shared/lib/router/utils/path-has-prefix";
import { detectDomainLocale } from "../../../shared/lib/i18n/detect-domain-locale";
import { normalizeLocalePath } from "../../../shared/lib/i18n/normalize-locale-path";
import { removePathPrefix } from "../../../shared/lib/router/utils/remove-path-prefix";
import { addRequestMeta } from "../../request-meta";
import { compileNonPath, matchHas, prepareDestination } from "../../../shared/lib/router/utils/prepare-destination";
import { createRequestResponseMocks } from "../mock-request";
import "../../node-polyfill-web-streams";
const debug = setupDebug("next:router-server:resolve-routes");
export function getResolveRoutes(fsChecker, config, opts, renderWorkers, renderWorkerOpts, ensureMiddleware) {
const routes = [
// _next/data with middleware handling
{
match: ()=>({}),
name: "middleware_next_data"
},
...opts.minimalMode ? [] : fsChecker.headers,
...opts.minimalMode ? [] : fsChecker.redirects,
// check middleware (using matchers)
{
match: ()=>({}),
name: "middleware"
},
...opts.minimalMode ? [] : fsChecker.rewrites.beforeFiles,
// check middleware (using matchers)
{
match: ()=>({}),
name: "before_files_end"
},
// we check exact matches on fs before continuing to
// after files rewrites
{
match: ()=>({}),
name: "check_fs"
},
...opts.minimalMode ? [] : fsChecker.rewrites.afterFiles,
// we always do the check: true handling before continuing to
// fallback rewrites
{
check: true,
match: ()=>({}),
name: "after files check: true"
},
...opts.minimalMode ? [] : fsChecker.rewrites.fallback
];
async function resolveRoutes({ req, res, isUpgradeReq, invokedOutputs }) {
var _this;
let finished = false;
let resHeaders = {};
let matchedOutput = null;
let parsedUrl = url.parse(req.url || "", true);
let didRewrite = false;
const urlParts = (req.url || "").split("?");
const urlNoQuery = urlParts[0];
// this normalizes repeated slashes in the path e.g. hello//world ->
// hello/world or backslashes to forward slashes, this does not
// handle trailing slash as that is handled the same as a next.config.js
// redirect
if (urlNoQuery == null ? void 0 : urlNoQuery.match(/(\\|\/\/)/)) {
parsedUrl = url.parse(normalizeRepeatedSlashes(req.url), true);
return {
parsedUrl,
resHeaders,
finished: true,
statusCode: 308
};
}
// TODO: inherit this from higher up
const protocol = ((_this = req == null ? void 0 : req.socket) == null ? void 0 : _this.encrypted) || req.headers["x-forwarded-proto"] === "https" ? "https" : "http";
// When there are hostname and port we build an absolute URL
const initUrl = config.experimental.trustHostHeader ? `https://${req.headers.host || "localhost"}${req.url}` : opts.port ? `${protocol}://${formatHostname(opts.hostname || "localhost")}:${opts.port}${req.url}` : req.url || "";
addRequestMeta(req, "__NEXT_INIT_URL", initUrl);
addRequestMeta(req, "__NEXT_INIT_QUERY", {
...parsedUrl.query
});
addRequestMeta(req, "_protocol", protocol);
if (!isUpgradeReq) {
addRequestMeta(req, "__NEXT_CLONABLE_BODY", getCloneableBody(req));
}
const maybeAddTrailingSlash = (pathname)=>{
if (config.trailingSlash && !config.skipMiddlewareUrlNormalize && !pathname.endsWith("/")) {
return `${pathname}/`;
}
return pathname;
};
let domainLocale;
let defaultLocale;
let initialLocaleResult = undefined;
if (config.i18n) {
var _parsedUrl_pathname;
const hadTrailingSlash = (_parsedUrl_pathname = parsedUrl.pathname) == null ? void 0 : _parsedUrl_pathname.endsWith("/");
const hadBasePath = pathHasPrefix(parsedUrl.pathname || "", config.basePath);
initialLocaleResult = normalizeLocalePath(removePathPrefix(parsedUrl.pathname || "/", config.basePath), config.i18n.locales);
domainLocale = detectDomainLocale(config.i18n.domains, getHostname(parsedUrl, req.headers));
defaultLocale = (domainLocale == null ? void 0 : domainLocale.defaultLocale) || config.i18n.defaultLocale;
parsedUrl.query.__nextDefaultLocale = defaultLocale;
parsedUrl.query.__nextLocale = initialLocaleResult.detectedLocale || defaultLocale;
// ensure locale is present for resolving routes
if (!initialLocaleResult.detectedLocale && !initialLocaleResult.pathname.startsWith("/_next/")) {
parsedUrl.pathname = addPathPrefix(initialLocaleResult.pathname === "/" ? `/${defaultLocale}` : addPathPrefix(initialLocaleResult.pathname || "", `/${defaultLocale}`), hadBasePath ? config.basePath : "");
if (hadTrailingSlash) {
parsedUrl.pathname = maybeAddTrailingSlash(parsedUrl.pathname);
}
}
}
const checkLocaleApi = (pathname)=>{
if (config.i18n && pathname === urlNoQuery && (initialLocaleResult == null ? void 0 : initialLocaleResult.detectedLocale) && pathHasPrefix(initialLocaleResult.pathname, "/api")) {
return true;
}
};
async function checkTrue() {
const pathname = parsedUrl.pathname || "";
if (checkLocaleApi(pathname)) {
return;
}
if (!(invokedOutputs == null ? void 0 : invokedOutputs.has(pathname))) {
const output = await fsChecker.getItem(pathname);
if (output) {
if (config.useFileSystemPublicRoutes || didRewrite || output.type !== "appFile" && output.type !== "pageFile") {
return output;
}
}
}
const dynamicRoutes = fsChecker.getDynamicRoutes();
let curPathname = parsedUrl.pathname;
if (config.basePath) {
if (!pathHasPrefix(curPathname || "", config.basePath)) {
return;
}
curPathname = (curPathname == null ? void 0 : curPathname.substring(config.basePath.length)) || "/";
}
const localeResult = fsChecker.handleLocale(curPathname || "");
for (const route of dynamicRoutes){
// when resolving fallback: false the
// render worker may return a no-fallback response
// which signals we need to continue resolving.
// TODO: optimize this to collect static paths
// to use at the routing layer
if (invokedOutputs == null ? void 0 : invokedOutputs.has(route.page)) {
continue;
}
const params = route.match(localeResult.pathname);
if (params) {
const pageOutput = await fsChecker.getItem(addPathPrefix(route.page, config.basePath || ""));
// i18n locales aren't matched for app dir
if ((pageOutput == null ? void 0 : pageOutput.type) === "appFile" && (initialLocaleResult == null ? void 0 : initialLocaleResult.detectedLocale)) {
continue;
}
if (pageOutput && (curPathname == null ? void 0 : curPathname.startsWith("/_next/data"))) {
parsedUrl.query.__nextDataReq = "1";
}
if (config.useFileSystemPublicRoutes || didRewrite) {
return pageOutput;
}
}
}
}
async function handleRoute(route) {
let curPathname = parsedUrl.pathname || "/";
if (config.i18n && route.internal) {
const hadTrailingSlash = curPathname.endsWith("/");
if (config.basePath) {
curPathname = removePathPrefix(curPathname, config.basePath);
}
const hadBasePath = curPathname !== parsedUrl.pathname;
const localeResult = normalizeLocalePath(curPathname, config.i18n.locales);
const isDefaultLocale = localeResult.detectedLocale === defaultLocale;
if (isDefaultLocale) {
curPathname = localeResult.pathname === "/" && hadBasePath ? config.basePath : addPathPrefix(localeResult.pathname, hadBasePath ? config.basePath : "");
} else if (hadBasePath) {
curPathname = curPathname === "/" ? config.basePath : addPathPrefix(curPathname, config.basePath);
}
if ((isDefaultLocale || hadBasePath) && hadTrailingSlash) {
curPathname = maybeAddTrailingSlash(curPathname);
}
}
let params = route.match(curPathname);
if ((route.has || route.missing) && params) {
const hasParams = matchHas(req, parsedUrl.query, route.has, route.missing);
if (hasParams) {
Object.assign(params, hasParams);
} else {
params = false;
}
}
if (params) {
if (fsChecker.interceptionRoutes && route.name === "before_files_end") {
for (const interceptionRoute of fsChecker.interceptionRoutes){
const result = await handleRoute(interceptionRoute);
if (result) {
return result;
}
}
}
if (route.name === "middleware_next_data") {
var _fsChecker_getMiddlewareMatchers;
if ((_fsChecker_getMiddlewareMatchers = fsChecker.getMiddlewareMatchers()) == null ? void 0 : _fsChecker_getMiddlewareMatchers.length) {
var _parsedUrl_pathname;
const nextDataPrefix = addPathPrefix(`/_next/data/${fsChecker.buildId}/`, config.basePath);
if (((_parsedUrl_pathname = parsedUrl.pathname) == null ? void 0 : _parsedUrl_pathname.startsWith(nextDataPrefix)) && parsedUrl.pathname.endsWith(".json")) {
parsedUrl.query.__nextDataReq = "1";
parsedUrl.pathname = parsedUrl.pathname.substring(nextDataPrefix.length - 1);
parsedUrl.pathname = parsedUrl.pathname.substring(0, parsedUrl.pathname.length - ".json".length);
parsedUrl.pathname = addPathPrefix(parsedUrl.pathname || "", config.basePath);
parsedUrl.pathname = parsedUrl.pathname === "/index" ? "/" : parsedUrl.pathname;
parsedUrl.pathname = maybeAddTrailingSlash(parsedUrl.pathname);
}
}
}
if (route.name === "check_fs") {
const pathname = parsedUrl.pathname || "";
if ((invokedOutputs == null ? void 0 : invokedOutputs.has(pathname)) || checkLocaleApi(pathname)) {
return;
}
const output = await fsChecker.getItem(pathname);
if (output && !(config.i18n && (initialLocaleResult == null ? void 0 : initialLocaleResult.detectedLocale) && pathHasPrefix(pathname, "/api"))) {
if (config.useFileSystemPublicRoutes || didRewrite || output.type !== "appFile" && output.type !== "pageFile") {
matchedOutput = output;
if (output.locale) {
parsedUrl.query.__nextLocale = output.locale;
}
return {
parsedUrl,
resHeaders,
finished: true,
matchedOutput
};
}
}
}
if (!opts.minimalMode && route.name === "middleware") {
const match = fsChecker.getMiddlewareMatchers();
if (// @ts-expect-error BaseNextRequest stuff
(match == null ? void 0 : match(parsedUrl.pathname, req, parsedUrl.query)) && (!ensureMiddleware || await (ensureMiddleware == null ? void 0 : ensureMiddleware().then(()=>true).catch(()=>false)))) {
var _this;
const workerResult = await ((_this = renderWorkers.app || renderWorkers.pages) == null ? void 0 : _this.initialize(renderWorkerOpts));
if (!workerResult) {
throw new Error(`Failed to initialize render worker "middleware"`);
}
const invokeHeaders = {
"x-invoke-path": "",
"x-invoke-query": "",
"x-invoke-output": "",
"x-middleware-invoke": "1"
};
Object.assign(req.headers, invokeHeaders);
debug("invoking middleware", req.url, invokeHeaders);
let middlewareRes = undefined;
let bodyStream = undefined;
try {
var _renderWorkers_pages;
let readableController;
const { res: mockedRes } = await createRequestResponseMocks({
url: req.url || "/",
method: req.method || "GET",
headers: filterReqHeaders(invokeHeaders, ipcForbiddenHeaders),
resWriter (chunk) {
readableController.enqueue(Buffer.from(chunk));
return true;
}
});
const initResult = await ((_renderWorkers_pages = renderWorkers.pages) == null ? void 0 : _renderWorkers_pages.initialize(renderWorkerOpts));
mockedRes.on("close", ()=>{
readableController.close();
});
try {
await (initResult == null ? void 0 : initResult.requestHandler(req, res, parsedUrl));
} catch (err) {
if (!("result" in err) || !("response" in err.result)) {
throw err;
}
middlewareRes = err.result.response;
res.statusCode = middlewareRes.status;
if (middlewareRes.body) {
bodyStream = middlewareRes.body;
} else if (middlewareRes.status) {
bodyStream = new ReadableStream({
start (controller) {
controller.enqueue("");
controller.close();
}
});
}
}
} catch (e) {
// If the client aborts before we can receive a response object
// (when the headers are flushed), then we can early exit without
// further processing.
if (isAbortError(e)) {
return {
parsedUrl,
resHeaders,
finished: true
};
}
throw e;
}
if (res.closed || res.finished || !middlewareRes) {
return {
parsedUrl,
resHeaders,
finished: true
};
}
const middlewareHeaders = toNodeOutgoingHttpHeaders(middlewareRes.headers);
debug("middleware res", middlewareRes.status, middlewareHeaders);
if (middlewareHeaders["x-middleware-override-headers"]) {
const overriddenHeaders = new Set();
let overrideHeaders = middlewareHeaders["x-middleware-override-headers"];
if (typeof overrideHeaders === "string") {
overrideHeaders = overrideHeaders.split(",");
}
for (const key of overrideHeaders){
overriddenHeaders.add(key.trim());
}
delete middlewareHeaders["x-middleware-override-headers"];
// Delete headers.
for (const key of Object.keys(req.headers)){
if (!overriddenHeaders.has(key)) {
delete req.headers[key];
}
}
// Update or add headers.
for (const key of overriddenHeaders.keys()){
const valueKey = "x-middleware-request-" + key;
const newValue = middlewareHeaders[valueKey];
const oldValue = req.headers[key];
if (oldValue !== newValue) {
req.headers[key] = newValue === null ? undefined : newValue;
}
delete middlewareHeaders[valueKey];
}
}
if (!middlewareHeaders["x-middleware-rewrite"] && !middlewareHeaders["x-middleware-next"] && !middlewareHeaders["location"]) {
middlewareHeaders["x-middleware-refresh"] = "1";
}
delete middlewareHeaders["x-middleware-next"];
for (const [key, value] of Object.entries({
...filterReqHeaders(middlewareHeaders, ipcForbiddenHeaders)
})){
if ([
"content-length",
"x-middleware-rewrite",
"x-middleware-redirect",
"x-middleware-refresh",
"x-middleware-invoke",
"x-invoke-path",
"x-invoke-query"
].includes(key)) {
continue;
}
if (value) {
resHeaders[key] = value;
req.headers[key] = value;
}
}
if (middlewareHeaders["x-middleware-rewrite"]) {
const value = middlewareHeaders["x-middleware-rewrite"];
const rel = relativizeURL(value, initUrl);
resHeaders["x-middleware-rewrite"] = rel;
const query = parsedUrl.query;
parsedUrl = url.parse(rel, true);
if (parsedUrl.protocol) {
return {
parsedUrl,
resHeaders,
finished: true
};
}
// keep internal query state
for (const key of Object.keys(query)){
if (key.startsWith("_next") || key.startsWith("__next")) {
parsedUrl.query[key] = query[key];
}
}
if (config.i18n) {
const curLocaleResult = normalizeLocalePath(parsedUrl.pathname || "", config.i18n.locales);
if (curLocaleResult.detectedLocale) {
parsedUrl.query.__nextLocale = curLocaleResult.detectedLocale;
}
}
}
if (middlewareHeaders["location"]) {
const value = middlewareHeaders["location"];
const rel = relativizeURL(value, initUrl);
resHeaders["location"] = rel;
parsedUrl = url.parse(rel, true);
return {
parsedUrl,
resHeaders,
finished: true,
statusCode: middlewareRes.status
};
}
if (middlewareHeaders["x-middleware-refresh"]) {
return {
parsedUrl,
resHeaders,
finished: true,
bodyStream,
statusCode: middlewareRes.status
};
}
}
}
// handle redirect
if (("statusCode" in route || "permanent" in route) && route.destination) {
const { parsedDestination } = prepareDestination({
appendParamsToQuery: false,
destination: route.destination,
params: params,
query: parsedUrl.query
});
const { query } = parsedDestination;
delete parsedDestination.query;
parsedDestination.search = stringifyQuery(req, query);
parsedDestination.pathname = normalizeRepeatedSlashes(parsedDestination.pathname);
return {
finished: true,
// @ts-expect-error custom ParsedUrl
parsedUrl: parsedDestination,
statusCode: getRedirectStatus(route)
};
}
// handle headers
if (route.headers) {
const hasParams = Object.keys(params).length > 0;
for (const header of route.headers){
let { key, value } = header;
if (hasParams) {
key = compileNonPath(key, params);
value = compileNonPath(value, params);
}
if (key.toLowerCase() === "set-cookie") {
if (!Array.isArray(resHeaders[key])) {
const val = resHeaders[key];
resHeaders[key] = typeof val === "string" ? [
val
] : [];
}
resHeaders[key].push(value);
} else {
resHeaders[key] = value;
}
}
}
// handle rewrite
if (route.destination) {
const { parsedDestination } = prepareDestination({
appendParamsToQuery: true,
destination: route.destination,
params: params,
query: parsedUrl.query
});
if (parsedDestination.protocol) {
return {
// @ts-expect-error custom ParsedUrl
parsedUrl: parsedDestination,
finished: true
};
}
if (config.i18n) {
const curLocaleResult = normalizeLocalePath(removePathPrefix(parsedDestination.pathname, config.basePath), config.i18n.locales);
if (curLocaleResult.detectedLocale) {
parsedUrl.query.__nextLocale = curLocaleResult.detectedLocale;
}
}
didRewrite = true;
parsedUrl.pathname = parsedDestination.pathname;
Object.assign(parsedUrl.query, parsedDestination.query);
}
// handle check: true
if (route.check) {
const output = await checkTrue();
if (output) {
return {
parsedUrl,
resHeaders,
finished: true,
matchedOutput: output
};
}
}
}
}
for (const route of routes){
const result = await handleRoute(route);
if (result) {
return result;
}
}
return {
finished,
parsedUrl,
resHeaders,
matchedOutput
};
}
return resolveRoutes;
}
//# sourceMappingURL=resolve-routes.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { };
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/router-utils/types.ts"],"names":[],"mappings":"AAAA,WAMgB"}

View File

@@ -0,0 +1,64 @@
import { errorToJSON } from "../../render";
import crypto from "crypto";
import isError from "../../../lib/is-error";
import { deserializeErr } from "./request-utils";
// we can't use process.send as jest-worker relies on
// it already and can cause unexpected message errors
// so we create an IPC server for communicating
export async function createIpcServer(server) {
// Generate a random key in memory to validate messages from other processes.
// This is just a simple guard against other processes attempting to send
// traffic to the IPC server.
const ipcValidationKey = crypto.randomBytes(32).toString("hex");
const ipcServer = require("http").createServer(async (req, res)=>{
try {
const url = new URL(req.url || "/", "http://n");
const key = url.searchParams.get("key");
if (key !== ipcValidationKey) {
return res.end();
}
const method = url.searchParams.get("method");
const args = JSON.parse(url.searchParams.get("args") || "[]");
if (!method || !Array.isArray(args)) {
return res.end();
}
if (typeof server[method] === "function") {
var _args_;
if (method === "logErrorWithOriginalStack" && ((_args_ = args[0]) == null ? void 0 : _args_.stack)) {
args[0] = deserializeErr(args[0]);
}
let result = await server[method](...args);
if (result && typeof result === "object" && result.stack) {
result = errorToJSON(result);
}
res.end(JSON.stringify(result || ""));
}
} catch (err) {
if (isError(err) && err.code !== "ENOENT") {
console.error(err);
}
res.end(JSON.stringify({
err: {
name: err.name,
message: err.message,
stack: err.stack
}
}));
}
});
const ipcPort = await new Promise((resolveIpc)=>{
ipcServer.listen(0, server.hostname, ()=>{
const addr = ipcServer.address();
if (addr && typeof addr === "object") {
resolveIpc(addr.port);
}
});
});
return {
ipcPort,
ipcServer,
ipcValidationKey
};
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/server-ipc/index.ts"],"names":["errorToJSON","crypto","isError","deserializeErr","createIpcServer","server","ipcValidationKey","randomBytes","toString","ipcServer","require","createServer","req","res","url","URL","key","searchParams","get","end","method","args","JSON","parse","Array","isArray","stack","result","stringify","err","code","console","error","name","message","ipcPort","Promise","resolveIpc","listen","hostname","addr","address","port"],"mappings":"AACA,SAASA,WAAW,QAAQ,eAAc;AAC1C,OAAOC,YAAY,SAAQ;AAC3B,OAAOC,aAAa,wBAAuB;AAC3C,SAASC,cAAc,QAAQ,kBAAiB;AAEhD,qDAAqD;AACrD,qDAAqD;AACrD,+CAA+C;AAC/C,OAAO,eAAeC,gBACpBC,MAAuC;IAMvC,6EAA6E;IAC7E,yEAAyE;IACzE,6BAA6B;IAC7B,MAAMC,mBAAmBL,OAAOM,WAAW,CAAC,IAAIC,QAAQ,CAAC;IAEzD,MAAMC,YAAY,AAACC,QAAQ,QAAkCC,YAAY,CACvE,OAAOC,KAAKC;QACV,IAAI;YACF,MAAMC,MAAM,IAAIC,IAAIH,IAAIE,GAAG,IAAI,KAAK;YACpC,MAAME,MAAMF,IAAIG,YAAY,CA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A,OAAO;QACLP;QACA1B;QACAH;IACF;AACF"}

View File

@@ -0,0 +1,23 @@
import { filterReqHeaders, ipcForbiddenHeaders } from "./utils";
export const invokeRequest = async (targetUrl, requestInit, readableBody)=>{
const invokeHeaders = filterReqHeaders({
"cache-control": "",
...requestInit.headers
}, ipcForbiddenHeaders);
return await fetch(targetUrl, {
headers: invokeHeaders,
method: requestInit.method,
redirect: "manual",
signal: requestInit.signal,
...requestInit.method !== "GET" && requestInit.method !== "HEAD" && readableBody ? {
body: readableBody,
duplex: "half"
} : {},
next: {
// @ts-ignore
internal: true
}
});
};
//# sourceMappingURL=invoke-request.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/server-ipc/invoke-request.ts"],"names":["filterReqHeaders","ipcForbiddenHeaders","invokeRequest","targetUrl","requestInit","readableBody","invokeHeaders","headers","fetch","method","redirect","signal","body","duplex","next","internal"],"mappings":"AAEA,SAASA,gBAAgB,EAAEC,mBAAmB,QAAQ,UAAS;AAE/D,OAAO,MAAMC,gBAAgB,OAC3BC,WACAC,aAKAC;IAEA,MAAMC,gBAAgBN,iBACpB;QACE,iBAAiB;QACjB,GAAGI,YAAYG,OAAO;IACxB,GACAN;IAGF,OAAO,MAAMO,MAAML,WAAW;QAC5BI,SAASD;QACTG,QAAQL,YAAYK,MAAM;QAC1BC,UAAU;QACVC,QAAQP,YAAYO,MAAM;QAE1B,GAAIP,YAAYK,MAAM,KAAK,SAC3BL,YAAYK,MAAM,KAAK,UACvBJ,eACI;YACEO,MAAMP;YACNQ,QAAQ;QACV,IACA,CAAC,CAAC;QAENC,MAAM;YACJ,aAAa;YACbC,UAAU;QACZ;IACF;AACF,EAAC"}

View File

@@ -0,0 +1,38 @@
import { PageNotFoundError } from "../../../shared/lib/utils";
import { invokeRequest } from "./invoke-request";
export const deserializeErr = (serializedErr)=>{
if (!serializedErr || typeof serializedErr !== "object" || !serializedErr.stack) {
return serializedErr;
}
let ErrorType = Error;
if (serializedErr.name === "PageNotFoundError") {
ErrorType = PageNotFoundError;
}
const err = new ErrorType(serializedErr.message);
err.stack = serializedErr.stack;
err.name = serializedErr.name;
err.digest = serializedErr.digest;
if (process.env.NEXT_RUNTIME !== "edge") {
const { decorateServerError } = require("next/dist/compiled/@next/react-dev-overlay/dist/middleware");
decorateServerError(err, serializedErr.source || "server");
}
return err;
};
export async function invokeIpcMethod({ fetchHostname = "localhost", method, args, ipcPort, ipcKey }) {
if (ipcPort) {
const res = await invokeRequest(`http://${fetchHostname}:${ipcPort}?key=${ipcKey}&method=${method}&args=${encodeURIComponent(JSON.stringify(args))}`, {
method: "GET",
headers: {}
});
const body = await res.text();
if (body.startsWith("{") && body.endsWith("}")) {
const parsedBody = JSON.parse(body);
if (parsedBody && typeof parsedBody === "object" && "err" in parsedBody && "stack" in parsedBody.err) {
throw deserializeErr(parsedBody.err);
}
return parsedBody;
}
}
}
//# sourceMappingURL=request-utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/server-ipc/request-utils.ts"],"names":["PageNotFoundError","invokeRequest","deserializeErr","serializedErr","stack","ErrorType","Error","name","err","message","digest","process","env","NEXT_RUNTIME","decorateServerError","require","source","invokeIpcMethod","fetchHostname","method","args","ipcPort","ipcKey","res","encodeURIComponent","JSON","stringify","headers","body","text","startsWith","endsWith","parsedBody","parse"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,4BAA2B;AAC7D,SAASC,aAAa,QAAQ,mBAAkB;AAEhD,OAAO,MAAMC,iBAAiB,CAACC;IAC7B,IACE,CAACA,iBACD,OAAOA,kBAAkB,YACzB,CAACA,cAAcC,KAAK,EACpB;QACA,OAAOD;IACT;IACA,IAAIE,YAAiBC;IAErB,IAAIH,cAAcI,IAAI,KAAK,qBAAqB;QAC9CF,YAAYL;IACd;IAEA,MAAMQ,MAAM,IAAIH,UAAUF,cAAcM,OAAO;IAC/CD,IAAIJ,KAAK,GAAGD,cAAcC,KAAK;IAC/BI,IAAID,IAAI,GAAGJ,cAAcI,IAAI;IAC3BC,IAAYE,MAAM,GAAGP,cAAcO,MAAM;IAE3C,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;QACvC,MAAM,EAAEC,mBAAmB,EAAE,GAC3BC,QAAQ;QACVD,oBAAoBN,KAAKL,cAAca,MAAM,IAAI;IACnD;IACA,OAAOR;AACT,EAAC;AAED,OAAO,eAAeS,gBAAgB,EACpCC,gBAAgB,WAAW,EAC3BC,MAAM,EACNC,IAAI,EACJC,OAAO,EACPC,MAAM,EAOP;IACC,IAAID,SAAS;QACX,MAAME,MAAM,MAAMtB,cAChB,CAAC,OAAO,EAAEiB,cAAc,CAAC,EAAEG,QAAQ,KAAK,EAAEC,OAAO,QAAQ,EACvDH,OACD,MAAM,EAAEK,mBAAmBC,KAAKC,SAAS,CAACN,OAAO,CAAC,EACnD;YACED,QAAQ;YACRQ,SAAS,CAAC;QACZ;QAEF,MAAMC,OAAO,MAAML,IAAIM,IAAI;QAE3B,IAAID,KAAKE,UAAU,CAAC,QAAQF,KAAKG,QAAQ,CAAC,MAAM;YAC9C,MAAMC,aAAaP,KAAKQ,KAAK,CAACL;YAE9B,IACEI,cACA,OAAOA,eAAe,YACtB,SAASA,cACT,WAAWA,WAAWxB,GAAG,EACzB;gBACA,MAAMN,eAAe8B,WAAWxB,GAAG;YACrC;YACA,OAAOwB;QACT;IACF;AACF"}

View File

@@ -0,0 +1,30 @@
export const ipcForbiddenHeaders = [
"accept-encoding",
"keepalive",
"keep-alive",
"content-encoding",
"transfer-encoding",
// https://github.com/nodejs/undici/issues/1470
"connection",
// marked as unsupported by undici: https://github.com/nodejs/undici/blob/c83b084879fa0bb8e0469d31ec61428ac68160d5/lib/core/request.js#L354
"expect"
];
export const actionsForbiddenHeaders = [
...ipcForbiddenHeaders,
"content-length"
];
export const filterReqHeaders = (headers, forbiddenHeaders)=>{
// Some browsers are not matching spec and sending Content-Length: 0. This causes issues in undici
// https://github.com/nodejs/undici/issues/2046
if (headers["content-length"] && headers["content-length"] === "0") {
delete headers["content-length"];
}
for (const [key, value] of Object.entries(headers)){
if (forbiddenHeaders.includes(key) || !(Array.isArray(value) || typeof value === "string")) {
delete headers[key];
}
}
return headers;
};
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/server-ipc/utils.ts"],"names":["ipcForbiddenHeaders","actionsForbiddenHeaders","filterReqHeaders","headers","forbiddenHeaders","key","value","Object","entries","includes","Array","isArray"],"mappings":"AAAA,OAAO,MAAMA,sBAAsB;IACjC;IACA;IACA;IACA;IACA;IACA,+CAA+C;IAC/C;IACA,2IAA2I;IAC3I;CACD,CAAA;AAED,OAAO,MAAMC,0BAA0B;OAClCD;IACH;CACD,CAAA;AAED,OAAO,MAAME,mBAAmB,CAC9BC,SACAC;IAEA,kGAAkG;IAClG,+CAA+C;IAC/C,IAAID,OAAO,CAAC,iBAAiB,IAAIA,OAAO,CAAC,iBAAiB,KAAK,KAAK;QAClE,OAAOA,OAAO,CAAC,iBAAiB;IAClC;IAEA,KAAK,MAAM,CAACE,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACL,SAAU;QAClD,IACEC,iBAAiBK,QAAQ,CAACJ,QAC1B,CAAEK,CAAAA,MAAMC,OAAO,CAACL,UAAU,OAAOA,UAAU,QAAO,GAClD;YACA,OAAOH,OAAO,CAACE,IAAI;QACrB;IACF;IACA,OAAOF;AACT,EAAC"}

View File

@@ -0,0 +1,65 @@
import v8 from "v8";
import http from "http";
// This is required before other imports to ensure the require hook is setup.
import "../require-hook";
import "../node-polyfill-fetch";
import { warn } from "../../build/output/log";
process.on("unhandledRejection", (err)=>{
console.error(err);
});
process.on("uncaughtException", (err)=>{
console.error(err);
});
export const RESTART_EXIT_CODE = 77;
const MAXIMUM_HEAP_SIZE_ALLOWED = v8.getHeapStatistics().heap_size_limit / 1024 / 1024 * 0.9;
export async function initializeServerWorker(requestHandler, upgradeHandler, opts) {
const server = http.createServer((req, res)=>{
return requestHandler(req, res).catch((err)=>{
res.statusCode = 500;
res.end("Internal Server Error");
console.error(err);
}).finally(()=>{
if (process.memoryUsage().heapUsed / 1024 / 1024 > MAXIMUM_HEAP_SIZE_ALLOWED) {
warn("The server is running out of memory, restarting to free up memory.");
server.close();
process.exit(RESTART_EXIT_CODE);
}
});
});
if (opts.keepAliveTimeout) {
server.keepAliveTimeout = opts.keepAliveTimeout;
}
return new Promise(async (resolve, reject)=>{
server.on("error", (err)=>{
console.error(`Invariant: failed to start server worker`, err);
process.exit(1);
});
if (upgradeHandler) {
server.on("upgrade", (req, socket, upgrade)=>{
upgradeHandler(req, socket, upgrade);
});
}
let hostname = opts.hostname || "localhost";
server.on("listening", async ()=>{
try {
const addr = server.address();
const host = addr ? typeof addr === "object" ? addr.address : addr : undefined;
const port = addr && typeof addr === "object" ? addr.port : 0;
if (!port || !host) {
console.error(`Invariant failed to detect render worker host/port`, addr);
process.exit(1);
}
resolve({
server,
port,
hostname: host
});
} catch (err) {
return reject(err);
}
});
server.listen(0, hostname);
});
}
//# sourceMappingURL=setup-server-worker.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/setup-server-worker.ts"],"names":["v8","http","warn","process","on","err","console","error","RESTART_EXIT_CODE","MAXIMUM_HEAP_SIZE_ALLOWED","getHeapStatistics","heap_size_limit","initializeServerWorker","requestHandler","upgradeHandler","opts","server","createServer","req","res","catch","statusCode","end","finally","memoryUsage","heapUsed","close","exit","keepAliveTimeout","Promise","resolve","reject","socket","upgrade","hostname","addr","address","host","undefined","port","listen"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAA+C,OAAM;AAE5D,6EAA6E;AAC7E,OAAO,kBAAiB;AACxB,OAAO,yBAAwB;AAE/B,SAASC,IAAI,QAAQ,yBAAwB;AAG7CC,QAAQC,EAAE,CAAC,sBAAsB,CAACC;IAChCC,QAAQC,KAAK,CAACF;AAChB;AAEAF,QAAQC,EAAE,CAAC,qBAAqB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AQ,CAACF,MAAM;oBAClB/B,QAAQC,KAAK,CACX,CAAC,kDAAkD,CAAC,EACpD4B;oBAEFhC,QAAQwB,IAAI,CAAC;gBACf;gBAEAG,QAAQ;oBACNd;oBACAuB;oBACAL,UAAUG;gBACZ;YACF,EAAE,OAAOhC,KAAK;gBACZ,OAAO0B,OAAO1B;YAChB;QACF;QACAW,OAAOwB,MAAM,CAAC,GAAGN;IACnB;AACF"}

View File

@@ -0,0 +1,32 @@
// eslint-disable-next-line no-shadow
export const enum AVIFTune {
auto,
psnr,
ssim,
}
export interface EncodeOptions {
cqLevel: number
denoiseLevel: number
cqAlphaLevel: number
tileRowsLog2: number
tileColsLog2: number
speed: number
subsample: number
chromaDeltaQ: boolean
sharpness: number
tune: AVIFTune
}
export interface AVIFModule extends EmscriptenWasm.Module {
encode(
data: BufferSource,
width: number,
height: number,
options: EncodeOptions
): Uint8Array
}
declare var moduleFactory: EmscriptenWasm.ModuleFactory<AVIFModule>
export default moduleFactory

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

272
node_modules/next/dist/esm/server/lib/squoosh/codecs.js generated vendored Normal file
View File

@@ -0,0 +1,272 @@
import { promises as fsp } from "fs";
import * as path from "path";
import { instantiateEmscriptenWasm, pathify } from "./emscripten-utils.js";
// @ts-ignore
import mozEnc from "./mozjpeg/mozjpeg_node_enc.js";
const mozEncWasm = path.resolve(__dirname, "./mozjpeg/mozjpeg_node_enc.wasm");
// @ts-ignore
import mozDec from "./mozjpeg/mozjpeg_node_dec.js";
const mozDecWasm = path.resolve(__dirname, "./mozjpeg/mozjpeg_node_dec.wasm");
// @ts-ignore
import webpEnc from "./webp/webp_node_enc.js";
const webpEncWasm = path.resolve(__dirname, "./webp/webp_node_enc.wasm");
// @ts-ignore
import webpDec from "./webp/webp_node_dec.js";
const webpDecWasm = path.resolve(__dirname, "./webp/webp_node_dec.wasm");
// @ts-ignore
import avifEnc from "./avif/avif_node_enc.js";
const avifEncWasm = path.resolve(__dirname, "./avif/avif_node_enc.wasm");
// @ts-ignore
import avifDec from "./avif/avif_node_dec.js";
const avifDecWasm = path.resolve(__dirname, "./avif/avif_node_dec.wasm");
// PNG
// @ts-ignore
import * as pngEncDec from "./png/squoosh_png.js";
const pngEncDecWasm = path.resolve(__dirname, "./png/squoosh_png_bg.wasm");
const pngEncDecInit = ()=>pngEncDec.default(fsp.readFile(pathify(pngEncDecWasm)));
// OxiPNG
// @ts-ignore
import * as oxipng from "./png/squoosh_oxipng.js";
const oxipngWasm = path.resolve(__dirname, "./png/squoosh_oxipng_bg.wasm");
const oxipngInit = ()=>oxipng.default(fsp.readFile(pathify(oxipngWasm)));
// Resize
// @ts-ignore
import * as resize from "./resize/squoosh_resize.js";
const resizeWasm = path.resolve(__dirname, "./resize/squoosh_resize_bg.wasm");
const resizeInit = ()=>resize.default(fsp.readFile(pathify(resizeWasm)));
// rotate
const rotateWasm = path.resolve(__dirname, "./rotate/rotate.wasm");
// Our decoders currently rely on a `ImageData` global.
import ImageData from "./image_data";
globalThis.ImageData = ImageData;
function resizeNameToIndex(name) {
switch(name){
case "triangle":
return 0;
case "catrom":
return 1;
case "mitchell":
return 2;
case "lanczos3":
return 3;
default:
throw Error(`Unknown resize algorithm "${name}"`);
}
}
function resizeWithAspect({ input_width, input_height, target_width, target_height }) {
if (!target_width && !target_height) {
throw Error("Need to specify at least width or height when resizing");
}
if (target_width && target_height) {
return {
width: target_width,
height: target_height
};
}
if (!target_width) {
return {
width: Math.round(input_width / input_height * target_height),
height: target_height
};
}
return {
width: target_width,
height: Math.round(input_height / input_width * target_width)
};
}
export const preprocessors = {
resize: {
name: "Resize",
description: "Resize the image before compressing",
instantiate: async ()=>{
await resizeInit();
return (buffer, input_width, input_height, { width, height, method, premultiply, linearRGB })=>{
({ width, height } = resizeWithAspect({
input_width,
input_height,
target_width: width,
target_height: height
}));
const imageData = new ImageData(resize.resize(buffer, input_width, input_height, width, height, resizeNameToIndex(method), premultiply, linearRGB), width, height);
resize.cleanup();
return imageData;
};
},
defaultOptions: {
method: "lanczos3",
fitMethod: "stretch",
premultiply: true,
linearRGB: true
}
},
rotate: {
name: "Rotate",
description: "Rotate image",
instantiate: async ()=>{
return async (buffer, width, height, { numRotations })=>{
const degrees = numRotations * 90 % 360;
const sameDimensions = degrees === 0 || degrees === 180;
const size = width * height * 4;
const instance = (await WebAssembly.instantiate(await fsp.readFile(pathify(rotateWasm)))).instance;
const { memory } = instance.exports;
const additionalPagesNeeded = Math.ceil((size * 2 - memory.buffer.byteLength + 8) / (64 * 1024));
if (additionalPagesNeeded > 0) {
memory.grow(additionalPagesNeeded);
}
const view = new Uint8ClampedArray(memory.buffer);
view.set(buffer, 8);
instance.exports.rotate(width, height, degrees);
return new ImageData(view.slice(size + 8, size * 2 + 8), sameDimensions ? width : height, sameDimensions ? height : width);
};
},
defaultOptions: {
numRotations: 0
}
}
};
export const codecs = {
mozjpeg: {
name: "MozJPEG",
extension: "jpg",
detectors: [
/^\xFF\xD8\xFF/
],
dec: ()=>instantiateEmscriptenWasm(mozDec, mozDecWasm),
enc: ()=>instantiateEmscriptenWasm(mozEnc, mozEncWasm),
defaultEncoderOptions: {
quality: 75,
baseline: false,
arithmetic: false,
progressive: true,
optimize_coding: true,
smoothing: 0,
color_space: 3 /*YCbCr*/ ,
quant_table: 3,
trellis_multipass: false,
trellis_opt_zero: false,
trellis_opt_table: false,
trellis_loops: 1,
auto_subsample: true,
chroma_subsample: 2,
separate_chroma_quality: false,
chroma_quality: 75
},
autoOptimize: {
option: "quality",
min: 0,
max: 100
}
},
webp: {
name: "WebP",
extension: "webp",
detectors: [
/^RIFF....WEBPVP8[LX ]/s
],
dec: ()=>instantiateEmscriptenWasm(webpDec, webpDecWasm),
enc: ()=>instantiateEmscriptenWasm(webpEnc, webpEncWasm),
defaultEncoderOptions: {
quality: 75,
target_size: 0,
target_PSNR: 0,
method: 4,
sns_strength: 50,
filter_strength: 60,
filter_sharpness: 0,
filter_type: 1,
partitions: 0,
segments: 4,
pass: 1,
show_compressed: 0,
preprocessing: 0,
autofilter: 0,
partition_limit: 0,
alpha_compression: 1,
alpha_filtering: 1,
alpha_quality: 100,
lossless: 0,
exact: 0,
image_hint: 0,
emulate_jpeg_size: 0,
thread_level: 0,
low_memory: 0,
near_lossless: 100,
use_delta_palette: 0,
use_sharp_yuv: 0
},
autoOptimize: {
option: "quality",
min: 0,
max: 100
}
},
avif: {
name: "AVIF",
extension: "avif",
// eslint-disable-next-line no-control-regex
detectors: [
/^\x00\x00\x00 ftypavif\x00\x00\x00\x00/
],
dec: ()=>instantiateEmscriptenWasm(avifDec, avifDecWasm),
enc: async ()=>{
return instantiateEmscriptenWasm(avifEnc, avifEncWasm);
},
defaultEncoderOptions: {
cqLevel: 33,
cqAlphaLevel: -1,
denoiseLevel: 0,
tileColsLog2: 0,
tileRowsLog2: 0,
speed: 6,
subsample: 1,
chromaDeltaQ: false,
sharpness: 0,
tune: 0 /* AVIFTune.auto */
},
autoOptimize: {
option: "cqLevel",
min: 62,
max: 0
}
},
oxipng: {
name: "OxiPNG",
extension: "png",
// eslint-disable-next-line no-control-regex
detectors: [
/^\x89PNG\x0D\x0A\x1A\x0A/
],
dec: async ()=>{
await pngEncDecInit();
return {
decode: (buffer)=>{
const imageData = pngEncDec.decode(buffer);
pngEncDec.cleanup();
return imageData;
}
};
},
enc: async ()=>{
await pngEncDecInit();
await oxipngInit();
return {
encode: (buffer, width, height, opts)=>{
const simplePng = pngEncDec.encode(new Uint8Array(buffer), width, height);
const imageData = oxipng.optimise(simplePng, opts.level, false);
oxipng.cleanup();
return imageData;
}
};
},
defaultEncoderOptions: {
level: 2
},
autoOptimize: {
option: "level",
min: 6,
max: 1
}
}
};
//# sourceMappingURL=codecs.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,121 @@
// These types roughly model the object that the JS files generated by Emscripten define. Copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/emscripten/index.d.ts and turned into a type definition rather than a global to support our way of using Emscripten.
declare namespace EmscriptenWasm {
type ModuleFactory<T extends Module = Module> = (
moduleOverrides?: ModuleOpts
) => Promise<T>
type EnvironmentType = 'WEB' | 'NODE' | 'SHELL' | 'WORKER'
// Options object for modularized Emscripten files. Shoe-horned by @surma.
// FIXME: This an incomplete definition!
interface ModuleOpts {
mainScriptUrlOrBlob?: string
noInitialRun?: boolean
locateFile?: (url: string) => string
onRuntimeInitialized?: () => void
}
interface Module {
print(str: string): void
printErr(str: string): void
arguments: string[]
environment: EnvironmentType
preInit: { (): void }[]
preRun: { (): void }[]
postRun: { (): void }[]
preinitializedWebGLContext: WebGLRenderingContext
noInitialRun: boolean
noExitRuntime: boolean
logReadFiles: boolean
filePackagePrefixURL: string
wasmBinary: ArrayBuffer
destroy(object: object): void
getPreloadedPackage(
remotePackageName: string,
remotePackageSize: number
): ArrayBuffer
instantiateWasm(
imports: WebAssembly.Imports,
successCallback: (module: WebAssembly.Module) => void
): WebAssembly.Exports
locateFile(url: string): string
onCustomMessage(event: MessageEvent): void
Runtime: any
ccall(
ident: string,
returnType: string | null,
argTypes: string[],
args: any[]
): any
cwrap(ident: string, returnType: string | null, argTypes: string[]): any
setValue(ptr: number, value: any, type: string, noSafe?: boolean): void
getValue(ptr: number, type: string, noSafe?: boolean): number
ALLOC_NORMAL: number
ALLOC_STACK: number
ALLOC_STATIC: number
ALLOC_DYNAMIC: number
ALLOC_NONE: number
allocate(slab: any, types: string, allocator: number, ptr: number): number
allocate(slab: any, types: string[], allocator: number, ptr: number): number
Pointer_stringify(ptr: number, length?: number): string
UTF16ToString(ptr: number): string
stringToUTF16(str: string, outPtr: number): void
UTF32ToString(ptr: number): string
stringToUTF32(str: string, outPtr: number): void
// USE_TYPED_ARRAYS == 1
HEAP: Int32Array
IHEAP: Int32Array
FHEAP: Float64Array
// USE_TYPED_ARRAYS == 2
HEAP8: Int8Array
HEAP16: Int16Array
HEAP32: Int32Array
HEAPU8: Uint8Array
HEAPU16: Uint16Array
HEAPU32: Uint32Array
HEAPF32: Float32Array
HEAPF64: Float64Array
TOTAL_STACK: number
TOTAL_MEMORY: number
FAST_MEMORY: number
addOnPreRun(cb: () => any): void
addOnInit(cb: () => any): void
addOnPreMain(cb: () => any): void
addOnExit(cb: () => any): void
addOnPostRun(cb: () => any): void
// Tools
intArrayFromString(
stringy: string,
dontAddNull?: boolean,
length?: number
): number[]
intArrayToString(array: number[]): string
writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void
writeArrayToMemory(array: number[], buffer: number): void
writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void
addRunDependency(id: any): void
removeRunDependency(id: any): void
preloadedImages: any
preloadedAudios: any
_malloc(size: number): number
_free(ptr: number): void
// Augmentations below by @surma.
onRuntimeInitialized: () => void | null
}
}

View File

@@ -0,0 +1,22 @@
import { fileURLToPath } from "url";
export function pathify(path) {
if (path.startsWith("file://")) {
path = fileURLToPath(path);
}
return path;
}
export function instantiateEmscriptenWasm(factory, path, workerJS = "") {
return factory({
locateFile (requestPath) {
// The glue code generated by emscripten uses the original
// file names of the worker file and the wasm binary.
// These will have changed in the bundling process and
// we need to inject them here.
if (requestPath.endsWith(".wasm")) return pathify(path);
if (requestPath.endsWith(".worker.js")) return pathify(workerJS);
return requestPath;
}
});
}
//# sourceMappingURL=emscripten-utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/squoosh/emscripten-utils.ts"],"names":["fileURLToPath","pathify","path","startsWith","instantiateEmscriptenWasm","factory","workerJS","locateFile","requestPath","endsWith"],"mappings":"AAAA,SAASA,aAAa,QAAQ,MAAK;AAEnC,OAAO,SAASC,QAAQC,IAAY;IAClC,IAAIA,KAAKC,UAAU,CAAC,YAAY;QAC9BD,OAAOF,cAAcE;IACvB;IACA,OAAOA;AACT;AAEA,OAAO,SAASE,0BACdC,OAAwC,EACxCH,IAAY,EACZI,WAAmB,EAAE;IAErB,OAAOD,QAAQ;QACbE,YAAWC,WAAW;YACpB,0DAA0D;YAC1D,qDAAqD;YACrD,sDAAsD;YACtD,+BAA+B;YAC/B,IAAIA,YAAYC,QAAQ,CAAC,UAAU,OAAOR,QAAQC;YAClD,IAAIM,YAAYC,QAAQ,CAAC,eAAe,OAAOR,QAAQK;YACvD,OAAOE;QACT;IACF;AACF"}

View File

@@ -0,0 +1,21 @@
export default class ImageData {
static from(input) {
return new ImageData(input.data || input._data, input.width, input.height);
}
get data() {
if (Object.prototype.toString.call(this._data) === "[object Object]") {
return Buffer.from(Object.values(this._data));
}
if (this._data instanceof Buffer || this._data instanceof Uint8Array || this._data instanceof Uint8ClampedArray) {
return Buffer.from(this._data);
}
throw new Error("invariant");
}
constructor(data, width, height){
this._data = data;
this.width = width;
this.height = height;
}
}
//# sourceMappingURL=image_data.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/squoosh/image_data.ts"],"names":["ImageData","from","input","data","_data","width","height","Object","prototype","toString","call","Buffer","values","Uint8Array","Uint8ClampedArray","Error","constructor"],"mappings":"AAAA,eAAe,MAAMA;IACnB,OAAOC,KAAKC,KAAgB,EAAa;QACvC,OAAO,IAAIF,UAAUE,MAAMC,IAAI,IAAID,MAAME,KAAK,EAAEF,MAAMG,KAAK,EAAEH,MAAMI,MAAM;IAC3E;IAMA,IAAIH,OAAe;QACjB,IAAII,OAAOC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAAC,IAAI,CAACN,KAAK,MAAM,mBAAmB;YACpE,OAAOO,OAAOV,IAAI,CAACM,OAAOK,MAAM,CAAC,IAAI,CAACR,KAAK;QAC7C;QACA,IACE,IAAI,CAACA,KAAK,YAAYO,UACtB,IAAI,CAACP,KAAK,YAAYS,cACtB,IAAI,CAACT,KAAK,YAAYU,mBACtB;YACA,OAAOH,OAAOV,IAAI,CAAC,IAAI,CAACG,KAAK;QAC/B;QACA,MAAM,IAAIW,MAAM;IAClB;IAEAC,YACEb,IAA6C,EAC7CE,KAAa,EACbC,MAAc,CACd;QACA,IAAI,CAACF,KAAK,GAAGD;QACb,IAAI,CAACE,KAAK,GAAGA;QACb,IAAI,CAACC,MAAM,GAAGA;IAChB;AACF"}

77
node_modules/next/dist/esm/server/lib/squoosh/impl.js generated vendored Normal file
View File

@@ -0,0 +1,77 @@
import { codecs as supportedFormats, preprocessors } from "./codecs";
import ImageData from "./image_data";
export async function decodeBuffer(_buffer) {
var _Object_entries_find;
const buffer = Buffer.from(_buffer);
const firstChunk = buffer.slice(0, 16);
const firstChunkString = Array.from(firstChunk).map((v)=>String.fromCodePoint(v)).join("");
const key = (_Object_entries_find = Object.entries(supportedFormats).find(([, { detectors }])=>detectors.some((detector)=>detector.exec(firstChunkString)))) == null ? void 0 : _Object_entries_find[0];
if (!key) {
throw Error(`Buffer has an unsupported format`);
}
const encoder = supportedFormats[key];
const mod = await encoder.dec();
const rgba = mod.decode(new Uint8Array(buffer));
return rgba;
}
export async function rotate(image, numRotations) {
image = ImageData.from(image);
const m = await preprocessors["rotate"].instantiate();
return await m(image.data, image.width, image.height, {
numRotations
});
}
export async function resize({ image, width, height }) {
image = ImageData.from(image);
const p = preprocessors["resize"];
const m = await p.instantiate();
return await m(image.data, image.width, image.height, {
...p.defaultOptions,
width,
height
});
}
export async function encodeJpeg(image, { quality }) {
image = ImageData.from(image);
const e = supportedFormats["mozjpeg"];
const m = await e.enc();
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
quality
});
return Buffer.from(r);
}
export async function encodeWebp(image, { quality }) {
image = ImageData.from(image);
const e = supportedFormats["webp"];
const m = await e.enc();
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
quality
});
return Buffer.from(r);
}
export async function encodeAvif(image, { quality }) {
image = ImageData.from(image);
const e = supportedFormats["avif"];
const m = await e.enc();
const val = e.autoOptimize.min || 62;
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions,
// Think of cqLevel as the "amount" of quantization (0 to 62),
// so a lower value yields higher quality (0 to 100).
cqLevel: Math.round(val - quality / 100 * val)
});
return Buffer.from(r);
}
export async function encodePng(image) {
image = ImageData.from(image);
const e = supportedFormats["oxipng"];
const m = await e.enc();
const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions
});
return Buffer.from(r);
}
//# sourceMappingURL=impl.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/squoosh/impl.ts"],"names":["codecs","supportedFormats","preprocessors","ImageData","decodeBuffer","_buffer","Object","buffer","Buffer","from","firstChunk","slice","firstChunkString","Array","map","v","String","fromCodePoint","join","key","entries","find","detectors","some","detector","exec","Error","encoder","mod","dec","rgba","decode","Uint8Array","rotate","image","numRotations","m","instantiate","data","width","height","resize","p","defaultOptions","encodeJpeg","quality","e","enc","r","encode","defaultEncoderOptions","encodeWebp","encodeAvif","val","autoOptimize","min","cqLevel","Math","round","encodePng"],"mappings":"AAAA,SAASA,UAAUC,gBAAgB,EAAEC,aAAa,QAAQ,WAAU;AACpE,OAAOC,eAAe,eAAc;AAIpC,OAAO,eAAeC,aACpBC,OAA4B;QAOhBC;IALZ,MAAMC,SAASC,OAAOC,IAAI,CAACJ;IAC3B,MAAMK,aAAaH,OAAOI,KAAK,CAAC,GAAG;IACnC,MAAMC,mBAAmBC,MAAMJ,IAAI,CAACC,YACjCI,GAAG,CAAC,CAACC,IAAMC,OAAOC,aAAa,CAACF,IAChCG,IAAI,CAAC;IACR,MAAMC,OAAMb,uBAAAA,OAAOc,OAAO,CAACnB,kBAAkBoB,IAAI,CAAC,CAAC,GAAG,EAAEC,SAAS,EAAE,CAAC,GAClEA,UAAUC,IAAI,CAAC,CAACC,WAAaA,SAASC,IAAI,CAACb,wCADjCN,oBAET,CAAC,EAAE;IACN,IAAI,CAACa,KAAK;QACR,MAAMO,MAAM,CAAC,gCAAgC,CAAC;IAChD;IACA,MAAMC,UAAU1B,gBAAgB,CAACkB,IAAI;IACrC,MAAMS,MAAM,MAAMD,QAAQE,GAAG;IAC7B,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AAMZ,EAAEa,MAAM,CAACf,MAAMI,IAAI,EAAEJ,MAAMK,KAAK,EAAEL,MAAMM,MAAM,EAAE;QAC9D,GAAGM,EAAEI,qBAAqB;QAC1BL;IACF;IACA,OAAOrC,OAAOC,IAAI,CAACuC;AACrB;AAEA,OAAO,eAAeI,WACpBlB,KAAgB,EAChB,EAAEW,OAAO,EAAuB;IAEhCX,QAAQ/B,UAAUM,IAAI,CAACyB;IAEvB,MAAMY,IAAI7C,gBAAgB,CAAC,OAAO;IAClC,MAAMmC,IAAI,MAAMU,EAAEC,GAAG;IACrB,MAAMM,MAAMP,EAAEQ,YAAY,CAACC,GAAG,IAAI;IAClC,MAAMP,IAAI,MAAMZ,EAAEa,MAAM,CAACf,MAAMI,IAAI,EAAEJ,MAAMK,KAAK,EAAEL,MAAMM,MAAM,EAAE;QAC9D,GAAGM,EAAEI,qBAAqB;QAC1B,8DAA8D;QAC9D,qDAAqD;QACrDM,SAASC,KAAKC,KAAK,CAACL,MAAM,AAACR,UAAU,MAAOQ;IAC9C;IACA,OAAO7C,OAAOC,IAAI,CAACuC;AACrB;AAEA,OAAO,eAAeW,UACpBzB,KAAgB;IAEhBA,QAAQ/B,UAAUM,IAAI,CAACyB;IAEvB,MAAMY,IAAI7C,gBAAgB,CAAC,SAAS;IACpC,MAAMmC,IAAI,MAAMU,EAAEC,GAAG;IACrB,MAAMC,IAAI,MAAMZ,EAAEa,MAAM,CAACf,MAAMI,IAAI,EAAEJ,MAAMK,KAAK,EAAEL,MAAMM,MAAM,EAAE;QAC9D,GAAGM,EAAEI,qBAAqB;IAC5B;IACA,OAAO1C,OAAOC,IAAI,CAACuC;AACrB"}

69
node_modules/next/dist/esm/server/lib/squoosh/main.js generated vendored Normal file
View File

@@ -0,0 +1,69 @@
import { Worker } from "next/dist/compiled/jest-worker";
import * as path from "path";
import { execOnce } from "../../../shared/lib/utils";
import { cpus } from "os";
const getWorker = execOnce(()=>new Worker(path.resolve(__dirname, "impl"), {
enableWorkerThreads: true,
// There will be at most 6 workers needed since each worker will take
// at least 1 operation type.
numWorkers: Math.max(1, Math.min(cpus().length - 1, 6)),
computeWorkerKey: (method)=>method
}));
export async function getMetadata(buffer) {
const worker = getWorker();
const { width, height } = await worker.decodeBuffer(buffer);
return {
width,
height
};
}
export async function processBuffer(buffer, operations, encoding, quality) {
const worker = getWorker();
let imageData = await worker.decodeBuffer(buffer);
for (const operation of operations){
if (operation.type === "rotate") {
imageData = await worker.rotate(imageData, operation.numRotations);
} else if (operation.type === "resize") {
const opt = {
image: imageData,
width: 0,
height: 0
};
if (operation.width && imageData.width && imageData.width > operation.width) {
opt.width = operation.width;
}
if (operation.height && imageData.height && imageData.height > operation.height) {
opt.height = operation.height;
}
if (opt.width > 0 || opt.height > 0) {
imageData = await worker.resize(opt);
}
}
}
switch(encoding){
case "jpeg":
return Buffer.from(await worker.encodeJpeg(imageData, {
quality
}));
case "webp":
return Buffer.from(await worker.encodeWebp(imageData, {
quality
}));
case "avif":
const avifQuality = quality - 20;
return Buffer.from(await worker.encodeAvif(imageData, {
quality: Math.max(avifQuality, 0)
}));
case "png":
return Buffer.from(await worker.encodePng(imageData));
default:
throw Error(`Unsupported encoding format`);
}
}
export async function decodeBuffer(buffer) {
const worker = getWorker();
const imageData = await worker.decodeBuffer(buffer);
return imageData;
}
//# sourceMappingURL=main.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/squoosh/main.ts"],"names":["Worker","path","execOnce","cpus","getWorker","resolve","__dirname","enableWorkerThreads","numWorkers","Math","max","min","length","computeWorkerKey","method","getMetadata","buffer","worker","width","height","decodeBuffer","processBuffer","operations","encoding","quality","imageData","operation","type","rotate","numRotations","opt","image","resize","Buffer","from","encodeJpeg","encodeWebp","avifQuality","encodeAvif","encodePng","Error"],"mappings":"AAAA,SAASA,MAAM,QAAQ,iCAAgC;AACvD,YAAYC,UAAU,OAAM;AAC5B,SAASC,QAAQ,QAAQ,4BAA2B;AACpD,SAASC,IAAI,QAA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AAQP;QACN,KAAK;YACH,OAAOU,OAAOC,IAAI,CAAC,MAAMjB,OAAOkB,UAAU,CAACV,WAAW;gBAAED;YAAQ;QAClE,KAAK;YACH,OAAOS,OAAOC,IAAI,CAAC,MAAMjB,OAAOmB,UAAU,CAACX,WAAW;gBAAED;YAAQ;QAClE,KAAK;YACH,MAAMa,cAAcb,UAAU;YAC9B,OAAOS,OAAOC,IAAI,CAChB,MAAMjB,OAAOqB,UAAU,CAACb,WAAW;gBACjCD,SAASf,KAAKC,GAAG,CAAC2B,aAAa;YACjC;QAEJ,KAAK;YACH,OAAOJ,OAAOC,IAAI,CAAC,MAAMjB,OAAOsB,SAAS,CAACd;QAC5C;YACE,MAAMe,MAAM,CAAC,2BAA2B,CAAC;IAC7C;AACF;AAEA,OAAO,eAAepB,aAAaJ,MAAc;IAC/C,MAAMC,SAAkCb;IACxC,MAAMqB,YAAY,MAAMR,OAAOG,YAAY,CAACJ;IAC5C,OAAOS;AACT"}

View File

@@ -0,0 +1,38 @@
// eslint-disable-next-line no-shadow
export const enum MozJpegColorSpace {
GRAYSCALE = 1,
RGB,
YCbCr,
}
export interface EncodeOptions {
quality: number
baseline: boolean
arithmetic: boolean
progressive: boolean
optimize_coding: boolean
smoothing: number
color_space: MozJpegColorSpace
quant_table: number
trellis_multipass: boolean
trellis_opt_zero: boolean
trellis_opt_table: boolean
trellis_loops: number
auto_subsample: boolean
chroma_subsample: number
separate_chroma_quality: boolean
chroma_quality: number
}
export interface MozJPEGModule extends EmscriptenWasm.Module {
encode(
data: BufferSource,
width: number,
height: number,
options: EncodeOptions
): Uint8Array
}
declare var moduleFactory: EmscriptenWasm.ModuleFactory<MozJPEGModule>
export default moduleFactory

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,95 @@
let wasm;
let cachedTextDecoder = new TextDecoder("utf-8", {
ignoreBOM: true,
fatal: true
});
cachedTextDecoder.decode();
let cachegetUint8Memory0 = null;
function getUint8Memory0() {
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachegetUint8Memory0;
}
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
let WASM_VECTOR_LEN = 0;
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1);
getUint8Memory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
function getArrayU8FromWasm0(ptr, len) {
return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len);
}
/**
* @param {Uint8Array} data
* @param {number} level
* @param {boolean} interlace
* @returns {Uint8Array}
*/ export function optimise(data, level, interlace) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
var ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
wasm.optimise(retptr, ptr0, len0, level, interlace);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getArrayU8FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 1);
return v1;
} finally{
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
async function load(module, imports) {
if (typeof Response === "function" && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === "function") {
return await WebAssembly.instantiateStreaming(module, imports);
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return {
instance,
module
};
} else {
return instance;
}
}
}
async function init(input) {
const imports = {};
imports.wbg = {};
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
if (typeof input === "string" || typeof Request === "function" && input instanceof Request || typeof URL === "function" && input instanceof URL) {
input = fetch(input);
}
const { instance, module } = await load(await input, imports);
wasm = instance.exports;
init.__wbindgen_wasm_module = module;
return wasm;
}
export default init;
// Manually remove the wasm and memory references to trigger GC
export function cleanup() {
wasm = null;
cachegetUint8Memory0 = null;
cachegetInt32Memory0 = null;
}
//# sourceMappingURL=squoosh_oxipng.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/server/lib/squoosh/png/squoosh_oxipng.js"],"names":["wasm","cachedTextDecoder","TextDecoder","ignoreBOM","fatal","decode","cachegetUint8Memory0","getUint8Memory0","buffer","memory","Uint8Array","getStringFromWasm0","ptr","len","subarray","WASM_VECTOR_LEN","passArray8ToWasm0","arg","malloc","length","set","cachegetInt32Memory0","getInt32Memory0","Int32Array","getArrayU8FromWasm0","optimise","data","level","interlace","retptr","__wbindgen_add_to_stack_pointer","ptr0","__wbindgen_malloc","len0","r0","r1","v1","slice","__wbindgen_free","load","module","imports","Response","WebAssembly","instantiateStreaming","bytes","arrayBuffer","instantiate","instance","Instance","init","input","wbg","__wbindgen_throw","arg0","arg1","Error","Request","URL","fetch","exports","__wbindgen_wasm_module","cleanup"],"mappings":"AAAA,IAAIA;AAEJ,IAAIC,oBAAoB,IAAIC,YAAY,SAAS;IAC/CC,WAAW;IACXC,OAAO;AACT;AAEAH,kBAAkBI,MAAM;AAExB,IAAIC,uBAAuB;AAC3B,SAASC;IACP,IACED,yBAAyB,QACzBA,qBAAqBE,MAAM,KAAKR,KAAKS,MAAM,CAACD,MAAM,EAClD;QACAF,uBAAuB,IAAII,WAAWV,KAAKS,MAAM,CAACD,MAAM;IAC1D;IACA,OAAOF;AACT;AAEA,SAASK,mBAAmBC,GAAG,EAAEC,GAAG;IAClC,OAAOZ,kBAAkBI,MAAM,CAACE,kBAAkBO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D,YAAYC,oBAAoB,CAACJ,QAAQC;QACxD;QAEA,MAAMI,QAAQ,MAAML,OAAOM,WAAW;QACtC,OAAO,MAAMH,YAAYI,WAAW,CAACF,OAAOJ;IAC9C,OAAO;QACL,MAAMO,WAAW,MAAML,YAAYI,WAAW,CAACP,QAAQC;QAEvD,IAAIO,oBAAoBL,YAAYM,QAAQ,EAAE;YAC5C,OAAO;gBAAED;gBAAUR;YAAO;QAC5B,OAAO;YACL,OAAOQ;QACT;IACF;AACF;AAEA,eAAeE,KAAKC,KAAK;IACvB,MAAMV,UAAU,CAAC;IACjBA,QAAQW,GAAG,GAAG,CAAC;IACfX,QAAQW,GAAG,CAACC,gBAAgB,GAAG,SAAUC,IAAI,EAAEC,IAAI;QACjD,MAAM,IAAIC,MAAM7C,mBAAmB2C,MAAMC;IAC3C;IAEA,IACE,OAAOJ,UAAU,YAChB,OAAOM,YAAY,cAAcN,iBAAiBM,WAClD,OAAOC,QAAQ,cAAcP,iBAAiBO,KAC/C;QACAP,QAAQQ,MAAMR;IAChB;IAEA,MAAM,EAAEH,QAAQ,EAAER,MAAM,EAAE,GAAG,MAAMD,KAAK,MAAMY,OAAOV;IAErDzC,OAAOgD,SAASY,OAAO;IACvBV,KAAKW,sBAAsB,GAAGrB;IAE9B,OAAOxC;AACT;AAEA,eAAekD,KAAI;AAEnB,+DAA+D;AAC/D,OAAO,SAASY;IACd9D,OAAO;IACPM,uBAAuB;IACvBe,uBAAuB;AACzB"}

View File

@@ -0,0 +1,144 @@
let wasm;
let cachedTextDecoder = new TextDecoder("utf-8", {
ignoreBOM: true,
fatal: true
});
cachedTextDecoder.decode();
let cachegetUint8Memory0 = null;
function getUint8Memory0() {
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachegetUint8Memory0;
}
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
let cachegetUint8ClampedMemory0 = null;
function getUint8ClampedMemory0() {
if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {
cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);
}
return cachegetUint8ClampedMemory0;
}
function getClampedArrayU8FromWasm0(ptr, len) {
return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);
}
const heap = new Array(32).fill(undefined);
heap.push(undefined, null, true, false);
let heap_next = heap.length;
function addHeapObject(obj) {
if (heap_next === heap.length) heap.push(heap.length + 1);
const idx = heap_next;
heap_next = heap[idx];
heap[idx] = obj;
return idx;
}
let WASM_VECTOR_LEN = 0;
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1);
getUint8Memory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
function getArrayU8FromWasm0(ptr, len) {
return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len);
}
/**
* @param {Uint8Array} data
* @param {number} width
* @param {number} height
* @returns {Uint8Array}
*/ export function encode(data, width, height) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
var ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
wasm.encode(retptr, ptr0, len0, width, height);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getArrayU8FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 1);
return v1;
} finally{
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
function getObject(idx) {
return heap[idx];
}
function dropObject(idx) {
if (idx < 36) return;
heap[idx] = heap_next;
heap_next = idx;
}
function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return ret;
}
/**
* @param {Uint8Array} data
* @returns {ImageData}
*/ export function decode(data) {
var ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
var ret = wasm.decode(ptr0, len0);
return takeObject(ret);
}
async function load(module, imports) {
if (typeof Response === "function" && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === "function") {
return await WebAssembly.instantiateStreaming(module, imports);
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return {
instance,
module
};
} else {
return instance;
}
}
}
async function init(input) {
const imports = {};
imports.wbg = {};
imports.wbg.__wbg_newwithownedu8clampedarrayandsh_787b2db8ea6bfd62 = function(arg0, arg1, arg2, arg3) {
var v0 = getClampedArrayU8FromWasm0(arg0, arg1).slice();
wasm.__wbindgen_free(arg0, arg1 * 1);
var ret = new ImageData(v0, arg2 >>> 0, arg3 >>> 0);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
if (typeof input === "string" || typeof Request === "function" && input instanceof Request || typeof URL === "function" && input instanceof URL) {
input = fetch(input);
}
const { instance, module } = await load(await input, imports);
wasm = instance.exports;
init.__wbindgen_wasm_module = module;
return wasm;
}
export default init;
// Manually remove the wasm and memory references to trigger GC
export function cleanup() {
wasm = null;
cachegetUint8ClampedMemory0 = null;
cachegetUint8Memory0 = null;
cachegetInt32Memory0 = null;
}
//# sourceMappingURL=squoosh_png.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/server/lib/squoosh/png/squoosh_png.js"],"names":["wasm","cachedTextDecoder","TextDecoder","ignoreBOM","fatal","decode","cachegetUint8Memory0","getUint8Memory0","buffer","memory","Uint8Array","getStringFromWasm0","ptr","len","subarray","cachegetUint8ClampedMemory0","getUint8ClampedMemory0","Uint8ClampedArray","getClampedArrayU8FromWasm0","heap","Array","fill","undefined","push","heap_next","length","addHeapObject","obj","idx","WASM_VECTOR_LEN","passArray8ToWasm0","arg","malloc","set","cachegetInt32Memory0","getInt32Memory0","Int32Array","getArrayU8FromWasm0","encode","data","width","height","retptr","__wbindgen_add_to_stack_pointer","ptr0","__wbindgen_malloc","len0","r0","r1","v1","slice","__wbindgen_free","getObject","dropObject","takeObject","ret","load","module","imports","Response","WebAssembly","instantiateStreaming","bytes","arrayBuffer","instantiate","instance","Instance","init","input","wbg","__wbg_newwithownedu8clampedarrayandsh_787b2db8ea6bfd62","arg0","arg1","arg2","arg3","v0","ImageData","__wbindgen_throw","Error","Request","URL","fetch","exports","__wbindgen_wasm_module","cleanup"],"mappings":"AAAA,IAAIA;AAEJ,IAAIC,oBAAoB,IAAIC,YAAY,SAAS;IAC/CC,WAAW;IACXC,OAAO;AACT;AAEAH,kBAAkBI,MAAM;AAExB,IAAIC,uBAAuB;AAC3B,SAASC;IACP,IACED,yBAAyB,QACzBA,qBAAqBE,MAAM,KAAKR,KAAKS,MAAM,CAACD,MAAM,EAClD;QACAF,uBAAuB,IAAII,WAAWV,KAAKS,MAAM,CAACD,MAAM;IAC1D;IACA,OAAOF;AACT;AAEA,SAASK,mBAAmBC,GAAG,EAAEC,GAAG;IAClC,OAAOZ,kBAAkBI,MAAM,CAACE,kBAAkBO,QAAQ,CAACF,KAAKA,MAAMC;AACxE;AAEA,IAAIE,8BAA8B;AAClC,SAASC;IACP,IACED,gCAAgC,QAChCA,4BAA4BP,MAAM,KAAKR,KAAKS,MAAM,CAACD,MAAM,EACzD;QACAO,8BAA8B,IAAIE,kBAAkBjB,KAAKS,MAAM,CAACD,MAAM;IACxE;IACA,OAAOO;AACT;AAEA,SAASG,2BAA2BN,GAAG,EAAEC,GAAG;IAC1C,OAAOG,yBAAyBF,QAAQ,CAACF,MAAM,GAAGA,MAAM,IAAIC;AAC9D;AAEA,MAAMM,OAAO,IAAIC,MAA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I;QAC9B,IAAIC,KAAKzD,2BAA2BqD,MAAMC,MAAMtB,KAAK;QACrDlD,KAAKmD,eAAe,CAACoB,MAAMC,OAAO;QAClC,IAAIjB,MAAM,IAAIqB,UAAUD,IAAIF,SAAS,GAAGC,SAAS;QACjD,OAAOhD,cAAc6B;IACvB;IACFG,QAAQW,GAAG,CAACQ,gBAAgB,GAAG,SAAUN,IAAI,EAAEC,IAAI;QACjD,MAAM,IAAIM,MAAMnE,mBAAmB4D,MAAMC;IAC3C;IAEA,IACE,OAAOJ,UAAU,YAChB,OAAOW,YAAY,cAAcX,iBAAiBW,WAClD,OAAOC,QAAQ,cAAcZ,iBAAiBY,KAC/C;QACAZ,QAAQa,MAAMb;IAChB;IAEA,MAAM,EAAEH,QAAQ,EAAER,MAAM,EAAE,GAAG,MAAMD,KAAK,MAAMY,OAAOV;IAErD1D,OAAOiE,SAASiB,OAAO;IACvBf,KAAKgB,sBAAsB,GAAG1B;IAE9B,OAAOzD;AACT;AAEA,eAAemE,KAAI;AAEnB,+DAA+D;AAC/D,OAAO,SAASiB;IACdpF,OAAO;IACPe,8BAA8B;IAC9BT,uBAAuB;IACvB4B,uBAAuB;AACzB"}

View File

@@ -0,0 +1,95 @@
let wasm;
let cachegetUint8Memory0 = null;
function getUint8Memory0() {
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachegetUint8Memory0;
}
let WASM_VECTOR_LEN = 0;
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1);
getUint8Memory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
let cachegetUint8ClampedMemory0 = null;
function getUint8ClampedMemory0() {
if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {
cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);
}
return cachegetUint8ClampedMemory0;
}
function getClampedArrayU8FromWasm0(ptr, len) {
return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);
}
/**
* @param {Uint8Array} input_image
* @param {number} input_width
* @param {number} input_height
* @param {number} output_width
* @param {number} output_height
* @param {number} typ_idx
* @param {boolean} premultiply
* @param {boolean} color_space_conversion
* @returns {Uint8ClampedArray}
*/ export function resize(input_image, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
var ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
wasm.resize(retptr, ptr0, len0, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getClampedArrayU8FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 1);
return v1;
} finally{
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
async function load(module, imports) {
if (typeof Response === "function" && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === "function") {
return await WebAssembly.instantiateStreaming(module, imports);
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return {
instance,
module
};
} else {
return instance;
}
}
}
async function init(input) {
const imports = {};
if (typeof input === "string" || typeof Request === "function" && input instanceof Request || typeof URL === "function" && input instanceof URL) {
input = fetch(input);
}
const { instance, module } = await load(await input, imports);
wasm = instance.exports;
init.__wbindgen_wasm_module = module;
return wasm;
}
export default init;
// Manually remove the wasm and memory references to trigger GC
export function cleanup() {
wasm = null;
cachegetUint8Memory0 = null;
cachegetInt32Memory0 = null;
}
//# sourceMappingURL=squoosh_resize.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/server/lib/squoosh/resize/squoosh_resize.js"],"names":["wasm","cachegetUint8Memory0","getUint8Memory0","buffer","memory","Uint8Array","WASM_VECTOR_LEN","passArray8ToWasm0","arg","malloc","ptr","length","set","cachegetInt32Memory0","getInt32Memory0","Int32Array","cachegetUint8ClampedMemory0","getUint8ClampedMemory0","Uint8ClampedArray","getClampedArrayU8FromWasm0","len","subarray","resize","input_image","input_width","input_height","output_width","output_height","typ_idx","premultiply","color_space_conversion","retptr","__wbindgen_add_to_stack_pointer","ptr0","__wbindgen_malloc","len0","r0","r1","v1","slice","__wbindgen_free","load","module","imports","Response","WebAssembly","instantiateStreaming","bytes","arrayBuffer","instantiate","instance","Instance","init","input","Request","URL","fetch","exports","__wbindgen_wasm_module","cleanup"],"mappings":"AAAA,IAAIA;AAEJ,IAAIC,uBAAuB;AAC3B,SAASC;IACP,IACED,yBAAyB,QACzBA,qBAAqBE,MAAM,KAAKH,KAAKI,MAAM,CAACD,MAAM,EAClD;QACAF,uBAAuB,IAAII,WAAWL,KAAKI,MAAM,CAACD,MAAM;IAC1D;IACA,OAAOF;AACT;AAEA,IAAIK,kBAAkB;AAEtB,SAASC,kBAAkBC,GAAG,EAAEC,MAAM;IACpC,MAAMC,MAAMD,OAAOD,IAAIG,MAAM,GAAG;IAChCT,kBAAkBU,GAAG,CAACJ,KAAKE,MAAM;IACjCJ,kBAAkBE,IAAIG,MAAM;IAC5B,OAAOD;AACT;AAEA,IAAIG,uBAAuB;AAC3B,SAASC;IACP,IACED,yBAAyB,QACzBA,qBAAqBV,MAAM,KAAKH,KAAKI,MAAM,CAACD,MAAM,EAClD;QACAU,uBAAuB,IAAIE,WAAWf,KAAKI,MAAM,CAACD,MAAM;IAC1D;IACA,OAAOU;AACT;AAEA,IAAIG,8BAA8B;AAClC,SAASC;IACP,IACED,gCAAgC,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AEvD,IAAIO,oBAAoBL,YAAYM,QAAQ,EAAE;YAC5C,OAAO;gBAAED;gBAAUR;YAAO;QAC5B,OAAO;YACL,OAAOQ;QACT;IACF;AACF;AAEA,eAAeE,KAAKC,KAAK;IACvB,MAAMV,UAAU,CAAC;IAEjB,IACE,OAAOU,UAAU,YAChB,OAAOC,YAAY,cAAcD,iBAAiBC,WAClD,OAAOC,QAAQ,cAAcF,iBAAiBE,KAC/C;QACAF,QAAQG,MAAMH;IAChB;IAEA,MAAM,EAAEH,QAAQ,EAAER,MAAM,EAAE,GAAG,MAAMD,KAAK,MAAMY,OAAOV;IAErD3C,OAAOkD,SAASO,OAAO;IACvBL,KAAKM,sBAAsB,GAAGhB;IAE9B,OAAO1C;AACT;AAEA,eAAeoD,KAAI;AAEnB,+DAA+D;AAC/D,OAAO,SAASO;IACd3D,OAAO;IACPC,uBAAuB;IACvBY,uBAAuB;AACzB"}

View File

@@ -0,0 +1,42 @@
export interface EncodeOptions {
quality: number
target_size: number
target_PSNR: number
method: number
sns_strength: number
filter_strength: number
filter_sharpness: number
filter_type: number
partitions: number
segments: number
pass: number
show_compressed: number
preprocessing: number
autofilter: number
partition_limit: number
alpha_compression: number
alpha_filtering: number
alpha_quality: number
lossless: number
exact: number
image_hint: number
emulate_jpeg_size: number
thread_level: number
low_memory: number
near_lossless: number
use_delta_palette: number
use_sharp_yuv: number
}
export interface WebPModule extends EmscriptenWasm.Module {
encode(
data: BufferSource,
width: number,
height: number,
options: EncodeOptions
): Uint8Array
}
declare var moduleFactory: EmscriptenWasm.ModuleFactory<WebPModule>
export default moduleFactory

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

219
node_modules/next/dist/esm/server/lib/start-server.js generated vendored Normal file
View File

@@ -0,0 +1,219 @@
import "../next";
import "../node-polyfill-fetch";
import "../require-hook";
import fs from "fs";
import path from "path";
import http from "http";
import https from "https";
import Watchpack from "watchpack";
import * as Log from "../../build/output/log";
import setupDebug from "next/dist/compiled/debug";
import { getDebugPort } from "./utils";
import { formatHostname } from "./format-hostname";
import { initialize } from "./router-server";
import { RESTART_EXIT_CODE } from "./setup-server-worker";
import { checkIsNodeDebugging } from "./is-node-debugging";
import { CONFIG_FILES } from "../../shared/lib/constants";
import chalk from "../../lib/chalk";
const debug = setupDebug("next:start-server");
export async function getRequestHandlers({ dir, port, isDev, server, hostname, minimalMode, isNodeDebugging, keepAliveTimeout, experimentalTestProxy }) {
return initialize({
dir,
port,
hostname,
dev: isDev,
minimalMode,
server,
workerType: "router",
isNodeDebugging: isNodeDebugging || false,
keepAliveTimeout,
experimentalTestProxy
});
}
function logStartInfo({ networkUrl, appUrl, hostname, envInfo, expFeatureInfo, formatDurationText }) {
Log.bootstrap(chalk.bold(chalk.hex("#ad7fa8")(`${`${Log.prefixes.ready} Next.js`} ${"13.5.1"}`)));
Log.bootstrap(`- Local: ${appUrl}`);
if (hostname) {
Log.bootstrap(`- Network: ${networkUrl}`);
}
if (envInfo == null ? void 0 : envInfo.length) Log.bootstrap(`- Environments: ${envInfo.join(", ")}`);
if (expFeatureInfo == null ? void 0 : expFeatureInfo.length) {
Log.bootstrap(`- Experiments (use at your own risk):`);
// only show maximum 3 flags
for (const exp of expFeatureInfo.slice(0, 3)){
Log.bootstrap(` · ${exp}`);
}
/* ${expFeatureInfo.length - 3} more */ if (expFeatureInfo.length > 3) {
Log.bootstrap(` · ...`);
}
}
// New line after the bootstrap info
Log.info("");
Log.event(`Ready in ${formatDurationText}`);
}
export async function startServer({ dir, port, isDev, hostname, minimalMode, allowRetry, keepAliveTimeout, isExperimentalTestProxy, selfSignedCertificate, envInfo, expFeatureInfo }) {
const startServerProcessStartTime = Date.now();
let handlersReady = ()=>{};
let handlersError = ()=>{};
let handlersPromise = new Promise((resolve, reject)=>{
handlersReady = resolve;
handlersError = reject;
});
let requestHandler = async (req, res)=>{
if (handlersPromise) {
await handlersPromise;
return requestHandler(req, res);
}
throw new Error("Invariant request handler was not setup");
};
let upgradeHandler = async (req, socket, head)=>{
if (handlersPromise) {
await handlersPromise;
return upgradeHandler(req, socket, head);
}
throw new Error("Invariant upgrade handler was not setup");
};
// setup server listener as fast as possible
if (selfSignedCertificate && !isDev) {
throw new Error("Using a self signed certificate is only supported with `next dev`.");
}
async function requestListener(req, res) {
try {
if (handlersPromise) {
await handlersPromise;
handlersPromise = undefined;
}
await requestHandler(req, res);
} catch (err) {
res.statusCode = 500;
res.end("Internal Server Error");
Log.error(`Failed to handle request for ${req.url}`);
console.error(err);
}
}
const server = selfSignedCertificate ? https.createServer({
key: fs.readFileSync(selfSignedCertificate.key),
cert: fs.readFileSync(selfSignedCertificate.cert)
}, requestListener) : http.createServer(requestListener);
if (keepAliveTimeout) {
server.keepAliveTimeout = keepAliveTimeout;
}
server.on("upgrade", async (req, socket, head)=>{
try {
await upgradeHandler(req, socket, head);
} catch (err) {
socket.destroy();
Log.error(`Failed to handle request for ${req.url}`);
console.error(err);
}
});
let portRetryCount = 0;
server.on("error", (err)=>{
if (allowRetry && port && isDev && err.code === "EADDRINUSE" && portRetryCount < 10) {
Log.warn(`Port ${port} is in use, trying ${port + 1} instead.`);
port += 1;
portRetryCount += 1;
server.listen(port, hostname);
} else {
Log.error(`Failed to start server`);
console.error(err);
process.exit(1);
}
});
const isNodeDebugging = checkIsNodeDebugging();
await new Promise((resolve)=>{
server.on("listening", async ()=>{
const addr = server.address();
const actualHostname = formatHostname(typeof addr === "object" ? (addr == null ? void 0 : addr.address) || hostname || "localhost" : addr);
const formattedHostname = !hostname || actualHostname === "0.0.0.0" ? "localhost" : actualHostname === "[::]" ? "[::1]" : formatHostname(hostname);
port = typeof addr === "object" ? (addr == null ? void 0 : addr.port) || port : port;
const networkUrl = `http://${actualHostname}:${port}`;
const appUrl = `${selfSignedCertificate ? "https" : "http"}://${formattedHostname}:${port}`;
if (isNodeDebugging) {
const debugPort = getDebugPort();
Log.info(`the --inspect${isNodeDebugging === "brk" ? "-brk" : ""} option was detected, the Next.js router server should be inspected at port ${debugPort}.`);
}
// expose the main port to render workers
process.env.PORT = port + "";
try {
const cleanup = (code)=>{
debug("start-server process cleanup");
server.close();
process.exit(code ?? 0);
};
const exception = (err)=>{
// This is the render worker, we keep the process alive
console.error(err);
};
process.on("exit", cleanup);
process.on("SIGINT", cleanup);
process.on("SIGTERM", cleanup);
process.on("uncaughtException", exception);
process.on("unhandledRejection", exception);
const initResult = await getRequestHandlers({
dir,
port,
isDev,
server,
hostname,
minimalMode,
isNodeDebugging: Boolean(isNodeDebugging),
keepAliveTimeout,
experimentalTestProxy: !!isExperimentalTestProxy
});
requestHandler = initResult[0];
upgradeHandler = initResult[1];
const startServerProcessDuration = Date.now() - startServerProcessStartTime;
const formatDurationText = startServerProcessDuration > 2000 ? `${Math.round(startServerProcessDuration / 100) / 10}s` : `${startServerProcessDuration}ms`;
handlersReady();
logStartInfo({
networkUrl,
appUrl,
hostname,
envInfo,
expFeatureInfo,
formatDurationText
});
} catch (err) {
// fatal error if we can't setup
handlersError();
console.error(err);
process.exit(1);
}
resolve();
});
server.listen(port, hostname);
});
if (isDev) {
function watchConfigFiles(dirToWatch, onChange) {
const wp = new Watchpack();
wp.watch({
files: CONFIG_FILES.map((file)=>path.join(dirToWatch, file))
});
wp.on("change", onChange);
}
watchConfigFiles(dir, async (filename)=>{
if (process.env.__NEXT_DISABLE_MEMORY_WATCHER) {
Log.info(`Detected change, manual restart required due to '__NEXT_DISABLE_MEMORY_WATCHER' usage`);
return;
}
Log.warn(`Found a change in ${path.basename(filename)}. Restarting the server to apply the changes...`);
process.exit(RESTART_EXIT_CODE);
});
}
}
if (process.env.NEXT_PRIVATE_WORKER && process.send) {
process.addListener("message", async (msg)=>{
if (msg && typeof msg && msg.nextWorkerOptions && process.send) {
await startServer(msg.nextWorkerOptions);
process.send({
nextServerReady: true
});
}
});
process.send({
nextWorkerReady: true
});
}
//# sourceMappingURL=start-server.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,113 @@
/**
* Contains predefined constants for the trace span name in next/server.
*
* Currently, next/server/tracer is internal implementation only for tracking
* next.js's implementation only with known span names defined here.
**/ // eslint typescript has a bug with TS enums
/* eslint-disable no-shadow */ var BaseServerSpan;
(function(BaseServerSpan) {
BaseServerSpan["handleRequest"] = "BaseServer.handleRequest";
BaseServerSpan["run"] = "BaseServer.run";
BaseServerSpan["pipe"] = "BaseServer.pipe";
BaseServerSpan["getStaticHTML"] = "BaseServer.getStaticHTML";
BaseServerSpan["render"] = "BaseServer.render";
BaseServerSpan["renderToResponseWithComponents"] = "BaseServer.renderToResponseWithComponents";
BaseServerSpan["renderToResponse"] = "BaseServer.renderToResponse";
BaseServerSpan["renderToHTML"] = "BaseServer.renderToHTML";
BaseServerSpan["renderError"] = "BaseServer.renderError";
BaseServerSpan["renderErrorToResponse"] = "BaseServer.renderErrorToResponse";
BaseServerSpan["renderErrorToHTML"] = "BaseServer.renderErrorToHTML";
BaseServerSpan["render404"] = "BaseServer.render404";
})(BaseServerSpan || (BaseServerSpan = {}));
var LoadComponentsSpan;
(function(LoadComponentsSpan) {
LoadComponentsSpan["loadDefaultErrorComponents"] = "LoadComponents.loadDefaultErrorComponents";
LoadComponentsSpan["loadComponents"] = "LoadComponents.loadComponents";
})(LoadComponentsSpan || (LoadComponentsSpan = {}));
var NextServerSpan;
(function(NextServerSpan) {
NextServerSpan["getRequestHandler"] = "NextServer.getRequestHandler";
NextServerSpan["getServer"] = "NextServer.getServer";
NextServerSpan["getServerRequestHandler"] = "NextServer.getServerRequestHandler";
NextServerSpan["createServer"] = "createServer.createServer";
})(NextServerSpan || (NextServerSpan = {}));
var NextNodeServerSpan;
(function(NextNodeServerSpan) {
NextNodeServerSpan["compression"] = "NextNodeServer.compression";
NextNodeServerSpan["getBuildId"] = "NextNodeServer.getBuildId";
NextNodeServerSpan["generateStaticRoutes"] = "NextNodeServer.generateStaticRoutes";
NextNodeServerSpan["generateFsStaticRoutes"] = "NextNodeServer.generateFsStaticRoutes";
NextNodeServerSpan["generatePublicRoutes"] = "NextNodeServer.generatePublicRoutes";
NextNodeServerSpan["generateImageRoutes"] = "NextNodeServer.generateImageRoutes.route";
NextNodeServerSpan["sendRenderResult"] = "NextNodeServer.sendRenderResult";
NextNodeServerSpan["proxyRequest"] = "NextNodeServer.proxyRequest";
NextNodeServerSpan["runApi"] = "NextNodeServer.runApi";
NextNodeServerSpan["render"] = "NextNodeServer.render";
NextNodeServerSpan["renderHTML"] = "NextNodeServer.renderHTML";
NextNodeServerSpan["imageOptimizer"] = "NextNodeServer.imageOptimizer";
NextNodeServerSpan["getPagePath"] = "NextNodeServer.getPagePath";
NextNodeServerSpan["getRoutesManifest"] = "NextNodeServer.getRoutesManifest";
NextNodeServerSpan["findPageComponents"] = "NextNodeServer.findPageComponents";
NextNodeServerSpan["getFontManifest"] = "NextNodeServer.getFontManifest";
NextNodeServerSpan["getServerComponentManifest"] = "NextNodeServer.getServerComponentManifest";
NextNodeServerSpan["getRequestHandler"] = "NextNodeServer.getRequestHandler";
NextNodeServerSpan["renderToHTML"] = "NextNodeServer.renderToHTML";
NextNodeServerSpan["renderError"] = "NextNodeServer.renderError";
NextNodeServerSpan["renderErrorToHTML"] = "NextNodeServer.renderErrorToHTML";
NextNodeServerSpan["render404"] = "NextNodeServer.render404";
NextNodeServerSpan[// nested inner span, does not require parent scope name
"route"] = "route";
NextNodeServerSpan["onProxyReq"] = "onProxyReq";
NextNodeServerSpan["apiResolver"] = "apiResolver";
NextNodeServerSpan["internalFetch"] = "internalFetch";
})(NextNodeServerSpan || (NextNodeServerSpan = {}));
var StartServerSpan;
(function(StartServerSpan) {
StartServerSpan["startServer"] = "startServer.startServer";
})(StartServerSpan || (StartServerSpan = {}));
var RenderSpan;
(function(RenderSpan) {
RenderSpan["getServerSideProps"] = "Render.getServerSideProps";
RenderSpan["getStaticProps"] = "Render.getStaticProps";
RenderSpan["renderToString"] = "Render.renderToString";
RenderSpan["renderDocument"] = "Render.renderDocument";
RenderSpan["createBodyResult"] = "Render.createBodyResult";
})(RenderSpan || (RenderSpan = {}));
var AppRenderSpan;
(function(AppRenderSpan) {
AppRenderSpan["renderToString"] = "AppRender.renderToString";
AppRenderSpan["renderToReadableStream"] = "AppRender.renderToReadableStream";
AppRenderSpan["getBodyResult"] = "AppRender.getBodyResult";
AppRenderSpan["fetch"] = "AppRender.fetch";
})(AppRenderSpan || (AppRenderSpan = {}));
var RouterSpan;
(function(RouterSpan) {
RouterSpan["executeRoute"] = "Router.executeRoute";
})(RouterSpan || (RouterSpan = {}));
var NodeSpan;
(function(NodeSpan) {
NodeSpan["runHandler"] = "Node.runHandler";
})(NodeSpan || (NodeSpan = {}));
var AppRouteRouteHandlersSpan;
(function(AppRouteRouteHandlersSpan) {
AppRouteRouteHandlersSpan["runHandler"] = "AppRouteRouteHandlers.runHandler";
})(AppRouteRouteHandlersSpan || (AppRouteRouteHandlersSpan = {}));
var ResolveMetadataSpan;
(function(ResolveMetadataSpan) {
ResolveMetadataSpan["generateMetadata"] = "ResolveMetadata.generateMetadata";
})(ResolveMetadataSpan || (ResolveMetadataSpan = {}));
// This list is used to filter out spans that are not relevant to the user
export const NextVanillaSpanAllowlist = [
"BaseServer.handleRequest",
"Render.getServerSideProps",
"Render.getStaticProps",
"AppRender.fetch",
"AppRender.getBodyResult",
"Render.renderDocument",
"Node.runHandler",
"AppRouteRouteHandlers.runHandler",
"ResolveMetadata.generateMetadata"
];
export { BaseServerSpan, LoadComponentsSpan, NextServerSpan, NextNodeServerSpan, StartServerSpan, RenderSpan, RouterSpan, AppRenderSpan, NodeSpan, AppRouteRouteHandlersSpan, ResolveMetadataSpan, };
//# sourceMappingURL=constants.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/trace/constants.ts"],"names":["BaseServerSpan","handleRequest","run","pipe","getStaticHTML","render","renderToResponseWithComponents","renderToResponse","renderToHTML","renderError","renderErrorToResponse","renderErrorToHTML","render404","LoadComponentsSpan","loadDefaultErrorComponents","loadComponents","NextServerSpan","getRequestHandler","getServer","getServerRequestHandler","createServer","NextNodeServerSpan","compression","getBuildId","generateStaticRoutes","generateFsStaticRoutes","generatePublicRoutes","generateImageRoutes","sendRenderResult","proxyRequest","runApi","renderHTML","imageOptimizer","getPagePath","getRoutesManifest","findPageComponents","getFontManifest","getServerComponentManifest","route","onProxyReq","apiResolver","internalFetch","StartServerSpan","startServer","RenderSpan","getServerSideProps","getStaticProps","renderToString","renderDocument","createBodyResult","AppRenderSpan","renderToReadableStream","getBodyResult","fetch","RouterSpan","executeRoute","NodeSpan","runHandler","AppRouteRouteHandlersSpan","ResolveMetadataSpan","generateMetadata","NextVanillaSpanAllowlist"],"mappings":"AAAA;;;;;EAKE,GAEF,4CAA4C;AAC5C,4BAA4B,OAE5B;UAAKA,cAAc;IAAdA,eACHC,mBAAgB;IADbD,eAEHE,SAAM;IAFHF,eAGHG,UAAO;IAHJH,eAIHI,mBAAgB;IAJbJ,eAKHK,YAAS;IALNL,eAMHM,oCAAiC;IAN9BN,eAOHO,sBAAmB;IAPhBP,eAQHQ,kBAAe;IARZR,eASHS,iBAAc;IATXT,eAUHU,2BAAwB;IAVrBV,eAWHW,uBAAoB;IAXjBX,eAYHY,eAAY;GAZTZ,mBAAAA;IAeL;UAAKa,kBAAkB;IAAlBA,mBACHC,gCAA6B;IAD1BD,mBAEHE,oBAAiB;GAFdF,uBAAAA;IAKL;UAAKG,cAAc;IAAdA,eACHC,uBAAoB;IADjBD,eAEHE,eAAY;IAFTF,eAGHG,6BAA0B;IAHvBH,eAIHI,kBAAe;GAJZJ,mBAAAA;IAOL;UAAKK,kBAAkB;IAAlBA,mBACHC,iBAAc;IADXD,mBAEHE,gBAAa;IAFVF,mBAGHG,0BAAuB;IAHpBH,mBAIHI,4BAAyB;IAJtBJ,mBAKHK,0BAAuB;IALpBL,mBAMHM,yBAAsB;IANnBN,mBAOHO,sBAAmB;IAPhBP,mBAQHQ,kBAAe;IARZR,mBASHS,YAAS;IATNT,mBAU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U,EACVJ,aAAa,EACbM,QAAQ,EACRE,yBAAyB,EACzBC,mBAAmB,KACpB"}

157
node_modules/next/dist/esm/server/lib/trace/tracer.js generated vendored Normal file
View File

@@ -0,0 +1,157 @@
import { NextVanillaSpanAllowlist } from "./constants";
let api;
// we want to allow users to use their own version of @opentelemetry/api if they
// want to, so we try to require it first, and if it fails we fall back to the
// version that is bundled with Next.js
// this is because @opentelemetry/api has to be synced with the version of
// @opentelemetry/tracing that is used, and we don't want to force users to use
// the version that is bundled with Next.js.
// the API is ~stable, so this should be fine
if (process.env.NEXT_RUNTIME === "edge") {
api = require("@opentelemetry/api");
} else {
try {
api = require("@opentelemetry/api");
} catch (err) {
api = require("next/dist/compiled/@opentelemetry/api");
}
}
const { context, trace, SpanStatusCode, SpanKind } = api;
const isPromise = (p)=>{
return p !== null && typeof p === "object" && typeof p.then === "function";
};
const closeSpanWithError = (span, error)=>{
if (error) {
span.recordException(error);
}
span.setStatus({
code: SpanStatusCode.ERROR,
message: error == null ? void 0 : error.message
});
span.end();
};
/** we use this map to propagate attributes from nested spans to the top span */ const rootSpanAttributesStore = new Map();
const rootSpanIdKey = api.createContextKey("next.rootSpanId");
let lastSpanId = 0;
const getSpanId = ()=>lastSpanId++;
class NextTracerImpl {
/**
* Returns an instance to the trace with configured name.
* Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
* This should be lazily evaluated.
*/ getTracerInstance() {
return trace.getTracer("next.js", "0.0.1");
}
getContext() {
return context;
}
getActiveScopeSpan() {
return trace.getSpan(context == null ? void 0 : context.active());
}
trace(...args) {
const [type, fnOrOptions, fnOrEmpty] = args;
// coerce options form overload
const { fn, options } = typeof fnOrOptions === "function" ? {
fn: fnOrOptions,
options: {}
} : {
fn: fnOrEmpty,
options: {
...fnOrOptions
}
};
if (!NextVanillaSpanAllowlist.includes(type) && process.env.NEXT_OTEL_VERBOSE !== "1" || options.hideSpan) {
return fn();
}
const spanName = options.spanName ?? type;
// Trying to get active scoped span to assign parent. If option specifies parent span manually, will try to use it.
let spanContext = this.getSpanContext((options == null ? void 0 : options.parentSpan) ?? this.getActiveScopeSpan());
let isRootSpan = false;
if (!spanContext) {
spanContext = api.ROOT_CONTEXT;
isRootSpan = true;
}
const spanId = getSpanId();
options.attributes = {
"next.span_name": spanName,
"next.span_type": type,
...options.attributes
};
return api.context.with(spanContext.setValue(rootSpanIdKey, spanId), ()=>this.getTracerInstance().startActiveSpan(spanName, options, (span)=>{
const onCleanup = ()=>{
rootSpanAttributesStore.delete(spanId);
};
if (isRootSpan) {
rootSpanAttributesStore.set(spanId, new Map(Object.entries(options.attributes ?? {})));
}
try {
if (fn.length > 1) {
return fn(span, (err)=>closeSpanWithError(span, err));
}
const result = fn(span);
if (isPromise(result)) {
result.then(()=>span.end(), (err)=>closeSpanWithError(span, err)).finally(onCleanup);
} else {
span.end();
onCleanup();
}
return result;
} catch (err) {
closeSpanWithError(span, err);
onCleanup();
throw err;
}
}));
}
wrap(...args) {
const tracer = this;
const [name, options, fn] = args.length === 3 ? args : [
args[0],
{},
args[1]
];
if (!NextVanillaSpanAllowlist.includes(name) && process.env.NEXT_OTEL_VERBOSE !== "1") {
return fn;
}
return function() {
let optionsObj = options;
if (typeof optionsObj === "function" && typeof fn === "function") {
optionsObj = optionsObj.apply(this, arguments);
}
const lastArgId = arguments.length - 1;
const cb = arguments[lastArgId];
if (typeof cb === "function") {
const scopeBoundCb = tracer.getContext().bind(context.active(), cb);
return tracer.trace(name, optionsObj, (_span, done)=>{
arguments[lastArgId] = function(err) {
done == null ? void 0 : done(err);
return scopeBoundCb.apply(this, arguments);
};
return fn.apply(this, arguments);
});
} else {
return tracer.trace(name, optionsObj, ()=>fn.apply(this, arguments));
}
};
}
startSpan(...args) {
const [type, options] = args;
const spanContext = this.getSpanContext((options == null ? void 0 : options.parentSpan) ?? this.getActiveScopeSpan());
return this.getTracerInstance().startSpan(type, options, spanContext);
}
getSpanContext(parentSpan) {
const spanContext = parentSpan ? trace.setSpan(context.active(), parentSpan) : undefined;
return spanContext;
}
getRootSpanAttributes() {
const spanId = context.active().getValue(rootSpanIdKey);
return rootSpanAttributesStore.get(spanId);
}
}
const getTracer = (()=>{
const tracer = new NextTracerImpl();
return ()=>tracer;
})();
export { getTracer, SpanStatusCode, SpanKind, };
//# sourceMappingURL=tracer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/trace/tracer.ts"],"names":["NextVanillaSpanAllowlist","api","process","env","NEXT_RUNTIME","require","err","context","trace","SpanStatusCode","SpanKind","isPromise","p","then","closeSpanWithError","span","error","recordException","setStatus","code","ERROR","message","end","rootSpanAttributesStore","Map","rootSpanIdKey","createContextKey","lastSpanId","getSpanId","NextTracerImpl","getTracerInstance","getTracer","getContext","getActiveScopeSpan","getSpan","active","args","type","fnOrOptions","fnOrEmpty","fn","options","includes","NEXT_OTEL_VERBOSE","hideSpan","spanName","spanContext","getSpanContext","parentSpan","isRootSpan","ROOT_CONTEXT","spanId","attributes","with","setValue","startActiveSpan","onCleanup","delete","set","Object","entries","length","result","finally","wrap","tracer","name","optionsObj","apply","arguments","lastArgId","cb","scopeBoundCb","bind","_span","done","startSpan","setSpan","undefined","getRootSpanAttributes","getValue","get"],"mappings":"AAAA,SAASA,wBAAwB,QAAmB,cAAa;AAUjE,IAAIC;AAEJ,gFAAgF;AAChF,8EAA8E;AAC9E,uCAAuC;AACvC,0EAA0E;AAC1E,+EAA+E;AAC/E,4CAA4C;AAC5C,6CAA6C;AAC7C,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCH,MAAMI,QAAQ;AAChB,OAAO;IACL,IAAI;QACFJ,MAAMI,QAAQ;IAChB,EAAE,OAAOC,KAAK;QACZL,MAAMI,QAAQ;IAChB;AACF;AAEA,MAAM,EAAEE,OAAO,EAAEC,KAAK,EAAEC,cAAc,EAAEC,QAAQ,EAAE,GAAGT;AAErD,MAAMU,YAAY,CAAIC;IACpB,OAAOA,MAAM,QAAQ,OAAOA,MAAM,Y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AACF;AAEA,MAAMpB,YAAY,AAAC,CAAA;IACjB,MAAMkC,SAAS,IAAIpC;IAEnB,OAAO,IAAMoC;AACf,CAAA;AAEA,SAEElC,SAAS,EAITtB,cAAc,EAEdC,QAAQ,KACT"}

29
node_modules/next/dist/esm/server/lib/utils.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
export function printAndExit(message, code = 1) {
if (code === 0) {
console.log(message);
} else {
console.error(message);
}
process.exit(code);
}
export const getDebugPort = ()=>{
var _process_execArgv_find, _process_env_NODE_OPTIONS_match, _process_env_NODE_OPTIONS_match1, _process_env_NODE_OPTIONS;
const debugPortStr = ((_process_execArgv_find = process.execArgv.find((localArg)=>localArg.startsWith("--inspect") || localArg.startsWith("--inspect-brk"))) == null ? void 0 : _process_execArgv_find.split("=")[1]) ?? ((_process_env_NODE_OPTIONS = process.env.NODE_OPTIONS) == null ? void 0 : (_process_env_NODE_OPTIONS_match1 = _process_env_NODE_OPTIONS.match) == null ? void 0 : (_process_env_NODE_OPTIONS_match = _process_env_NODE_OPTIONS_match1.call(_process_env_NODE_OPTIONS, /--inspect(-brk)?(=(\S+))?( |$)/)) == null ? void 0 : _process_env_NODE_OPTIONS_match[3]);
return debugPortStr ? parseInt(debugPortStr, 10) : 9229;
};
const NODE_INSPECT_RE = /--inspect(-brk)?(=\S+)?( |$)/;
export function getNodeOptionsWithoutInspect() {
return (process.env.NODE_OPTIONS || "").replace(NODE_INSPECT_RE, "");
}
export function getPort(args) {
if (typeof args["--port"] === "number") {
return args["--port"];
}
const parsed = process.env.PORT && parseInt(process.env.PORT, 10);
if (typeof parsed === "number" && !Number.isNaN(parsed)) {
return parsed;
}
return 3000;
}
//# sourceMappingURL=utils.js.map

1
node_modules/next/dist/esm/server/lib/utils.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/utils.ts"],"names":["printAndExit","message","code","console","log","error","process","exit","getDebugPort","debugPortStr","execArgv","find","localArg","startsWith","split","env","NODE_OPTIONS","match","parseInt","NODE_INSPECT_RE","getNodeOptionsWithoutInspect","replace","getPort","args","parsed","PORT","Number","isNaN"],"mappings":"AAEA,OAAO,SAASA,aAAaC,OAAe,EAAEC,OAAO,CAAC;IACpD,IAAIA,SAAS,GAAG;QACdC,QAAQC,GAAG,CAACH;IACd,OAAO;QACLE,QAAQE,KAAK,CAACJ;IAChB;IAEAK,QAAQC,IAAI,CAACL;AACf;AAEA,OAAO,MAAMM,eAAe;QAExBF,wBAOAA,iCAAAA,kCAAAA;IARF,MAAMG,eACJH,EAAAA,yBAAAA,QAAQI,QAAQ,CACbC,IAAI,CACH,CAACC,WACCA,SAASC,UAAU,CAAC,gBACpBD,SAASC,UAAU,CAAC,sCAJ1BP,uBAMIQ,KAAK,CAAC,IAAI,CAAC,EAAE,OACjBR,4BAAAA,QAAQS,GAAG,CAACC,YAAY,sBAAxBV,mCAAAA,0BAA0BW,KAAK,sBAA/BX,kCAAAA,sCAAAA,2BAAkC,sDAAlCA,+BAAqE,CAAC,EAAE;IAC1E,OAAOG,eAAeS,SAAST,cAAc,MAAM;AACrD,EAAC;AAED,MAAMU,kBAAkB;AACxB,OAAO,SAASC;IACd,OAAO,AAACd,CAAAA,QAAQS,GAAG,CAACC,YAAY,IAAI,EAAC,EAAGK,OAAO,CAACF,iBAAiB;AACnE;AAEA,OAAO,SAASG,QAAQC,IAA0B;IAChD,IAAI,OAAOA,IAAI,CAAC,SAAS,KAAK,UAAU;QACtC,OAAOA,IAAI,CAAC,SAAS;IACvB;IAEA,MAAMC,SAASlB,QAAQS,GAAG,CAACU,IAAI,IAAIP,SAASZ,QAAQS,GAAG,CAACU,IAAI,EAAE;IAC9D,IAAI,OAAOD,WAAW,YAAY,CAACE,OAAOC,KAAK,CAACH,SAAS;QACvD,OAAOA;IACT;IAEA,OAAO;AACT"}

17
node_modules/next/dist/esm/server/lib/worker-utils.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import http from "http";
export const getFreePort = async ()=>{
return new Promise((resolve, reject)=>{
const server = http.createServer(()=>{});
server.listen(0, ()=>{
const address = server.address();
server.close();
if (address && typeof address === "object") {
resolve(address.port);
} else {
reject(new Error("invalid address from server: " + (address == null ? void 0 : address.toString())));
}
});
});
};
//# sourceMappingURL=worker-utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/worker-utils.ts"],"names":["http","getFreePort","Promise","resolve","reject","server","createServer","listen","address","close","port","Error","toString"],"mappings":"AAAA,OAAOA,UAAU,OAAM;AAEvB,OAAO,MAAMC,cAAc;IACzB,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3B,MAAMC,SAASL,KAAKM,YAAY,CAAC,KAAO;QACxCD,OAAOE,MAAM,CAAC,GAAG;YACf,MAAMC,UAAUH,OAAOG,OAAO;YAC9BH,OAAOI,KAAK;YAEZ,IAAID,WAAW,OAAOA,YAAY,UAAU;gBAC1CL,QAAQK,QAAQE,IAAI;YACtB,OAAO;gBACLN,OAAO,IAAIO,MAAM,mCAAkCH,2BAAAA,QAASI,QAAQ;YACtE;QACF;IACF;AACF,EAAC"}