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

13
node_modules/next/dist/server/lib/app-dir-module.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import type { ComponentsType } from '../../build/webpack/loaders/next-app-loader';
/**
* LoaderTree is generated in next-app-loader.
*/
export type LoaderTree = [
segment: string,
parallelRoutes: {
[parallelRouterKey: string]: LoaderTree;
},
components: ComponentsType
];
export declare function getLayoutOrPageModule(loaderTree: LoaderTree): Promise<readonly [any, "page" | "layout" | undefined]>;
export declare function getComponentTypeModule(loaderTree: LoaderTree, componentType: 'layout' | 'not-found'): Promise<any>;

53
node_modules/next/dist/server/lib/app-dir-module.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getLayoutOrPageModule: null,
getComponentTypeModule: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getLayoutOrPageModule: function() {
return getLayoutOrPageModule;
},
getComponentTypeModule: function() {
return getComponentTypeModule;
}
});
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
];
}
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","getComponentTypeModule","loaderTree","layout","page","defaultPage","isLayout","isPage","isDefaultPage","value","undefined","modType","componentType","component"],"mappings":";;;;;;;;;;;;;;;IAWsBA,qBAAqB;eAArBA;;IAwBAC,sBAAsB;eAAtBA;;;AAxBf,eAAeD,sBAAsBE,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;AAEO,eAAeV,uBACpBC,UAAsB,EACtBU,aAAqC;IAErC,MAAM,EAAE,CAACA,cAAc,EAAEC,SAAS,EAAE,GAAGX,UAAU,CAAC,EAAE;IACpD,IAAI,OAAOW,cAAc,aAAa;QACpC,OAAO,MAAMA,SAAS,CAAC,EAAE;IAC3B;IACA,OAAOH;AACT"}

2
node_modules/next/dist/server/lib/cpu-profile.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
declare const privateCpuProfileName: string | undefined;
declare const isCpuProfileEnabled: string | undefined;

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

@@ -0,0 +1,28 @@
"use strict";
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

1
node_modules/next/dist/server/lib/cpu-profile.js.map generated vendored Normal file
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"}

11
node_modules/next/dist/server/lib/etag.d.ts generated vendored Normal file
View File

@@ -0,0 +1,11 @@
/**
* 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 declare const fnv1a52: (str: string) => number;
export declare const generateETag: (payload: string, weak?: boolean) => string;

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

@@ -0,0 +1,56 @@
/**
* 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.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
fnv1a52: null,
generateETag: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
fnv1a52: function() {
return fnv1a52;
},
generateETag: function() {
return generateETag;
}
});
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);
};
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/server/lib/etag.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/etag.ts"],"names":["fnv1a52","generateETag","str","len","length","i","t0","v0","t1","v1","t2","v2","t3","v3","charCodeAt","payload","weak","prefix","toString"],"mappings":"AAAA;;;;;;;;CAQC;;;;;;;;;;;;;;;IACYA,OAAO;eAAPA;;IAoCAC,YAAY;eAAZA;;;AApCN,MAAMD,UAAU,CAACE;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;AAEO,MAAMZ,eAAe,CAACc,SAAiBC,OAAO,KAAK;IACxD,MAAMC,SAASD,OAAO,QAAQ;IAC9B,OACEC,SAASjB,QAAQe,SAASG,QAAQ,CAAC,MAAMH,QAAQX,MAAM,CAACc,QAAQ,CAAC,MAAM;AAE3E"}

23
node_modules/next/dist/server/lib/find-page-file.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
/**
* 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 declare function findPageFile(pagesDir: string, normalizedPagePath: string, pageExtensions: string[], isAppDir: boolean): Promise<string | null>;
/**
*
* 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 declare function createValidFileMatcher(pageExtensions: string[], appDirPath: string | undefined): {
isPageFile: (filePath: string) => boolean;
isAppRouterPage: (filePath: string) => boolean;
isMetadataFile: (filePath: string) => boolean;
isRootNotFound: (filePath: string) => boolean;
};

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

@@ -0,0 +1,116 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
findPageFile: null,
createValidFileMatcher: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
findPageFile: function() {
return findPageFile;
},
createValidFileMatcher: function() {
return createValidFileMatcher;
}
});
const _fileexists = require("../../lib/file-exists");
const _getpagepaths = require("../../shared/lib/page-path/get-page-paths");
const _nonnullable = require("../../lib/non-nullable");
const _path = require("path");
const _fs = require("fs");
const _log = require("../../build/output/log");
const _chalk = /*#__PURE__*/ _interop_require_default(require("../../lib/chalk"));
const _ismetadataroute = require("../../lib/metadata/is-metadata-route");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function isTrueCasePagePath(pagePath, pagesDir) {
const pageSegments = (0, _path.normalize)(pagePath).split(_path.sep).filter(Boolean);
const segmentExistsPromises = pageSegments.map(async (segment, i)=>{
const segmentParentDir = (0, _path.join)(pagesDir, ...pageSegments.slice(0, i));
const parentDirEntries = await _fs.promises.readdir(segmentParentDir);
return parentDirEntries.includes(segment);
});
return (await Promise.all(segmentExistsPromises)).every(Boolean);
}
async function findPageFile(pagesDir, normalizedPagePath, pageExtensions, isAppDir) {
const pagePaths = (0, _getpagepaths.getPagePaths)(normalizedPagePath, pageExtensions, isAppDir);
const [existingPath, ...others] = (await Promise.all(pagePaths.map(async (path)=>{
const filePath = (0, _path.join)(pagesDir, path);
try {
return await (0, _fileexists.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.nonNullable);
if (!existingPath) {
return null;
}
if (!await isTrueCasePagePath(existingPath, pagesDir)) {
return null;
}
if (others.length > 0) {
(0, _log.warn)(`Duplicate page detected. ${_chalk.default.cyan((0, _path.join)("pages", existingPath))} and ${_chalk.default.cyan((0, _path.join)("pages", others[0]))} both resolve to ${_chalk.default.cyan(normalizedPagePath)}.`);
}
return existingPath;
}
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 (0, _ismetadataroute.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 + _path.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":["findPageFile","createValidFileMatcher","isTrueCasePagePath","pagePath","pagesDir","pageSegments","normalize","split","sep","filter","Boolean","segmentExistsPromises","map","segment","i","segmentParentDir","join","slice","parentDirEntries","fsPromises","readdir","includes","Promise","all","every","normalizedPagePath","pageExtensions","isAppDir","pagePaths","getPagePaths","existingPath","others","path","filePath","fileExists","err","code","nonNullable","length","warn","chalk","cyan","appDirPath","getExtensionRegexString","extensions","validExtensionFileRegex","RegExp","leafOnlyPageFileRegex","rootNotFoundFileRegex","isMetadataFile","appDirRelativePath","replace","isMetadataRouteFile","isAppRouterPage","test","isPageFile","isRootNotFound","startsWith","rest"],"mappings":";;;;;;;;;;;;;;;IA6BsBA,YAAY;eAAZA;;IAiDNC,sBAAsB;eAAtBA;;;4BA9EW;8BACE;6BACD;sBACS;oBACE;qBAClB;8DACH;iCACkB;;;;;;AAEpC,eAAeC,mBAAmBC,QAAgB,EAAEC,QAAgB;IAClE,MAAMC,eAAeC,IAAAA,eAAS,EAACH,UAAUI,KAAK,CAACC,SAAG,EAAEC,MAAM,CAACC;IAC3D,MAAMC,wBAAwBN,aAAaO,GAAG,CAAC,OAAOC,SAASC;QAC7D,MAAMC,mBAAmBC,IAAAA,UAAI,EAACZ,aAAaC,aAAaY,KAAK,CAAC,GAAGH;QACjE,MAAMI,mBAAmB,MAAMC,YAAU,CAACC,OAAO,CAACL;QAClD,OAAOG,iBAAiBG,QAAQ,CAACR;IACnC;IAEA,OAAO,AAAC,CAAA,MAAMS,QAAQC,GAAG,CAACZ,sBAAqB,EAAGa,KAAK,CAACd;AAC1D;AAWO,eAAeV,aACpBI,QAAgB,EAChBqB,kBAA0B,EAC1BC,cAAwB,EACxBC,QAAiB;IAEjB,MAAMC,YAAYC,IAAAA,0BAAY,EAACJ,oBAAoBC,gBAAgBC;IACnE,MAAM,CAACG,cAAc,GAAGC,OAAO,GAAG,AAChC,CAAA,MAAMT,QAAQC,GAAG,CACfK,UAAUhB,GAAG,CAAC,OAAOoB;QACnB,MAAMC,WAAWjB,IAAAA,UAAI,EAACZ,UAAU4B;QAChC,IAAI;YACF,OAAO,AAAC,MAAME,IAAAA,sBAAU,EAACD,YAAaD,OAAO;QAC/C,EAAE,OAAOG,KAAU;gBACZA;YAAL,IAAI,EAACA,wBAAAA,YAAAA,IAAKC,IAAI,qBAATD,UAAWd,QAAQ,CAAC,aAAY,MAAMc;QAC7C;QACA,OAAO;IACT,GACF,EACA1B,MAAM,CAAC4B,wBAAW;IAEpB,IAAI,CAACP,cAAc;QACjB,OAAO;IACT;IAEA,IAAI,CAAE,MAAM5B,mBAAmB4B,cAAc1B,WAAY;QACvD,OAAO;IACT;IAEA,IAAI2B,OAAOO,MAAM,GAAG,GAAG;QACrBC,IAAAA,SAAI,EACF,CAAC,yBAAyB,EAAEC,cAAK,CAACC,IAAI,CACpCzB,IAAAA,UAAI,EAAC,SAASc,eACd,KAAK,EAAEU,cAAK,CAACC,IAAI,CACjBzB,IAAAA,UAAI,EAAC,SAASe,MAAM,CAAC,EAAE,GACvB,iBAAiB,EAAES,cAAK,CAACC,IAAI,CAAChB,oBAAoB,CAAC,CAAC;IAE1D;IAEA,OAAOK;AACT;AASO,SAAS7B,uBACdyB,cAAwB,EACxBgB,UAA8B;IAE9B,MAAMC,0BAA0B,CAACC,aAC/B,CAAC,GAAG,EAAEA,WAAW5B,IAAI,CAAC,KAAK,CAAC,CAAC;IAE/B,MAAM6B,0BAA0B,IAAIC,OAClC,QAAQH,wBAAwBjB,kBAAkB;IAEpD,MAAMqB,wBAAwB,IAAID,OAChC,CAAC,sCAAsC,EAAEH,wBACvCjB,gBACA,CAAC,CAAC;IAEN,MAAMsB,wBAAwB,IAAIF,OAChC,CAAC,aAAa,EAAEH,wBAAwBjB,gBAAgB,CAAC,CAAC;IAE5D;;;;;;;;;;GAUC,GAED;;;GAGC,GACD,SAASuB,eAAehB,QAAgB;QACtC,MAAMiB,qBAAqBR,aACvBT,SAASkB,OAAO,CAACT,YAAY,MAC7BT;QAEJ,OAAOmB,IAAAA,oCAAmB,EAACF,oBAAoBxB,gBAAgB;IACjE;IAEA,4EAA4E;IAC5E,2CAA2C;IAC3C,SAAS2B,gBAAgBpB,QAAgB;QACvC,OAAOc,sBAAsBO,IAAI,CAACrB,aAAagB,eAAehB;IAChE;IAEA,SAASsB,WAAWtB,QAAgB;QAClC,OAAOY,wBAAwBS,IAAI,CAACrB,aAAagB,eAAehB;IAClE;IAEA,SAASuB,eAAevB,QAAgB;QACtC,IAAI,CAACS,YAAY;YACf,OAAO;QACT;QACA,IAAI,CAACT,SAASwB,UAAU,CAACf,aAAalC,SAAG,GAAG;YAC1C,OAAO;QACT;QACA,MAAMkD,OAAOzB,SAAShB,KAAK,CAACyB,WAAWJ,MAAM,GAAG;QAChD,OAAOU,sBAAsBM,IAAI,CAACI;IACpC;IAEA,OAAO;QACLH;QACAF;QACAJ;QACAO;IACF;AACF"}

View File

@@ -0,0 +1,7 @@
/**
* Formats a hostname so that it is a valid host that can be fetched by wrapping
* IPv6 hosts with brackets.
* @param hostname
* @returns
*/
export declare function formatHostname(hostname: string): string;

16
node_modules/next/dist/server/lib/format-hostname.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "formatHostname", {
enumerable: true,
get: function() {
return formatHostname;
}
});
const _isipv6 = require("./is-ipv6");
function formatHostname(hostname) {
return (0, _isipv6.isIPv6)(hostname) ? `[${hostname}]` : hostname;
}
//# sourceMappingURL=format-hostname.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/lib/format-hostname.ts"],"names":["formatHostname","hostname","isIPv6"],"mappings":";;;;+BAQgBA;;;eAAAA;;;wBARO;AAQhB,SAASA,eAAeC,QAAgB;IAC7C,OAAOC,IAAAA,cAAM,EAACD,YAAY,CAAC,CAAC,EAAEA,SAAS,CAAC,CAAC,GAAGA;AAC9C"}

View File

@@ -0,0 +1,7 @@
import { IncrementalCache } from './incremental-cache';
declare let initializeResult: undefined | {
ipcPort: number;
ipcValidationKey: string;
};
export declare function initialize(...constructorArgs: ConstructorParameters<typeof IncrementalCache>): Promise<NonNullable<typeof initializeResult>>;
export {};

View File

@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "initialize", {
enumerable: true,
get: function() {
return initialize;
}
});
const _serveripc = require("./server-ipc");
const _incrementalcache = require("./incremental-cache");
let initializeResult;
async function initialize(...constructorArgs) {
const incrementalCache = new _incrementalcache.IncrementalCache(...constructorArgs);
const { ipcPort, ipcValidationKey } = await (0, _serveripc.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":["initialize","initializeResult","constructorArgs","incrementalCache","IncrementalCache","ipcPort","ipcValidationKey","createIpcServer","revalidateTag","args","get","set","lock","unlock"],"mappings":";;;;+BAUsBA;;;eAAAA;;;2BAVU;kCACC;AAEjC,IAAIC;AAOG,eAAeD,WACpB,GAAGE,eAA+D;IAElE,MAAMC,mBAAmB,IAAIC,kCAAgB,IAAIF;IAEjD,MAAM,EAAEG,OAAO,EAAEC,gBAAgB,EAAE,GAAG,MAAMC,IAAAA,0BAAe,EAAC;QAC1D,MAAMC,eACJ,GAAGC,IAAmD;YAEtD,OAAON,iBAAiBK,aAAa,IAAIC;QAC3C;QAEA,MAAMC,KAAI,GAAGD,IAAyC;YACpD,OAAON,iBAAiBO,GAAG,IAAID;QACjC;QAEA,MAAME,KAAI,GAAGF,IAAyC;YACpD,OAAON,iBAAiBQ,GAAG,IAAIF;QACjC;QAEA,MAAMG,MAAK,GAAGH,IAA0C;YACtD,OAAON,iBAAiBS,IAAI,IAAIH;QAClC;QAEA,MAAMI,QAAO,GAAGJ,IAA4C;YAC1D,OAAON,iBAAiBU,MAAM,IAAIJ;QACpC;IACF;IAEA,OAAO;QACLJ;QACAC;IACF;AACF"}

View File

@@ -0,0 +1,24 @@
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './';
export default class FetchCache implements CacheHandler {
private headers;
private cacheEndpoint?;
private debug;
static isAvailable(ctx: {
_requestHeaders: CacheHandlerContext['_requestHeaders'];
}): boolean;
constructor(ctx: CacheHandlerContext);
revalidateTag(tag: string): Promise<void>;
get(key: string, ctx: {
tags?: string[];
softTags?: string[];
fetchCache?: boolean;
fetchUrl?: string;
fetchIdx?: number;
}): Promise<CacheHandlerValue | null>;
set(key: string, data: CacheHandlerValue['value'], { fetchCache, fetchIdx, fetchUrl, tags, }: {
tags?: string[];
fetchCache?: boolean;
fetchUrl?: string;
fetchIdx?: number;
}): Promise<void>;
}

View File

@@ -0,0 +1,262 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return FetchCache;
}
});
const _lrucache = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lru-cache"));
const _constants = require("../../../lib/constants");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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";
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.default({
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(",")) || "",
[_constants.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() - _constants.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,27 @@
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './';
import { CacheFs } from '../../../shared/lib/utils';
type FileSystemCacheContext = Omit<CacheHandlerContext, 'fs' | 'serverDistDir'> & {
fs: CacheFs;
serverDistDir: string;
};
export default class FileSystemCache implements CacheHandler {
private fs;
private flushToDisk?;
private serverDistDir;
private appDir;
private tagsManifestPath?;
private revalidatedTags;
constructor(ctx: FileSystemCacheContext);
private loadTagsManifest;
revalidateTag(tag: string): Promise<void>;
get(key: string, { tags, softTags, fetchCache, }?: {
tags?: string[];
softTags?: string[];
fetchCache?: boolean;
}): Promise<CacheHandlerValue | null>;
set(key: string, data: CacheHandlerValue['value'], ctx: {
tags?: string[];
}): Promise<void>;
private getFsPath;
}
export {};

View File

@@ -0,0 +1,289 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return FileSystemCache;
}
});
const _lrucache = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lru-cache"));
const _path = /*#__PURE__*/ _interop_require_default(require("../../../shared/lib/isomorphic/path"));
const _constants = require("../../../lib/constants");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
let memoryCache;
let tagsManifest;
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.default({
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.default.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.default.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[_constants.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.default.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.default.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.default.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.default.join(this.serverDistDir, "..", "cache", "fetch-cache", pathname),
isAppPath: false
};
}
let isAppPath = false;
let filePath = _path.default.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.default.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,78 @@
import type { CacheFs } from '../../../shared/lib/utils';
import { PrerenderManifest } from '../../../build';
import { IncrementalCacheValue, IncrementalCacheEntry } from '../../response-cache';
export interface CacheHandlerContext {
fs?: CacheFs;
dev?: boolean;
flushToDisk?: boolean;
serverDistDir?: string;
maxMemoryCacheSize?: number;
fetchCacheKeyPrefix?: string;
prerenderManifest?: PrerenderManifest;
revalidatedTags: string[];
_appDir: boolean;
_requestHeaders: IncrementalCache['requestHeaders'];
}
export interface CacheHandlerValue {
lastModified?: number;
age?: number;
cacheState?: string;
value: IncrementalCacheValue | null;
}
export declare class CacheHandler {
constructor(_ctx: CacheHandlerContext);
get(..._args: Parameters<IncrementalCache['get']>): Promise<CacheHandlerValue | null>;
set(..._args: Parameters<IncrementalCache['set']>): Promise<void>;
revalidateTag(_tag: string): Promise<void>;
}
export declare class IncrementalCache {
dev?: boolean;
cacheHandler?: CacheHandler;
prerenderManifest: PrerenderManifest;
requestHeaders: Record<string, undefined | string | string[]>;
requestProtocol?: 'http' | 'https';
allowedRevalidateHeaderKeys?: string[];
minimalMode?: boolean;
fetchCacheKeyPrefix?: string;
revalidatedTags?: string[];
isOnDemandRevalidate?: boolean;
private locks;
private unlocks;
constructor({ fs, dev, appDir, flushToDisk, fetchCache, minimalMode, serverDistDir, requestHeaders, requestProtocol, maxMemoryCacheSize, getPrerenderManifest, fetchCacheKeyPrefix, CurCacheHandler, allowedRevalidateHeaderKeys, }: {
fs?: CacheFs;
dev: boolean;
appDir?: boolean;
fetchCache?: boolean;
minimalMode?: boolean;
serverDistDir?: string;
flushToDisk?: boolean;
requestProtocol?: 'http' | 'https';
allowedRevalidateHeaderKeys?: string[];
requestHeaders: IncrementalCache['requestHeaders'];
maxMemoryCacheSize?: number;
getPrerenderManifest: () => PrerenderManifest;
fetchCacheKeyPrefix?: string;
CurCacheHandler?: typeof CacheHandler;
});
private calculateRevalidate;
_getPathname(pathname: string, fetchCache?: boolean): string;
unlock(cacheKey: string): Promise<void>;
lock(cacheKey: string): Promise<() => Promise<void>>;
revalidateTag(tag: string): Promise<any>;
fetchCacheKey(url: string, init?: RequestInit | Request): Promise<string>;
get(cacheKey: string, ctx?: {
fetchCache?: boolean;
revalidate?: number | false;
fetchUrl?: string;
fetchIdx?: number;
tags?: string[];
softTags?: string[];
}): Promise<IncrementalCacheEntry | null>;
set(pathname: string, data: IncrementalCacheValue | null, ctx: {
revalidate?: number | false;
fetchCache?: boolean;
fetchUrl?: string;
fetchIdx?: number;
tags?: string[];
}): Promise<any>;
}

View File

@@ -0,0 +1,395 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
CacheHandler: null,
IncrementalCache: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
CacheHandler: function() {
return CacheHandler;
},
IncrementalCache: function() {
return IncrementalCache;
}
});
const _fetchcache = /*#__PURE__*/ _interop_require_default(require("./fetch-cache"));
const _filesystemcache = /*#__PURE__*/ _interop_require_default(require("./file-system-cache"));
const _path = /*#__PURE__*/ _interop_require_default(require("../../../shared/lib/isomorphic/path"));
const _encodedecode = require("../../stream-utils/encode-decode");
const _base64arraybuffer = require("../../../shared/lib/base64-arraybuffer");
const _normalizepagepath = require("../../../shared/lib/page-path/normalize-page-path");
const _constants = require("../../../lib/constants");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function toRoute(pathname) {
return pathname.replace(/\/$/, "").replace(/\/index$/, "") || "/";
}
class CacheHandler {
// eslint-disable-next-line
constructor(_ctx){}
async get(..._args) {
return {};
}
async set(..._args) {}
async revalidateTag(_tag) {}
}
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.default;
}
if (_fetchcache.default.isAvailable({
_requestHeaders: requestHeaders
}) && minimalMode && fetchCache) {
if (debug) {
console.log("using fetch cache handler");
}
CurCacheHandler = _fetchcache.default;
}
} 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[_constants.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[_constants.NEXT_CACHE_REVALIDATED_TAGS_HEADER] === "string" && requestHeaders[_constants.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[_constants.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 : (0, _normalizepagepath.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 : (0, _base64arraybuffer.encode)(value));
const curBuffer = typeof value === "string" ? (0, _encodedecode.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((0, _base64arraybuffer.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 = (0, _encodedecode.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 * _constants.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.default.posix.join("/_next/data", `${(0, _normalizepagepath.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

1
node_modules/next/dist/server/lib/is-ipv6.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export declare function isIPv6(s: string): boolean;

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

@@ -0,0 +1,41 @@
// 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.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "isIPv6", {
enumerable: true,
get: function() {
return isIPv6;
}
});
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,})?$");
function isIPv6(s) {
return IPv6Reg.test(s);
}
//# sourceMappingURL=is-ipv6.js.map

1
node_modules/next/dist/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":["isIPv6","v4Seg","v4Str","v6Seg","IPv6Reg","RegExp","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;;;;;+BAkBzBA;;;eAAAA;;;AAhBhB,MAAMC,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;AAGG,SAASH,OAAOM,CAAS;IAC9B,OAAOF,QAAQG,IAAI,CAACD;AACtB"}

View File

@@ -0,0 +1 @@
export declare function checkIsNodeDebugging(): boolean | "brk";

20
node_modules/next/dist/server/lib/is-node-debugging.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "checkIsNodeDebugging", {
enumerable: true,
get: function() {
return checkIsNodeDebugging;
}
});
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":";;;;+BAAgBA;;;eAAAA;;;AAAT,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 @@
export declare function matchNextDataPathname(pathname: string | null | undefined): false | Record<string, any>;

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "matchNextDataPathname", {
enumerable: true,
get: function() {
return matchNextDataPathname;
}
});
const _pathmatch = require("../../shared/lib/router/utils/path-match");
const matcher = (0, _pathmatch.getPathMatch)("/_next/data/:path*");
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":["matchNextDataPathname","matcher","getPathMatch","pathname"],"mappings":";;;;+BAIgBA;;;eAAAA;;;2BAJa;AAE7B,MAAMC,UAAUC,IAAAA,uBAAY,EAAC;AAEtB,SAASF,sBAAsBG,QAAmC;IACvE,IAAI,OAAOA,aAAa,UAAU,OAAO;IAEzC,OAAOF,QAAQE;AACjB"}

114
node_modules/next/dist/server/lib/mock-request.d.ts generated vendored Normal file
View File

@@ -0,0 +1,114 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import type { ServerResponse, OutgoingHttpHeaders, OutgoingHttpHeader, IncomingMessage, IncomingHttpHeaders } from 'http';
import type { Socket } from 'net';
import Stream from 'stream';
interface MockedRequestOptions {
url: string;
headers: IncomingHttpHeaders;
method: string;
readable?: Stream.Readable;
socket?: Socket | null;
}
export declare class MockedRequest extends Stream.Readable implements IncomingMessage {
url: string;
readonly statusCode?: number | undefined;
readonly statusMessage?: string | undefined;
readonly headers: IncomingHttpHeaders;
readonly method: string;
readonly httpVersion = "1.0";
readonly httpVersionMajor = 1;
readonly httpVersionMinor = 0;
private bodyReadable?;
socket: Socket;
constructor({ url, headers, method, socket, readable, }: MockedRequestOptions);
get headersDistinct(): NodeJS.Dict<string[]>;
_read(size: number): void;
/**
* The `connection` property is just an alias for the `socket` property.
*
* @deprecated — since v13.0.0 - Use socket instead.
*/
get connection(): Socket;
get aborted(): boolean;
get complete(): boolean;
get trailers(): NodeJS.Dict<string>;
get trailersDistinct(): NodeJS.Dict<string[]>;
get rawTrailers(): string[];
get rawHeaders(): string[];
setTimeout(): this;
}
export interface MockedResponseOptions {
statusCode?: number;
socket?: Socket | null;
headers?: OutgoingHttpHeaders;
resWriter?: (chunk: Buffer | string) => boolean;
}
export declare class MockedResponse extends Stream.Writable implements ServerResponse {
statusCode: number;
statusMessage: string;
finished: boolean;
headersSent: boolean;
readonly socket: Socket | null;
private resWriter;
readonly headPromise: Promise<void>;
private headPromiseResolve?;
constructor(res?: MockedResponseOptions);
appendHeader(name: string, value: string | string[]): this;
/**
* The `connection` property is just an alias for the `socket` property.
*
* @deprecated — since v13.0.0 - Use socket instead.
*/
get connection(): Socket | null;
write(chunk: Buffer | string): boolean;
end(): this;
/**
* 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(): void;
_write(chunk: Buffer | string, _encoding: string, callback: () => void): void;
writeHead(statusCode: number, statusMessage?: string | undefined, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] | undefined): this;
writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] | undefined): this;
hasHeader(name: string): boolean;
getHeader(name: string): string | undefined;
getHeaders(): OutgoingHttpHeaders;
getHeaderNames(): string[];
setHeader(name: string, value: OutgoingHttpHeader): this;
removeHeader(name: string): void;
get strictContentLength(): boolean;
writeEarlyHints(): void;
get req(): IncomingMessage;
assignSocket(): void;
detachSocket(): void;
writeContinue(): void;
writeProcessing(): void;
get upgrading(): boolean;
get chunkedEncoding(): boolean;
get shouldKeepAlive(): boolean;
get useChunkedEncodingByDefault(): boolean;
get sendDate(): boolean;
setTimeout(): this;
addTrailers(): void;
flushHeaders(): void;
}
interface RequestResponseMockerOptions {
url: string;
headers?: IncomingHttpHeaders;
method?: string;
bodyReadable?: Stream.Readable;
resWriter?: (chunk: Buffer | string) => boolean;
socket?: Socket | null;
}
export declare function createRequestResponseMocks({ url, headers, method, bodyReadable, resWriter, socket, }: RequestResponseMockerOptions): {
req: MockedRequest;
res: MockedResponse;
};
export {};

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

@@ -0,0 +1,328 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
MockedRequest: null,
MockedResponse: null,
createRequestResponseMocks: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
MockedRequest: function() {
return MockedRequest;
},
MockedResponse: function() {
return MockedResponse;
},
createRequestResponseMocks: function() {
return createRequestResponseMocks;
}
});
const _stream = /*#__PURE__*/ _interop_require_default(require("stream"));
const _utils = require("../web/utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
class MockedRequest extends _stream.default.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.");
}
}
class MockedResponse extends _stream.default.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 ? (0, _utils.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 (0, _utils.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.");
}
}
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 @@
import '../node-polyfill-fetch';

View File

@@ -0,0 +1,2 @@
import type { CacheFs } from '../../shared/lib/utils';
export declare const nodeFs: CacheFs;

27
node_modules/next/dist/server/lib/node-fs-methods.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "nodeFs", {
enumerable: true,
get: function() {
return nodeFs;
}
});
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const nodeFs = {
readFile: (f)=>_fs.default.promises.readFile(f),
readFileSync: (f)=>_fs.default.readFileSync(f),
writeFile: (f, d)=>_fs.default.promises.writeFile(f, d),
mkdir: (dir)=>_fs.default.promises.mkdir(dir, {
recursive: true
}),
stat: (f)=>_fs.default.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":["nodeFs","readFile","f","_fs","promises","readFileSync","writeFile","d","mkdir","dir","recursive","stat"],"mappings":";;;;+BAGaA;;;eAAAA;;;2DAHG;;;;;;AAGT,MAAMA,SAAkB;IAC7BC,UAAU,CAACC,IAAMC,WAAG,CAACC,QAAQ,CAACH,QAAQ,CAACC;IACvCG,cAAc,CAACH,IAAMC,WAAG,CAACE,YAAY,CAACH;IACtCI,WAAW,CAACJ,GAAGK,IAAMJ,WAAG,CAACC,QAAQ,CAACE,SAAS,CAACJ,GAAGK;IAC/CC,OAAO,CAACC,MAAQN,WAAG,CAACC,QAAQ,CAACI,KAAK,CAACC,KAAK;YAAEC,WAAW;QAAK;IAC1DC,MAAM,CAACT,IAAMC,WAAG,CAACC,QAAQ,CAACO,IAAI,CAACT;AACjC"}

8
node_modules/next/dist/server/lib/patch-fetch.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import type { StaticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external';
import type * as ServerHooks from '../../client/components/hooks-server-context';
export declare function validateTags(tags: any[], description: string): string[];
export declare function addImplicitTags(staticGenerationStore: ReturnType<StaticGenerationAsyncStorage['getStore']>): string[];
export declare function patchFetch({ serverHooks, staticGenerationAsyncStorage, }: {
serverHooks: typeof ServerHooks;
staticGenerationAsyncStorage: StaticGenerationAsyncStorage;
}): void;

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

@@ -0,0 +1,524 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
validateTags: null,
addImplicitTags: null,
patchFetch: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
validateTags: function() {
return validateTags;
},
addImplicitTags: function() {
return addImplicitTags;
},
patchFetch: function() {
return patchFetch;
}
});
const _constants = require("./trace/constants");
const _tracer = require("./trace/tracer");
const _constants1 = require("../../lib/constants");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log"));
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const isEdgeRuntime = process.env.NEXT_RUNTIME === "edge";
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 > _constants1.NEXT_CACHE_TAG_MAX_LENGTH) {
invalidTags.push({
tag,
reason: `exceeded max length of ${_constants1.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;
};
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 = `${_constants1.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 = `${_constants1.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
});
}
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 (0, _tracer.getTracer)().trace(isInternal ? _constants.NextNodeServerSpan.internalFetch : _constants.AppRenderSpan.fetch, {
kind: _tracer.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" ? _constants1.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

1
node_modules/next/dist/server/lib/patch-fetch.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

25
node_modules/next/dist/server/lib/render-server.d.ts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
/// <reference types="node" />
import type { RequestHandler } from '../next';
import { PropagateToWorkersField } from './router-utils/types';
export declare function clearModuleContext(target: string): Promise<void> | undefined;
export declare function deleteAppClientCache(): void | undefined;
export declare function deleteCache(filePaths: string[]): void;
export declare function propagateServerField(dir: string, field: PropagateToWorkersField, value: any): Promise<void>;
export declare function initialize(opts: {
dir: string;
port: number;
dev: boolean;
minimalMode?: boolean;
hostname?: string;
workerType: 'router' | 'render';
isNodeDebugging: boolean;
keepAliveTimeout?: number;
serverFields?: any;
server?: any;
experimentalTestProxy: boolean;
_ipcPort?: string;
_ipcKey?: string;
}): Promise<{
requestHandler: RequestHandler;
upgradeHandler: (req: import("http").IncomingMessage, socket: any, head: any) => Promise<void>;
} | undefined>;

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

@@ -0,0 +1,107 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
clearModuleContext: null,
deleteAppClientCache: null,
deleteCache: null,
propagateServerField: null,
initialize: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
clearModuleContext: function() {
return clearModuleContext;
},
deleteAppClientCache: function() {
return deleteAppClientCache;
},
deleteCache: function() {
return deleteCache;
},
propagateServerField: function() {
return propagateServerField;
},
initialize: function() {
return initialize;
}
});
const _next = /*#__PURE__*/ _interop_require_default(require("../next"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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");
}
function clearModuleContext(target) {
return sandboxContext == null ? void 0 : sandboxContext.clearModuleContext(target);
}
function deleteAppClientCache() {
return requireCacheHotReloader == null ? void 0 : requireCacheHotReloader.deleteAppClientCache();
}
function deleteCache(filePaths) {
for (const filePath of filePaths){
requireCacheHotReloader == null ? void 0 : requireCacheHotReloader.deleteCache(filePath);
}
}
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;
}
}
}
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 = (0, _next.default)({
...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":["clearModuleContext","deleteAppClientCache","deleteCache","propagateServerField","initialize","result","apps","sandboxContext","requireCacheHotReloader","process","env","NODE_ENV","require","target","filePaths","filePath","dir","field","value","app","Error","appField","server","apply","Array","isArray","opts","type","__NEXT_PRIVATE_RENDER_WORKER","title","requestHandler","upgradeHandler","next","_routerWorker","workerType","_renderWorker","hostname","customServer","httpServer","port","isNodeDebugging","getRequestHandler","getUpgradeHandler","prepare","serverFields"],"mappings":";;;;;;;;;;;;;;;;;;IA8BgBA,kBAAkB;eAAlBA;;IAIAC,oBAAoB;eAApBA;;IAIAC,WAAW;eAAXA;;IAMMC,oBAAoB;eAApBA;;IAuBAC,UAAU;eAAVA;;;6DAjEL;;;;;;AAGjB,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;AAEO,SAASZ,mBAAmBa,MAAc;IAC/C,OAAON,kCAAAA,eAAgBP,kBAAkB,CAACa;AAC5C;AAEO,SAASZ;IACd,OAAOO,2CAAAA,wBAAyBP,oBAAoB;AACtD;AAEO,SAASC,YAAYY,SAAmB;IAC7C,KAAK,MAAMC,YAAYD,UAAW;QAChCN,2CAAAA,wBAAyBN,WAAW,CAACa;IACvC;AACF;AAEO,eAAeZ,qBACpBa,GAAW,EACXC,KAA8B,EAC9BC,KAAU;IAEV,MAAMC,MAAMb,IAAI,CAACU,IAAI;IACrB,IAAI,CAACG,KAAK;QACR,MAAM,IAAIC,MAAM;IAClB;IACA,IAAIC,WAAW,AAACF,IAAYG,MAAM;IAElC,IAAID,UAAU;QACZ,IAAI,OAAOA,QAAQ,CAACJ,MAAM,KAAK,YAAY;YACzC,MAAMI,QAAQ,CAACJ,MAAM,CAACM,KAAK,CACzB,AAACJ,IAAYG,MAAM,EACnBE,MAAMC,OAAO,CAACP,SAASA,QAAQ,EAAE;QAErC,OAAO;YACLG,QAAQ,CAACJ,MAAM,GAAGC;QACpB;IACF;AACF;AAEO,eAAed,WAAWsB,IAchC;IACC,8DAA8D;IAC9D,4BAA4B;IAC5B,IAAIrB,MAAM,CAACqB,KAAKV,GAAG,CAAC,EAAE;QACpB,OAAOX,MAAM,CAACqB,KAAKV,GAAG,CAAC;IACzB;IAEA,MAAMW,OAAOlB,QAAQC,GAAG,CAACkB,4BAA4B;IACrD,IAAID,MAAM;QACRlB,QAAQoB,KAAK,GAAG,wBAAwBF;IAC1C;IAEA,IAAIG;IACJ,IAAIC;IAEJ,MAAMZ,MAAMa,IAAAA,aAAI,EAAC;QACf,GAAGN,IAAI;QACPO,eAAeP,KAAKQ,UAAU,KAAK;QACnCC,eAAeT,KAAKQ,UAAU,KAAK;QACnCE,UAAUV,KAAKU,QAAQ,IAAI;QAC3BC,cAAc;QACdC,YAAYZ,KAAKJ,MAAM;QACvBiB,MAAMb,KAAKa,IAAI;QACfC,iBAAiBd,KAAKc,eAAe;IACvC;IACAlC,IAAI,CAACoB,KAAKV,GAAG,CAAC,GAAGG;IACjBW,iBAAiBX,IAAIsB,iBAAiB;IACtCV,iBAAiBZ,IAAIuB,iBAAiB;IAEtC,MAAMvB,IAAIwB,OAAO,CAACjB,KAAKkB,YAAY;IAEnCvC,MAAM,CAACqB,KAAKV,GAAG,CAAC,GAAG;QACjBc;QACAC;IACF;IACA,OAAO1B,MAAM,CAACqB,KAAKV,GAAG,CAAC;AACzB"}

29
node_modules/next/dist/server/lib/route-resolver.d.ts generated vendored Normal file
View File

@@ -0,0 +1,29 @@
import type { NextConfigComplete } from '../config-shared';
import type { IncomingMessage, ServerResponse } from 'http';
import '../require-hook';
import '../node-polyfill-fetch';
type RouteResult = {
type: 'rewrite';
url: string;
statusCode: number;
headers: Record<string, undefined | number | string | string[]>;
} | {
type: 'error';
error: {
name: string;
message: string;
stack: any[];
};
} | {
type: 'none';
};
type MiddlewareConfig = {
matcher: string[] | null;
files: string[];
};
type ServerAddress = {
hostname?: string;
port?: number;
};
export declare function makeResolver(dir: string, nextConfig: NextConfigComplete, middleware: MiddlewareConfig, { hostname, port }: Partial<ServerAddress>): Promise<(req: IncomingMessage, res: ServerResponse) => Promise<RouteResult | void>>;
export {};

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

@@ -0,0 +1,185 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "makeResolver", {
enumerable: true,
get: function() {
return makeResolver;
}
});
require("../require-hook");
require("../node-polyfill-fetch");
const _url = /*#__PURE__*/ _interop_require_default(require("url"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _findpagefile = require("./find-page-file");
const _requestmeta = require("../request-meta");
const _debug = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/debug"));
const _bodystreams = require("../body-streams");
const _findpagesdir = require("../../lib/find-pages-dir");
const _filesystem = require("./router-utils/filesystem");
const _proxyrequest = require("./router-utils/proxy-request");
const _resolveroutes = require("./router-utils/resolve-routes");
const _constants = require("../../shared/lib/constants");
const _formathostname = require("./format-hostname");
const _nextrequest = require("../web/spec-extension/adapters/next-request");
const _middlewareroutematcher = require("../../shared/lib/router/utils/middleware-route-matcher");
const _pipereadable = require("../pipe-readable");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const debug = (0, _debug.default)("next:router-server");
async function makeResolver(dir, nextConfig, middleware, { hostname = "localhost", port = 3000 }) {
const fsChecker = await (0, _filesystem.setupFsCheck)({
dir,
dev: true,
minimalMode: false,
config: nextConfig
});
const { appDir, pagesDir } = (0, _findpagesdir.findPagesDir)(dir);
// we format the hostname so that it can be fetched
const fetchHostname = (0, _formathostname.formatHostname)(hostname);
fsChecker.ensureCallback(async (item)=>{
let result = null;
if (item.type === "appFile") {
if (!appDir) {
throw new Error("no app dir present");
}
result = await (0, _findpagefile.findPageFile)(appDir, item.itemPath, nextConfig.pageExtensions, true);
} else if (item.type === "pageFile") {
if (!pagesDir) {
throw new Error("no pages dir present");
}
result = await (0, _findpagefile.findPageFile)(pagesDir, item.itemPath, nextConfig.pageExtensions, false);
}
if (!result) {
throw new Error(`failed to find page file ${item.type} ${item.itemPath}`);
}
});
const distDir = _path.default.join(dir, nextConfig.distDir);
const middlewareInfo = middleware ? {
name: "middleware",
paths: middleware.files.map((file)=>_path.default.join(process.cwd(), file)),
wasm: [],
assets: []
} : {};
if (middleware == null ? void 0 : middleware.files.length) {
var _middleware_matcher;
fsChecker.middlewareMatcher = (0, _middlewareroutematcher.getMiddlewareRouteMatcher)(((_middleware_matcher = middleware.matcher) == null ? void 0 : _middleware_matcher.map((item)=>({
regexp: item,
originalSource: item
}))) || [
{
regexp: ".*",
originalSource: "/:path*"
}
]);
}
const resolveRoutes = (0, _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 = (0, _bodystreams.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: (0, _nextrequest.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: (0, _nextrequest.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.default.format(parsedUrl);
res.statusCode = statusCode;
res.setHeader("location", destination);
if (statusCode === _constants.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 (0, _pipereadable.pipeReadable)(bodyStream, res);
}
if (finished && parsedUrl.protocol) {
var _getRequestMeta;
await (0, _proxyrequest.proxyRequest)(req, res, parsedUrl, undefined, (_getRequestMeta = (0, _requestmeta.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.default.format(parsedUrl)
};
};
}
//# sourceMappingURL=route-resolver.js.map

File diff suppressed because one or more lines are too long

22
node_modules/next/dist/server/lib/router-server.d.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import type { WorkerRequestHandler, WorkerUpgradeHandler } from './setup-server-worker';
import '../node-polyfill-fetch';
import '../node-environment';
import '../require-hook';
export type RenderWorker = Pick<typeof import('./render-server'), 'initialize' | 'deleteCache' | 'clearModuleContext' | 'deleteAppClientCache' | 'propagateServerField'>;
export interface RenderWorkers {
app?: RenderWorker;
pages?: RenderWorker;
}
export declare function initialize(opts: {
dir: string;
port: number;
dev: boolean;
server?: import('http').Server;
minimalMode?: boolean;
hostname?: string;
workerType: 'router' | 'render';
isNodeDebugging: boolean;
keepAliveTimeout?: number;
customServer?: boolean;
experimentalTestProxy?: boolean;
}): Promise<[WorkerRequestHandler, WorkerUpgradeHandler]>;

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

@@ -0,0 +1,490 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "initialize", {
enumerable: true,
get: function() {
return initialize;
}
});
require("../node-polyfill-fetch");
require("../node-environment");
require("../require-hook");
const _url = /*#__PURE__*/ _interop_require_default(require("url"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _config = /*#__PURE__*/ _interop_require_default(require("../config"));
const _servestatic = require("../serve-static");
const _debug = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/debug"));
const _storage = require("../../telemetry/storage");
const _utils = require("../../shared/lib/utils");
const _findpagesdir = require("../../lib/find-pages-dir");
const _filesystem = require("./router-utils/filesystem");
const _proxyrequest = require("./router-utils/proxy-request");
const _pipereadable = require("../pipe-readable");
const _mockrequest = require("./mock-request");
const _resolveroutes = require("./router-utils/resolve-routes");
const _requestmeta = require("../request-meta");
const _pathhasprefix = require("../../shared/lib/router/utils/path-has-prefix");
const _removepathprefix = require("../../shared/lib/router/utils/remove-path-prefix");
const _compression = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/compression"));
const _baseserver = require("../base-server");
const _nextrequest = require("../web/spec-extension/adapters/next-request");
const _constants = require("../../shared/lib/constants");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const debug = (0, _debug.default)("next:router-server:main");
const devInstances = {};
const requestHandlers = {};
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 (0, _config.default)(opts.dev ? _constants.PHASE_DEVELOPMENT_SERVER : _constants.PHASE_PRODUCTION_SERVER, opts.dir, {
silent: false
});
let compress;
if ((config == null ? void 0 : config.compress) !== false) {
compress = (0, _compression.default)();
}
const fsChecker = await (0, _filesystem.setupFsCheck)({
dev: opts.dev,
dir: opts.dir,
config,
minimalMode: opts.minimalMode
});
const renderWorkers = {};
let devInstance;
if (opts.dev) {
const telemetry = new _storage.Telemetry({
distDir: _path.default.join(opts.dir, config.distDir)
});
const { pagesDir, appDir } = (0, _findpagesdir.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 = (0, _mockrequest.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 = (0, _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 && (0, _removepathprefix.removePathPrefix)(invokePath, config.basePath).startsWith(`/${parsedUrl.query.__nextLocale}/api`)) {
invokePath = fsChecker.handleLocale((0, _removepathprefix.removePathPrefix)(invokePath, config.basePath)).pathname;
}
if (req.headers["x-nextjs-data"] && ((_fsChecker_getMiddlewareMatchers = fsChecker.getMiddlewareMatchers()) == null ? void 0 : _fsChecker_getMiddlewareMatchers.length) && (0, _removepathprefix.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 _baseserver.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 ((0, _pipereadable.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 && (0, _pathhasprefix.pathHasPrefix)(origUrl, config.basePath)) {
req.url = (0, _removepathprefix.removePathPrefix)(origUrl, config.basePath);
}
const parsedUrl = _url.default.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: (0, _nextrequest.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 && (0, _pathhasprefix.pathHasPrefix)(origUrl, config.basePath)) {
req.url = (0, _removepathprefix.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.default.format(parsedUrl);
res.statusCode = statusCode;
res.setHeader("location", destination);
if (statusCode === _constants.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 (0, _pipereadable.pipeReadable)(bodyStream, res);
}
if (finished && parsedUrl.protocol) {
var _getRequestMeta;
return await (0, _proxyrequest.proxyRequest)(req, res, parsedUrl, undefined, (_getRequestMeta = (0, _requestmeta.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.default.parse("/405", true), "pages", "/405", handleIndex, {
"x-invoke-status": "405"
});
}
try {
return await (0, _servestatic.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.default.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 _utils.DecodeError) {
invokePath = "/400";
invokeStatus = "400";
} else {
console.error(err);
}
res.statusCode = Number(invokeStatus);
return await invokeRender(_url.default.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: (0, _nextrequest.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 (0, _proxyrequest.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,8 @@
export declare function buildDataRoute(page: string, buildId: string): {
page: string;
routeKeys: {
[named: string]: string;
} | undefined;
dataRouteRegex: string;
namedDataRouteRegex: string | undefined;
};

View File

@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "buildDataRoute", {
enumerable: true,
get: function() {
return buildDataRoute;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("../../../shared/lib/isomorphic/path"));
const _normalizepagepath = require("../../../shared/lib/page-path/normalize-page-path");
const _isdynamic = require("../../../shared/lib/router/utils/is-dynamic");
const _routeregex = require("../../../shared/lib/router/utils/route-regex");
const _loadcustomroutes = require("../../../lib/load-custom-routes");
const _escaperegexp = require("../../../shared/lib/escape-regexp");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function buildDataRoute(page, buildId) {
const pagePath = (0, _normalizepagepath.normalizePagePath)(page);
const dataRoute = _path.default.posix.join("/_next/data", buildId, `${pagePath}.json`);
let dataRouteRegex;
let namedDataRouteRegex;
let routeKeys;
if ((0, _isdynamic.isDynamicRoute)(page)) {
const routeRegex = (0, _routeregex.getNamedRouteRegex)(dataRoute.replace(/\.json$/, ""), true);
dataRouteRegex = (0, _loadcustomroutes.normalizeRouteRegex)(routeRegex.re.source.replace(/\(\?:\\\/\)\?\$$/, `\\.json$`));
namedDataRouteRegex = routeRegex.namedRegex.replace(/\(\?:\/\)\?\$$/, `\\.json$`);
routeKeys = routeRegex.routeKeys;
} else {
dataRouteRegex = (0, _loadcustomroutes.normalizeRouteRegex)(new RegExp(`^${_path.default.posix.join("/_next/data", (0, _escaperegexp.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":["buildDataRoute","page","buildId","pagePath","normalizePagePath","dataRoute","path","posix","join","dataRouteRegex","namedDataRouteRegex","routeKeys","isDynamicRoute","routeRegex","getNamedRouteRegex","replace","normalizeRouteRegex","re","source","namedRegex","RegExp","escapeStringRegexp"],"mappings":";;;;+BAOgBA;;;eAAAA;;;6DAPC;mCACiB;2BACH;4BACI;kCACC;8BACD;;;;;;AAE5B,SAASA,eAAeC,IAAY,EAAEC,OAAe;IAC1D,MAAMC,WAAWC,IAAAA,oCAAiB,EAACH;IACnC,MAAMI,YAAYC,aAAI,CAACC,KAAK,CAACC,IAAI,CAAC,eAAeN,SAAS,CAAC,EAAEC,SAAS,KAAK,CAAC;IAE5E,IAAIM;IACJ,IAAIC;IACJ,IAAIC;IAEJ,IAAIC,IAAAA,yBAAc,EAACX,OAAO;QACxB,MAAMY,aAAaC,IAAAA,8BAAkB,EACnCT,UAAUU,OAAO,CAAC,WAAW,KAC7B;QAGFN,iBAAiBO,IAAAA,qCAAmB,EAClCH,WAAWI,EAAE,CAACC,MAAM,CAACH,OAAO,CAAC,oBAAoB,CAAC,QAAQ,CAAC;QAE7DL,sBAAsBG,WAAWM,UAAU,CAAEJ,OAAO,CAClD,kBACA,CAAC,QAAQ,CAAC;QAEZJ,YAAYE,WAAWF,SAAS;IAClC,OAAO;QACLF,iBAAiBO,IAAAA,qCAAmB,EAClC,IAAII,OACF,CAAC,CAAC,EAAEd,aAAI,CAACC,KAAK,CAACC,IAAI,CACjB,eACAa,IAAAA,gCAAkB,EAACnB,UACnB,CAAC,EAAEC,SAAS,KAAK,CAAC,EAClB,CAAC,CAAC,EACJe,MAAM;IAEZ;IAEA,OAAO;QACLjB;QACAU;QACAF;QACAC;IACF;AACF"}

View File

@@ -0,0 +1,75 @@
import type { ManifestRoute, PrerenderManifest } from '../../../build';
import type { NextConfigComplete } from '../../config-shared';
import { PatchMatcher } from '../../../shared/lib/router/utils/path-match';
import { MiddlewareRouteMatch } from '../../../shared/lib/router/utils/middleware-route-matcher';
export type FsOutput = {
type: 'appFile' | 'pageFile' | 'nextImage' | 'publicFolder' | 'nextStaticFolder' | 'legacyStaticFolder' | 'devVirtualFsItem';
itemPath: string;
fsPath?: string;
itemsRoot?: string;
locale?: string;
};
export type FilesystemDynamicRoute = ManifestRoute & {
/**
* The path matcher that can be used to match paths against this route.
*/
match: PatchMatcher;
};
export declare const buildCustomRoute: <T>(type: 'redirect' | 'header' | 'rewrite' | 'before_files_rewrite', item: T & {
source: string;
}, basePath?: string, caseSensitive?: boolean) => T & {
match: PatchMatcher;
check?: boolean | undefined;
};
export declare function setupFsCheck(opts: {
dir: string;
dev: boolean;
minimalMode?: boolean;
config: NextConfigComplete;
addDevWatcherCallback?: (arg: (files: Map<string, {
timestamp: number;
}>) => void) => void;
}): Promise<{
headers: (import("../../../lib/load-custom-routes").Header & {
match: PatchMatcher;
check?: boolean | undefined;
})[];
rewrites: {
beforeFiles: (import("../../../lib/load-custom-routes").Rewrite & {
match: PatchMatcher;
check?: boolean | undefined;
})[];
afterFiles: (import("../../../lib/load-custom-routes").Rewrite & {
match: PatchMatcher;
check?: boolean | undefined;
})[];
fallback: (import("../../../lib/load-custom-routes").Rewrite & {
match: PatchMatcher;
check?: boolean | undefined;
})[];
};
redirects: (import("../../../lib/load-custom-routes").Redirect & {
match: PatchMatcher;
check?: boolean | undefined;
})[];
buildId: string;
handleLocale: (pathname: string, locales?: string[]) => {
locale: string | undefined;
pathname: string;
};
appFiles: Set<string>;
pageFiles: Set<string>;
dynamicRoutes: FilesystemDynamicRoute[];
nextDataRoutes: Set<string>;
interceptionRoutes: {
match: PatchMatcher;
check?: boolean | undefined;
}[] | undefined;
devVirtualFsItems: Set<string>;
prerenderManifest: PrerenderManifest;
middlewareMatcher: MiddlewareRouteMatch | undefined;
ensureCallback(fn: (item: FsOutput) => Promise<void> | undefined): void;
getItem(itemPath: string): Promise<FsOutput | null>;
getDynamicRoutes(): FilesystemDynamicRoute[];
getMiddlewareMatchers(): MiddlewareRouteMatch | undefined;
}>;

View File

@@ -0,0 +1,489 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
buildCustomRoute: null,
setupFsCheck: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
buildCustomRoute: function() {
return buildCustomRoute;
},
setupFsCheck: function() {
return setupFsCheck;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _promises = /*#__PURE__*/ _interop_require_default(require("fs/promises"));
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../../build/output/log"));
const _debug = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/debug"));
const _lrucache = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/lru-cache"));
const _loadcustomroutes = /*#__PURE__*/ _interop_require_default(require("../../../lib/load-custom-routes"));
const _redirectstatus = require("../../../lib/redirect-status");
const _fileexists = require("../../../lib/file-exists");
const _recursivereaddir = require("../../../lib/recursive-readdir");
const _utils = require("../../../shared/lib/router/utils");
const _escaperegexp = require("../../../shared/lib/escape-regexp");
const _pathmatch = require("../../../shared/lib/router/utils/path-match");
const _routeregex = require("../../../shared/lib/router/utils/route-regex");
const _routematcher = require("../../../shared/lib/router/utils/route-matcher");
const _pathhasprefix = require("../../../shared/lib/router/utils/path-has-prefix");
const _normalizelocalepath = require("../../../shared/lib/i18n/normalize-locale-path");
const _removepathprefix = require("../../../shared/lib/router/utils/remove-path-prefix");
const _middlewareroutematcher = require("../../../shared/lib/router/utils/middleware-route-matcher");
const _constants = require("../../../shared/lib/constants");
const _normalizepathsep = require("../../../shared/lib/page-path/normalize-path-sep");
const _getmetadataroute = require("../../../lib/metadata/get-metadata-route");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const debug = (0, _debug.default)("next:router-server:filesystem");
const buildCustomRoute = (type, item, basePath, caseSensitive)=>{
const restrictedRedirectPaths = [
"/_next"
].map((p)=>basePath ? `${basePath}${p}` : p);
const match = (0, _pathmatch.getPathMatch)(item.source, {
strict: true,
removeUnnamedParams: true,
regexModifier: !item.internal ? (regex)=>(0, _redirectstatus.modifyRouteRegex)(regex, type === "redirect" ? restrictedRedirectPaths : undefined) : undefined,
sensitive: caseSensitive
});
return {
...item,
...type === "rewrite" ? {
check: true
} : {},
match
};
};
async function setupFsCheck(opts) {
const getItemsLru = !opts.dev ? new _lrucache.default({
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.default.join(opts.dir, opts.config.distDir);
const publicFolderPath = _path.default.join(opts.dir, "public");
const nextStaticFolderPath = _path.default.join(distDir, "static");
const legacyStaticFolderPath = _path.default.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.default.join(opts.dir, opts.config.distDir, _constants.BUILD_ID_FILE);
buildId = await _promises.default.readFile(buildIdPath, "utf8");
try {
for (const file of (await (0, _recursivereaddir.recursiveReadDir)(publicFolderPath))){
// Ensure filename is encoded and normalized.
publicFolderItems.add(encodeURI((0, _normalizepathsep.normalizePathSep)(file)));
}
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
}
try {
for (const file of (await (0, _recursivereaddir.recursiveReadDir)(legacyStaticFolderPath))){
// Ensure filename is encoded and normalized.
legacyStaticFolderItems.add(encodeURI((0, _normalizepathsep.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 (0, _recursivereaddir.recursiveReadDir)(nextStaticFolderPath))){
// Ensure filename is encoded and normalized.
nextStaticFolderItems.add(_path.default.posix.join("/_next/static", encodeURI((0, _normalizepathsep.normalizePathSep)(file))));
}
} catch (err) {
if (opts.config.output !== "standalone") throw err;
}
const routesManifestPath = _path.default.join(distDir, _constants.ROUTES_MANIFEST);
const prerenderManifestPath = _path.default.join(distDir, _constants.PRERENDER_MANIFEST);
const middlewareManifestPath = _path.default.join(distDir, "server", _constants.MIDDLEWARE_MANIFEST);
const pagesManifestPath = _path.default.join(distDir, "server", _constants.PAGES_MANIFEST);
const appRoutesManifestPath = _path.default.join(distDir, _constants.APP_PATH_ROUTES_MANIFEST);
const routesManifest = JSON.parse(await _promises.default.readFile(routesManifestPath, "utf8"));
prerenderManifest = JSON.parse(await _promises.default.readFile(prerenderManifestPath, "utf8"));
const middlewareManifest = JSON.parse(await _promises.default.readFile(middlewareManifestPath, "utf8").catch(()=>"{}"));
const pagesManifest = JSON.parse(await _promises.default.readFile(pagesManifestPath, "utf8"));
const appRoutesManifest = JSON.parse(await _promises.default.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((0, _normalizelocalepath.normalizeLocalePath)(key, opts.config.i18n.locales).pathname);
} else {
pageFiles.add(key);
}
}
for (const key of Object.keys(appRoutesManifest)){
appFiles.add(appRoutesManifest[key]);
}
const escapedBuildId = (0, _escaperegexp.escapeStringRegexp)(buildId);
for (const route of routesManifest.dataRoutes){
if ((0, _utils.isDynamicRoute)(route.page)) {
const routeRegex = (0, _routeregex.getRouteRegex)(route.page);
dynamicRoutes.push({
...route,
regex: routeRegex.re.toString(),
match: (0, _routematcher.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: (0, _routematcher.getRouteMatcher)((0, _routeregex.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 = (0, _middlewareroutematcher.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 (0, _loadcustomroutes.default)(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 = (0, _normalizelocalepath.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 && !(0, _pathhasprefix.pathHasPrefix)(itemPath, basePath)) {
return null;
}
itemPath = (0, _removepathprefix.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 (!(0, _pathhasprefix.pathHasPrefix)(curItemPath, "/static")) {
continue;
}
curItemPath = curItemPath.substring("/static".length);
try {
curDecodedItemPath = decodeURIComponent(curItemPath);
} catch {}
}
if (type === "nextStaticFolder" && !(0, _pathhasprefix.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.default.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 (0, _fileexists.fileExists)(fsPath, _fileexists.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.default.posix.join(itemsRoot, tempItemPath);
found = await (0, _fileexists.fileExists)(fsPath, _fileexists.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 ? (0, _getmetadataroute.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,4 @@
/// <reference types="node" />
import type { IncomingMessage, ServerResponse } from 'http';
import type { NextUrlWithParsedQuery } from '../../request-meta';
export declare function proxyRequest(req: IncomingMessage, res: ServerResponse, parsedUrl: NextUrlWithParsedQuery, upgradeHead?: any, reqBody?: any, proxyTimeout?: number | null): Promise<void>;

View File

@@ -0,0 +1,108 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "proxyRequest", {
enumerable: true,
get: function() {
return proxyRequest;
}
});
const _url = /*#__PURE__*/ _interop_require_default(require("url"));
const _serverrouteutils = require("../../server-route-utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function proxyRequest(req, res, parsedUrl, upgradeHead, reqBody, proxyTimeout) {
const { query } = parsedUrl;
delete parsedUrl.query;
parsedUrl.search = (0, _serverrouteutils.stringifyQuery)(req, query);
const target = _url.default.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":["proxyRequest","req","res","parsedUrl","upgradeHead","reqBody","proxyTimeout","query","search","stringifyQuery","target","url","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":";;;;+BAMsBA;;;eAAAA;;;4DAHN;kCACe;;;;;;AAExB,eAAeA,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,GAAGC,IAAAA,gCAAc,EAACR,KAAYM;IAE9C,MAAMG,SAASC,YAAG,CAACC,MAAM,CAACT;IAC1B,MAAMU,YACJC,QAAQ;IAEV,MAAMC,QAAQ,IAAIF,UAAU;QAC1BH;QACAM,cAAc;QACdC,YAAY;QACZC,MAAM;QACNC,IAAI;QACJ,4DAA4D;QAC5D,yDAAyD;QACzDb,cAAcA,iBAAiB,OAAOc,YAAYd,gBAAgB;IACpE;IAEA,MAAM,IAAIe,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;YACpBxB,IAAIuB,EAAE,CAAC,SAAS,IAAMC,SAASC,OAAO;QACxC;QACAZ,MAAMU,EAAE,CAAC,YAAY,CAACG;YACpB,IAAI1B,IAAI2B,SAAS,EAAE;gBACjBD,SAASD,OAAO;YAClB,OAAO;gBACLzB,IAAIuB,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,EAAE3B,OAAO,CAAC,EAAEuB;YAC3C,IAAI,CAACT,UAAU;gBACbA,WAAW;gBACXD,YAAYU;gBAEZ,IAAI,CAAC/B,IAAI2B,SAAS,EAAE;oBAClB3B,IAAIoC,UAAU,GAAG;oBACjBpC,IAAIqC,GAAG,CAAC;gBACV;YACF;QACF;QAEA,wDAAwD;QACxD,IAAInC,aAAa;YACfW,MAAMU,EAAE,CAAC,cAAc,CAACC;gBACtBA,SAASD,EAAE,CAAC,SAAS;oBACnB,IAAI,CAACD,UAAU;wBACbA,WAAW;wBACXF,aAAa;oBACf;gBACF;YACF;YACAP,MAAMI,EAAE,CAAClB,KAA+BC,KAAKE;YAC7CkB,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,CAACvC,KAAKC,KAAK;gBAClBuC,QAAQpC;YACV;QACF;IACF;AACF"}

View File

@@ -0,0 +1,24 @@
import type { FsOutput } from './filesystem';
import type { IncomingMessage, ServerResponse } from 'http';
import type { NextConfigComplete } from '../../config-shared';
import type { RenderWorker, initialize } from '../router-server';
import { UnwrapPromise } from '../../../lib/coalesced-function';
import { NextUrlWithParsedQuery } from '../../request-meta';
import '../../node-polyfill-web-streams';
export declare function getResolveRoutes(fsChecker: UnwrapPromise<ReturnType<typeof import('./filesystem').setupFsCheck>>, config: NextConfigComplete, opts: Parameters<typeof initialize>[0], renderWorkers: {
app?: RenderWorker;
pages?: RenderWorker;
}, renderWorkerOpts: Parameters<RenderWorker['initialize']>[0], ensureMiddleware?: () => Promise<void>): ({ req, res, isUpgradeReq, invokedOutputs, }: {
req: IncomingMessage;
res: ServerResponse;
isUpgradeReq: boolean;
signal: AbortSignal;
invokedOutputs?: Set<string> | undefined;
}) => Promise<{
finished: boolean;
statusCode?: number | undefined;
bodyStream?: ReadableStream<any> | null | undefined;
resHeaders: Record<string, string | string[]>;
parsedUrl: NextUrlWithParsedQuery;
matchedOutput?: FsOutput | null | undefined;
}>;

View File

@@ -0,0 +1,530 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getResolveRoutes", {
enumerable: true,
get: function() {
return getResolveRoutes;
}
});
const _url = /*#__PURE__*/ _interop_require_default(require("url"));
const _debug = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/debug"));
const _bodystreams = require("../../body-streams");
const _utils = require("../server-ipc/utils");
const _serverrouteutils = require("../../server-route-utils");
const _formathostname = require("../format-hostname");
const _utils1 = require("../../web/utils");
const _pipereadable = require("../../pipe-readable");
const _gethostname = require("../../../shared/lib/get-hostname");
const _redirectstatus = require("../../../lib/redirect-status");
const _utils2 = require("../../../shared/lib/utils");
const _relativizeurl = require("../../../shared/lib/router/utils/relativize-url");
const _addpathprefix = require("../../../shared/lib/router/utils/add-path-prefix");
const _pathhasprefix = require("../../../shared/lib/router/utils/path-has-prefix");
const _detectdomainlocale = require("../../../shared/lib/i18n/detect-domain-locale");
const _normalizelocalepath = require("../../../shared/lib/i18n/normalize-locale-path");
const _removepathprefix = require("../../../shared/lib/router/utils/remove-path-prefix");
const _requestmeta = require("../../request-meta");
const _preparedestination = require("../../../shared/lib/router/utils/prepare-destination");
const _mockrequest = require("../mock-request");
require("../../node-polyfill-web-streams");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const debug = (0, _debug.default)("next:router-server:resolve-routes");
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.default.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.default.parse((0, _utils2.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}://${(0, _formathostname.formatHostname)(opts.hostname || "localhost")}:${opts.port}${req.url}` : req.url || "";
(0, _requestmeta.addRequestMeta)(req, "__NEXT_INIT_URL", initUrl);
(0, _requestmeta.addRequestMeta)(req, "__NEXT_INIT_QUERY", {
...parsedUrl.query
});
(0, _requestmeta.addRequestMeta)(req, "_protocol", protocol);
if (!isUpgradeReq) {
(0, _requestmeta.addRequestMeta)(req, "__NEXT_CLONABLE_BODY", (0, _bodystreams.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 = (0, _pathhasprefix.pathHasPrefix)(parsedUrl.pathname || "", config.basePath);
initialLocaleResult = (0, _normalizelocalepath.normalizeLocalePath)((0, _removepathprefix.removePathPrefix)(parsedUrl.pathname || "/", config.basePath), config.i18n.locales);
domainLocale = (0, _detectdomainlocale.detectDomainLocale)(config.i18n.domains, (0, _gethostname.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 = (0, _addpathprefix.addPathPrefix)(initialLocaleResult.pathname === "/" ? `/${defaultLocale}` : (0, _addpathprefix.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) && (0, _pathhasprefix.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 (!(0, _pathhasprefix.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((0, _addpathprefix.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 = (0, _removepathprefix.removePathPrefix)(curPathname, config.basePath);
}
const hadBasePath = curPathname !== parsedUrl.pathname;
const localeResult = (0, _normalizelocalepath.normalizeLocalePath)(curPathname, config.i18n.locales);
const isDefaultLocale = localeResult.detectedLocale === defaultLocale;
if (isDefaultLocale) {
curPathname = localeResult.pathname === "/" && hadBasePath ? config.basePath : (0, _addpathprefix.addPathPrefix)(localeResult.pathname, hadBasePath ? config.basePath : "");
} else if (hadBasePath) {
curPathname = curPathname === "/" ? config.basePath : (0, _addpathprefix.addPathPrefix)(curPathname, config.basePath);
}
if ((isDefaultLocale || hadBasePath) && hadTrailingSlash) {
curPathname = maybeAddTrailingSlash(curPathname);
}
}
let params = route.match(curPathname);
if ((route.has || route.missing) && params) {
const hasParams = (0, _preparedestination.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 = (0, _addpathprefix.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 = (0, _addpathprefix.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) && (0, _pathhasprefix.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 (0, _mockrequest.createRequestResponseMocks)({
url: req.url || "/",
method: req.method || "GET",
headers: (0, _utils.filterReqHeaders)(invokeHeaders, _utils.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 ((0, _pipereadable.isAbortError)(e)) {
return {
parsedUrl,
resHeaders,
finished: true
};
}
throw e;
}
if (res.closed || res.finished || !middlewareRes) {
return {
parsedUrl,
resHeaders,
finished: true
};
}
const middlewareHeaders = (0, _utils1.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({
...(0, _utils.filterReqHeaders)(middlewareHeaders, _utils.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 = (0, _relativizeurl.relativizeURL)(value, initUrl);
resHeaders["x-middleware-rewrite"] = rel;
const query = parsedUrl.query;
parsedUrl = _url.default.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 = (0, _normalizelocalepath.normalizeLocalePath)(parsedUrl.pathname || "", config.i18n.locales);
if (curLocaleResult.detectedLocale) {
parsedUrl.query.__nextLocale = curLocaleResult.detectedLocale;
}
}
}
if (middlewareHeaders["location"]) {
const value = middlewareHeaders["location"];
const rel = (0, _relativizeurl.relativizeURL)(value, initUrl);
resHeaders["location"] = rel;
parsedUrl = _url.default.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 } = (0, _preparedestination.prepareDestination)({
appendParamsToQuery: false,
destination: route.destination,
params: params,
query: parsedUrl.query
});
const { query } = parsedDestination;
delete parsedDestination.query;
parsedDestination.search = (0, _serverrouteutils.stringifyQuery)(req, query);
parsedDestination.pathname = (0, _utils2.normalizeRepeatedSlashes)(parsedDestination.pathname);
return {
finished: true,
// @ts-expect-error custom ParsedUrl
parsedUrl: parsedDestination,
statusCode: (0, _redirectstatus.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 = (0, _preparedestination.compileNonPath)(key, params);
value = (0, _preparedestination.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 } = (0, _preparedestination.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 = (0, _normalizelocalepath.normalizeLocalePath)((0, _removepathprefix.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

View File

@@ -0,0 +1,45 @@
/// <reference types="node" />
import type { NextConfigComplete } from '../../config-shared';
import { Telemetry } from '../../../telemetry/storage';
import { IncomingMessage, ServerResponse } from 'http';
import { UnwrapPromise } from '../../../lib/coalesced-function';
import { MiddlewareMatcher } from '../../../build/analysis/get-page-static-info';
import { MiddlewareRouteMatch } from '../../../shared/lib/router/utils/middleware-route-matcher';
import type { RenderWorkers } from '../router-server';
import { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types';
type SetupOpts = {
renderWorkers: RenderWorkers;
dir: string;
turbo?: boolean;
appDir?: string;
pagesDir?: string;
telemetry: Telemetry;
isCustomServer?: boolean;
fsChecker: UnwrapPromise<ReturnType<typeof import('./filesystem').setupFsCheck>>;
nextConfig: NextConfigComplete;
port: number;
};
export declare function setupDev(opts: SetupOpts): Promise<{
serverFields: {
actualMiddlewareFile?: string | undefined;
actualInstrumentationHookFile?: string | undefined;
appPathRoutes?: Record<string, string | string[]> | undefined;
middleware?: {
page: string;
match: MiddlewareRouteMatch;
matchers?: MiddlewareMatcher[] | undefined;
} | undefined;
hasAppNotFound?: boolean | undefined;
interceptionRoutes?: {
match: import("../../../shared/lib/router/utils/path-match").PatchMatcher;
check?: boolean | undefined;
}[] | undefined;
};
hotReloader: NextJsHotReloaderInterface;
requestHandler: (req: IncomingMessage, res: ServerResponse<IncomingMessage>) => Promise<{
finished: boolean;
}>;
logErrorWithOriginalStack: (err: unknown, type?: "warning" | "uncaughtException" | "unhandledRejection" | "app-dir" | undefined) => Promise<void>;
ensureMiddleware(): Promise<void>;
}>;
export {};

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 @@
export type PropagateToWorkersField = 'actualMiddlewareFile' | 'actualInstrumentationHookFile' | 'reloadMatchers' | 'loadEnvConfig' | 'appPathRoutes' | 'middleware';

View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
//# sourceMappingURL=types.js.map

View File

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

View File

@@ -0,0 +1,6 @@
import type NextServer from '../../next-server';
export declare function createIpcServer(server: InstanceType<typeof NextServer>): Promise<{
ipcPort: number;
ipcServer: import('http').Server;
ipcValidationKey: string;
}>;

76
node_modules/next/dist/server/lib/server-ipc/index.js generated vendored Normal file
View File

@@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createIpcServer", {
enumerable: true,
get: function() {
return createIpcServer;
}
});
const _render = require("../../render");
const _crypto = /*#__PURE__*/ _interop_require_default(require("crypto"));
const _iserror = /*#__PURE__*/ _interop_require_default(require("../../../lib/is-error"));
const _requestutils = require("./request-utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
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.default.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] = (0, _requestutils.deserializeErr)(args[0]);
}
let result = await server[method](...args);
if (result && typeof result === "object" && result.stack) {
result = (0, _render.errorToJSON)(result);
}
res.end(JSON.stringify(result || ""));
}
} catch (err) {
if ((0, _iserror.default)(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":["createIpcServer","server","ipcValidationKey","crypto","randomBytes","toString","ipcServer","require","createServer","req","res","url","URL","key","searchParams","get","end","method","args","JSON","parse","Array","isArray","stack","deserializeErr","result","errorToJSON","stringify","err","isError","code","console","error","name","message","ipcPort","Promise","resolveIpc","listen","hostname","addr","address","port"],"mappings":";;;;+BASsBA;;;eAAAA;;;wBARM;+DACT;gEACC;8BACW;;;;;;AAKxB,eAAeA,gBACpBC,MAAuC;IAMvC,6EAA6E;IAC7E,yEAAyE;IACzE,6BAA6B;IAC7B,MAAMC,mBAAmBC,eAAM,CAACC,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,CAACC,GAAG,CAAC;YAEjC,IAAIF,QAAQX,kBAAkB;gBAC5B,OAAOQ,IAAIM,GAAG;YAChB;YAEA,MAAMC,SAASN,IAAIG,YAAY,CAACC,GAAG,CAAC;YACpC,MAAMG,OAAcC,KAAKC,KAAK,CAACT,IAAIG,YAAY,CAACC,GAAG,CAAC,WAAW;YAE/D,IAAI,CAACE,UAAU,CAACI,MAAMC,OAAO,CAACJ,OAAO;gBACnC,OAAOR,IAAIM,GAAG;YAChB;YAEA,IAAI,OAAO,AAACf,MAAc,CAACgB,OAAO,KAAK,YAAY;oBACHC;gBAA9C,IAAID,WAAW,iCAA+BC,SAAAA,IAAI,CAAC,EAAE,qBAAPA,OAASK,KAAK,GAAE;oBAC5DL,IAAI,CAAC,EAAE,GAAGM,IAAAA,4BAAc,EAACN,IAAI,CAAC,EAAE;gBAClC;gBACA,IAAIO,SAAS,MAAM,AAACxB,MAAc,CAACgB,OAAO,IAAIC;gBAE9C,IAAIO,UAAU,OAAOA,WAAW,YAAYA,OAAOF,KAAK,EAAE;oBACxDE,SAASC,IAAAA,mBAAW,EAACD;gBACvB;gBACAf,IAAIM,GAAG,CAACG,KAAKQ,SAAS,CAACF,UAAU;YACnC;QACF,EAAE,OAAOG,KAAU;YACjB,IAAIC,IAAAA,gBAAO,EAACD,QAAQA,IAAIE,IAAI,KAAK,UAAU;gBACzCC,QAAQC,KAAK,CAACJ;YAChB;YACAlB,IAAIM,GAAG,CACLG,KAAKQ,SAAS,CAAC;gBACbC,KAAK;oBAAEK,MAAML,IAAIK,IAAI;oBAAEC,SAASN,IAAIM,OAAO;oBAAEX,OAAOK,IAAIL,KAAK;gBAAC;YAChE;QAEJ;IACF;IAGF,MAAMY,UAAU,MAAM,IAAIC,QAAgB,CAACC;QACzC/B,UAAUgC,MAAM,CAAC,GAAGrC,OAAOsC,QAAQ,EAAE;YACnC,MAAMC,OAAOlC,UAAUmC,OAAO;YAE9B,IAAID,QAAQ,OAAOA,SAAS,UAAU;gBACpCH,WAAWG,KAAKE,IAAI;YACtB;QACF;IACF;IAEA,OAAO;QACLP;QACA7B;QACAJ;IACF;AACF"}

View File

@@ -0,0 +1,7 @@
import type { IncomingMessage } from 'http';
import type { Readable } from 'stream';
export declare const invokeRequest: (targetUrl: string, requestInit: {
headers: IncomingMessage['headers'];
method: IncomingMessage['method'];
signal?: AbortSignal;
}, readableBody?: Readable | ReadableStream) => Promise<Response>;

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "invokeRequest", {
enumerable: true,
get: function() {
return invokeRequest;
}
});
const _utils = require("./utils");
const invokeRequest = async (targetUrl, requestInit, readableBody)=>{
const invokeHeaders = (0, _utils.filterReqHeaders)({
"cache-control": "",
...requestInit.headers
}, _utils.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":["invokeRequest","targetUrl","requestInit","readableBody","invokeHeaders","filterReqHeaders","headers","ipcForbiddenHeaders","fetch","method","redirect","signal","body","duplex","next","internal"],"mappings":";;;;+BAIaA;;;eAAAA;;;uBAFyC;AAE/C,MAAMA,gBAAgB,OAC3BC,WACAC,aAKAC;IAEA,MAAMC,gBAAgBC,IAAAA,uBAAgB,EACpC;QACE,iBAAiB;QACjB,GAAGH,YAAYI,OAAO;IACxB,GACAC,0BAAmB;IAGrB,OAAO,MAAMC,MAAMP,WAAW;QAC5BK,SAASF;QACTK,QAAQP,YAAYO,MAAM;QAC1BC,UAAU;QACVC,QAAQT,YAAYS,MAAM;QAE1B,GAAIT,YAAYO,MAAM,KAAK,SAC3BP,YAAYO,MAAM,KAAK,UACvBN,eACI;YACES,MAAMT;YACNU,QAAQ;QACV,IACA,CAAC,CAAC;QAENC,MAAM;YACJ,aAAa;YACbC,UAAU;QACZ;IACF;AACF"}

View File

@@ -0,0 +1,8 @@
export declare const deserializeErr: (serializedErr: any) => any;
export declare function invokeIpcMethod({ fetchHostname, method, args, ipcPort, ipcKey, }: {
fetchHostname?: string;
method: string;
args: any[];
ipcPort?: string;
ipcKey?: string;
}): Promise<any>;

View File

@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
deserializeErr: null,
invokeIpcMethod: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
deserializeErr: function() {
return deserializeErr;
},
invokeIpcMethod: function() {
return invokeIpcMethod;
}
});
const _utils = require("../../../shared/lib/utils");
const _invokerequest = require("./invoke-request");
const deserializeErr = (serializedErr)=>{
if (!serializedErr || typeof serializedErr !== "object" || !serializedErr.stack) {
return serializedErr;
}
let ErrorType = Error;
if (serializedErr.name === "PageNotFoundError") {
ErrorType = _utils.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;
};
async function invokeIpcMethod({ fetchHostname = "localhost", method, args, ipcPort, ipcKey }) {
if (ipcPort) {
const res = await (0, _invokerequest.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":["deserializeErr","invokeIpcMethod","serializedErr","stack","ErrorType","Error","name","PageNotFoundError","err","message","digest","process","env","NEXT_RUNTIME","decorateServerError","require","source","fetchHostname","method","args","ipcPort","ipcKey","res","invokeRequest","encodeURIComponent","JSON","stringify","headers","body","text","startsWith","endsWith","parsedBody","parse"],"mappings":";;;;;;;;;;;;;;;IAGaA,cAAc;eAAdA;;IA2BSC,eAAe;eAAfA;;;uBA9BY;+BACJ;AAEvB,MAAMD,iBAAiB,CAACE;IAC7B,IACE,CAACA,iBACD,OAAOA,kBAAkB,YACzB,CAACA,cAAcC,KAAK,EACpB;QACA,OAAOD;IACT;IACA,IAAIE,YAAiBC;IAErB,IAAIH,cAAcI,IAAI,KAAK,qBAAqB;QAC9CF,YAAYG,wBAAiB;IAC/B;IAEA,MAAMC,MAAM,IAAIJ,UAAUF,cAAcO,OAAO;IAC/CD,IAAIL,KAAK,GAAGD,cAAcC,KAAK;IAC/BK,IAAIF,IAAI,GAAGJ,cAAcI,IAAI;IAC3BE,IAAYE,MAAM,GAAGR,cAAcQ,MAAM;IAE3C,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;QACvC,MAAM,EAAEC,mBAAmB,EAAE,GAC3BC,QAAQ;QACVD,oBAAoBN,KAAKN,cAAcc,MAAM,IAAI;IACnD;IACA,OAAOR;AACT;AAEO,eAAeP,gBAAgB,EACpCgB,gBAAgB,WAAW,EAC3BC,MAAM,EACNC,IAAI,EACJC,OAAO,EACPC,MAAM,EAOP;IACC,IAAID,SAAS;QACX,MAAME,MAAM,MAAMC,IAAAA,4BAAa,EAC7B,CAAC,OAAO,EAAEN,cAAc,CAAC,EAAEG,QAAQ,KAAK,EAAEC,OAAO,QAAQ,EACvDH,OACD,MAAM,EAAEM,mBAAmBC,KAAKC,SAAS,CAACP,OAAO,CAAC,EACnD;YACED,QAAQ;YACRS,SAAS,CAAC;QACZ;QAEF,MAAMC,OAAO,MAAMN,IAAIO,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,MAAMR,eAAegC,WAAWxB,GAAG;YACrC;YACA,OAAOwB;QACT;IACF;AACF"}

View File

@@ -0,0 +1,3 @@
export declare const ipcForbiddenHeaders: string[];
export declare const actionsForbiddenHeaders: string[];
export declare const filterReqHeaders: (headers: Record<string, undefined | string | number | string[]>, forbiddenHeaders: string[]) => Record<string, string | string[] | undefined>;

56
node_modules/next/dist/server/lib/server-ipc/utils.js generated vendored Normal file
View File

@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ipcForbiddenHeaders: null,
actionsForbiddenHeaders: null,
filterReqHeaders: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ipcForbiddenHeaders: function() {
return ipcForbiddenHeaders;
},
actionsForbiddenHeaders: function() {
return actionsForbiddenHeaders;
},
filterReqHeaders: function() {
return filterReqHeaders;
}
});
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"
];
const actionsForbiddenHeaders = [
...ipcForbiddenHeaders,
"content-length"
];
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":";;;;;;;;;;;;;;;;IAAaA,mBAAmB;eAAnBA;;IAYAC,uBAAuB;eAAvBA;;IAKAC,gBAAgB;eAAhBA;;;AAjBN,MAAMF,sBAAsB;IACjC;IACA;IACA;IACA;IACA;IACA,+CAA+C;IAC/C;IACA,2IAA2I;IAC3I;CACD;AAEM,MAAMC,0BAA0B;OAClCD;IACH;CACD;AAEM,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"}

View File

@@ -0,0 +1,24 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import http, { IncomingMessage, ServerResponse } from 'http';
import '../require-hook';
import '../node-polyfill-fetch';
import { Duplex } from 'stream';
export declare const RESTART_EXIT_CODE = 77;
export type WorkerRequestHandler = (req: IncomingMessage, res: ServerResponse) => Promise<any>;
export type WorkerUpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => any;
export declare function initializeServerWorker(requestHandler: WorkerRequestHandler, upgradeHandler: WorkerUpgradeHandler, opts: {
dir: string;
port: number;
dev: boolean;
minimalMode?: boolean;
hostname?: string;
workerType: 'router' | 'render';
isNodeDebugging: boolean;
keepAliveTimeout?: number;
}): Promise<{
port: number;
hostname: string;
server: http.Server;
}>;

View File

@@ -0,0 +1,91 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
RESTART_EXIT_CODE: null,
initializeServerWorker: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
RESTART_EXIT_CODE: function() {
return RESTART_EXIT_CODE;
},
initializeServerWorker: function() {
return initializeServerWorker;
}
});
const _v8 = /*#__PURE__*/ _interop_require_default(require("v8"));
const _http = /*#__PURE__*/ _interop_require_default(require("http"));
require("../require-hook");
require("../node-polyfill-fetch");
const _log = require("../../build/output/log");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
process.on("unhandledRejection", (err)=>{
console.error(err);
});
process.on("uncaughtException", (err)=>{
console.error(err);
});
const RESTART_EXIT_CODE = 77;
const MAXIMUM_HEAP_SIZE_ALLOWED = _v8.default.getHeapStatistics().heap_size_limit / 1024 / 1024 * 0.9;
async function initializeServerWorker(requestHandler, upgradeHandler, opts) {
const server = _http.default.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) {
(0, _log.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":["RESTART_EXIT_CODE","initializeServerWorker","process","on","err","console","error","MAXIMUM_HEAP_SIZE_ALLOWED","v8","getHeapStatistics","heap_size_limit","requestHandler","upgradeHandler","opts","server","http","createServer","req","res","catch","statusCode","end","finally","memoryUsage","heapUsed","warn","close","exit","keepAliveTimeout","Promise","resolve","reject","socket","upgrade","hostname","addr","address","host","undefined","port","listen"],"mappings":";;;;;;;;;;;;;;;IAkBaA,iBAAiB;eAAjBA;;IAgBSC,sBAAsB;eAAtBA;;;2DAlCP;6DACuC;QAG/C;QACA;qBAEc;;;;;;AAGrBC,QAAQC,EAAE,CAAC,sBAAsB,CAACC;IAChCC,QAAQC,KAAK,CAACF;AAChB;AAEAF,QAAQC,EAAE,CAAC,qBAAqB,CAACC;IAC/BC,QAAQC,KAAK,CAACF;AAChB;AAEO,MAAMJ,oBAAoB;AAEjC,MAAMO,4BACJ,AAACC,WAAE,CAACC,iBAAiB,GAAGC,eAAe,GAAG,OAAO,OAAQ;AAapD,eAAeT,uBACpBU,cAAoC,EACpCC,cAAoC,EACpCC,IASC;IAMD,MAAMC,SAASC,aAAI,CAACC,YAAY,CAAC,CAACC,KAAKC;QACrC,OAAOP,eAAeM,KAAKC,KACxBC,KAAK,CAAC,CAACf;YACNc,IAAIE,UAAU,GAAG;YACjBF,IAAIG,GAAG,CAAC;YACRhB,QAAQC,KAAK,CAACF;QAChB,GACCkB,OAAO,CAAC;YACP,IACEpB,QAAQqB,WAAW,GAAGC,QAAQ,GAAG,OAAO,OACxCjB,2BACA;gBACAkB,IAAAA,SAAI,EACF;gBAEFX,OAAOY,KAAK;gBACZxB,QAAQyB,IAAI,CAAC3B;YACf;QACF;IACJ;IAEA,IAAIa,KAAKe,gBAAgB,EAAE;QACzBd,OAAOc,gBAAgB,GAAGf,KAAKe,gBAAgB;IACjD;IAEA,OAAO,IAAIC,QAAQ,OAAOC,SAASC;QACjCjB,OAAOX,EAAE,CAAC,SAAS,CAACC;YAClBC,QAAQC,KAAK,CAAC,CAAC,wCAAwC,CAAC,EAAEF;YAC1DF,QAAQyB,IAAI,CAAC;QACf;QAEA,IAAIf,gBAAgB;YAClBE,OAAOX,EAAE,CAAC,WAAW,CAACc,KAAKe,QAAQC;gBACjCrB,eAAeK,KAAKe,QAAQC;YAC9B;QACF;QACA,IAAIC,WAAWrB,KAAKqB,QAAQ,IAAI;QAEhCpB,OAAOX,EAAE,CAAC,aAAa;YACrB,IAAI;gBACF,MAAMgC,OAAOrB,OAAOsB,OAAO;gBAC3B,MAAMC,OAAOF,OACT,OAAOA,SAAS,WACdA,KAAKC,OAAO,GACZD,OACFG;gBACJ,MAAMC,OAAOJ,QAAQ,OAAOA,SAAS,WAAWA,KAAKI,IAAI,GAAG;gBAE5D,IAAI,CAACA,QAAQ,CAACF,MAAM;oBAClBhC,QAAQC,KAAK,CACX,CAAC,kDAAkD,CAAC,EACpD6B;oBAEFjC,QAAQyB,IAAI,CAAC;gBACf;gBAEAG,QAAQ;oBACNhB;oBACAyB;oBACAL,UAAUG;gBACZ;YACF,EAAE,OAAOjC,KAAK;gBACZ,OAAO2B,OAAO3B;YAChB;QACF;QACAU,OAAO0B,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

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

Binary file not shown.

158
node_modules/next/dist/server/lib/squoosh/codecs.d.ts generated vendored Normal file
View File

@@ -0,0 +1,158 @@
/// <reference types="node" />
interface DecodeModule extends EmscriptenWasm.Module {
decode: (data: Uint8Array) => ImageData;
}
export interface ResizeOptions {
width?: number;
height?: number;
method: 'triangle' | 'catrom' | 'mitchell' | 'lanczos3';
premultiply: boolean;
linearRGB: boolean;
}
export interface RotateOptions {
numRotations: number;
}
import type { MozJPEGModule as MozJPEGEncodeModule } from './mozjpeg/mozjpeg_enc';
import type { WebPModule as WebPEncodeModule } from './webp/webp_enc';
import type { AVIFModule as AVIFEncodeModule } from './avif/avif_enc';
import ImageData from './image_data';
export declare const preprocessors: {
readonly resize: {
readonly name: "Resize";
readonly description: "Resize the image before compressing";
readonly instantiate: () => Promise<(buffer: Uint8Array, input_width: number, input_height: number, { width, height, method, premultiply, linearRGB }: ResizeOptions) => ImageData>;
readonly defaultOptions: {
readonly method: "lanczos3";
readonly fitMethod: "stretch";
readonly premultiply: true;
readonly linearRGB: true;
};
};
readonly rotate: {
readonly name: "Rotate";
readonly description: "Rotate image";
readonly instantiate: () => Promise<(buffer: Uint8Array, width: number, height: number, { numRotations }: RotateOptions) => Promise<ImageData>>;
readonly defaultOptions: {
readonly numRotations: 0;
};
};
};
export declare const codecs: {
readonly mozjpeg: {
readonly name: "MozJPEG";
readonly extension: "jpg";
readonly detectors: readonly [RegExp];
readonly dec: () => Promise<DecodeModule>;
readonly enc: () => Promise<MozJPEGEncodeModule>;
readonly defaultEncoderOptions: {
readonly quality: 75;
readonly baseline: false;
readonly arithmetic: false;
readonly progressive: true;
readonly optimize_coding: true;
readonly smoothing: 0;
readonly color_space: 3;
readonly quant_table: 3;
readonly trellis_multipass: false;
readonly trellis_opt_zero: false;
readonly trellis_opt_table: false;
readonly trellis_loops: 1;
readonly auto_subsample: true;
readonly chroma_subsample: 2;
readonly separate_chroma_quality: false;
readonly chroma_quality: 75;
};
readonly autoOptimize: {
readonly option: "quality";
readonly min: 0;
readonly max: 100;
};
};
readonly webp: {
readonly name: "WebP";
readonly extension: "webp";
readonly detectors: readonly [RegExp];
readonly dec: () => Promise<DecodeModule>;
readonly enc: () => Promise<WebPEncodeModule>;
readonly defaultEncoderOptions: {
readonly quality: 75;
readonly target_size: 0;
readonly target_PSNR: 0;
readonly method: 4;
readonly sns_strength: 50;
readonly filter_strength: 60;
readonly filter_sharpness: 0;
readonly filter_type: 1;
readonly partitions: 0;
readonly segments: 4;
readonly pass: 1;
readonly show_compressed: 0;
readonly preprocessing: 0;
readonly autofilter: 0;
readonly partition_limit: 0;
readonly alpha_compression: 1;
readonly alpha_filtering: 1;
readonly alpha_quality: 100;
readonly lossless: 0;
readonly exact: 0;
readonly image_hint: 0;
readonly emulate_jpeg_size: 0;
readonly thread_level: 0;
readonly low_memory: 0;
readonly near_lossless: 100;
readonly use_delta_palette: 0;
readonly use_sharp_yuv: 0;
};
readonly autoOptimize: {
readonly option: "quality";
readonly min: 0;
readonly max: 100;
};
};
readonly avif: {
readonly name: "AVIF";
readonly extension: "avif";
readonly detectors: readonly [RegExp];
readonly dec: () => Promise<DecodeModule>;
readonly enc: () => Promise<AVIFEncodeModule>;
readonly defaultEncoderOptions: {
readonly cqLevel: 33;
readonly cqAlphaLevel: -1;
readonly denoiseLevel: 0;
readonly tileColsLog2: 0;
readonly tileRowsLog2: 0;
readonly speed: 6;
readonly subsample: 1;
readonly chromaDeltaQ: false;
readonly sharpness: 0;
readonly tune: 0;
};
readonly autoOptimize: {
readonly option: "cqLevel";
readonly min: 62;
readonly max: 0;
};
};
readonly oxipng: {
readonly name: "OxiPNG";
readonly extension: "png";
readonly detectors: readonly [RegExp];
readonly dec: () => Promise<{
decode: (buffer: Buffer | Uint8Array) => any;
}>;
readonly enc: () => Promise<{
encode: (buffer: Uint8ClampedArray | ArrayBuffer, width: number, height: number, opts: {
level: number;
}) => any;
}>;
readonly defaultEncoderOptions: {
readonly level: 2;
};
readonly autoOptimize: {
readonly option: "level";
readonly min: 6;
readonly max: 1;
};
};
};
export {};

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

@@ -0,0 +1,325 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
preprocessors: null,
codecs: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
preprocessors: function() {
return preprocessors;
},
codecs: function() {
return codecs;
}
});
const _fs = require("fs");
const _path = /*#__PURE__*/ _interop_require_wildcard(require("path"));
const _emscriptenutils = require("./emscripten-utils.js");
const _mozjpeg_node_enc = /*#__PURE__*/ _interop_require_default(require("./mozjpeg/mozjpeg_node_enc.js"));
const _mozjpeg_node_dec = /*#__PURE__*/ _interop_require_default(require("./mozjpeg/mozjpeg_node_dec.js"));
const _webp_node_enc = /*#__PURE__*/ _interop_require_default(require("./webp/webp_node_enc.js"));
const _webp_node_dec = /*#__PURE__*/ _interop_require_default(require("./webp/webp_node_dec.js"));
const _avif_node_enc = /*#__PURE__*/ _interop_require_default(require("./avif/avif_node_enc.js"));
const _avif_node_dec = /*#__PURE__*/ _interop_require_default(require("./avif/avif_node_dec.js"));
const _squoosh_png = /*#__PURE__*/ _interop_require_wildcard(require("./png/squoosh_png.js"));
const _squoosh_oxipng = /*#__PURE__*/ _interop_require_wildcard(require("./png/squoosh_oxipng.js"));
const _squoosh_resize = /*#__PURE__*/ _interop_require_wildcard(require("./resize/squoosh_resize.js"));
const _image_data = /*#__PURE__*/ _interop_require_default(require("./image_data"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const mozEncWasm = _path.resolve(__dirname, "./mozjpeg/mozjpeg_node_enc.wasm");
const mozDecWasm = _path.resolve(__dirname, "./mozjpeg/mozjpeg_node_dec.wasm");
const webpEncWasm = _path.resolve(__dirname, "./webp/webp_node_enc.wasm");
const webpDecWasm = _path.resolve(__dirname, "./webp/webp_node_dec.wasm");
const avifEncWasm = _path.resolve(__dirname, "./avif/avif_node_enc.wasm");
const avifDecWasm = _path.resolve(__dirname, "./avif/avif_node_dec.wasm");
const pngEncDecWasm = _path.resolve(__dirname, "./png/squoosh_png_bg.wasm");
const pngEncDecInit = ()=>_squoosh_png.default(_fs.promises.readFile((0, _emscriptenutils.pathify)(pngEncDecWasm)));
const oxipngWasm = _path.resolve(__dirname, "./png/squoosh_oxipng_bg.wasm");
const oxipngInit = ()=>_squoosh_oxipng.default(_fs.promises.readFile((0, _emscriptenutils.pathify)(oxipngWasm)));
const resizeWasm = _path.resolve(__dirname, "./resize/squoosh_resize_bg.wasm");
const resizeInit = ()=>_squoosh_resize.default(_fs.promises.readFile((0, _emscriptenutils.pathify)(resizeWasm)));
// rotate
const rotateWasm = _path.resolve(__dirname, "./rotate/rotate.wasm");
globalThis.ImageData = _image_data.default;
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)
};
}
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 _image_data.default(_squoosh_resize.resize(buffer, input_width, input_height, width, height, resizeNameToIndex(method), premultiply, linearRGB), width, height);
_squoosh_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 _fs.promises.readFile((0, _emscriptenutils.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 _image_data.default(view.slice(size + 8, size * 2 + 8), sameDimensions ? width : height, sameDimensions ? height : width);
};
},
defaultOptions: {
numRotations: 0
}
}
};
const codecs = {
mozjpeg: {
name: "MozJPEG",
extension: "jpg",
detectors: [
/^\xFF\xD8\xFF/
],
dec: ()=>(0, _emscriptenutils.instantiateEmscriptenWasm)(_mozjpeg_node_dec.default, mozDecWasm),
enc: ()=>(0, _emscriptenutils.instantiateEmscriptenWasm)(_mozjpeg_node_enc.default, 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: ()=>(0, _emscriptenutils.instantiateEmscriptenWasm)(_webp_node_dec.default, webpDecWasm),
enc: ()=>(0, _emscriptenutils.instantiateEmscriptenWasm)(_webp_node_enc.default, 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: ()=>(0, _emscriptenutils.instantiateEmscriptenWasm)(_avif_node_dec.default, avifDecWasm),
enc: async ()=>{
return (0, _emscriptenutils.instantiateEmscriptenWasm)(_avif_node_enc.default, 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 = _squoosh_png.decode(buffer);
_squoosh_png.cleanup();
return imageData;
}
};
},
enc: async ()=>{
await pngEncDecInit();
await oxipngInit();
return {
encode: (buffer, width, height, opts)=>{
const simplePng = _squoosh_png.encode(new Uint8Array(buffer), width, height);
const imageData = _squoosh_oxipng.optimise(simplePng, opts.level, false);
_squoosh_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,2 @@
export declare function pathify(path: string): string;
export declare function instantiateEmscriptenWasm<T extends EmscriptenWasm.Module>(factory: EmscriptenWasm.ModuleFactory<T>, path: string, workerJS?: string): Promise<T>;

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