📚 Documentação inicial do ALETHEIA

- MANUAL-PRODUTO.md: Manual do usuário final
- MANUAL-VENDAS.md: Estratégia comercial e vendas
- MANUAL-TECNICO.md: Infraestrutura e deploy
- README.md: Visão geral do projeto
This commit is contained in:
2026-02-10 15:08:15 -03:00
commit 20a26affaa
16617 changed files with 3202171 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getComponentTypeModule: null,
getLayoutOrPageModule: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getComponentTypeModule: function() {
return getComponentTypeModule;
},
getLayoutOrPageModule: function() {
return getLayoutOrPageModule;
}
});
const _segment = require("../../shared/lib/segment");
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] === _segment.DEFAULT_SEGMENT_KEY;
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,113 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getStartServerInfo: null,
logStartInfo: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getStartServerInfo: function() {
return getStartServerInfo;
},
logStartInfo: function() {
return logStartInfo;
}
});
const _env = require("@next/env");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log"));
const _picocolors = require("../../lib/picocolors");
const _constants = require("../../shared/lib/constants");
const _config = /*#__PURE__*/ _interop_require_wildcard(require("../config"));
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 = {
__proto__: null
};
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;
}
function logStartInfo({ networkUrl, appUrl, envInfo, expFeatureInfo, maxExperimentalFeatures = Infinity }) {
_log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"14.2.15"}`))}${process.env.TURBOPACK ? " (turbo)" : ""}`);
if (appUrl) {
_log.bootstrap(`- Local: ${appUrl}`);
}
if (networkUrl) {
_log.bootstrap(`- Network: ${networkUrl}`);
}
if (envInfo == null ? void 0 : envInfo.length) _log.bootstrap(`- Environments: ${envInfo.join(", ")}`);
if (expFeatureInfo == null ? void 0 : expFeatureInfo.length) {
_log.bootstrap(`- Experiments (use with caution):`);
// only show a maximum number of flags
for (const exp of expFeatureInfo.slice(0, maxExperimentalFeatures)){
_log.bootstrap(` · ${exp}`);
}
/* indicate if there are more than the maximum shown no. flags */ if (expFeatureInfo.length > maxExperimentalFeatures) {
_log.bootstrap(` · ...`);
}
}
// New line after the bootstrap info
_log.info("");
}
async function getStartServerInfo(dir, dev) {
let expFeatureInfo = [];
await (0, _config.default)(dev ? _constants.PHASE_DEVELOPMENT_SERVER : _constants.PHASE_PRODUCTION_BUILD, dir, {
onLoadUserConfig (userConfig) {
const userNextConfigExperimental = (0, _config.getEnabledExperimentalFeatures)(userConfig.experimental);
expFeatureInfo = userNextConfigExperimental.sort((a, b)=>a.length - b.length);
}
});
// we need to reset env if we are going to create
// the worker process with the esm loader so that the
// initial env state is correct
let envInfo = [];
const { loadedEnvFiles } = (0, _env.loadEnvConfig)(dir, true, console, false);
if (loadedEnvFiles.length > 0) {
envInfo = loadedEnvFiles.map((f)=>f.path);
}
return {
envInfo,
expFeatureInfo
};
}
//# sourceMappingURL=app-info-log.js.map

View File

@@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "DevBundlerService", {
enumerable: true,
get: function() {
return DevBundlerService;
}
});
const _mockrequest = require("./mock-request");
class DevBundlerService {
constructor(bundler, handler){
this.bundler = bundler;
this.handler = handler;
this.ensurePage = async (definition)=>{
// TODO: remove after ensure is pulled out of server
return await this.bundler.hotReloader.ensurePage(definition);
};
this.logErrorWithOriginalStack = async (...args)=>{
return await this.bundler.logErrorWithOriginalStack(...args);
};
}
async getFallbackErrorComponents(url) {
await this.bundler.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 this.bundler.hotReloader.ensurePage({
page: "/_error",
clientOnly: false,
definition: undefined,
url
});
}
async getCompilationError(page) {
const errors = await this.bundler.hotReloader.getCompilationErrors(page);
if (!errors) return;
// Return the very first error we found.
return errors[0];
}
async revalidate({ urlPath, revalidateHeaders, opts: revalidateOpts }) {
const mocked = (0, _mockrequest.createRequestResponseMocks)({
url: urlPath,
headers: revalidateHeaders
});
await this.handler(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 {};
}
}
//# sourceMappingURL=dev-bundler-service.js.map

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

View File

@@ -0,0 +1,111 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createValidFileMatcher: null,
findPageFile: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createValidFileMatcher: function() {
return createValidFileMatcher;
},
findPageFile: function() {
return findPageFile;
}
});
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 _picocolors = require("../../lib/picocolors");
const _ismetadataroute = require("../../lib/metadata/is-metadata-route");
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. ${(0, _picocolors.cyan)((0, _path.join)("pages", existingPath))} and ${(0, _picocolors.cyan)((0, _path.join)("pages", others[0]))} both resolve to ${(0, _picocolors.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,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,320 @@
"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";
const DEBUG = Boolean(process.env.NEXT_PRIVATE_DEBUG_CACHE);
async function fetchRetryWithTimeout(url, init, retryIndex = 0) {
const controller = new AbortController();
const timeout = setTimeout(()=>{
controller.abort();
}, 500);
return fetch(url, {
...init || {},
signal: controller.signal
}).catch((err)=>{
if (retryIndex === 3) {
throw err;
} else {
if (DEBUG) {
console.log(`Fetch failed for ${url} retry ${retryIndex}`);
}
return fetchRetryWithTimeout(url, init, retryIndex + 1);
}
}).finally(()=>{
clearTimeout(timeout);
});
}
class FetchCache {
hasMatchingTags(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
const set1 = new Set(arr1);
const set2 = new Set(arr2);
if (set1.size !== set2.size) return false;
for (let tag of set1){
if (!set2.has(tag)) return false;
}
return true;
}
static isAvailable(ctx) {
return !!(ctx._requestHeaders["x-vercel-sc-host"] || process.env.SUSPENSE_CACHE_URL);
}
constructor(ctx){
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) {
const scProto = process.env.SUSPENSE_CACHE_PROTO || "https";
this.cacheEndpoint = `${scProto}://${scHost}${scBasePath || ""}`;
if (DEBUG) {
console.log("using cache endpoint", this.cacheEndpoint);
}
} else if (DEBUG) {
console.log("no cache endpoint available");
}
if (ctx.maxMemoryCacheSize) {
if (!memoryCache) {
if (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.kind === "PAGE" && value.pageData)) == null ? void 0 : _JSON_stringify.length) || 0);
}
});
}
} else {
if (DEBUG) {
console.log("not using memory store for fetch cache");
}
}
}
resetRequestCache() {
memoryCache == null ? void 0 : memoryCache.reset();
}
async revalidateTag(...args) {
let [tags] = args;
tags = typeof tags === "string" ? [
tags
] : tags;
if (DEBUG) {
console.log("revalidateTag", tags);
}
if (!tags.length) return;
if (Date.now() < rateLimitedUntil) {
if (DEBUG) {
console.log("rate limited ", rateLimitedUntil);
}
return;
}
for(let i = 0; i < Math.ceil(tags.length / 64); i++){
const currentTags = tags.slice(i * 64, i * 64 + 64);
try {
const res = await fetchRetryWithTimeout(`${this.cacheEndpoint}/v1/suspense-cache/revalidate?tags=${currentTags.map((tag)=>encodeURIComponent(tag)).join(",")}`, {
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`, currentTags, err);
}
}
}
async get(...args) {
var _data_value;
const [key, ctx = {}] = args;
const { tags, softTags, kindHint, fetchIdx, fetchUrl } = ctx;
if (kindHint !== "fetch") {
return null;
}
if (Date.now() < rateLimitedUntil) {
if (DEBUG) {
console.log("rate limited");
}
return null;
}
// memory cache is cleared at the end of each request
// so that revalidate events are pulled from upstream
// on successive requests
let data = memoryCache == null ? void 0 : memoryCache.get(key);
const hasFetchKindAndMatchingTags = (data == null ? void 0 : (_data_value = data.value) == null ? void 0 : _data_value.kind) === "FETCH" && this.hasMatchingTags(tags ?? [], data.value.tags ?? []);
// Get data from fetch cache. Also check if new tags have been
// specified with the same cache key (fetch URL)
if (this.cacheEndpoint && (!data || !hasFetchKindAndMatchingTags)) {
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 (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") {
DEBUG && console.log({
cached
});
throw new Error("invalid cache value");
}
// if new tags were specified, merge those tags to the existing tags
if (cached.kind === "FETCH") {
cached.tags ??= [];
for (const tag of tags ?? []){
if (!cached.tags.includes(tag)) {
cached.tags.push(tag);
}
}
}
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 (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 (DEBUG) {
console.error(`Failed to get from fetch-cache`, err);
}
}
}
return data || null;
}
async set(...args) {
const [key, data, ctx] = args;
const { fetchCache, fetchIdx, fetchUrl, tags } = ctx;
if (!fetchCache) return;
if (Date.now() < rateLimitedUntil) {
if (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 (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) {
DEBUG && console.log(await res.text());
throw new Error(`invalid response ${res.status}`);
}
if (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 (DEBUG) {
console.error(`Failed to update fetch cache`, err);
}
}
}
return;
}
}
//# sourceMappingURL=fetch-cache.js.map

View File

@@ -0,0 +1,322 @@
"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.pagesDir = !!ctx._pagesDir;
this.revalidatedTags = ctx.revalidatedTags;
this.experimental = ctx.experimental;
this.debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE;
if (ctx.maxMemoryCacheSize && !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");
}
if (this.serverDistDir && this.fs) {
this.tagsManifestPath = _path.default.join(this.serverDistDir, "..", "cache", "fetch-cache", "tags-manifest.json");
this.loadTagsManifest();
}
}
resetRequestCache() {}
loadTagsManifest() {
if (!this.tagsManifestPath || !this.fs || tagsManifest) return;
try {
tagsManifest = JSON.parse(this.fs.readFileSync(this.tagsManifestPath, "utf8"));
} catch (err) {
tagsManifest = {
version: 1,
items: {}
};
}
if (this.debug) console.log("loadTagsManifest", tagsManifest);
}
async revalidateTag(...args) {
let [tags] = args;
tags = typeof tags === "string" ? [
tags
] : tags;
if (this.debug) {
console.log("revalidateTag", tags);
}
if (tags.length === 0) {
return;
}
// 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
await this.loadTagsManifest();
if (!tagsManifest || !this.tagsManifestPath) {
return;
}
for (const tag of tags){
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 || {}));
if (this.debug) {
console.log("Updated tags manifest", tagsManifest);
}
} catch (err) {
console.warn("Failed to update tags manifest.", err);
}
}
async get(...args) {
var _data_value, _data_value1;
const [key, ctx = {}] = args;
const { tags, softTags, kindHint } = ctx;
let data = memoryCache == null ? void 0 : memoryCache.get(key);
if (this.debug) {
console.log("get", key, tags, kindHint, !!data);
}
// let's check the disk for seed data
if (!data && process.env.NEXT_RUNTIME !== "edge") {
try {
const filePath = this.getFilePath(`${key}.body`, "app");
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$/, _constants.NEXT_META_SUFFIX), "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 {
// Determine the file kind if we didn't know it already.
let kind = kindHint;
if (!kind) {
kind = this.detectFileKind(`${key}.html`);
}
const isAppPath = kind === "app";
const filePath = this.getFilePath(kind === "fetch" ? key : `${key}.html`, kind);
const fileData = await this.fs.readFile(filePath, "utf8");
const { mtime } = await this.fs.stat(filePath);
if (kind === "fetch" && this.flushToDisk) {
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_value3;
const storedTags = (_data_value3 = data.value) == null ? void 0 : _data_value3.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)))) {
if (this.debug) {
console.log("tags vs storedTags mismatch", tags, storedTags);
}
await this.set(key, data.value, {
tags
});
}
}
} else {
const pageData = isAppPath ? await this.fs.readFile(this.getFilePath(`${key}${this.experimental.ppr ? _constants.RSC_PREFETCH_SUFFIX : _constants.RSC_SUFFIX}`, "app"), "utf8") : JSON.parse(await this.fs.readFile(this.getFilePath(`${key}${_constants.NEXT_DATA_SUFFIX}`, "pages"), "utf8"));
let meta;
if (isAppPath) {
try {
meta = JSON.parse(await this.fs.readFile(filePath.replace(/\.html$/, _constants.NEXT_META_SUFFIX), "utf8"));
} catch {}
}
data = {
lastModified: mtime.getTime(),
value: {
kind: "PAGE",
html: fileData,
pageData,
postponed: meta == null ? void 0 : meta.postponed,
headers: meta == null ? void 0 : meta.headers,
status: meta == null ? void 0 : 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(...args) {
const [key, data, ctx] = args;
memoryCache == null ? void 0 : memoryCache.set(key, {
value: data,
lastModified: Date.now()
});
if (this.debug) {
console.log("set", key);
}
if (!this.flushToDisk) return;
if ((data == null ? void 0 : data.kind) === "ROUTE") {
const filePath = this.getFilePath(`${key}.body`, "app");
await this.fs.mkdir(_path.default.dirname(filePath));
await this.fs.writeFile(filePath, data.body);
const meta = {
headers: data.headers,
status: data.status,
postponed: undefined
};
await this.fs.writeFile(filePath.replace(/\.body$/, _constants.NEXT_META_SUFFIX), JSON.stringify(meta, null, 2));
return;
}
if ((data == null ? void 0 : data.kind) === "PAGE") {
const isAppPath = typeof data.pageData === "string";
const htmlPath = this.getFilePath(`${key}.html`, isAppPath ? "app" : "pages");
await this.fs.mkdir(_path.default.dirname(htmlPath));
await this.fs.writeFile(htmlPath, data.html);
await this.fs.writeFile(this.getFilePath(`${key}${isAppPath ? this.experimental.ppr ? _constants.RSC_PREFETCH_SUFFIX : _constants.RSC_SUFFIX : _constants.NEXT_DATA_SUFFIX}`, isAppPath ? "app" : "pages"), isAppPath ? data.pageData : JSON.stringify(data.pageData));
if (data.headers || data.status) {
const meta = {
headers: data.headers,
status: data.status,
postponed: data.postponed
};
await this.fs.writeFile(htmlPath.replace(/\.html$/, _constants.NEXT_META_SUFFIX), JSON.stringify(meta));
}
} else if ((data == null ? void 0 : data.kind) === "FETCH") {
const filePath = this.getFilePath(key, "fetch");
await this.fs.mkdir(_path.default.dirname(filePath));
await this.fs.writeFile(filePath, JSON.stringify({
...data,
tags: ctx.tags
}));
}
}
detectFileKind(pathname) {
if (!this.appDir && !this.pagesDir) {
throw new Error("Invariant: Can't determine file path kind, no page directory enabled");
}
// If app directory isn't enabled, then assume it's pages and avoid the fs
// hit.
if (!this.appDir && this.pagesDir) {
return "pages";
} else if (this.appDir && !this.pagesDir) {
return "app";
}
// If both are enabled, we need to test each in order, starting with
// `pages`.
let filePath = this.getFilePath(pathname, "pages");
if (this.fs.existsSync(filePath)) {
return "pages";
}
filePath = this.getFilePath(pathname, "app");
if (this.fs.existsSync(filePath)) {
return "app";
}
throw new Error(`Invariant: Unable to determine file path kind for ${pathname}`);
}
getFilePath(pathname, kind) {
switch(kind){
case "fetch":
// we store in .next/cache/fetch-cache so it can be persisted
// across deploys
return _path.default.join(this.serverDistDir, "..", "cache", "fetch-cache", pathname);
case "pages":
return _path.default.join(this.serverDistDir, "pages", pathname);
case "app":
return _path.default.join(this.serverDistDir, "app", pathname);
default:
throw new Error("Invariant: Can't determine file path kind");
}
}
}
//# sourceMappingURL=file-system-cache.js.map

View File

@@ -0,0 +1,407 @@
"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 _normalizepagepath = require("../../../shared/lib/page-path/normalize-page-path");
const _constants = require("../../../lib/constants");
const _toroute = require("../to-route");
const _sharedrevalidatetimings = require("./shared-revalidate-timings");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
class CacheHandler {
// eslint-disable-next-line
constructor(_ctx){}
async get(..._args) {
return {};
}
async set(..._args) {}
async revalidateTag(..._args) {}
resetRequestCache() {}
}
class IncrementalCache {
constructor({ fs, dev, appDir, pagesDir, flushToDisk, fetchCache, minimalMode, serverDistDir, requestHeaders, requestProtocol, maxMemoryCacheSize, getPrerenderManifest, fetchCacheKeyPrefix, CurCacheHandler, allowedRevalidateHeaderKeys, experimental }){
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;
this.hasCustomCacheHandler = Boolean(CurCacheHandler);
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.disableForTestmode = process.env.NEXT_PRIVATE_TEST_PROXY === "true";
// 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.revalidateTimings = new _sharedrevalidatetimings.SharedRevalidateTimings(this.prerenderManifest);
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,
_pagesDir: !!pagesDir,
_appDir: !!appDir,
_requestHeaders: requestHeaders,
fetchCacheKeyPrefix,
experimental
});
}
}
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.revalidateTimings.get((0, _toroute.toRoute)(pathname)) ?? 1;
const revalidateAfter = typeof initialRevalidateSeconds === "number" ? initialRevalidateSeconds * 1000 + fromTime : initialRevalidateSeconds;
return revalidateAfter;
}
_getPathname(pathname, fetchCache) {
return fetchCache ? pathname : (0, _normalizepagepath.normalizePagePath)(pathname);
}
resetRequestCache() {
var _this_cacheHandler_resetRequestCache, _this_cacheHandler;
(_this_cacheHandler = this.cacheHandler) == null ? void 0 : (_this_cacheHandler_resetRequestCache = _this_cacheHandler.resetRequestCache) == null ? void 0 : _this_cacheHandler_resetRequestCache.call(_this_cacheHandler);
}
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(tags) {
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, tags);
}
// 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";
const bodyChunks = [];
const encoder = new TextEncoder();
const decoder = new TextDecoder();
if (init.body) {
// handle ReadableStream body
if (typeof init.body.getReader === "function") {
const readableBody = init.body;
const chunks = [];
try {
await readableBody.pipeTo(new WritableStream({
write (chunk) {
if (typeof chunk === "string") {
chunks.push(encoder.encode(chunk));
bodyChunks.push(chunk);
} else {
chunks.push(chunk);
bodyChunks.push(decoder.decode(chunk, {
stream: true
}));
}
}
}));
// Flush the decoder.
bodyChunks.push(decoder.decode());
// Create a new buffer with all the chunks.
const length = chunks.reduce((total, arr)=>total + arr.length, 0);
const arrayBuffer = new Uint8Array(length);
// Push each of the chunks into the new array buffer.
let offset = 0;
for (const chunk of chunks){
arrayBuffer.set(chunk, offset);
offset += chunk.length;
}
init._ogBody = arrayBuffer;
} catch (err) {
console.error("Problem reading body", err);
}
} 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(await blob.text());
init._ogBody = new Blob([
arrayBuffer
], {
type: blob.type
});
} else if (typeof init.body === "string") {
bodyChunks.push(init.body);
init._ogBody = init.body;
}
}
const headers = typeof (init.headers || {}).keys === "function" ? Object.fromEntries(init.headers) : Object.assign({}, init.headers);
if ("traceparent" in headers) delete headers["traceparent"];
const cacheString = JSON.stringify([
MAIN_KEY_PREFIX,
this.fetchCacheKeyPrefix || "",
url,
init.method,
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 = encoder.encode(cacheString);
return bufferToHex(await crypto.subtle.digest("SHA-256", buffer));
} else {
const crypto1 = require("crypto");
return crypto1.createHash("sha256").update(cacheString).digest("hex");
}
}
// get data from cache if available
async get(cacheKey, ctx = {}) {
var _this_cacheHandler, _cacheData_value;
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.disableForTestmode || this.dev && (ctx.kindHint !== "fetch" || this.requestHeaders["cache-control"] === "no-cache")) {
return null;
}
cacheKey = this._getPathname(cacheKey, ctx.kindHint === "fetch");
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 = (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.revalidateTimings.get((0, _toroute.toRoute)(cacheKey));
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.kindHint !== "fetch");
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.disableForTestmode || this.dev && !ctx.fetchCache) return;
// FetchCache has upper limit of 2MB per-entry currently
const itemSize = JSON.stringify(data).length;
if (ctx.fetchCache && // we don't show this error/warning when a custom cache handler is being used
// as it might not have this limit
!this.hasCustomCacheHandler && itemSize > 2 * 1024 * 1024) {
if (this.dev) {
throw new Error(`Failed to set Next.js data cache, items over 2MB can not be cached (${itemSize} bytes)`);
}
return;
}
pathname = this._getPathname(pathname, ctx.fetchCache);
try {
var _this_cacheHandler;
// Set the value for the revalidate seconds so if it changes we can
// update the cache with the new value.
if (typeof ctx.revalidate !== "undefined" && !ctx.fetchCache) {
this.revalidateTimings.set(pathname, 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

View File

@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "SharedRevalidateTimings", {
enumerable: true,
get: function() {
return SharedRevalidateTimings;
}
});
class SharedRevalidateTimings {
static #_ = /**
* The in-memory cache of revalidate timings for routes. This cache is
* populated when the cache is updated with new timings.
*/ this.timings = new Map();
constructor(/**
* The prerender manifest that contains the initial revalidate timings for
* routes.
*/ prerenderManifest){
this.prerenderManifest = prerenderManifest;
}
/**
* Try to get the revalidate timings for a route. This will first try to get
* the timings from the in-memory cache. If the timings are not present in the
* in-memory cache, then the timings will be sourced from the prerender
* manifest.
*
* @param route the route to get the revalidate timings for
* @returns the revalidate timings for the route, or undefined if the timings
* are not present in the in-memory cache or the prerender manifest
*/ get(route) {
var _this_prerenderManifest_routes_route;
// This is a copy on write cache that is updated when the cache is updated.
// If the cache is never written to, then the timings will be sourced from
// the prerender manifest.
let revalidate = SharedRevalidateTimings.timings.get(route);
if (typeof revalidate !== "undefined") return revalidate;
revalidate = (_this_prerenderManifest_routes_route = this.prerenderManifest.routes[route]) == null ? void 0 : _this_prerenderManifest_routes_route.initialRevalidateSeconds;
if (typeof revalidate !== "undefined") return revalidate;
return undefined;
}
/**
* Set the revalidate timings for a route.
*
* @param route the route to set the revalidate timings for
* @param revalidate the revalidate timings for the route
*/ set(route, revalidate) {
SharedRevalidateTimings.timings.set(route, revalidate);
}
/**
* Clear the in-memory cache of revalidate timings for routes.
*/ clear() {
SharedRevalidateTimings.timings.clear();
}
}
//# sourceMappingURL=shared-revalidate-timings.js.map

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

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,329 @@
"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 and undefined for the
// `remoteAddress` property.
this.socket = new Proxy({}, {
get: (_target, prop)=>{
if (prop !== "encrypted" && prop !== "remoteAddress") {
throw new Error("Method not implemented");
}
if (prop === "remoteAddress") return undefined;
// 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)=>{
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) {
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 == 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);
}
flushHeaders() {
// This is a no-op because we don't actually have a socket to flush the
// headers to.
}
// 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.");
}
}
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

View File

@@ -0,0 +1,28 @@
"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 = {
existsSync: _fs.default.existsSync,
readFile: _fs.default.promises.readFile,
readFileSync: _fs.default.readFileSync,
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,616 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
addImplicitTags: null,
patchFetch: null,
validateRevalidate: null,
validateTags: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
addImplicitTags: function() {
return addImplicitTags;
},
patchFetch: function() {
return patchFetch;
},
validateRevalidate: function() {
return validateRevalidate;
},
validateTags: function() {
return validateTags;
}
});
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"));
const _dynamicrendering = require("../app-render/dynamic-rendering");
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 = {
__proto__: null
};
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 isPatchedFetch(fetch) {
return "__nextPatched" in fetch && fetch.__nextPatched === true;
}
function validateRevalidate(revalidateVal, pathname) {
try {
let normalizedRevalidate = undefined;
if (revalidateVal === false) {
normalizedRevalidate = revalidateVal;
} else if (typeof revalidateVal === "number" && !isNaN(revalidateVal) && revalidateVal > -1) {
normalizedRevalidate = revalidateVal;
} else if (typeof revalidateVal !== "undefined") {
throw new Error(`Invalid revalidate value "${revalidateVal}" on "${pathname}", must be a non-negative number or "false"`);
}
return normalizedRevalidate;
} catch (err) {
// handle client component error from attempting to check revalidate value
if (err instanceof Error && err.message.includes("Invalid revalidate")) {
throw err;
}
return undefined;
}
}
function validateTags(tags, description) {
const validTags = [];
const invalidTags = [];
for(let i = 0; i < tags.length; i++){
const tag = tags[i];
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 (validTags.length > _constants1.NEXT_CACHE_TAG_MAX_ITEMS) {
console.warn(`Warning: exceeded max tag count for ${description}, dropped tags:`, tags.slice(i).join(", "));
break;
}
}
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 = [];
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 parsedPathname = new URL(urlPathname, "http://n").pathname;
const tag = `${_constants1.NEXT_CACHE_IMPLICIT_TAG_ID}${parsedPathname}`;
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) {
var _staticGenerationStore_requestEndedState;
if (!staticGenerationStore || ((_staticGenerationStore_requestEndedState = staticGenerationStore.requestEndedState) == null ? void 0 : _staticGenerationStore_requestEndedState.ended) || process.env.NODE_ENV !== "development") {
return;
}
staticGenerationStore.fetchMetrics ??= [];
const dedupeFields = [
"url",
"status",
"method"
];
// don't add metric if one already exists for the fetch
if (staticGenerationStore.fetchMetrics.some((metric)=>dedupeFields.every((field)=>metric[field] === ctx[field]))) {
return;
}
staticGenerationStore.fetchMetrics.push({
...ctx,
end: Date.now(),
idx: staticGenerationStore.nextFetchId || 0
});
// only store top 10 metrics to avoid storing too many
if (staticGenerationStore.fetchMetrics.length > 10) {
// sort slowest first as these should be highlighted
staticGenerationStore.fetchMetrics.sort((a, b)=>{
const aDur = a.end - a.start;
const bDur = b.end - b.start;
if (aDur < bDur) {
return 1;
} else if (aDur > bDur) {
return -1;
}
return 0;
});
// now grab top 10
staticGenerationStore.fetchMetrics = staticGenerationStore.fetchMetrics.slice(0, 10);
}
}
function createPatchedFetcher(originFetch, { serverHooks: { DynamicServerError }, staticGenerationAsyncStorage }) {
// Create the patched fetch function. We don't set the type here, as it's
// verified as the return value of this function.
const patched = async (input, init)=>{
var _init_method, _init_next;
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 = (init == null ? void 0 : (_init_next = init.next) == null ? void 0 : _init_next.internal) === true;
const hideSpan = process.env.NEXT_OTEL_FETCH_DISABLED === "1";
return (0, _tracer.getTracer)().trace(isInternal ? _constants.NextNodeServerSpan.internalFetch : _constants.AppRenderSpan.fetch, {
hideSpan,
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;
// If this is an internal fetch, we should not do any special treatment.
if (isInternal) return originFetch(input, init);
const staticGenerationStore = staticGenerationAsyncStorage.getStore();
// If the staticGenerationStore is not available, we can't do any
// special treatment of fetch, therefore fallback to the original
// fetch implementation.
if (!staticGenerationStore || staticGenerationStore.isDraftMode) {
return originFetch(input, init);
}
const isRequestInput = input && typeof input === "object" && typeof input.method === "string";
const getRequestMeta = (field)=>{
// If request input is present but init is not, retrieve from input first.
const value = init == null ? void 0 : init[field];
return value || (isRequestInput ? input[field] : null);
};
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 fetchCacheMode = staticGenerationStore.fetchCache;
const isUsingNoStore = !!staticGenerationStore.isUnstableNoStore;
let _cache = getRequestMeta("cache");
let cacheReason = "";
if (typeof _cache === "string" && typeof curRevalidate !== "undefined") {
// when providing fetch with a Request input, it'll automatically set a cache value of 'default'
// we only want to warn if the user is explicitly setting a cache value
if (!(isRequestInput && _cache === "default")) {
_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;
} else if (_cache === "no-cache" || _cache === "no-store" || fetchCacheMode === "force-no-store" || fetchCacheMode === "only-no-store") {
curRevalidate = 0;
}
if (_cache === "no-cache" || _cache === "no-store") {
cacheReason = `cache: ${_cache}`;
}
revalidate = validateRevalidate(curRevalidate, staticGenerationStore.urlPathname);
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;
switch(fetchCacheMode){
case "force-no-store":
{
cacheReason = "fetchCache = force-no-store";
break;
}
case "only-no-store":
{
if (_cache === "force-cache" || typeof revalidate !== "undefined" && (revalidate === false || revalidate > 0)) {
throw new Error(`cache: 'force-cache' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-no-store'`);
}
cacheReason = "fetchCache = only-no-store";
break;
}
case "only-cache":
{
if (_cache === "no-store") {
throw new Error(`cache: 'no-store' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-cache'`);
}
break;
}
case "force-cache":
{
if (typeof curRevalidate === "undefined" || curRevalidate === 0) {
cacheReason = "fetchCache = force-cache";
revalidate = false;
}
break;
}
default:
}
if (typeof revalidate === "undefined") {
if (fetchCacheMode === "default-cache") {
revalidate = false;
cacheReason = "fetchCache = default-cache";
} else if (autoNoCache) {
revalidate = 0;
cacheReason = "auto no cache";
} else if (fetchCacheMode === "default-no-store") {
revalidate = 0;
cacheReason = "fetchCache = default-no-store";
} else if (isUsingNoStore) {
revalidate = 0;
cacheReason = "noStore call";
} else {
cacheReason = "auto cache";
revalidate = typeof staticGenerationStore.revalidate === "boolean" || typeof staticGenerationStore.revalidate === "undefined" ? false : staticGenerationStore.revalidate;
}
} else if (!cacheReason) {
cacheReason = `revalidate: ${revalidate}`;
}
if (// when force static is configured we don't bail from
// `revalidate: 0` values
!(staticGenerationStore.forceStatic && revalidate === 0) && // we don't consider autoNoCache to switch to dynamic during
// revalidate although if it occurs during build we do
!autoNoCache && // If the revalidate value isn't currently set or the value is less
// than the current revalidate value, we should update the revalidate
// value.
(typeof staticGenerationStore.revalidate === "undefined" || typeof revalidate === "number" && (staticGenerationStore.revalidate === false || typeof staticGenerationStore.revalidate === "number" && revalidate < staticGenerationStore.revalidate))) {
// If we were setting the revalidate value to 0, we should try to
// postpone instead first.
if (revalidate === 0) {
(0, _dynamicrendering.trackDynamicFetch)(staticGenerationStore, "revalidate: 0");
}
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 { _ogBody, body, signal, ...otherInput } = init;
init = {
...otherInput,
body: _ogBody || body,
signal: isStale ? undefined : signal
};
}
// 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;
let isForegroundRevalidate = false;
if (cacheKey && staticGenerationStore.incrementalCache) {
handleUnlock = await staticGenerationStore.incrementalCache.lock(cacheKey);
const entry = staticGenerationStore.isOnDemandRevalidate ? null : await staticGenerationStore.incrementalCache.get(cacheKey, {
kindHint: "fetch",
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) {
isForegroundRevalidate = true;
} else {
if (entry.isStale) {
staticGenerationStore.pendingRevalidates ??= {};
if (!staticGenerationStore.pendingRevalidates[cacheKey]) {
staticGenerationStore.pendingRevalidates[cacheKey] = doOriginalFetch(true).catch(console.error).finally(()=>{
staticGenerationStore.pendingRevalidates ??= {};
delete staticGenerationStore.pendingRevalidates[cacheKey || ""];
});
}
}
const resData = entry.value.data;
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(Buffer.from(resData.body, "base64"), {
headers: resData.headers,
status: resData.status
});
Object.defineProperty(response, "url", {
value: entry.value.data.url
});
return response;
}
}
}
if (staticGenerationStore.isStaticGeneration && init && typeof init === "object") {
const { cache } = init;
// Delete `cache` property as Cloudflare Workers will throw an error
if (isEdgeRuntime) delete init.cache;
if (!staticGenerationStore.forceStatic && cache === "no-store") {
const dynamicUsageReason = `no-store fetch ${input}${staticGenerationStore.urlPathname ? ` ${staticGenerationStore.urlPathname}` : ""}`;
// If enabled, we should bail out of static generation.
(0, _dynamicrendering.trackDynamicFetch)(staticGenerationStore, dynamicUsageReason);
// PPR is not enabled, or React postpone is not available, we
// should set the revalidate to 0.
staticGenerationStore.revalidate = 0;
const err = new DynamicServerError(dynamicUsageReason);
staticGenerationStore.dynamicUsageErr = err;
staticGenerationStore.dynamicUsageDescription = dynamicUsageReason;
throw err;
}
const hasNextConfig = "next" in init;
const { next = {} } = init;
if (typeof next.revalidate === "number" && (typeof staticGenerationStore.revalidate === "undefined" || typeof staticGenerationStore.revalidate === "number" && next.revalidate < staticGenerationStore.revalidate)) {
if (!staticGenerationStore.forceDynamic && !staticGenerationStore.forceStatic && next.revalidate === 0) {
const dynamicUsageReason = `revalidate: 0 fetch ${input}${staticGenerationStore.urlPathname ? ` ${staticGenerationStore.urlPathname}` : ""}`;
// If enabled, we should bail out of static generation.
(0, _dynamicrendering.trackDynamicFetch)(staticGenerationStore, dynamicUsageReason);
const err = new DynamicServerError(dynamicUsageReason);
staticGenerationStore.dynamicUsageErr = err;
staticGenerationStore.dynamicUsageDescription = dynamicUsageReason;
throw err;
}
if (!staticGenerationStore.forceStatic || next.revalidate !== 0) {
staticGenerationStore.revalidate = next.revalidate;
}
}
if (hasNextConfig) delete init.next;
}
// if we are revalidating the whole page via time or on-demand and
// the fetch cache entry is stale we should still de-dupe the
// origin hit if it's a cache-able entry
if (cacheKey && isForegroundRevalidate) {
staticGenerationStore.pendingRevalidates ??= {};
const pendingRevalidate = staticGenerationStore.pendingRevalidates[cacheKey];
if (pendingRevalidate) {
const res = await pendingRevalidate;
return res.clone();
}
return staticGenerationStore.pendingRevalidates[cacheKey] = doOriginalFetch(true, cacheReasonOverride).then((res)=>{
return res.clone();
}).finally(async ()=>{
staticGenerationStore.pendingRevalidates ??= {};
delete staticGenerationStore.pendingRevalidates[cacheKey || ""];
await handleUnlock();
});
} else {
return doOriginalFetch(false, cacheReasonOverride).finally(handleUnlock);
}
});
};
// Attach the necessary properties to the patched fetch function.
patched.__nextPatched = true;
patched.__nextGetStaticStore = ()=>staticGenerationAsyncStorage;
patched._nextOriginalFetch = originFetch;
return patched;
}
function patchFetch(options) {
// If we've already patched fetch, we should not patch it again.
if (isPatchedFetch(globalThis.fetch)) return;
// Grab the original fetch function. We'll attach this so we can use it in
// the patched fetch function.
const original = globalThis.fetch;
// Set the global fetch to the patched fetch.
globalThis.fetch = createPatchedFetcher(original, options);
}
//# sourceMappingURL=patch-fetch.js.map

View File

@@ -0,0 +1,114 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
clearAllModuleContexts: null,
clearModuleContext: null,
deleteAppClientCache: null,
deleteCache: null,
initialize: null,
propagateServerField: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
clearAllModuleContexts: function() {
return clearAllModuleContexts;
},
clearModuleContext: function() {
return clearModuleContext;
},
deleteAppClientCache: function() {
return deleteAppClientCache;
},
deleteCache: function() {
return deleteCache;
},
initialize: function() {
return initialize;
},
propagateServerField: function() {
return propagateServerField;
}
});
const _next = /*#__PURE__*/ _interop_require_default(require("../next"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
let initializations = {};
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 clearAllModuleContexts() {
return sandboxContext == null ? void 0 : sandboxContext.clearAllModuleContexts();
}
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 initialization = await initializations[dir];
if (!initialization) {
throw new Error("Invariant cant propagate server field, no app initialized");
}
const { app } = initialization;
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 initializeImpl(opts) {
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,
hostname: opts.hostname || "localhost",
customServer: false,
httpServer: opts.server,
port: opts.port,
isNodeDebugging: opts.isNodeDebugging
});
requestHandler = app.getRequestHandler();
upgradeHandler = app.getUpgradeHandler();
await app.prepare(opts.serverFields);
return {
requestHandler,
upgradeHandler,
app
};
}
async function initialize(opts) {
// if we already setup the server return as we only need to do
// this on first worker boot
if (initializations[opts.dir]) {
return initializations[opts.dir];
}
return initializations[opts.dir] = initializeImpl(opts);
}
//# sourceMappingURL=render-server.js.map

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "formatRevalidate", {
enumerable: true,
get: function() {
return formatRevalidate;
}
});
const _constants = require("../../lib/constants");
function formatRevalidate({ revalidate, swrDelta }) {
const swrHeader = swrDelta ? `stale-while-revalidate=${swrDelta}` : "stale-while-revalidate";
if (revalidate === 0) {
return "private, no-cache, no-store, max-age=0, must-revalidate";
} else if (typeof revalidate === "number") {
return `s-maxage=${revalidate}, ${swrHeader}`;
}
return `s-maxage=${_constants.CACHE_ONE_YEAR}, ${swrHeader}`;
}
//# sourceMappingURL=revalidate.js.map

View File

@@ -0,0 +1,490 @@
// this must come first as it includes require hooks
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "initialize", {
enumerable: true,
get: function() {
return initialize;
}
});
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 _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 _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 _ispostpone = require("./router-utils/is-postpone");
const _parseurl = require("../../shared/lib/router/utils/parse-url");
const _constants = require("../../shared/lib/constants");
const _redirectstatuscode = require("../../client/components/redirect-status-code");
const _devbundlerservice = require("./dev-bundler-service");
const _trace = require("../../trace");
const _ensureleadingslash = require("../../shared/lib/page-path/ensure-leading-slash");
const _getnextpathnameinfo = require("../../shared/lib/router/utils/get-next-pathname-info");
const _gethostname = require("../../shared/lib/get-hostname");
const _detectdomainlocale = require("../../shared/lib/i18n/detect-domain-locale");
const _normalizedassetprefix = require("../../shared/lib/normalized-asset-prefix");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const debug = (0, _debug.default)("next:router-server:main");
const isNextFont = (pathname)=>pathname && /\/media\/[^/]+\.(woff|woff2|eot|ttf|otf)$/.test(pathname);
const requestHandlers = {};
async function initialize(opts) {
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 renderServer = {};
let developmentBundler;
let devBundlerService;
if (opts.dev) {
const { Telemetry } = require("../../telemetry/storage");
const telemetry = new Telemetry({
distDir: _path.default.join(opts.dir, config.distDir)
});
const { pagesDir, appDir } = (0, _findpagesdir.findPagesDir)(opts.dir);
const { setupDevBundler } = require("./router-utils/setup-dev-bundler");
const setupDevBundlerSpan = opts.startServerSpan ? opts.startServerSpan.traceChild("setup-dev-bundler") : (0, _trace.trace)("setup-dev-bundler");
developmentBundler = await setupDevBundlerSpan.traceAsyncFn(()=>setupDevBundler({
// Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.
renderServer,
appDir,
pagesDir,
telemetry,
fsChecker,
dir: opts.dir,
nextConfig: config,
isCustomServer: opts.customServer,
turbo: !!process.env.TURBOPACK,
port: opts.port
}));
devBundlerService = new _devbundlerservice.DevBundlerService(developmentBundler, // The request handler is assigned below, this allows us to create a lazy
// reference to it.
(req, res)=>{
return requestHandlers[opts.dir](req, res);
});
}
renderServer.instance = require("./render-server");
const requestHandlerImpl = async (req, res)=>{
if (!opts.minimalMode && config.i18n && config.i18n.localeDetection !== false) {
var _this;
const urlParts = (req.url || "").split("?", 1);
let urlNoQuery = urlParts[0] || "";
if (config.basePath) {
urlNoQuery = (0, _removepathprefix.removePathPrefix)(urlNoQuery, config.basePath);
}
const pathnameInfo = (0, _getnextpathnameinfo.getNextPathnameInfo)(urlNoQuery, {
nextConfig: config
});
const domainLocale = (0, _detectdomainlocale.detectDomainLocale)(config.i18n.domains, (0, _gethostname.getHostname)({
hostname: urlNoQuery
}, req.headers));
const defaultLocale = (domainLocale == null ? void 0 : domainLocale.defaultLocale) || config.i18n.defaultLocale;
const { getLocaleRedirect } = require("../../shared/lib/i18n/get-locale-redirect");
const parsedUrl = (0, _parseurl.parseUrl)((_this = req.url || "") == null ? void 0 : _this.replace(/^\/+/, "/"));
const redirect = getLocaleRedirect({
defaultLocale,
domainLocale,
headers: req.headers,
nextConfig: config,
pathLocale: pathnameInfo.locale,
urlParsed: {
...parsedUrl,
pathname: pathnameInfo.locale ? `/${pathnameInfo.locale}${urlNoQuery}` : urlNoQuery
}
});
if (redirect) {
res.setHeader("Location", redirect);
res.statusCode = _redirectstatuscode.RedirectStatusCode.TemporaryRedirect;
res.end(redirect);
return;
}
}
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, invokePath, handleIndex, additionalRequestMeta) {
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 = 404;
res.setHeader("content-type", "application/json");
res.end("{}");
return null;
}
if (!handlers) {
throw new Error("Failed to initialize render server");
}
(0, _requestmeta.addRequestMeta)(req, "invokePath", invokePath);
(0, _requestmeta.addRequestMeta)(req, "invokeQuery", parsedUrl.query);
(0, _requestmeta.addRequestMeta)(req, "middlewareInvoke", false);
for(const key in additionalRequestMeta || {}){
(0, _requestmeta.addRequestMeta)(req, key, additionalRequestMeta[key]);
}
debug("invokeRender", req.url, req.headers);
try {
var _renderServer_instance;
const initResult = await (renderServer == null ? void 0 : (_renderServer_instance = renderServer.instance) == null ? void 0 : _renderServer_instance.initialize(renderServerOpts));
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 (developmentBundler) {
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 developmentBundler.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 (developmentBundler && (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 developmentBundler.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 === _redirectstatuscode.RedirectStatusCode.PermanentRedirect) {
res.setHeader("Refresh", `0;url=${destination}`);
}
return res.end(destination);
}
// handle middleware body response
if (bodyStream) {
res.statusCode = statusCode || 200;
return await (0, _pipereadable.pipeToNodeResponse)(bodyStream, res);
}
if (finished && parsedUrl.protocol) {
var _getRequestMeta;
return await (0, _proxyrequest.proxyRequest)(req, res, parsedUrl, undefined, (_getRequestMeta = (0, _requestmeta.getRequestMeta)(req, "clonableBody")) == 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, "/_error", handleIndex, {
invokeStatus: 500,
invokeError: new Error(`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 && !isNextFont(parsedUrl.pathname)) {
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), "/405", handleIndex, {
invokeStatus: 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), invokePath, handleIndex, {
invokeStatus
});
}
throw err;
}
}
if (matchedOutput) {
invokedOutputs.add(matchedOutput.itemPath);
return await invokeRender(parsedUrl, parsedUrl.pathname || "/", handleIndex, {
invokeOutput: matchedOutput.itemPath
});
}
// 404 case
res.setHeader("Cache-Control", "private, 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 ? developmentBundler == null ? void 0 : developmentBundler.serverFields.hasAppNotFound : await fsChecker.getItem(_constants.UNDERSCORE_NOT_FOUND_ROUTE);
res.statusCode = 404;
if (appNotFound) {
return await invokeRender(parsedUrl, _constants.UNDERSCORE_NOT_FOUND_ROUTE, handleIndex, {
invokeStatus: 404
});
}
await invokeRender(parsedUrl, "/404", handleIndex, {
invokeStatus: 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), invokePath, 0, {
invokeStatus: res.statusCode
});
} catch (err2) {
console.error(err2);
}
res.statusCode = 500;
res.end("Internal Server Error");
}
};
let requestHandler = requestHandlerImpl;
if (config.experimental.testProxy) {
// Intercept fetch and other testmode apis.
const { wrapRequestHandlerWorker, interceptTestApis } = require("next/dist/experimental/testmode/server");
requestHandler = wrapRequestHandlerWorker(requestHandler);
interceptTestApis();
}
requestHandlers[opts.dir] = requestHandler;
const renderServerOpts = {
port: opts.port,
dir: opts.dir,
hostname: opts.hostname,
minimalMode: opts.minimalMode,
dev: !!opts.dev,
server: opts.server,
isNodeDebugging: !!opts.isNodeDebugging,
serverFields: (developmentBundler == null ? void 0 : developmentBundler.serverFields) || {},
experimentalTestProxy: !!config.experimental.testProxy,
experimentalHttpsServer: !!opts.experimentalHttpsServer,
bundlerService: devBundlerService,
startServerSpan: opts.startServerSpan
};
renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl;
// pre-initialize workers
const handlers = await renderServer.instance.initialize(renderServerOpts);
const logError = async (type, err)=>{
if ((0, _ispostpone.isPostpone)(err)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return;
}
await (developmentBundler == null ? void 0 : developmentBundler.logErrorWithOriginalStack(err, type));
};
process.on("uncaughtException", logError.bind(null, "uncaughtException"));
process.on("unhandledRejection", logError.bind(null, "unhandledRejection"));
const resolveRoutes = (0, _resolveroutes.getResolveRoutes)(fsChecker, config, opts, renderServer.instance, renderServerOpts, developmentBundler == null ? void 0 : developmentBundler.ensureMiddleware);
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 && developmentBundler && req.url) {
const { basePath, assetPrefix } = config;
let hmrPrefix = basePath;
// assetPrefix overrides basePath for HMR path
if (assetPrefix) {
hmrPrefix = (0, _normalizedassetprefix.normalizedAssetPrefix)(assetPrefix);
if (URL.canParse(hmrPrefix)) {
// remove trailing slash from pathname
// return empty string if pathname is '/'
// to avoid conflicts with '/_next' below
hmrPrefix = new URL(hmrPrefix).pathname.replace(/\/$/, "");
}
}
const isHMRRequest = req.url.startsWith((0, _ensureleadingslash.ensureLeadingSlash)(`${hmrPrefix}/_next/webpack-hmr`));
// only handle HMR requests if the basePath in the request
// matches the basePath for the handler responding to the request
if (isHMRRequest) {
return developmentBundler.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);
}
// If there's no matched output, we don't handle the request as user's
// custom WS server may be listening on the same path.
} catch (err) {
console.error("Error handling upgrade request", err);
socket.end();
}
};
return [
requestHandler,
upgradeHandler,
handlers.app
];
}
//# sourceMappingURL=router-server.js.map

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,536 @@
"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");
const _rsc = require("../../future/normalizers/request/rsc");
const _postponed = require("../../future/normalizers/request/postponed");
const _prefetchrsc = require("../../future/normalizers/request/prefetch-rsc");
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 = {
__proto__: null
};
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);
try {
buildId = await _promises.default.readFile(buildIdPath, "utf8");
} catch (err) {
if (err.code !== "ENOENT") throw err;
throw new Error(`Could not find a production build in the '${opts.config.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`);
}
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 = {
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;
const normalizers = {
// Because we can't know if the app directory is enabled or not at this
// stage, we assume that it is.
rsc: new _rsc.RSCPathnameNormalizer(),
prefetchRSC: opts.config.experimental.ppr ? new _prefetchrsc.PrefetchRSCPathnameNormalizer() : undefined,
postponed: opts.config.experimental.ppr ? new _postponed.PostponedPathnameNormalizer() : undefined
};
return {
headers,
rewrites,
redirects,
buildId,
handleLocale,
appFiles,
pageFiles,
dynamicRoutes,
nextDataRoutes,
exportPathMapRoutes: 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;
}
const { basePath, assetPrefix } = opts.config;
const hasBasePath = (0, _pathhasprefix.pathHasPrefix)(itemPath, basePath);
const hasAssetPrefix = (0, _pathhasprefix.pathHasPrefix)(itemPath, assetPrefix);
// Return null if either path doesn't start with basePath or assetPrefix
if ((basePath || assetPrefix) && !hasBasePath && !hasAssetPrefix) {
return null;
}
// Either remove basePath or assetPrefix, not both (due to routes with same name as basePath)
if (basePath && hasBasePath) {
itemPath = (0, _removepathprefix.removePathPrefix)(itemPath, basePath) || "/";
} else if (assetPrefix && hasAssetPrefix) {
itemPath = (0, _removepathprefix.removePathPrefix)(itemPath, assetPrefix) || "/";
}
// Simulate minimal mode requests by normalizing RSC and postponed
// requests.
if (opts.minimalMode) {
var _normalizers_prefetchRSC, _normalizers_postponed;
if ((_normalizers_prefetchRSC = normalizers.prefetchRSC) == null ? void 0 : _normalizers_prefetchRSC.match(itemPath)) {
itemPath = normalizers.prefetchRSC.normalize(itemPath, true);
} else if (normalizers.rsc.match(itemPath)) {
itemPath = normalizers.rsc.normalize(itemPath, true);
} else if ((_normalizers_postponed = normalizers.postponed) == null ? void 0 : _normalizers_postponed.match(itemPath)) {
itemPath = normalizers.postponed.normalize(itemPath, true);
}
}
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) {
var _i18n_domains;
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,
// default locales from domains need to be matched too
...((_i18n_domains = i18n.domains) == null ? void 0 : _i18n_domains.map((item)=>item.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 {}
}
let matchedItem = items.has(curItemPath);
// check decoded variant as well
if (!matchedItem && !opts.dev) {
matchedItem = items.has(curDecodedItemPath);
if (matchedItem) curItemPath = curDecodedItemPath;
else {
// x-ref: https://github.com/vercel/next.js/issues/54008
// There're cases that urls get decoded before requests, we should support both encoded and decoded ones.
// e.g. nginx could decode the proxy urls, the below ones should be treated as the same:
// decoded version: `/_next/static/chunks/pages/blog/[slug]-d4858831b91b69f6.js`
// encoded version: `/_next/static/chunks/pages/blog/%5Bslug%5D-d4858831b91b69f6.js`
try {
// encode the special characters in the path and retrieve again to determine if path exists.
const encodedCurItemPath = encodeURI(curItemPath);
matchedItem = items.has(encodedCurItemPath);
} catch {}
}
}
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

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "isPostpone", {
enumerable: true,
get: function() {
return isPostpone;
}
});
const REACT_POSTPONE_TYPE = Symbol.for("react.postpone");
function isPostpone(error) {
return typeof error === "object" && error !== null && error.$$typeof === REACT_POSTPONE_TYPE;
}
//# sourceMappingURL=is-postpone.js.map

View File

@@ -0,0 +1,110 @@
"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,
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,
headers: {
"x-forwarded-host": req.headers.host || ""
}
});
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,545 @@
"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 _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
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 _nextdata = require("../../future/normalizers/request/next-data");
const _basepath = require("../../future/normalizers/request/base-path");
const _postponed = require("../../future/normalizers/request/postponed");
const _requestmeta = require("../../request-meta");
const _preparedestination = require("../../../shared/lib/router/utils/prepare-destination");
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, renderServer, renderServerOpts, 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 _req_socket, _req_headers_xforwardedproto;
let finished = false;
let resHeaders = {};
let matchedOutput = null;
let parsedUrl = _url.default.parse(req.url || "", true);
let didRewrite = false;
const urlParts = (req.url || "").split("?", 1);
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 = (req == null ? void 0 : (_req_socket = req.socket) == null ? void 0 : _req_socket.encrypted) || ((_req_headers_xforwardedproto = req.headers["x-forwarded-proto"]) == null ? void 0 : _req_headers_xforwardedproto.includes("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, "initURL", initUrl);
(0, _requestmeta.addRequestMeta)(req, "initQuery", {
...parsedUrl.query
});
(0, _requestmeta.addRequestMeta)(req, "initProtocol", protocol);
if (!isUpgradeReq) {
(0, _requestmeta.addRequestMeta)(req, "clonableBody", (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);
}
}
} else {
// As i18n isn't configured we remove the locale related query params.
delete parsedUrl.query.__nextLocale;
delete parsedUrl.query.__nextDefaultLocale;
delete parsedUrl.query.__nextInferredLocaleFromDefault;
}
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;
}
}
}
}
const normalizers = {
basePath: config.basePath && config.basePath !== "/" ? new _basepath.BasePathPathnameNormalizer(config.basePath) : undefined,
data: new _nextdata.NextDataPathnameNormalizer(fsChecker.buildId),
postponed: config.experimental.ppr ? new _postponed.PostponedPathnameNormalizer() : undefined
};
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.exportPathMapRoutes && route.name === "before_files_end") {
for (const exportPathMapRoute of fsChecker.exportPathMapRoutes){
const result = await handleRoute(exportPathMapRoute);
if (result) {
return result;
}
}
}
if (route.name === "middleware_next_data" && parsedUrl.pathname) {
var _fsChecker_getMiddlewareMatchers;
if ((_fsChecker_getMiddlewareMatchers = fsChecker.getMiddlewareMatchers()) == null ? void 0 : _fsChecker_getMiddlewareMatchers.length) {
var _normalizers_basePath, _normalizers_postponed;
let normalized = parsedUrl.pathname;
// Remove the base path if it exists.
const hadBasePath = (_normalizers_basePath = normalizers.basePath) == null ? void 0 : _normalizers_basePath.match(parsedUrl.pathname);
if (hadBasePath && normalizers.basePath) {
normalized = normalizers.basePath.normalize(normalized, true);
}
let updated = false;
if (normalizers.data.match(normalized)) {
updated = true;
parsedUrl.query.__nextDataReq = "1";
normalized = normalizers.data.normalize(normalized, true);
} else if ((_normalizers_postponed = normalizers.postponed) == null ? void 0 : _normalizers_postponed.match(normalized)) {
updated = true;
normalized = normalizers.postponed.normalize(normalized, true);
}
if (config.i18n) {
const curLocaleResult = (0, _normalizelocalepath.normalizeLocalePath)(normalized, config.i18n.locales);
if (curLocaleResult.detectedLocale) {
parsedUrl.query.__nextLocale = curLocaleResult.detectedLocale;
}
}
// If we updated the pathname, and it had a base path, re-add the
// base path.
if (updated) {
if (hadBasePath) {
normalized = _nodepath.default.posix.join(config.basePath, normalized);
}
// Re-add the trailing slash (if required).
normalized = maybeAddTrailingSlash(normalized);
parsedUrl.pathname = normalized;
}
}
}
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)) {
if (ensureMiddleware) {
await ensureMiddleware(req.url);
}
const serverResult = await (renderServer == null ? void 0 : renderServer.initialize(renderServerOpts));
if (!serverResult) {
throw new Error(`Failed to initialize render server "middleware"`);
}
(0, _requestmeta.addRequestMeta)(req, "invokePath", "");
(0, _requestmeta.addRequestMeta)(req, "invokeOutput", "");
(0, _requestmeta.addRequestMeta)(req, "invokeQuery", {});
(0, _requestmeta.addRequestMeta)(req, "middlewareInvoke", true);
debug("invoking middleware", req.url, req.headers);
let middlewareRes = undefined;
let bodyStream = undefined;
try {
try {
await serverResult.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"
].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

View File

@@ -0,0 +1,830 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
propagateServerField: null,
setupDevBundler: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
propagateServerField: function() {
return propagateServerField;
},
setupDevBundler: function() {
return setupDevBundler;
}
});
const _swc = require("../../../build/swc");
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
const _url = /*#__PURE__*/ _interop_require_default(require("url"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _querystring = /*#__PURE__*/ _interop_require_default(require("querystring"));
const _watchpack = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/watchpack"));
const _env = require("@next/env");
const _iserror = /*#__PURE__*/ _interop_require_default(require("../../../lib/is-error"));
const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up"));
const _filesystem = require("./filesystem");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../../build/output/log"));
const _hotreloaderwebpack = /*#__PURE__*/ _interop_require_default(require("../../dev/hot-reloader-webpack"));
const _shared = require("../../../trace/shared");
const _loadjsconfig = /*#__PURE__*/ _interop_require_default(require("../../../build/load-jsconfig"));
const _findpagefile = require("../find-page-file");
const _events = require("../../../telemetry/events");
const _defineenvplugin = require("../../../build/webpack/plugins/define-env-plugin");
const _logappdirerror = require("../../dev/log-app-dir-error");
const _utils = require("../../../shared/lib/router/utils");
const _entries = require("../../../build/entries");
const _verifytypescriptsetup = require("../../../lib/verify-typescript-setup");
const _verifypartytownsetup = require("../../../lib/verify-partytown-setup");
const _routeregex = require("../../../shared/lib/router/utils/route-regex");
const _apppaths = require("../../../shared/lib/router/utils/app-paths");
const _builddataroute = require("./build-data-route");
const _routematcher = require("../../../shared/lib/router/utils/route-matcher");
const _normalizepathsep = require("../../../shared/lib/page-path/normalize-path-sep");
const _createclientrouterfilter = require("../../../lib/create-client-router-filter");
const _absolutepathtopage = require("../../../shared/lib/page-path/absolute-path-to-page");
const _generateinterceptionroutesrewrites = require("../../../lib/generate-interception-routes-rewrites");
const _constants = require("../../../shared/lib/constants");
const _middlewareroutematcher = require("../../../shared/lib/router/utils/middleware-route-matcher");
const _utils1 = require("../../../build/utils");
const _middleware = require("../../../client/components/react-dev-overlay/server/middleware");
const _middlewareturbopack = require("../../../client/components/react-dev-overlay/server/middleware-turbopack");
const _shared1 = require("../../../build/webpack/plugins/next-types-plugin/shared");
const _hotreloadertypes = require("../../dev/hot-reloader-types");
const _pagetypes = require("../../../lib/page-types");
const _hotreloaderturbopack = require("../../dev/hot-reloader-turbopack");
const _errorsource = require("../../../shared/lib/error-source");
const _encryptionutils = require("../../app-render/encryption-utils");
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 = {
__proto__: null
};
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;
}
async function verifyTypeScript(opts) {
let usingTypeScript = false;
const verifyResult = await (0, _verifytypescriptsetup.verifyTypeScriptSetup)({
dir: opts.dir,
distDir: opts.nextConfig.distDir,
intentDirs: [
opts.pagesDir,
opts.appDir
].filter(Boolean),
typeCheckPreflight: false,
tsconfigPath: opts.nextConfig.typescript.tsconfigPath,
disableStaticImages: opts.nextConfig.images.disableStaticImages,
hasAppDir: !!opts.appDir,
hasPagesDir: !!opts.pagesDir
});
if (verifyResult.version) {
usingTypeScript = true;
}
return usingTypeScript;
}
class ModuleBuildError extends Error {
}
async function propagateServerField(opts, field, args) {
var _opts_renderServer_instance, _opts_renderServer;
await ((_opts_renderServer = opts.renderServer) == null ? void 0 : (_opts_renderServer_instance = _opts_renderServer.instance) == null ? void 0 : _opts_renderServer_instance.propagateServerField(opts.dir, field, args));
}
async function startWatcher(opts) {
const { nextConfig, appDir, pagesDir, dir } = opts;
const { useFileSystemPublicRoutes } = nextConfig;
const usingTypeScript = await verifyTypeScript(opts);
const distDir = _path.default.join(opts.dir, opts.nextConfig.distDir);
(0, _shared.setGlobal)("distDir", distDir);
(0, _shared.setGlobal)("phase", _constants.PHASE_DEVELOPMENT_SERVER);
const validFileMatcher = (0, _findpagefile.createValidFileMatcher)(nextConfig.pageExtensions, appDir);
const serverFields = {};
const hotReloader = opts.turbo ? await (0, _hotreloaderturbopack.createHotReloaderTurbopack)(opts, serverFields, distDir) : new _hotreloaderwebpack.default(opts.dir, {
appDir,
pagesDir,
distDir: distDir,
config: opts.nextConfig,
buildId: "development",
encryptionKey: await (0, _encryptionutils.generateEncryptionKeyBase64)(),
telemetry: opts.telemetry,
rewrites: opts.fsChecker.rewrites,
previewProps: opts.fsChecker.prerenderManifest.preview
});
await hotReloader.start();
if (opts.nextConfig.experimental.nextScriptWorkers) {
await (0, _verifypartytownsetup.verifyPartytownSetup)(opts.dir, _path.default.join(distDir, _constants.CLIENT_STATIC_FILES_PATH));
}
opts.fsChecker.ensureCallback(async function ensure(item) {
if (item.type === "appFile" || item.type === "pageFile") {
await hotReloader.ensurePage({
clientOnly: false,
page: item.itemPath,
isApp: item.type === "appFile",
definition: undefined
});
}
});
let resolved = false;
let prevSortedRoutes = [];
await new Promise(async (resolve, reject)=>{
if (pagesDir) {
// Watchpack doesn't emit an event for an empty directory
_fs.default.readdir(pagesDir, (_, files)=>{
if (files == null ? void 0 : files.length) {
return;
}
if (!resolved) {
resolve();
resolved = true;
}
});
}
const pages = pagesDir ? [
pagesDir
] : [];
const app = appDir ? [
appDir
] : [];
const directories = [
...pages,
...app
];
const rootDir = pagesDir || appDir;
const files = [
...(0, _utils1.getPossibleMiddlewareFilenames)(_path.default.join(rootDir, ".."), nextConfig.pageExtensions),
...(0, _utils1.getPossibleInstrumentationHookFilenames)(_path.default.join(rootDir, ".."), nextConfig.pageExtensions)
];
let nestedMiddleware = [];
const envFiles = [
".env.development.local",
".env.local",
".env.development",
".env"
].map((file)=>_path.default.join(dir, file));
files.push(...envFiles);
// tsconfig/jsconfig paths hot-reloading
const tsconfigPaths = [
_path.default.join(dir, "tsconfig.json"),
_path.default.join(dir, "jsconfig.json")
];
files.push(...tsconfigPaths);
const wp = new _watchpack.default({
ignored: (pathname)=>{
return !files.some((file)=>file.startsWith(pathname)) && !directories.some((d)=>pathname.startsWith(d) || d.startsWith(pathname));
}
});
const fileWatchTimes = new Map();
let enabledTypeScript = usingTypeScript;
let previousClientRouterFilters;
let previousConflictingPagePaths = new Set();
wp.on("aggregated", async ()=>{
var _serverFields_middleware, _serverFields_middleware1;
let middlewareMatchers;
const routedPages = [];
const knownFiles = wp.getTimeInfoEntries();
const appPaths = {};
const pageNameSet = new Set();
const conflictingAppPagePaths = new Set();
const appPageFilePaths = new Map();
const pagesPageFilePaths = new Map();
let envChange = false;
let tsconfigChange = false;
let conflictingPageChange = 0;
let hasRootAppNotFound = false;
const { appFiles, pageFiles } = opts.fsChecker;
appFiles.clear();
pageFiles.clear();
_shared1.devPageFiles.clear();
const sortedKnownFiles = [
...knownFiles.keys()
].sort((0, _entries.sortByPageExts)(nextConfig.pageExtensions));
for (const fileName of sortedKnownFiles){
if (!files.includes(fileName) && !directories.some((d)=>fileName.startsWith(d))) {
continue;
}
const meta = knownFiles.get(fileName);
const watchTime = fileWatchTimes.get(fileName);
// If the file is showing up for the first time or the meta.timestamp is changed since last time
const watchTimeChange = watchTime === undefined || watchTime && watchTime !== (meta == null ? void 0 : meta.timestamp);
fileWatchTimes.set(fileName, meta == null ? void 0 : meta.timestamp);
if (envFiles.includes(fileName)) {
if (watchTimeChange) {
envChange = true;
}
continue;
}
if (tsconfigPaths.includes(fileName)) {
if (fileName.endsWith("tsconfig.json")) {
enabledTypeScript = true;
}
if (watchTimeChange) {
tsconfigChange = true;
}
continue;
}
if ((meta == null ? void 0 : meta.accuracy) === undefined || !validFileMatcher.isPageFile(fileName)) {
continue;
}
const isAppPath = Boolean(appDir && (0, _normalizepathsep.normalizePathSep)(fileName).startsWith((0, _normalizepathsep.normalizePathSep)(appDir) + "/"));
const isPagePath = Boolean(pagesDir && (0, _normalizepathsep.normalizePathSep)(fileName).startsWith((0, _normalizepathsep.normalizePathSep)(pagesDir) + "/"));
const rootFile = (0, _absolutepathtopage.absolutePathToPage)(fileName, {
dir: dir,
extensions: nextConfig.pageExtensions,
keepIndex: false,
pagesType: _pagetypes.PAGE_TYPES.ROOT
});
if ((0, _utils1.isMiddlewareFile)(rootFile)) {
var _staticInfo_middleware;
const staticInfo = await (0, _entries.getStaticInfoIncludingLayouts)({
pageFilePath: fileName,
config: nextConfig,
appDir: appDir,
page: rootFile,
isDev: true,
isInsideAppDir: isAppPath,
pageExtensions: nextConfig.pageExtensions
});
if (nextConfig.output === "export") {
_log.error('Middleware cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export');
continue;
}
serverFields.actualMiddlewareFile = rootFile;
await propagateServerField(opts, "actualMiddlewareFile", serverFields.actualMiddlewareFile);
middlewareMatchers = ((_staticInfo_middleware = staticInfo.middleware) == null ? void 0 : _staticInfo_middleware.matchers) || [
{
regexp: ".*",
originalSource: "/:path*"
}
];
continue;
}
if ((0, _utils1.isInstrumentationHookFile)(rootFile) && nextConfig.experimental.instrumentationHook) {
serverFields.actualInstrumentationHookFile = rootFile;
await propagateServerField(opts, "actualInstrumentationHookFile", serverFields.actualInstrumentationHookFile);
continue;
}
if (fileName.endsWith(".ts") || fileName.endsWith(".tsx")) {
enabledTypeScript = true;
}
if (!(isAppPath || isPagePath)) {
continue;
}
// Collect all current filenames for the TS plugin to use
_shared1.devPageFiles.add(fileName);
let pageName = (0, _absolutepathtopage.absolutePathToPage)(fileName, {
dir: isAppPath ? appDir : pagesDir,
extensions: nextConfig.pageExtensions,
keepIndex: isAppPath,
pagesType: isAppPath ? _pagetypes.PAGE_TYPES.APP : _pagetypes.PAGE_TYPES.PAGES
});
if (!isAppPath && pageName.startsWith("/api/") && nextConfig.output === "export") {
_log.error('API Routes cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export');
continue;
}
if (isAppPath) {
const isRootNotFound = validFileMatcher.isRootNotFound(fileName);
hasRootAppNotFound = true;
if (isRootNotFound) {
continue;
}
if (!isRootNotFound && !validFileMatcher.isAppRouterPage(fileName)) {
continue;
}
// Ignore files/directories starting with `_` in the app directory
if ((0, _normalizepathsep.normalizePathSep)(pageName).includes("/_")) {
continue;
}
const originalPageName = pageName;
pageName = (0, _apppaths.normalizeAppPath)(pageName).replace(/%5F/g, "_");
if (!appPaths[pageName]) {
appPaths[pageName] = [];
}
appPaths[pageName].push(originalPageName);
if (useFileSystemPublicRoutes) {
appFiles.add(pageName);
}
if (routedPages.includes(pageName)) {
continue;
}
} else {
if (useFileSystemPublicRoutes) {
pageFiles.add(pageName);
// always add to nextDataRoutes for now but in future only add
// entries that actually use getStaticProps/getServerSideProps
opts.fsChecker.nextDataRoutes.add(pageName);
}
}
(isAppPath ? appPageFilePaths : pagesPageFilePaths).set(pageName, fileName);
if (appDir && pageNameSet.has(pageName)) {
conflictingAppPagePaths.add(pageName);
} else {
pageNameSet.add(pageName);
}
/**
* If there is a middleware that is not declared in the root we will
* warn without adding it so it doesn't make its way into the system.
*/ if (/[\\\\/]_middleware$/.test(pageName)) {
nestedMiddleware.push(pageName);
continue;
}
routedPages.push(pageName);
}
const numConflicting = conflictingAppPagePaths.size;
conflictingPageChange = numConflicting - previousConflictingPagePaths.size;
if (conflictingPageChange !== 0) {
if (numConflicting > 0) {
let errorMessage = `Conflicting app and page file${numConflicting === 1 ? " was" : "s were"} found, please remove the conflicting files to continue:\n`;
for (const p of conflictingAppPagePaths){
const appPath = _path.default.relative(dir, appPageFilePaths.get(p));
const pagesPath = _path.default.relative(dir, pagesPageFilePaths.get(p));
errorMessage += ` "${pagesPath}" - "${appPath}"\n`;
}
hotReloader.setHmrServerError(new Error(errorMessage));
} else if (numConflicting === 0) {
hotReloader.clearHmrServerError();
await propagateServerField(opts, "reloadMatchers", undefined);
}
}
previousConflictingPagePaths = conflictingAppPagePaths;
let clientRouterFilters;
if (nextConfig.experimental.clientRouterFilter) {
clientRouterFilters = (0, _createclientrouterfilter.createClientRouterFilter)(Object.keys(appPaths), nextConfig.experimental.clientRouterFilterRedirects ? (nextConfig._originalRedirects || []).filter((r)=>!r.internal) : [], nextConfig.experimental.clientRouterFilterAllowedRate);
if (!previousClientRouterFilters || JSON.stringify(previousClientRouterFilters) !== JSON.stringify(clientRouterFilters)) {
envChange = true;
previousClientRouterFilters = clientRouterFilters;
}
}
if (!usingTypeScript && enabledTypeScript) {
// we tolerate the error here as this is best effort
// and the manual install command will be shown
await verifyTypeScript(opts).then(()=>{
tsconfigChange = true;
}).catch(()=>{});
}
if (envChange || tsconfigChange) {
var _hotReloader_activeWebpackConfigs;
if (envChange) {
// only log changes in router server
(0, _env.loadEnvConfig)(dir, true, _log, true, (envFilePath)=>{
_log.info(`Reload env: ${envFilePath}`);
});
await propagateServerField(opts, "loadEnvConfig", [
{
dev: true,
forceReload: true,
silent: true
}
]);
}
let tsconfigResult;
if (tsconfigChange) {
try {
tsconfigResult = await (0, _loadjsconfig.default)(dir, nextConfig);
} catch (_) {
/* do we want to log if there are syntax errors in tsconfig while editing? */ }
}
if (hotReloader.turbopackProject) {
const hasRewrites = opts.fsChecker.rewrites.afterFiles.length > 0 || opts.fsChecker.rewrites.beforeFiles.length > 0 || opts.fsChecker.rewrites.fallback.length > 0;
await hotReloader.turbopackProject.update({
defineEnv: (0, _swc.createDefineEnv)({
isTurbopack: true,
clientRouterFilters,
config: nextConfig,
dev: true,
distDir,
fetchCacheKeyPrefix: opts.nextConfig.experimental.fetchCacheKeyPrefix,
hasRewrites,
// TODO: Implement
middlewareMatchers: undefined
})
});
}
(_hotReloader_activeWebpackConfigs = hotReloader.activeWebpackConfigs) == null ? void 0 : _hotReloader_activeWebpackConfigs.forEach((config, idx)=>{
const isClient = idx === 0;
const isNodeServer = idx === 1;
const isEdgeServer = idx === 2;
const hasRewrites = opts.fsChecker.rewrites.afterFiles.length > 0 || opts.fsChecker.rewrites.beforeFiles.length > 0 || opts.fsChecker.rewrites.fallback.length > 0;
if (tsconfigChange) {
var _config_resolve_plugins, _config_resolve;
(_config_resolve = config.resolve) == null ? void 0 : (_config_resolve_plugins = _config_resolve.plugins) == null ? void 0 : _config_resolve_plugins.forEach((plugin)=>{
// look for the JsConfigPathsPlugin and update with
// the latest paths/baseUrl config
if (plugin && plugin.jsConfigPlugin && tsconfigResult) {
var _config_resolve_modules, _config_resolve, _jsConfig_compilerOptions;
const { resolvedBaseUrl, jsConfig } = tsconfigResult;
const currentResolvedBaseUrl = plugin.resolvedBaseUrl;
const resolvedUrlIndex = (_config_resolve = config.resolve) == null ? void 0 : (_config_resolve_modules = _config_resolve.modules) == null ? void 0 : _config_resolve_modules.findIndex((item)=>item === currentResolvedBaseUrl);
if (resolvedBaseUrl) {
if (resolvedBaseUrl.baseUrl !== currentResolvedBaseUrl.baseUrl) {
// remove old baseUrl and add new one
if (resolvedUrlIndex && resolvedUrlIndex > -1) {
var _config_resolve_modules1, _config_resolve1;
(_config_resolve1 = config.resolve) == null ? void 0 : (_config_resolve_modules1 = _config_resolve1.modules) == null ? void 0 : _config_resolve_modules1.splice(resolvedUrlIndex, 1);
}
// If the resolvedBaseUrl is implicit we only remove the previous value.
// Only add the baseUrl if it's explicitly set in tsconfig/jsconfig
if (!resolvedBaseUrl.isImplicit) {
var _config_resolve_modules2, _config_resolve2;
(_config_resolve2 = config.resolve) == null ? void 0 : (_config_resolve_modules2 = _config_resolve2.modules) == null ? void 0 : _config_resolve_modules2.push(resolvedBaseUrl.baseUrl);
}
}
}
if ((jsConfig == null ? void 0 : (_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.paths) && resolvedBaseUrl) {
Object.keys(plugin.paths).forEach((key)=>{
delete plugin.paths[key];
});
Object.assign(plugin.paths, jsConfig.compilerOptions.paths);
plugin.resolvedBaseUrl = resolvedBaseUrl;
}
}
});
}
if (envChange) {
var _config_plugins;
(_config_plugins = config.plugins) == null ? void 0 : _config_plugins.forEach((plugin)=>{
// we look for the DefinePlugin definitions so we can
// update them on the active compilers
if (plugin && typeof plugin.definitions === "object" && plugin.definitions.__NEXT_DEFINE_ENV) {
const newDefine = (0, _defineenvplugin.getDefineEnv)({
isTurbopack: false,
clientRouterFilters,
config: nextConfig,
dev: true,
distDir,
fetchCacheKeyPrefix: opts.nextConfig.experimental.fetchCacheKeyPrefix,
hasRewrites,
isClient,
isEdgeServer,
isNodeOrEdgeCompilation: isNodeServer || isEdgeServer,
isNodeServer,
middlewareMatchers: undefined
});
Object.keys(plugin.definitions).forEach((key)=>{
if (!(key in newDefine)) {
delete plugin.definitions[key];
}
});
Object.assign(plugin.definitions, newDefine);
}
});
}
});
await hotReloader.invalidate({
reloadAfterInvalidation: envChange
});
}
if (nestedMiddleware.length > 0) {
_log.error(new _utils1.NestedMiddlewareError(nestedMiddleware, dir, pagesDir || appDir).message);
nestedMiddleware = [];
}
// Make sure to sort parallel routes to make the result deterministic.
serverFields.appPathRoutes = Object.fromEntries(Object.entries(appPaths).map(([k, v])=>[
k,
v.sort()
]));
await propagateServerField(opts, "appPathRoutes", serverFields.appPathRoutes);
// TODO: pass this to fsChecker/next-dev-server?
serverFields.middleware = middlewareMatchers ? {
match: null,
page: "/",
matchers: middlewareMatchers
} : undefined;
await propagateServerField(opts, "middleware", serverFields.middleware);
serverFields.hasAppNotFound = hasRootAppNotFound;
opts.fsChecker.middlewareMatcher = ((_serverFields_middleware = serverFields.middleware) == null ? void 0 : _serverFields_middleware.matchers) ? (0, _middlewareroutematcher.getMiddlewareRouteMatcher)((_serverFields_middleware1 = serverFields.middleware) == null ? void 0 : _serverFields_middleware1.matchers) : undefined;
const interceptionRoutes = (0, _generateinterceptionroutesrewrites.generateInterceptionRoutesRewrites)(Object.keys(appPaths), opts.nextConfig.basePath).map((item)=>(0, _filesystem.buildCustomRoute)("before_files_rewrite", item, opts.nextConfig.basePath, opts.nextConfig.experimental.caseSensitiveRoutes));
opts.fsChecker.rewrites.beforeFiles.push(...interceptionRoutes);
const exportPathMap = typeof nextConfig.exportPathMap === "function" && await (nextConfig.exportPathMap == null ? void 0 : nextConfig.exportPathMap.call(nextConfig, {}, {
dev: true,
dir: opts.dir,
outDir: null,
distDir: distDir,
buildId: "development"
})) || {};
const exportPathMapEntries = Object.entries(exportPathMap || {});
if (exportPathMapEntries.length > 0) {
opts.fsChecker.exportPathMapRoutes = exportPathMapEntries.map(([key, value])=>(0, _filesystem.buildCustomRoute)("before_files_rewrite", {
source: key,
destination: `${value.page}${value.query ? "?" : ""}${_querystring.default.stringify(value.query)}`
}, opts.nextConfig.basePath, opts.nextConfig.experimental.caseSensitiveRoutes));
}
try {
// we serve a separate manifest with all pages for the client in
// dev mode so that we can match a page after a rewrite on the client
// before it has been built and is populated in the _buildManifest
const sortedRoutes = (0, _utils.getSortedRoutes)(routedPages);
opts.fsChecker.dynamicRoutes = sortedRoutes.map((page)=>{
const regex = (0, _routeregex.getRouteRegex)(page);
return {
regex: regex.re.toString(),
match: (0, _routematcher.getRouteMatcher)(regex),
page
};
});
const dataRoutes = [];
for (const page of sortedRoutes){
const route = (0, _builddataroute.buildDataRoute)(page, "development");
const routeRegex = (0, _routeregex.getRouteRegex)(route.page);
dataRoutes.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.nextConfig.i18n ? new RegExp(route.dataRouteRegex.replace(`/development/`, `/development/(?<nextLocale>[^/]+?)/`)) : new RegExp(route.dataRouteRegex),
groups: routeRegex.groups
})
});
}
opts.fsChecker.dynamicRoutes.unshift(...dataRoutes);
if (!(prevSortedRoutes == null ? void 0 : prevSortedRoutes.every((val, idx)=>val === sortedRoutes[idx]))) {
const addedRoutes = sortedRoutes.filter((route)=>!prevSortedRoutes.includes(route));
const removedRoutes = prevSortedRoutes.filter((route)=>!sortedRoutes.includes(route));
// emit the change so clients fetch the update
hotReloader.send({
action: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE,
data: [
{
devPagesManifest: true
}
]
});
addedRoutes.forEach((route)=>{
hotReloader.send({
action: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.ADDED_PAGE,
data: [
route
]
});
});
removedRoutes.forEach((route)=>{
hotReloader.send({
action: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.REMOVED_PAGE,
data: [
route
]
});
});
}
prevSortedRoutes = sortedRoutes;
if (!resolved) {
resolve();
resolved = true;
}
} catch (e) {
if (!resolved) {
reject(e);
resolved = true;
} else {
_log.warn("Failed to reload dynamic routes:", e);
}
} finally{
// Reload the matchers. The filesystem would have been written to,
// and the matchers need to re-scan it to update the router.
await propagateServerField(opts, "reloadMatchers", undefined);
}
});
wp.watch({
directories: [
dir
],
startTime: 0
});
});
const clientPagesManifestPath = `/_next/${_constants.CLIENT_STATIC_FILES_PATH}/development/${_constants.DEV_CLIENT_PAGES_MANIFEST}`;
opts.fsChecker.devVirtualFsItems.add(clientPagesManifestPath);
const devMiddlewareManifestPath = `/_next/${_constants.CLIENT_STATIC_FILES_PATH}/development/${_constants.DEV_MIDDLEWARE_MANIFEST}`;
opts.fsChecker.devVirtualFsItems.add(devMiddlewareManifestPath);
async function requestHandler(req, res) {
var _parsedUrl_pathname, _parsedUrl_pathname1;
const parsedUrl = _url.default.parse(req.url || "/");
if ((_parsedUrl_pathname = parsedUrl.pathname) == null ? void 0 : _parsedUrl_pathname.includes(clientPagesManifestPath)) {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(JSON.stringify({
pages: prevSortedRoutes.filter((route)=>!opts.fsChecker.appFiles.has(route))
}));
return {
finished: true
};
}
if ((_parsedUrl_pathname1 = parsedUrl.pathname) == null ? void 0 : _parsedUrl_pathname1.includes(devMiddlewareManifestPath)) {
var _serverFields_middleware;
res.statusCode = 200;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(JSON.stringify(((_serverFields_middleware = serverFields.middleware) == null ? void 0 : _serverFields_middleware.matchers) || []));
return {
finished: true
};
}
return {
finished: false
};
}
async function logErrorWithOriginalStack(err, type) {
let usedOriginalStack = false;
if ((0, _iserror.default)(err) && err.stack) {
try {
const frames = (0, _middleware.parseStack)(err.stack);
// Filter out internal edge related runtime stack
const frame = frames.find(({ file })=>!(file == null ? void 0 : file.startsWith("eval")) && !(file == null ? void 0 : file.includes("web/adapter")) && !(file == null ? void 0 : file.includes("web/globals")) && !(file == null ? void 0 : file.includes("sandbox/context")) && !(file == null ? void 0 : file.includes("<anonymous>")));
let originalFrame, isEdgeCompiler;
const frameFile = frame == null ? void 0 : frame.file;
if ((frame == null ? void 0 : frame.lineNumber) && frameFile) {
if (hotReloader.turbopackProject) {
try {
originalFrame = await (0, _middlewareturbopack.createOriginalStackFrame)(hotReloader.turbopackProject, {
file: frameFile,
methodName: frame.methodName,
line: frame.lineNumber ?? 0,
column: frame.column,
isServer: true
});
} catch {}
} else {
var _hotReloader_edgeServerStats, _hotReloader_serverStats, _frame_file, _frame_file1;
const moduleId = frameFile.replace(/^(webpack-internal:\/\/\/|file:\/\/)/, "");
const modulePath = frameFile.replace(/^(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/, "");
const src = (0, _errorsource.getErrorSource)(err);
isEdgeCompiler = src === _constants.COMPILER_NAMES.edgeServer;
const compilation = isEdgeCompiler ? (_hotReloader_edgeServerStats = hotReloader.edgeServerStats) == null ? void 0 : _hotReloader_edgeServerStats.compilation : (_hotReloader_serverStats = hotReloader.serverStats) == null ? void 0 : _hotReloader_serverStats.compilation;
const source = await (0, _middleware.getSourceById)(!!((_frame_file = frame.file) == null ? void 0 : _frame_file.startsWith(_path.default.sep)) || !!((_frame_file1 = frame.file) == null ? void 0 : _frame_file1.startsWith("file:")), moduleId, compilation);
try {
var _hotReloader_edgeServerStats1, _hotReloader_serverStats1;
originalFrame = await (0, _middleware.createOriginalStackFrame)({
source,
frame,
moduleId,
modulePath,
rootDirectory: opts.dir,
errorMessage: err.message,
compilation: isEdgeCompiler ? (_hotReloader_edgeServerStats1 = hotReloader.edgeServerStats) == null ? void 0 : _hotReloader_edgeServerStats1.compilation : (_hotReloader_serverStats1 = hotReloader.serverStats) == null ? void 0 : _hotReloader_serverStats1.compilation
});
} catch {}
}
if ((originalFrame == null ? void 0 : originalFrame.originalCodeFrame) && originalFrame.originalStackFrame) {
const { originalCodeFrame, originalStackFrame } = originalFrame;
const { file, lineNumber, column, methodName } = originalStackFrame;
_log[type === "warning" ? "warn" : "error"](`${file} (${lineNumber}:${column}) @ ${methodName}`);
let errorToLog;
if (isEdgeCompiler) {
errorToLog = err.message;
} else if ((0, _iserror.default)(err) && hotReloader.turbopackProject) {
const stack = await traceTurbopackErrorStack(hotReloader.turbopackProject, err, frames);
const error = new Error(err.message);
error.stack = stack;
error.digest = err.digest;
errorToLog = error;
} else {
errorToLog = err;
}
if (type === "warning") {
_log.warn(errorToLog);
} else if (type === "app-dir") {
(0, _logappdirerror.logAppDirError)(errorToLog);
} else if (type) {
_log.error(`${type}:`, errorToLog);
} else {
_log.error(errorToLog);
}
console[type === "warning" ? "warn" : "error"](originalCodeFrame);
usedOriginalStack = true;
}
}
} catch (_) {
// failed to load original stack using source maps
// this un-actionable by users so we don't show the
// internal error and only show the provided stack
}
}
if (!usedOriginalStack) {
if (err instanceof ModuleBuildError) {
_log.error(err.message);
} else if (type === "warning") {
_log.warn(err);
} else if (type === "app-dir") {
(0, _logappdirerror.logAppDirError)(err);
} else if (type) {
_log.error(`${type}:`, err);
} else {
_log.error(err);
}
}
}
return {
serverFields,
hotReloader,
requestHandler,
logErrorWithOriginalStack,
async ensureMiddleware (requestUrl) {
if (!serverFields.actualMiddlewareFile) return;
return hotReloader.ensurePage({
page: serverFields.actualMiddlewareFile,
clientOnly: false,
definition: undefined,
url: requestUrl
});
}
};
}
async function setupDevBundler(opts) {
const isSrcDir = _path.default.relative(opts.dir, opts.pagesDir || opts.appDir || "").startsWith("src");
const result = await startWatcher(opts);
opts.telemetry.record((0, _events.eventCliSession)(_path.default.join(opts.dir, opts.nextConfig.distDir), opts.nextConfig, {
webpackVersion: 5,
isSrcDir,
turboFlag: !!opts.turbo,
cliCommand: "dev",
appDir: !!opts.appDir,
pagesDir: !!opts.pagesDir,
isCustomServer: !!opts.isCustomServer,
hasNowJson: !!await (0, _findup.default)("now.json", {
cwd: opts.dir
})
}));
return result;
}
// Returns a trace rewritten through Turbopack's sourcemaps
async function traceTurbopackErrorStack(project, error, frames) {
let originalFrames = await Promise.all(frames.map(async (f)=>{
try {
const traced = await (0, _middlewareturbopack.batchedTraceSource)(project, {
file: f.file,
methodName: f.methodName,
line: f.lineNumber ?? 0,
column: f.column,
isServer: true
});
return (traced == null ? void 0 : traced.frame) ?? f;
} catch {
return f;
}
}));
return error.name + ": " + error.message + "\n" + originalFrames.map((f)=>{
if (f == null) {
return null;
}
let line = " at";
if (f.methodName != null) {
line += " " + f.methodName;
}
if (f.file != null) {
const file = f.file.startsWith("/") || // Built-in "filenames" like `<anonymous>` shouldn't be made relative
f.file.startsWith("<") || f.file.startsWith("node:") ? f.file : `./${f.file}`;
line += ` (${file}`;
if (f.lineNumber != null) {
line += ":" + f.lineNumber;
if (f.column != null) {
line += ":" + f.column;
}
}
line += ")";
}
return line;
}).filter(Boolean).join("\n");
}
//# sourceMappingURL=setup-dev-bundler.js.map

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getIsServerAction: null,
getServerActionRequestMetadata: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getIsServerAction: function() {
return getIsServerAction;
},
getServerActionRequestMetadata: function() {
return getServerActionRequestMetadata;
}
});
const _approuterheaders = require("../../client/components/app-router-headers");
function getServerActionRequestMetadata(req) {
let actionId;
let contentType;
if (req.headers instanceof Headers) {
actionId = req.headers.get(_approuterheaders.ACTION.toLowerCase()) ?? null;
contentType = req.headers.get("content-type");
} else {
actionId = req.headers[_approuterheaders.ACTION.toLowerCase()] ?? null;
contentType = req.headers["content-type"] ?? null;
}
const isURLEncodedAction = Boolean(req.method === "POST" && contentType === "application/x-www-form-urlencoded");
const isMultipartAction = Boolean(req.method === "POST" && (contentType == null ? void 0 : contentType.startsWith("multipart/form-data")));
const isFetchAction = Boolean(actionId !== undefined && typeof actionId === "string" && req.method === "POST");
const isServerAction = Boolean(isFetchAction || isURLEncodedAction || isMultipartAction);
return {
actionId,
isURLEncodedAction,
isMultipartAction,
isFetchAction,
isServerAction
};
}
function getIsServerAction(req) {
return getServerActionRequestMetadata(req).isServerAction;
}
//# sourceMappingURL=server-action-request-meta.js.map

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,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 _errorsource = require("../../../shared/lib/error-source");
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.NODE_ENV === "development" && process.env.NEXT_RUNTIME !== "edge") {
(0, _errorsource.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,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
actionsForbiddenHeaders: null,
filterReqHeaders: null,
ipcForbiddenHeaders: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
actionsForbiddenHeaders: function() {
return actionsForbiddenHeaders;
},
filterReqHeaders: function() {
return filterReqHeaders;
},
ipcForbiddenHeaders: function() {
return ipcForbiddenHeaders;
}
});
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",
"set-cookie"
];
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,136 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
decodeBuffer: null,
getMetadata: null,
processBuffer: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
decodeBuffer: function() {
return decodeBuffer;
},
getMetadata: function() {
return getMetadata;
},
processBuffer: function() {
return processBuffer;
}
});
const _jestworker = require("next/dist/compiled/jest-worker");
const _path = /*#__PURE__*/ _interop_require_wildcard(require("path"));
const _utils = require("../../../shared/lib/utils");
const _os = require("os");
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 = {
__proto__: null
};
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 getWorker = (0, _utils.execOnce)(()=>new _jestworker.Worker(_path.resolve(__dirname, "impl"), {
enableWorkerThreads: true,
// There will be at most 6 workers needed since each worker will take
// at least 1 operation type.
numWorkers: Math.max(1, Math.min((0, _os.cpus)().length - 1, 6)),
computeWorkerKey: (method)=>method
}));
async function getMetadata(buffer) {
const worker = getWorker();
const { width, height } = await worker.decodeBuffer(buffer);
return {
width,
height
};
}
async function processBuffer(buffer, operations, encoding, quality) {
const worker = getWorker();
let imageData = await worker.decodeBuffer(buffer);
for (const operation of operations){
if (operation.type === "rotate") {
imageData = await worker.rotate(imageData, operation.numRotations);
} else if (operation.type === "resize") {
const opt = {
image: imageData,
width: 0,
height: 0
};
if (operation.width && imageData.width && imageData.width > operation.width) {
opt.width = operation.width;
}
if (operation.height && imageData.height && imageData.height > operation.height) {
opt.height = operation.height;
}
if (opt.width > 0 || opt.height > 0) {
imageData = await worker.resize(opt);
}
}
}
switch(encoding){
case "jpeg":
return Buffer.from(await worker.encodeJpeg(imageData, {
quality
}));
case "webp":
return Buffer.from(await worker.encodeWebp(imageData, {
quality
}));
case "avif":
const avifQuality = quality - 20;
return Buffer.from(await worker.encodeAvif(imageData, {
quality: Math.max(avifQuality, 0)
}));
case "png":
return Buffer.from(await worker.encodePng(imageData));
default:
throw Error(`Unsupported encoding format`);
}
}
async function decodeBuffer(buffer) {
const worker = getWorker();
const imageData = await worker.decodeBuffer(buffer);
return imageData;
}
//# sourceMappingURL=main.js.map

View File

@@ -0,0 +1,325 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getRequestHandlers: null,
startServer: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getRequestHandlers: function() {
return getRequestHandlers;
},
startServer: function() {
return startServer;
}
});
require("../next");
require("../require-hook");
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
const _v8 = /*#__PURE__*/ _interop_require_default(require("v8"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _http = /*#__PURE__*/ _interop_require_default(require("http"));
const _https = /*#__PURE__*/ _interop_require_default(require("https"));
const _os = /*#__PURE__*/ _interop_require_default(require("os"));
const _watchpack = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/watchpack"));
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log"));
const _debug = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/debug"));
const _utils = require("./utils");
const _formathostname = require("./format-hostname");
const _routerserver = require("./router-server");
const _constants = require("../../shared/lib/constants");
const _appinfolog = require("./app-info-log");
const _turbopackwarning = require("../../lib/turbopack-warning");
const _trace = require("../../trace");
const _ispostpone = require("./router-utils/is-postpone");
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 = {
__proto__: null
};
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;
}
if (performance.getEntriesByName("next-start").length === 0) {
performance.mark("next-start");
}
const debug = (0, _debug.default)("next:start-server");
let startServerSpan;
async function getRequestHandlers({ dir, port, isDev, server, hostname, minimalMode, isNodeDebugging, keepAliveTimeout, experimentalHttpsServer }) {
return (0, _routerserver.initialize)({
dir,
port,
hostname,
dev: isDev,
minimalMode,
server,
isNodeDebugging: isNodeDebugging || false,
keepAliveTimeout,
experimentalHttpsServer,
startServerSpan
});
}
async function startServer(serverOptions) {
const { dir, isDev, hostname, minimalMode, allowRetry, keepAliveTimeout, selfSignedCertificate } = serverOptions;
let { port } = serverOptions;
process.title = `next-server (v${"14.2.15"})`;
let handlersReady = ()=>{};
let handlersError = ()=>{};
let handlersPromise = new Promise((resolve, reject)=>{
handlersReady = resolve;
handlersError = reject;
});
let requestHandler = async (req, res)=>{
if (handlersPromise) {
await handlersPromise;
return requestHandler(req, res);
}
throw new Error("Invariant request handler was not setup");
};
let upgradeHandler = async (req, socket, head)=>{
if (handlersPromise) {
await handlersPromise;
return upgradeHandler(req, socket, head);
}
throw new Error("Invariant upgrade handler was not setup");
};
// setup server listener as fast as possible
if (selfSignedCertificate && !isDev) {
throw new Error("Using a self signed certificate is only supported with `next dev`.");
}
async function requestListener(req, res) {
try {
if (handlersPromise) {
await handlersPromise;
handlersPromise = undefined;
}
await requestHandler(req, res);
} catch (err) {
res.statusCode = 500;
res.end("Internal Server Error");
_log.error(`Failed to handle request for ${req.url}`);
console.error(err);
} finally{
if (isDev) {
if (_v8.default.getHeapStatistics().used_heap_size > 0.8 * _v8.default.getHeapStatistics().heap_size_limit) {
_log.warn(`Server is approaching the used memory threshold, restarting...`);
(0, _trace.trace)("server-restart-close-to-memory-threshold", undefined, {
"memory.heapSizeLimit": String(_v8.default.getHeapStatistics().heap_size_limit),
"memory.heapUsed": String(_v8.default.getHeapStatistics().used_heap_size)
}).stop();
await (0, _trace.flushAllTraces)();
process.exit(_utils.RESTART_EXIT_CODE);
}
}
}
}
const server = selfSignedCertificate ? _https.default.createServer({
key: _fs.default.readFileSync(selfSignedCertificate.key),
cert: _fs.default.readFileSync(selfSignedCertificate.cert)
}, requestListener) : _http.default.createServer(requestListener);
if (keepAliveTimeout) {
server.keepAliveTimeout = keepAliveTimeout;
}
server.on("upgrade", async (req, socket, head)=>{
try {
await upgradeHandler(req, socket, head);
} catch (err) {
socket.destroy();
_log.error(`Failed to handle request for ${req.url}`);
console.error(err);
}
});
let portRetryCount = 0;
server.on("error", (err)=>{
if (allowRetry && port && isDev && err.code === "EADDRINUSE" && portRetryCount < 10) {
_log.warn(`Port ${port} is in use, trying ${port + 1} instead.`);
port += 1;
portRetryCount += 1;
server.listen(port, hostname);
} else {
_log.error(`Failed to start server`);
console.error(err);
process.exit(1);
}
});
const nodeDebugType = (0, _utils.checkNodeDebugType)();
await new Promise((resolve)=>{
server.on("listening", async ()=>{
const addr = server.address();
const actualHostname = (0, _formathostname.formatHostname)(typeof addr === "object" ? (addr == null ? void 0 : addr.address) || hostname || "localhost" : addr);
const formattedHostname = !hostname || actualHostname === "0.0.0.0" ? "localhost" : actualHostname === "[::]" ? "[::1]" : (0, _formathostname.formatHostname)(hostname);
port = typeof addr === "object" ? (addr == null ? void 0 : addr.port) || port : port;
const networkUrl = hostname ? `http://${actualHostname}:${port}` : null;
const appUrl = `${selfSignedCertificate ? "https" : "http"}://${formattedHostname}:${port}`;
if (nodeDebugType) {
const debugPort = (0, _utils.getDebugPort)();
_log.info(`the --${nodeDebugType} option was detected, the Next.js router server should be inspected at port ${debugPort}.`);
}
// expose the main port to render workers
process.env.PORT = port + "";
process.env.__NEXT_PRIVATE_ORIGIN = appUrl;
// Only load env and config in dev to for logging purposes
let envInfo;
let expFeatureInfo;
if (isDev) {
const startServerInfo = await (0, _appinfolog.getStartServerInfo)(dir, isDev);
envInfo = startServerInfo.envInfo;
expFeatureInfo = startServerInfo.expFeatureInfo;
}
(0, _appinfolog.logStartInfo)({
networkUrl,
appUrl,
envInfo,
expFeatureInfo,
maxExperimentalFeatures: 3
});
_log.event(`Starting...`);
try {
const cleanup = ()=>{
debug("start-server process cleanup");
server.close(()=>process.exit(0));
};
const exception = (err)=>{
if ((0, _ispostpone.isPostpone)(err)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return;
}
// This is the render worker, we keep the process alive
console.error(err);
};
// Make sure commands gracefully respect termination signals (e.g. from Docker)
// Allow the graceful termination to be manually configurable
if (!process.env.NEXT_MANUAL_SIG_HANDLE) {
process.on("SIGINT", cleanup);
process.on("SIGTERM", cleanup);
}
process.on("rejectionHandled", ()=>{
// It is ok to await a Promise late in Next.js as it allows for better
// prefetching patterns to avoid waterfalls. We ignore loggining these.
// We should've already errored in anyway unhandledRejection.
});
process.on("uncaughtException", exception);
process.on("unhandledRejection", exception);
const initResult = await getRequestHandlers({
dir,
port,
isDev,
server,
hostname,
minimalMode,
isNodeDebugging: Boolean(nodeDebugType),
keepAliveTimeout,
experimentalHttpsServer: !!selfSignedCertificate
});
requestHandler = initResult[0];
upgradeHandler = initResult[1];
const startServerProcessDuration = performance.mark("next-start-end") && performance.measure("next-start-duration", "next-start", "next-start-end").duration;
handlersReady();
const formatDurationText = startServerProcessDuration > 2000 ? `${Math.round(startServerProcessDuration / 100) / 10}s` : `${Math.round(startServerProcessDuration)}ms`;
_log.event(`Ready in ${formatDurationText}`);
if (process.env.TURBOPACK) {
await (0, _turbopackwarning.validateTurboNextConfig)({
dir: serverOptions.dir,
isDev: true
});
}
} catch (err) {
// fatal error if we can't setup
handlersError();
console.error(err);
process.exit(1);
}
resolve();
});
server.listen(port, hostname);
});
if (isDev) {
function watchConfigFiles(dirToWatch, onChange) {
const wp = new _watchpack.default();
wp.watch({
files: _constants.CONFIG_FILES.map((file)=>_path.default.join(dirToWatch, file))
});
wp.on("change", onChange);
}
watchConfigFiles(dir, async (filename)=>{
if (process.env.__NEXT_DISABLE_MEMORY_WATCHER) {
_log.info(`Detected change, manual restart required due to '__NEXT_DISABLE_MEMORY_WATCHER' usage`);
return;
}
_log.warn(`Found a change in ${_path.default.basename(filename)}. Restarting the server to apply the changes...`);
process.exit(_utils.RESTART_EXIT_CODE);
});
}
}
if (process.env.NEXT_PRIVATE_WORKER && process.send) {
process.addListener("message", async (msg)=>{
if (msg && typeof msg && msg.nextWorkerOptions && process.send) {
startServerSpan = (0, _trace.trace)("start-dev-server", undefined, {
cpus: String(_os.default.cpus().length),
platform: _os.default.platform(),
"memory.freeMem": String(_os.default.freemem()),
"memory.totalMem": String(_os.default.totalmem()),
"memory.heapSizeLimit": String(_v8.default.getHeapStatistics().heap_size_limit)
});
await startServerSpan.traceAsyncFn(()=>startServer(msg.nextWorkerOptions));
const memoryUsage = process.memoryUsage();
startServerSpan.setAttribute("memory.rss", String(memoryUsage.rss));
startServerSpan.setAttribute("memory.heapTotal", String(memoryUsage.heapTotal));
startServerSpan.setAttribute("memory.heapUsed", String(memoryUsage.heapUsed));
process.send({
nextServerReady: true
});
}
});
process.send({
nextWorkerReady: true
});
}
//# sourceMappingURL=start-server.js.map

View File

@@ -0,0 +1,37 @@
/**
* This transforms a URL pathname into a route. It removes any trailing slashes
* and the `/index` suffix.
*
* @param {string} pathname - The URL path that needs to be optimized.
* @returns {string} - The route
*
* @example
* // returns '/example'
* toRoute('/example/index/');
*
* @example
* // returns '/example'
* toRoute('/example/');
*
* @example
* // returns '/'
* toRoute('/index/');
*
* @example
* // returns '/'
* toRoute('/');
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "toRoute", {
enumerable: true,
get: function() {
return toRoute;
}
});
function toRoute(pathname) {
return pathname.replace(/(?:\/index)?\/?$/, "") || "/";
}
//# sourceMappingURL=to-route.js.map

View File

@@ -0,0 +1,202 @@
/**
* Contains predefined constants for the trace span name in next/server.
*
* Currently, next/server/tracer is internal implementation only for tracking
* next.js's implementation only with known span names defined here.
**/ // eslint typescript has a bug with TS enums
/* eslint-disable no-shadow */ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
AppRenderSpan: null,
AppRouteRouteHandlersSpan: null,
BaseServerSpan: null,
LoadComponentsSpan: null,
LogSpanAllowList: null,
MiddlewareSpan: null,
NextNodeServerSpan: null,
NextServerSpan: null,
NextVanillaSpanAllowlist: null,
NodeSpan: null,
RenderSpan: null,
ResolveMetadataSpan: null,
RouterSpan: null,
StartServerSpan: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
AppRenderSpan: function() {
return AppRenderSpan;
},
AppRouteRouteHandlersSpan: function() {
return AppRouteRouteHandlersSpan;
},
BaseServerSpan: function() {
return BaseServerSpan;
},
LoadComponentsSpan: function() {
return LoadComponentsSpan;
},
LogSpanAllowList: function() {
return LogSpanAllowList;
},
MiddlewareSpan: function() {
return MiddlewareSpan;
},
NextNodeServerSpan: function() {
return NextNodeServerSpan;
},
NextServerSpan: function() {
return NextServerSpan;
},
NextVanillaSpanAllowlist: function() {
return NextVanillaSpanAllowlist;
},
NodeSpan: function() {
return NodeSpan;
},
RenderSpan: function() {
return RenderSpan;
},
ResolveMetadataSpan: function() {
return ResolveMetadataSpan;
},
RouterSpan: function() {
return RouterSpan;
},
StartServerSpan: function() {
return StartServerSpan;
}
});
var BaseServerSpan;
(function(BaseServerSpan) {
BaseServerSpan["handleRequest"] = "BaseServer.handleRequest";
BaseServerSpan["run"] = "BaseServer.run";
BaseServerSpan["pipe"] = "BaseServer.pipe";
BaseServerSpan["getStaticHTML"] = "BaseServer.getStaticHTML";
BaseServerSpan["render"] = "BaseServer.render";
BaseServerSpan["renderToResponseWithComponents"] = "BaseServer.renderToResponseWithComponents";
BaseServerSpan["renderToResponse"] = "BaseServer.renderToResponse";
BaseServerSpan["renderToHTML"] = "BaseServer.renderToHTML";
BaseServerSpan["renderError"] = "BaseServer.renderError";
BaseServerSpan["renderErrorToResponse"] = "BaseServer.renderErrorToResponse";
BaseServerSpan["renderErrorToHTML"] = "BaseServer.renderErrorToHTML";
BaseServerSpan["render404"] = "BaseServer.render404";
})(BaseServerSpan || (BaseServerSpan = {}));
var LoadComponentsSpan;
(function(LoadComponentsSpan) {
LoadComponentsSpan["loadDefaultErrorComponents"] = "LoadComponents.loadDefaultErrorComponents";
LoadComponentsSpan["loadComponents"] = "LoadComponents.loadComponents";
})(LoadComponentsSpan || (LoadComponentsSpan = {}));
var NextServerSpan;
(function(NextServerSpan) {
NextServerSpan["getRequestHandler"] = "NextServer.getRequestHandler";
NextServerSpan["getServer"] = "NextServer.getServer";
NextServerSpan["getServerRequestHandler"] = "NextServer.getServerRequestHandler";
NextServerSpan["createServer"] = "createServer.createServer";
})(NextServerSpan || (NextServerSpan = {}));
var NextNodeServerSpan;
(function(NextNodeServerSpan) {
NextNodeServerSpan["compression"] = "NextNodeServer.compression";
NextNodeServerSpan["getBuildId"] = "NextNodeServer.getBuildId";
NextNodeServerSpan["createComponentTree"] = "NextNodeServer.createComponentTree";
NextNodeServerSpan["clientComponentLoading"] = "NextNodeServer.clientComponentLoading";
NextNodeServerSpan["getLayoutOrPageModule"] = "NextNodeServer.getLayoutOrPageModule";
NextNodeServerSpan["generateStaticRoutes"] = "NextNodeServer.generateStaticRoutes";
NextNodeServerSpan["generateFsStaticRoutes"] = "NextNodeServer.generateFsStaticRoutes";
NextNodeServerSpan["generatePublicRoutes"] = "NextNodeServer.generatePublicRoutes";
NextNodeServerSpan["generateImageRoutes"] = "NextNodeServer.generateImageRoutes.route";
NextNodeServerSpan["sendRenderResult"] = "NextNodeServer.sendRenderResult";
NextNodeServerSpan["proxyRequest"] = "NextNodeServer.proxyRequest";
NextNodeServerSpan["runApi"] = "NextNodeServer.runApi";
NextNodeServerSpan["render"] = "NextNodeServer.render";
NextNodeServerSpan["renderHTML"] = "NextNodeServer.renderHTML";
NextNodeServerSpan["imageOptimizer"] = "NextNodeServer.imageOptimizer";
NextNodeServerSpan["getPagePath"] = "NextNodeServer.getPagePath";
NextNodeServerSpan["getRoutesManifest"] = "NextNodeServer.getRoutesManifest";
NextNodeServerSpan["findPageComponents"] = "NextNodeServer.findPageComponents";
NextNodeServerSpan["getFontManifest"] = "NextNodeServer.getFontManifest";
NextNodeServerSpan["getServerComponentManifest"] = "NextNodeServer.getServerComponentManifest";
NextNodeServerSpan["getRequestHandler"] = "NextNodeServer.getRequestHandler";
NextNodeServerSpan["renderToHTML"] = "NextNodeServer.renderToHTML";
NextNodeServerSpan["renderError"] = "NextNodeServer.renderError";
NextNodeServerSpan["renderErrorToHTML"] = "NextNodeServer.renderErrorToHTML";
NextNodeServerSpan["render404"] = "NextNodeServer.render404";
NextNodeServerSpan["startResponse"] = "NextNodeServer.startResponse";
// nested inner span, does not require parent scope name
NextNodeServerSpan["route"] = "route";
NextNodeServerSpan["onProxyReq"] = "onProxyReq";
NextNodeServerSpan["apiResolver"] = "apiResolver";
NextNodeServerSpan["internalFetch"] = "internalFetch";
})(NextNodeServerSpan || (NextNodeServerSpan = {}));
var StartServerSpan;
(function(StartServerSpan) {
StartServerSpan["startServer"] = "startServer.startServer";
})(StartServerSpan || (StartServerSpan = {}));
var RenderSpan;
(function(RenderSpan) {
RenderSpan["getServerSideProps"] = "Render.getServerSideProps";
RenderSpan["getStaticProps"] = "Render.getStaticProps";
RenderSpan["renderToString"] = "Render.renderToString";
RenderSpan["renderDocument"] = "Render.renderDocument";
RenderSpan["createBodyResult"] = "Render.createBodyResult";
})(RenderSpan || (RenderSpan = {}));
var AppRenderSpan;
(function(AppRenderSpan) {
AppRenderSpan["renderToString"] = "AppRender.renderToString";
AppRenderSpan["renderToReadableStream"] = "AppRender.renderToReadableStream";
AppRenderSpan["getBodyResult"] = "AppRender.getBodyResult";
AppRenderSpan["fetch"] = "AppRender.fetch";
})(AppRenderSpan || (AppRenderSpan = {}));
var RouterSpan;
(function(RouterSpan) {
RouterSpan["executeRoute"] = "Router.executeRoute";
})(RouterSpan || (RouterSpan = {}));
var NodeSpan;
(function(NodeSpan) {
NodeSpan["runHandler"] = "Node.runHandler";
})(NodeSpan || (NodeSpan = {}));
var AppRouteRouteHandlersSpan;
(function(AppRouteRouteHandlersSpan) {
AppRouteRouteHandlersSpan["runHandler"] = "AppRouteRouteHandlers.runHandler";
})(AppRouteRouteHandlersSpan || (AppRouteRouteHandlersSpan = {}));
var ResolveMetadataSpan;
(function(ResolveMetadataSpan) {
ResolveMetadataSpan["generateMetadata"] = "ResolveMetadata.generateMetadata";
ResolveMetadataSpan["generateViewport"] = "ResolveMetadata.generateViewport";
})(ResolveMetadataSpan || (ResolveMetadataSpan = {}));
var MiddlewareSpan;
(function(MiddlewareSpan) {
MiddlewareSpan["execute"] = "Middleware.execute";
})(MiddlewareSpan || (MiddlewareSpan = {}));
const NextVanillaSpanAllowlist = [
"Middleware.execute",
"BaseServer.handleRequest",
"Render.getServerSideProps",
"Render.getStaticProps",
"AppRender.fetch",
"AppRender.getBodyResult",
"Render.renderDocument",
"Node.runHandler",
"AppRouteRouteHandlers.runHandler",
"ResolveMetadata.generateMetadata",
"ResolveMetadata.generateViewport",
"NextNodeServer.createComponentTree",
"NextNodeServer.findPageComponents",
"NextNodeServer.getLayoutOrPageModule",
"NextNodeServer.startResponse",
"NextNodeServer.clientComponentLoading"
];
const LogSpanAllowList = [
"NextNodeServer.findPageComponents",
"NextNodeServer.createComponentTree",
"NextNodeServer.clientComponentLoading"
];
//# sourceMappingURL=constants.js.map

View File

@@ -0,0 +1,214 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
SpanKind: null,
SpanStatusCode: null,
getTracer: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
SpanKind: function() {
return SpanKind;
},
SpanStatusCode: function() {
return SpanStatusCode;
},
getTracer: function() {
return getTracer;
}
});
const _constants = require("./constants");
let api;
// we want to allow users to use their own version of @opentelemetry/api if they
// want to, so we try to require it first, and if it fails we fall back to the
// version that is bundled with Next.js
// this is because @opentelemetry/api has to be synced with the version of
// @opentelemetry/tracing that is used, and we don't want to force users to use
// the version that is bundled with Next.js.
// the API is ~stable, so this should be fine
if (process.env.NEXT_RUNTIME === "edge") {
api = require("@opentelemetry/api");
} else {
try {
api = require("@opentelemetry/api");
} catch (err) {
api = require("next/dist/compiled/@opentelemetry/api");
}
}
const { context, propagation, trace, SpanStatusCode, SpanKind, ROOT_CONTEXT } = api;
const isPromise = (p)=>{
return p !== null && typeof p === "object" && typeof p.then === "function";
};
const closeSpanWithError = (span, error)=>{
if ((error == null ? void 0 : error.bubble) === true) {
span.setAttribute("next.bubble", true);
} else {
if (error) {
span.recordException(error);
}
span.setStatus({
code: SpanStatusCode.ERROR,
message: error == null ? void 0 : error.message
});
}
span.end();
};
/** we use this map to propagate attributes from nested spans to the top span */ const rootSpanAttributesStore = new Map();
const rootSpanIdKey = api.createContextKey("next.rootSpanId");
let lastSpanId = 0;
const getSpanId = ()=>lastSpanId++;
class NextTracerImpl {
/**
* Returns an instance to the trace with configured name.
* Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
* This should be lazily evaluated.
*/ getTracerInstance() {
return trace.getTracer("next.js", "0.0.1");
}
getContext() {
return context;
}
getActiveScopeSpan() {
return trace.getSpan(context == null ? void 0 : context.active());
}
withPropagatedContext(carrier, fn, getter) {
const activeContext = context.active();
if (trace.getSpanContext(activeContext)) {
// Active span is already set, too late to propagate.
return fn();
}
const remoteContext = propagation.extract(activeContext, carrier, getter);
return context.with(remoteContext, fn);
}
trace(...args) {
var _trace_getSpanContext;
const [type, fnOrOptions, fnOrEmpty] = args;
// coerce options form overload
const { fn, options } = typeof fnOrOptions === "function" ? {
fn: fnOrOptions,
options: {}
} : {
fn: fnOrEmpty,
options: {
...fnOrOptions
}
};
const spanName = options.spanName ?? type;
if (!_constants.NextVanillaSpanAllowlist.includes(type) && process.env.NEXT_OTEL_VERBOSE !== "1" || options.hideSpan) {
return fn();
}
// Trying to get active scoped span to assign parent. If option specifies parent span manually, will try to use it.
let spanContext = this.getSpanContext((options == null ? void 0 : options.parentSpan) ?? this.getActiveScopeSpan());
let isRootSpan = false;
if (!spanContext) {
spanContext = (context == null ? void 0 : context.active()) ?? ROOT_CONTEXT;
isRootSpan = true;
} else if ((_trace_getSpanContext = trace.getSpanContext(spanContext)) == null ? void 0 : _trace_getSpanContext.isRemote) {
isRootSpan = true;
}
const spanId = getSpanId();
options.attributes = {
"next.span_name": spanName,
"next.span_type": type,
...options.attributes
};
return context.with(spanContext.setValue(rootSpanIdKey, spanId), ()=>this.getTracerInstance().startActiveSpan(spanName, options, (span)=>{
const startTime = "performance" in globalThis ? globalThis.performance.now() : undefined;
const onCleanup = ()=>{
rootSpanAttributesStore.delete(spanId);
if (startTime && process.env.NEXT_OTEL_PERFORMANCE_PREFIX && _constants.LogSpanAllowList.includes(type || "")) {
performance.measure(`${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-${(type.split(".").pop() || "").replace(/[A-Z]/g, (match)=>"-" + match.toLowerCase())}`, {
start: startTime,
end: performance.now()
});
}
};
if (isRootSpan) {
rootSpanAttributesStore.set(spanId, new Map(Object.entries(options.attributes ?? {})));
}
try {
if (fn.length > 1) {
return fn(span, (err)=>closeSpanWithError(span, err));
}
const result = fn(span);
if (isPromise(result)) {
// If there's error make sure it throws
return result.then((res)=>{
span.end();
// Need to pass down the promise result,
// it could be react stream response with error { error, stream }
return res;
}).catch((err)=>{
closeSpanWithError(span, err);
throw err;
}).finally(onCleanup);
} else {
span.end();
onCleanup();
}
return result;
} catch (err) {
closeSpanWithError(span, err);
onCleanup();
throw err;
}
}));
}
wrap(...args) {
const tracer = this;
const [name, options, fn] = args.length === 3 ? args : [
args[0],
{},
args[1]
];
if (!_constants.NextVanillaSpanAllowlist.includes(name) && process.env.NEXT_OTEL_VERBOSE !== "1") {
return fn;
}
return function() {
let optionsObj = options;
if (typeof optionsObj === "function" && typeof fn === "function") {
optionsObj = optionsObj.apply(this, arguments);
}
const lastArgId = arguments.length - 1;
const cb = arguments[lastArgId];
if (typeof cb === "function") {
const scopeBoundCb = tracer.getContext().bind(context.active(), cb);
return tracer.trace(name, optionsObj, (_span, done)=>{
arguments[lastArgId] = function(err) {
done == null ? void 0 : done(err);
return scopeBoundCb.apply(this, arguments);
};
return fn.apply(this, arguments);
});
} else {
return tracer.trace(name, optionsObj, ()=>fn.apply(this, arguments));
}
};
}
startSpan(...args) {
const [type, options] = args;
const spanContext = this.getSpanContext((options == null ? void 0 : options.parentSpan) ?? this.getActiveScopeSpan());
return this.getTracerInstance().startSpan(type, options, spanContext);
}
getSpanContext(parentSpan) {
const spanContext = parentSpan ? trace.setSpan(context.active(), parentSpan) : undefined;
return spanContext;
}
getRootSpanAttributes() {
const spanId = context.active().getValue(rootSpanIdKey);
return rootSpanAttributesStore.get(spanId);
}
}
const getTracer = (()=>{
const tracer = new NextTracerImpl();
return ()=>tracer;
})();
//# sourceMappingURL=tracer.js.map

View File

@@ -0,0 +1,87 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
RESTART_EXIT_CODE: null,
checkNodeDebugType: null,
getDebugPort: null,
getMaxOldSpaceSize: null,
getNodeOptionsWithoutInspect: null,
myParseInt: null,
printAndExit: 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;
},
checkNodeDebugType: function() {
return checkNodeDebugType;
},
getDebugPort: function() {
return getDebugPort;
},
getMaxOldSpaceSize: function() {
return getMaxOldSpaceSize;
},
getNodeOptionsWithoutInspect: function() {
return getNodeOptionsWithoutInspect;
},
myParseInt: function() {
return myParseInt;
},
printAndExit: function() {
return printAndExit;
}
});
const _commander = require("next/dist/compiled/commander");
function printAndExit(message, code = 1) {
if (code === 0) {
console.log(message);
} else {
console.error(message);
}
process.exit(code);
}
const getDebugPort = ()=>{
var _process_execArgv_find, _process_env_NODE_OPTIONS_match, _process_env_NODE_OPTIONS_match1, _process_env_NODE_OPTIONS;
const debugPortStr = ((_process_execArgv_find = process.execArgv.find((localArg)=>localArg.startsWith("--inspect") || localArg.startsWith("--inspect-brk"))) == null ? void 0 : _process_execArgv_find.split("=", 2)[1]) ?? ((_process_env_NODE_OPTIONS = process.env.NODE_OPTIONS) == null ? void 0 : (_process_env_NODE_OPTIONS_match1 = _process_env_NODE_OPTIONS.match) == null ? void 0 : (_process_env_NODE_OPTIONS_match = _process_env_NODE_OPTIONS_match1.call(_process_env_NODE_OPTIONS, /--inspect(-brk)?(=(\S+))?( |$)/)) == null ? void 0 : _process_env_NODE_OPTIONS_match[3]);
return debugPortStr ? parseInt(debugPortStr, 10) : 9229;
};
const NODE_INSPECT_RE = /--inspect(-brk)?(=\S+)?( |$)/;
function getNodeOptionsWithoutInspect() {
return (process.env.NODE_OPTIONS || "").replace(NODE_INSPECT_RE, "");
}
function myParseInt(value) {
// parseInt takes a string and a radix
const parsedValue = parseInt(value, 10);
if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) {
throw new _commander.InvalidArgumentError(`'${value}' is not a non-negative number.`);
}
return parsedValue;
}
const RESTART_EXIT_CODE = 77;
function checkNodeDebugType() {
var _process_env_NODE_OPTIONS_match, _process_env_NODE_OPTIONS, _process_env_NODE_OPTIONS_match1, _process_env_NODE_OPTIONS1;
let nodeDebugType = undefined;
if (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+)?( |$)/))) {
nodeDebugType = "inspect";
}
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+)?( |$)/))) {
nodeDebugType = "inspect-brk";
}
return nodeDebugType;
}
function getMaxOldSpaceSize() {
var _process_env_NODE_OPTIONS_match, _process_env_NODE_OPTIONS;
const maxOldSpaceSize = (_process_env_NODE_OPTIONS = process.env.NODE_OPTIONS) == null ? void 0 : (_process_env_NODE_OPTIONS_match = _process_env_NODE_OPTIONS.match(/--max[-_]old[-_]space[-_]size=(\d+)/)) == null ? void 0 : _process_env_NODE_OPTIONS_match[1];
return maxOldSpaceSize ? parseInt(maxOldSpaceSize, 10) : undefined;
}
//# sourceMappingURL=utils.js.map