feat(blog): add file-based blog with dynamic slugs, MDX content and layout shell

- Introduced blog routing using Next.js App Router
- Implemented dynamic [slug] pages for blog posts
- Added MDX-based content loading via lib/posts
- Integrated shared TopBar layout with navigation
- Established clear content, lib and component separation
This commit is contained in:
PascalSchattenburg
2026-01-22 14:14:15 +01:00
parent b717952234
commit d147843c76
10412 changed files with 2475583 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
import type { Duplex } from 'stream';
import type { IncomingMessage, ServerResponse } from 'node:http';
export declare const blockCrossSite: (req: IncomingMessage, res: ServerResponse | Duplex, allowedDevOrigins: string[] | undefined, hostname: string | undefined) => boolean;

View File

@@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "blockCrossSite", {
enumerable: true,
get: function() {
return blockCrossSite;
}
});
const _url = require("../../../lib/url");
const _log = require("../../../build/output/log");
const _csrfprotection = require("../../app-render/csrf-protection");
function warnOrBlockRequest(res, origin, mode) {
const originString = origin ? `from ${origin}` : '';
if (mode === 'warn') {
(0, _log.warnOnce)(`Cross origin request detected ${originString} to /_next/* resource. In a future major version of Next.js, you will need to explicitly configure "allowedDevOrigins" in next.config to allow this.\nRead more: https://nextjs.org/docs/app/api-reference/config/next-config-js/allowedDevOrigins`);
return false;
}
(0, _log.warnOnce)(`Blocked cross-origin request ${originString} to /_next/* resource. To allow this, configure "allowedDevOrigins" in next.config\nRead more: https://nextjs.org/docs/app/api-reference/config/next-config-js/allowedDevOrigins`);
if ('statusCode' in res) {
res.statusCode = 403;
}
res.end('Unauthorized');
return true;
}
function isInternalDevEndpoint(req) {
if (!req.url) return false;
try {
// TODO: We should standardize on a single prefix for this
const isMiddlewareRequest = req.url.includes('/__nextjs');
const isInternalAsset = req.url.includes('/_next');
// Static media requests are excluded, as they might be loaded via CSS and would fail
// CORS checks.
const isIgnoredRequest = req.url.includes('/_next/image') || req.url.includes('/_next/static/media');
return !isIgnoredRequest && (isInternalAsset || isMiddlewareRequest);
} catch (err) {
return false;
}
}
const blockCrossSite = (req, res, allowedDevOrigins, hostname)=>{
// in the future, these will be blocked by default when allowed origins aren't configured.
// for now, we warn when allowed origins aren't configured
const mode = typeof allowedDevOrigins === 'undefined' ? 'warn' : 'block';
const allowedOrigins = [
'*.localhost',
'localhost',
...allowedDevOrigins || []
];
if (hostname) {
allowedOrigins.push(hostname);
}
// only process internal URLs/middleware
if (!isInternalDevEndpoint(req)) {
return false;
}
// block non-cors request from cross-site e.g. script tag on
// different host
if (req.headers['sec-fetch-mode'] === 'no-cors' && req.headers['sec-fetch-site'] === 'cross-site') {
return warnOrBlockRequest(res, undefined, mode);
}
// ensure websocket requests from allowed origin
const rawOrigin = req.headers['origin'];
if (rawOrigin && rawOrigin !== 'null') {
const parsedOrigin = (0, _url.parseUrl)(rawOrigin);
if (parsedOrigin) {
const originLowerCase = parsedOrigin.hostname.toLowerCase();
if (!(0, _csrfprotection.isCsrfOriginAllowed)(originLowerCase, allowedOrigins)) {
return warnOrBlockRequest(res, originLowerCase, mode);
}
}
}
return false;
};
//# sourceMappingURL=block-cross-site.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
export declare function buildDataRoute(page: string, buildId: string): {
page: string;
routeKeys: {
[named: string]: string;
} | undefined;
dataRouteRegex: string;
namedDataRouteRegex: string | undefined;
};

View File

@@ -0,0 +1,48 @@
"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, {
prefixRouteKeys: true,
includeSuffix: true,
excludeOptionalTrailingSlash: true
});
dataRouteRegex = (0, _loadcustomroutes.normalizeRouteRegex)(routeRegex.re.source);
namedDataRouteRegex = routeRegex.namedRegex;
routeKeys = routeRegex.routeKeys;
} else {
dataRouteRegex = (0, _loadcustomroutes.normalizeRouteRegex)(new RegExp(`^${_path.default.posix.join('/_next/data', (0, _escaperegexp.escapeStringRegexp)(buildId), `${pagePath}\\.json`)}$`).source);
}
return {
page,
routeKeys,
dataRouteRegex,
namedDataRouteRegex
};
}
//# sourceMappingURL=build-data-route.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/router-utils/build-data-route.ts"],"sourcesContent":["import path from '../../../shared/lib/isomorphic/path'\nimport { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils/is-dynamic'\nimport { getNamedRouteRegex } from '../../../shared/lib/router/utils/route-regex'\nimport { normalizeRouteRegex } from '../../../lib/load-custom-routes'\nimport { escapeStringRegexp } from '../../../shared/lib/escape-regexp'\n\nexport function buildDataRoute(page: string, buildId: string) {\n const pagePath = normalizePagePath(page)\n const dataRoute = path.posix.join('/_next/data', buildId, `${pagePath}.json`)\n\n let dataRouteRegex: string\n let namedDataRouteRegex: string | undefined\n let routeKeys: { [named: string]: string } | undefined\n\n if (isDynamicRoute(page)) {\n const routeRegex = getNamedRouteRegex(dataRoute, {\n prefixRouteKeys: true,\n includeSuffix: true,\n excludeOptionalTrailingSlash: true,\n })\n\n dataRouteRegex = normalizeRouteRegex(routeRegex.re.source)\n namedDataRouteRegex = routeRegex.namedRegex\n routeKeys = routeRegex.routeKeys\n } else {\n dataRouteRegex = normalizeRouteRegex(\n new RegExp(\n `^${path.posix.join(\n '/_next/data',\n escapeStringRegexp(buildId),\n `${pagePath}\\\\.json`\n )}$`\n ).source\n )\n }\n\n return {\n page,\n routeKeys,\n dataRouteRegex,\n namedDataRouteRegex,\n }\n}\n"],"names":["buildDataRoute","page","buildId","pagePath","normalizePagePath","dataRoute","path","posix","join","dataRouteRegex","namedDataRouteRegex","routeKeys","isDynamicRoute","routeRegex","getNamedRouteRegex","prefixRouteKeys","includeSuffix","excludeOptionalTrailingSlash","normalizeRouteRegex","re","source","namedRegex","RegExp","escapeStringRegexp"],"mappings":";;;;+BAOgBA;;;eAAAA;;;6DAPC;mCACiB;2BACH;4BACI;kCACC;8BACD;;;;;;AAE5B,SAASA,eAAeC,IAAY,EAAEC,OAAe;IAC1D,MAAMC,WAAWC,IAAAA,oCAAiB,EAACH;IACnC,MAAMI,YAAYC,aAAI,CAACC,KAAK,CAACC,IAAI,CAAC,eAAeN,SAAS,GAAGC,SAAS,KAAK,CAAC;IAE5E,IAAIM;IACJ,IAAIC;IACJ,IAAIC;IAEJ,IAAIC,IAAAA,yBAAc,EAACX,OAAO;QACxB,MAAMY,aAAaC,IAAAA,8BAAkB,EAACT,WAAW;YAC/CU,iBAAiB;YACjBC,eAAe;YACfC,8BAA8B;QAChC;QAEAR,iBAAiBS,IAAAA,qCAAmB,EAACL,WAAWM,EAAE,CAACC,MAAM;QACzDV,sBAAsBG,WAAWQ,UAAU;QAC3CV,YAAYE,WAAWF,SAAS;IAClC,OAAO;QACLF,iBAAiBS,IAAAA,qCAAmB,EAClC,IAAII,OACF,CAAC,CAAC,EAAEhB,aAAI,CAACC,KAAK,CAACC,IAAI,CACjB,eACAe,IAAAA,gCAAkB,EAACrB,UACnB,GAAGC,SAAS,OAAO,CAAC,EACpB,CAAC,CAAC,EACJiB,MAAM;IAEZ;IAEA,OAAO;QACLnB;QACAU;QACAF;QACAC;IACF;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,9 @@
export declare const SEGMENT_PATH_KEY = "nextSegmentPath";
export type PrefetchSegmentDataRoute = {
source: string;
destination: string;
routeKeys: {
[key: string]: string;
};
};
export declare function buildPrefetchSegmentDataRoute(page: string, segmentPath: string): PrefetchSegmentDataRoute;

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
SEGMENT_PATH_KEY: null,
buildPrefetchSegmentDataRoute: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
SEGMENT_PATH_KEY: function() {
return SEGMENT_PATH_KEY;
},
buildPrefetchSegmentDataRoute: function() {
return buildPrefetchSegmentDataRoute;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("../../../shared/lib/isomorphic/path"));
const _normalizepagepath = require("../../../shared/lib/page-path/normalize-page-path");
const _routeregex = require("../../../shared/lib/router/utils/route-regex");
const _constants = require("../../../lib/constants");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const SEGMENT_PATH_KEY = 'nextSegmentPath';
function buildPrefetchSegmentDataRoute(page, segmentPath) {
const pagePath = (0, _normalizepagepath.normalizePagePath)(page);
const destination = _path.default.posix.join(`${pagePath}${_constants.RSC_SEGMENTS_DIR_SUFFIX}`, `${segmentPath}${_constants.RSC_SEGMENT_SUFFIX}`);
const { namedRegex, routeKeys } = (0, _routeregex.getNamedRouteRegex)(destination, {
prefixRouteKeys: true,
includePrefix: true,
includeSuffix: true,
excludeOptionalTrailingSlash: true,
backreferenceDuplicateKeys: true
});
return {
destination,
source: namedRegex,
routeKeys
};
}
//# sourceMappingURL=build-prefetch-segment-data-route.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/router-utils/build-prefetch-segment-data-route.ts"],"sourcesContent":["import path from '../../../shared/lib/isomorphic/path'\nimport { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'\nimport { getNamedRouteRegex } from '../../../shared/lib/router/utils/route-regex'\nimport {\n RSC_SEGMENT_SUFFIX,\n RSC_SEGMENTS_DIR_SUFFIX,\n} from '../../../lib/constants'\n\nexport const SEGMENT_PATH_KEY = 'nextSegmentPath'\n\nexport type PrefetchSegmentDataRoute = {\n source: string\n destination: string\n routeKeys: { [key: string]: string }\n}\n\nexport function buildPrefetchSegmentDataRoute(\n page: string,\n segmentPath: string\n): PrefetchSegmentDataRoute {\n const pagePath = normalizePagePath(page)\n\n const destination = path.posix.join(\n `${pagePath}${RSC_SEGMENTS_DIR_SUFFIX}`,\n `${segmentPath}${RSC_SEGMENT_SUFFIX}`\n )\n\n const { namedRegex, routeKeys } = getNamedRouteRegex(destination, {\n prefixRouteKeys: true,\n includePrefix: true,\n includeSuffix: true,\n excludeOptionalTrailingSlash: true,\n backreferenceDuplicateKeys: true,\n })\n\n return {\n destination,\n source: namedRegex,\n routeKeys,\n }\n}\n"],"names":["SEGMENT_PATH_KEY","buildPrefetchSegmentDataRoute","page","segmentPath","pagePath","normalizePagePath","destination","path","posix","join","RSC_SEGMENTS_DIR_SUFFIX","RSC_SEGMENT_SUFFIX","namedRegex","routeKeys","getNamedRouteRegex","prefixRouteKeys","includePrefix","includeSuffix","excludeOptionalTrailingSlash","backreferenceDuplicateKeys","source"],"mappings":";;;;;;;;;;;;;;;IAQaA,gBAAgB;eAAhBA;;IAQGC,6BAA6B;eAA7BA;;;6DAhBC;mCACiB;4BACC;2BAI5B;;;;;;AAEA,MAAMD,mBAAmB;AAQzB,SAASC,8BACdC,IAAY,EACZC,WAAmB;IAEnB,MAAMC,WAAWC,IAAAA,oCAAiB,EAACH;IAEnC,MAAMI,cAAcC,aAAI,CAACC,KAAK,CAACC,IAAI,CACjC,GAAGL,WAAWM,kCAAuB,EAAE,EACvC,GAAGP,cAAcQ,6BAAkB,EAAE;IAGvC,MAAM,EAAEC,UAAU,EAAEC,SAAS,EAAE,GAAGC,IAAAA,8BAAkB,EAACR,aAAa;QAChES,iBAAiB;QACjBC,eAAe;QACfC,eAAe;QACfC,8BAA8B;QAC9BC,4BAA4B;IAC9B;IAEA,OAAO;QACLb;QACAc,QAAQR;QACRC;IACF;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,17 @@
import type { CacheLife } from '../../use-cache/cache-life';
/**
* Generates TypeScript type definitions for custom cacheLife profiles.
* This creates overloaded function signatures for the cacheLife() function
* that provide autocomplete and documentation for each profile.
*/
export declare function generateCacheLifeTypes(cacheLife: {
[profile: string]: CacheLife;
}): string;
/**
* Writes cache-life type definitions to a file if cacheLifeConfig exists.
* This is used by both the CLI (next type-gen) and dev server to generate
* cache-life.d.ts in the types directory.
*/
export declare function writeCacheLifeTypes(cacheLifeConfig: undefined | {
[profile: string]: CacheLife;
}, filePath: string): void;

View File

@@ -0,0 +1,211 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
generateCacheLifeTypes: null,
writeCacheLifeTypes: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
generateCacheLifeTypes: function() {
return generateCacheLifeTypes;
},
writeCacheLifeTypes: function() {
return writeCacheLifeTypes;
}
});
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const MINUTE_IN_SECONDS = 60;
const HOUR_IN_SECONDS = MINUTE_IN_SECONDS * 60 // nevermind leap seconds
;
const DAY_IN_SECONDS = HOUR_IN_SECONDS * 24;
const WEEK_IN_SECONDS = DAY_IN_SECONDS * 7;
// Nevermind leap years, or you know, July
const MONTH_30_DAYS_IN_SECONDS = DAY_IN_SECONDS * 30;
function formatTimespan(seconds) {
if (seconds > 0) {
if (seconds === MONTH_30_DAYS_IN_SECONDS) {
return '1 month';
}
if (seconds === WEEK_IN_SECONDS) {
return '1 week';
}
if (seconds === DAY_IN_SECONDS) {
return '1 day';
}
if (seconds === HOUR_IN_SECONDS) {
return '1 hour';
}
if (seconds === MINUTE_IN_SECONDS) {
return '1 minute';
}
if (seconds % MONTH_30_DAYS_IN_SECONDS === 0) {
return seconds / MONTH_30_DAYS_IN_SECONDS + ' months';
}
if (seconds % 18144000 === 0) {
return seconds / 18144000 + ' months';
}
if (seconds % WEEK_IN_SECONDS === 0) {
return seconds / WEEK_IN_SECONDS + ' weeks';
}
if (seconds % DAY_IN_SECONDS === 0) {
return seconds / DAY_IN_SECONDS + ' days';
}
if (seconds % HOUR_IN_SECONDS === 0) {
return seconds / HOUR_IN_SECONDS + ' hours';
}
if (seconds % MINUTE_IN_SECONDS === 0) {
return seconds / MINUTE_IN_SECONDS + ' minutes';
}
}
return seconds + ' seconds';
}
function formatTimespanWithSeconds(seconds) {
if (seconds === undefined) {
return 'default';
}
if (seconds >= 0xfffffffe) {
return 'never';
}
const text = seconds + ' seconds';
const descriptive = formatTimespan(seconds);
if (descriptive === text) {
return text;
}
return text + ' (' + descriptive + ')';
}
function generateCacheLifeTypes(cacheLife) {
let overloads = '';
const profileNames = Object.keys(cacheLife);
for(let i = 0; i < profileNames.length; i++){
const profileName = profileNames[i];
const profile = cacheLife[profileName];
if (typeof profile !== 'object' || profile === null) {
continue;
}
let description = '';
if (profile.stale === undefined) {
description += `
* This cache may be stale on clients for the default stale time of the scope before checking with the server.`;
} else if (profile.stale >= 0xfffffffe) {
description += `
* This cache may be stale on clients indefinitely before checking with the server.`;
} else {
description += `
* This cache may be stale on clients for ${formatTimespan(profile.stale)} before checking with the server.`;
}
if (profile.revalidate !== undefined && profile.expire !== undefined && profile.revalidate >= profile.expire) {
description += `
* This cache will expire after ${formatTimespan(profile.expire)}. The next request will recompute it.`;
} else {
if (profile.revalidate === undefined) {
description += `
* It will inherit the default revalidate time of its scope since it does not define its own.`;
} else if (profile.revalidate >= 0xfffffffe) {
// Nothing to mention.
} else {
description += `
* If the server receives a new request after ${formatTimespan(profile.revalidate)}, start revalidating new values in the background.`;
}
if (profile.expire === undefined) {
description += `
* It will inherit the default expiration time of its scope since it does not define its own.`;
} else if (profile.expire >= 0xfffffffe) {
description += `
* It lives for the maximum age of the server cache. If this entry has no traffic for a while, it may serve an old value the next request.`;
} else {
description += `
* If this entry has no traffic for ${formatTimespan(profile.expire)} it will expire. The next request will recompute it.`;
}
}
overloads += `
/**
* Cache this \`"use cache"\` for a timespan defined by the \`${JSON.stringify(profileName)}\` profile.
* \`\`\`
* stale: ${formatTimespanWithSeconds(profile.stale)}
* revalidate: ${formatTimespanWithSeconds(profile.revalidate)}
* expire: ${formatTimespanWithSeconds(profile.expire)}
* \`\`\`
* ${description}
*/
export function cacheLife(profile: ${JSON.stringify(profileName)}): void
`;
}
overloads += `
/**
* Cache this \`"use cache"\` using a custom timespan.
* \`\`\`
* stale: ... // seconds
* revalidate: ... // seconds
* expire: ... // seconds
* \`\`\`
*
* This is similar to Cache-Control: max-age=\`stale\`,s-max-age=\`revalidate\`,stale-while-revalidate=\`expire-revalidate\`
*
* If a value is left out, the lowest of other cacheLife() calls or the default, is used instead.
*/
export function cacheLife(profile: {
/**
* This cache may be stale on clients for ... seconds before checking with the server.
*/
stale?: number,
/**
* If the server receives a new request after ... seconds, start revalidating new values in the background.
*/
revalidate?: number,
/**
* If this entry has no traffic for ... seconds it will expire. The next request will recompute it.
*/
expire?: number
}): void
`;
// Redefine the cacheLife() accepted arguments.
return `// Type definitions for Next.js cacheLife configs
declare module 'next/cache' {
export { unstable_cache } from 'next/dist/server/web/spec-extension/unstable-cache'
export {
updateTag,
revalidateTag,
revalidatePath,
refresh,
} from 'next/dist/server/web/spec-extension/revalidate'
export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store'
${overloads}
import { cacheTag } from 'next/dist/server/use-cache/cache-tag'
export { cacheTag }
export const unstable_cacheTag: typeof cacheTag
export const unstable_cacheLife: typeof cacheLife
}
`;
}
function writeCacheLifeTypes(cacheLifeConfig, filePath) {
if (!cacheLifeConfig || Object.keys(cacheLifeConfig).length === 0) {
return;
}
const dirname = _path.default.dirname(filePath);
if (!_fs.default.existsSync(dirname)) {
_fs.default.mkdirSync(dirname, {
recursive: true
});
}
const content = generateCacheLifeTypes(cacheLifeConfig);
_fs.default.writeFileSync(filePath, content);
}
//# sourceMappingURL=cache-life-type-utils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
/**
* We only encode path delimiters for path segments from
* getStaticPaths so we need to attempt decoding the URL
* to match against and only escape the path delimiters
* this allows non-ascii values to be handled e.g.
* Japanese characters.
* */
declare function decodePathParams(pathname: string): string;
export { decodePathParams };

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "decodePathParams", {
enumerable: true,
get: function() {
return decodePathParams;
}
});
const _escapepathdelimiters = /*#__PURE__*/ _interop_require_default(require("../../../shared/lib/router/utils/escape-path-delimiters"));
const _utils = require("../../../shared/lib/utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
/**
* We only encode path delimiters for path segments from
* getStaticPaths so we need to attempt decoding the URL
* to match against and only escape the path delimiters
* this allows non-ascii values to be handled e.g.
* Japanese characters.
* */ function decodePathParams(pathname) {
// TODO: investigate adding this handling for non-SSG
// pages so non-ascii names also work there.
return pathname.split('/').map((seg)=>{
try {
seg = (0, _escapepathdelimiters.default)(decodeURIComponent(seg), true);
} catch (_) {
// An improperly encoded URL was provided
throw Object.defineProperty(new _utils.DecodeError('Failed to decode path param(s).'), "__NEXT_ERROR_CODE", {
value: "E539",
enumerable: false,
configurable: true
});
}
return seg;
}).join('/');
}
//# sourceMappingURL=decode-path-params.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/router-utils/decode-path-params.ts"],"sourcesContent":["import escapePathDelimiters from '../../../shared/lib/router/utils/escape-path-delimiters'\nimport { DecodeError } from '../../../shared/lib/utils'\n\n/**\n * We only encode path delimiters for path segments from\n * getStaticPaths so we need to attempt decoding the URL\n * to match against and only escape the path delimiters\n * this allows non-ascii values to be handled e.g.\n * Japanese characters.\n * */\nfunction decodePathParams(pathname: string): string {\n // TODO: investigate adding this handling for non-SSG\n // pages so non-ascii names also work there.\n return pathname\n .split('/')\n .map((seg) => {\n try {\n seg = escapePathDelimiters(decodeURIComponent(seg), true)\n } catch (_) {\n // An improperly encoded URL was provided\n throw new DecodeError('Failed to decode path param(s).')\n }\n return seg\n })\n .join('/')\n}\n\nexport { decodePathParams }\n"],"names":["decodePathParams","pathname","split","map","seg","escapePathDelimiters","decodeURIComponent","_","DecodeError","join"],"mappings":";;;;+BA2BSA;;;eAAAA;;;6EA3BwB;uBACL;;;;;;AAE5B;;;;;;GAMG,GACH,SAASA,iBAAiBC,QAAgB;IACxC,qDAAqD;IACrD,4CAA4C;IAC5C,OAAOA,SACJC,KAAK,CAAC,KACNC,GAAG,CAAC,CAACC;QACJ,IAAI;YACFA,MAAMC,IAAAA,6BAAoB,EAACC,mBAAmBF,MAAM;QACtD,EAAE,OAAOG,GAAG;YACV,yCAAyC;YACzC,MAAM,qBAAkD,CAAlD,IAAIC,kBAAW,CAAC,oCAAhB,qBAAA;uBAAA;4BAAA;8BAAA;YAAiD;QACzD;QACA,OAAOJ;IACT,GACCK,IAAI,CAAC;AACV","ignoreList":[0]}

View File

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

View File

@@ -0,0 +1,590 @@
"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 = require("../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("../../normalizers/request/rsc");
const _encodeuripath = require("../../../shared/lib/encode-uri-path");
const _ismetadataroute = require("../../../lib/metadata/is-metadata-route");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__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);
let builtRegex = '';
const match = (0, _pathmatch.getPathMatch)(item.source, {
strict: true,
removeUnnamedParams: true,
regexModifier: (regex)=>{
if (!item.internal) {
regex = (0, _redirectstatus.modifyRouteRegex)(regex, type === 'redirect' ? restrictedRedirectPaths : undefined);
}
builtRegex = regex;
return builtRegex;
},
sensitive: caseSensitive
});
return {
...item,
regex: builtRegex,
...type === 'rewrite' ? {
check: true
} : {},
match
};
};
async function setupFsCheck(opts) {
const getItemsLru = !opts.dev ? new _lrucache.LRUCache(1024 * 1024, function length(value) {
if (!value) return 0;
return (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();
// Map normalized path to the file path. This is essential
// for parallel and group routes as their original path
// cannot be restored from the request path.
// Example:
// [normalized-path] -> [file-path]
// /icon-<hash>.png -> .../app/@parallel/icon.png
// /icon-<hash>.png -> .../app/(group)/icon.png
// /icon.png -> .../app/icon.png
const staticMetadataFiles = new Map();
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 Object.defineProperty(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`), "__NEXT_ERROR_CODE", {
value: "E427",
enumerable: false,
configurable: true
});
}
try {
for (const file of (await (0, _recursivereaddir.recursiveReadDir)(publicFolderPath))){
// Ensure filename is encoded and normalized.
publicFolderItems.add((0, _encodeuripath.encodeURIPath)((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((0, _encodeuripath.encodeURIPath)((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', (0, _encodeuripath.encodeURIPath)((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 functionsConfigManifestPath = _path.default.join(distDir, 'server', _constants.FUNCTIONS_CONFIG_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 functionsConfigManifest = JSON.parse(await _promises.default.readFile(functionsConfigManifestPath, '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.getNamedRouteRegex)(route.page, {
prefixRouteKeys: true
});
dynamicRoutes.push({
...route,
regex: routeRegex.re.toString(),
namedRegex: routeRegex.namedRegex,
routeKeys: routeRegex.routeKeys,
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){
// If a route is marked as skipInternalRouting, it's not for the internal
// router, and instead has been added to support external routers.
if (route.skipInternalRouting) {
continue;
}
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);
} else if (functionsConfigManifest == null ? void 0 : functionsConfigManifest.functions['/_middleware']) {
middlewareMatcher = (0, _middlewareroutematcher.getMiddlewareRouteMatcher)(functionsConfigManifest.functions['/_middleware'].matchers ?? [
{
regexp: '.*',
originalSource: '/:path*'
}
]);
}
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('customRoutes', customRoutes);
debug('publicFolderItems', publicFolderItems);
debug('nextStaticFolderItems', nextStaticFolderItems);
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()
};
return {
headers,
rewrites,
redirects,
buildId,
handleLocale,
appFiles,
pageFiles,
staticMetadataFiles,
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 } = opts.config;
const hasBasePath = (0, _pathhasprefix.pathHasPrefix)(itemPath, basePath);
// Return null if path doesn't start with basePath
if (basePath && !hasBasePath) {
return null;
}
// Remove basePath if it exists.
if (basePath && hasBasePath) {
itemPath = (0, _removepathprefix.removePathPrefix)(itemPath, basePath) || '/';
}
// Simulate minimal mode requests by normalizing RSC and postponed
// requests.
if (opts.minimalMode) {
if (normalizers.rsc.match(itemPath)) {
itemPath = normalizers.rsc.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'
};
}
if (opts.dev && (0, _ismetadataroute.isMetadataRouteFile)(itemPath, [], false)) {
const fsPath = staticMetadataFiles.get(itemPath);
if (fsPath) {
return {
// "nextStaticFolder" sets Cache-Control "no-store" on dev.
type: 'nextStaticFolder',
fsPath,
itemPath: fsPath
};
}
}
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 = (0, _encodeuripath.encodeURIPath)(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;
}
case 'appFile':
case 'pageFile':
case 'nextImage':
case 'devVirtualFsItem':
{
break;
}
default:
{
;
type;
}
}
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') {
const isAppFile = type === 'appFile';
// Attempt to ensure the page/app file is compiled and ready
if (ensureFn) {
const ensureItemPath = isAppFile ? (0, _getmetadataroute.normalizeMetadataRoute)(curItemPath) : curItemPath;
try {
await ensureFn({
type,
itemPath: ensureItemPath
});
} catch (error) {
continue;
}
}
} else {
continue;
}
}
// i18n locales aren't matched for app dir
if (type === 'appFile' && locale && locale !== (i18n == null ? void 0 : i18n.defaultLocale)) {
continue;
}
const itemResult = {
type,
fsPath,
locale,
itemsRoot,
itemPath: curItemPath
};
getItemsLru == null ? void 0 : getItemsLru.set(itemKey, itemResult);
return itemResult;
}
}
getItemsLru == null ? void 0 : getItemsLru.set(itemKey, null);
return null;
},
getDynamicRoutes () {
// this should include data routes
return this.dynamicRoutes;
},
getMiddlewareMatchers () {
return this.middlewareMatcher;
}
};
}
//# sourceMappingURL=filesystem.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
import type { InstrumentationModule, InstrumentationOnRequestError } from '../../instrumentation/types';
export declare function getInstrumentationModule(projectDir: string, distDir: string): Promise<InstrumentationModule | undefined>;
export declare function instrumentationOnRequestError(projectDir: string, distDir: string, ...args: Parameters<InstrumentationOnRequestError>): Promise<void>;
export declare function ensureInstrumentationRegistered(projectDir: string, distDir: string): Promise<void>;

View File

@@ -0,0 +1,89 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ensureInstrumentationRegistered: null,
getInstrumentationModule: null,
instrumentationOnRequestError: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ensureInstrumentationRegistered: function() {
return ensureInstrumentationRegistered;
},
getInstrumentationModule: function() {
return getInstrumentationModule;
},
instrumentationOnRequestError: function() {
return instrumentationOnRequestError;
}
});
const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
const _iserror = /*#__PURE__*/ _interop_require_default(require("../../../lib/is-error"));
const _constants = require("../../../lib/constants");
const _interopdefault = require("../../../lib/interop-default");
const _instrumentationnodeextensions = require("./instrumentation-node-extensions");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
let cachedInstrumentationModule;
async function getInstrumentationModule(projectDir, distDir) {
if (cachedInstrumentationModule) {
return cachedInstrumentationModule;
}
try {
cachedInstrumentationModule = (0, _interopdefault.interopDefault)(await require(_nodepath.default.join(projectDir, distDir, 'server', `${_constants.INSTRUMENTATION_HOOK_FILENAME}.js`)));
return cachedInstrumentationModule;
} catch (err) {
if ((0, _iserror.default)(err) && err.code !== 'ENOENT' && err.code !== 'MODULE_NOT_FOUND' && err.code !== 'ERR_MODULE_NOT_FOUND') {
throw err;
}
}
}
let instrumentationModulePromise = null;
async function registerInstrumentation(projectDir, distDir) {
// Ensure registerInstrumentation is not called in production build
if (process.env.NEXT_PHASE === 'phase-production-build') {
return;
}
if (!instrumentationModulePromise) {
instrumentationModulePromise = getInstrumentationModule(projectDir, distDir);
}
const instrumentation = await instrumentationModulePromise;
if (instrumentation == null ? void 0 : instrumentation.register) {
try {
await instrumentation.register();
(0, _instrumentationnodeextensions.afterRegistration)();
} catch (err) {
err.message = `An error occurred while loading instrumentation hook: ${err.message}`;
throw err;
}
}
}
async function instrumentationOnRequestError(projectDir, distDir, ...args) {
const instrumentation = await getInstrumentationModule(projectDir, distDir);
try {
var _instrumentation_onRequestError;
await (instrumentation == null ? void 0 : (_instrumentation_onRequestError = instrumentation.onRequestError) == null ? void 0 : _instrumentation_onRequestError.call(instrumentation, ...args));
} catch (err) {
// Log the soft error and continue, since the original error has already been thrown
console.error('Error in instrumentation.onRequestError:', err);
}
}
let registerInstrumentationPromise = null;
function ensureInstrumentationRegistered(projectDir, distDir) {
if (!registerInstrumentationPromise) {
registerInstrumentationPromise = registerInstrumentation(projectDir, distDir);
}
return registerInstrumentationPromise;
}
//# sourceMappingURL=instrumentation-globals.external.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/router-utils/instrumentation-globals.external.ts"],"sourcesContent":["import path from 'node:path'\nimport isError from '../../../lib/is-error'\nimport { INSTRUMENTATION_HOOK_FILENAME } from '../../../lib/constants'\nimport type {\n InstrumentationModule,\n InstrumentationOnRequestError,\n} from '../../instrumentation/types'\nimport { interopDefault } from '../../../lib/interop-default'\nimport { afterRegistration as extendInstrumentationAfterRegistration } from './instrumentation-node-extensions'\n\nlet cachedInstrumentationModule: InstrumentationModule\n\nexport async function getInstrumentationModule(\n projectDir: string,\n distDir: string\n): Promise<InstrumentationModule | undefined> {\n if (cachedInstrumentationModule) {\n return cachedInstrumentationModule\n }\n\n try {\n cachedInstrumentationModule = interopDefault(\n await require(\n path.join(\n projectDir,\n distDir,\n 'server',\n `${INSTRUMENTATION_HOOK_FILENAME}.js`\n )\n )\n )\n return cachedInstrumentationModule\n } catch (err: unknown) {\n if (\n isError(err) &&\n err.code !== 'ENOENT' &&\n err.code !== 'MODULE_NOT_FOUND' &&\n err.code !== 'ERR_MODULE_NOT_FOUND'\n ) {\n throw err\n }\n }\n}\n\nlet instrumentationModulePromise: Promise<any> | null = null\n\nasync function registerInstrumentation(projectDir: string, distDir: string) {\n // Ensure registerInstrumentation is not called in production build\n if (process.env.NEXT_PHASE === 'phase-production-build') {\n return\n }\n if (!instrumentationModulePromise) {\n instrumentationModulePromise = getInstrumentationModule(projectDir, distDir)\n }\n const instrumentation = await instrumentationModulePromise\n if (instrumentation?.register) {\n try {\n await instrumentation.register()\n extendInstrumentationAfterRegistration()\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n}\n\nexport async function instrumentationOnRequestError(\n projectDir: string,\n distDir: string,\n ...args: Parameters<InstrumentationOnRequestError>\n) {\n const instrumentation = await getInstrumentationModule(projectDir, distDir)\n try {\n await instrumentation?.onRequestError?.(...args)\n } catch (err) {\n // Log the soft error and continue, since the original error has already been thrown\n console.error('Error in instrumentation.onRequestError:', err)\n }\n}\n\nlet registerInstrumentationPromise: Promise<void> | null = null\nexport function ensureInstrumentationRegistered(\n projectDir: string,\n distDir: string\n) {\n if (!registerInstrumentationPromise) {\n registerInstrumentationPromise = registerInstrumentation(\n projectDir,\n distDir\n )\n }\n return registerInstrumentationPromise\n}\n"],"names":["ensureInstrumentationRegistered","getInstrumentationModule","instrumentationOnRequestError","cachedInstrumentationModule","projectDir","distDir","interopDefault","require","path","join","INSTRUMENTATION_HOOK_FILENAME","err","isError","code","instrumentationModulePromise","registerInstrumentation","process","env","NEXT_PHASE","instrumentation","register","extendInstrumentationAfterRegistration","message","args","onRequestError","console","error","registerInstrumentationPromise"],"mappings":";;;;;;;;;;;;;;;;IAiFgBA,+BAA+B;eAA/BA;;IArEMC,wBAAwB;eAAxBA;;IAsDAC,6BAA6B;eAA7BA;;;iEAlEL;gEACG;2BAC0B;gCAKf;+CAC6C;;;;;;AAE5E,IAAIC;AAEG,eAAeF,yBACpBG,UAAkB,EAClBC,OAAe;IAEf,IAAIF,6BAA6B;QAC/B,OAAOA;IACT;IAEA,IAAI;QACFA,8BAA8BG,IAAAA,8BAAc,EAC1C,MAAMC,QACJC,iBAAI,CAACC,IAAI,CACPL,YACAC,SACA,UACA,GAAGK,wCAA6B,CAAC,GAAG,CAAC;QAI3C,OAAOP;IACT,EAAE,OAAOQ,KAAc;QACrB,IACEC,IAAAA,gBAAO,EAACD,QACRA,IAAIE,IAAI,KAAK,YACbF,IAAIE,IAAI,KAAK,sBACbF,IAAIE,IAAI,KAAK,wBACb;YACA,MAAMF;QACR;IACF;AACF;AAEA,IAAIG,+BAAoD;AAExD,eAAeC,wBAAwBX,UAAkB,EAAEC,OAAe;IACxE,mEAAmE;IACnE,IAAIW,QAAQC,GAAG,CAACC,UAAU,KAAK,0BAA0B;QACvD;IACF;IACA,IAAI,CAACJ,8BAA8B;QACjCA,+BAA+Bb,yBAAyBG,YAAYC;IACtE;IACA,MAAMc,kBAAkB,MAAML;IAC9B,IAAIK,mCAAAA,gBAAiBC,QAAQ,EAAE;QAC7B,IAAI;YACF,MAAMD,gBAAgBC,QAAQ;YAC9BC,IAAAA,gDAAsC;QACxC,EAAE,OAAOV,KAAU;YACjBA,IAAIW,OAAO,GAAG,CAAC,sDAAsD,EAAEX,IAAIW,OAAO,EAAE;YACpF,MAAMX;QACR;IACF;AACF;AAEO,eAAeT,8BACpBE,UAAkB,EAClBC,OAAe,EACf,GAAGkB,IAA+C;IAElD,MAAMJ,kBAAkB,MAAMlB,yBAAyBG,YAAYC;IACnE,IAAI;YACIc;QAAN,OAAMA,oCAAAA,kCAAAA,gBAAiBK,cAAc,qBAA/BL,qCAAAA,oBAAqCI;IAC7C,EAAE,OAAOZ,KAAK;QACZ,oFAAoF;QACpFc,QAAQC,KAAK,CAAC,4CAA4Cf;IAC5D;AACF;AAEA,IAAIgB,iCAAuD;AACpD,SAAS3B,gCACdI,UAAkB,EAClBC,OAAe;IAEf,IAAI,CAACsB,gCAAgC;QACnCA,iCAAiCZ,wBAC/BX,YACAC;IAEJ;IACA,OAAOsB;AACT","ignoreList":[0]}

View File

@@ -0,0 +1,5 @@
/**
* This extension augments opentelemetry after registration if applicable.
* This extension must only be loaded in Node environments.
*/
export declare function afterRegistration(): void;

View File

@@ -0,0 +1,96 @@
/**
* This extension augments opentelemetry after registration if applicable.
* This extension must only be loaded in Node environments.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "afterRegistration", {
enumerable: true,
get: function() {
return afterRegistration;
}
});
const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external");
const _invarianterror = require("../../../shared/lib/invariant-error");
const _clientandserverreferences = require("../../../lib/client-and-server-references");
function afterRegistration() {
if (process.env.NEXT_RUNTIME === 'edge') {
throw Object.defineProperty(new _invarianterror.InvariantError('Node.js instrumentation extensions should not be loaded in the Edge runtime.'), "__NEXT_ERROR_CODE", {
value: "E775",
enumerable: false,
configurable: true
});
}
extendTracerProviderForCacheComponents();
}
// In theory we only want to enable this extension when cacheComponents is enabled
// however there are certain servers that might load instrumentation before nextConfig is available
// and so gating it on the config might lead to skipping this extension even when it is necessary.
// When cacheComponents is disabled this extension should be a no-op so we enable it universally.
// Additionally, soon, cacheComponents will be enabled always so this just pulls the extension forward in time
function extendTracerProviderForCacheComponents() {
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
try {
api = require('@opentelemetry/api');
} catch (err) {
api = require('next/dist/compiled/@opentelemetry/api');
}
const provider = api.trace.getTracerProvider();
// When Cache Components is enabled we need to instrument the tracer
// to exit the workUnitAsyncStorage context when generating spans.
const originalGetTracer = provider.getTracer.bind(provider);
provider.getTracer = (...args)=>{
const tracer = originalGetTracer.apply(provider, args);
if (WeakTracers.has(tracer)) {
return tracer;
}
const originalStartSpan = tracer.startSpan;
tracer.startSpan = (...startSpanArgs)=>{
return _workunitasyncstorageexternal.workUnitAsyncStorage.exit(()=>originalStartSpan.apply(tracer, startSpanArgs));
};
const originalStartActiveSpan = tracer.startActiveSpan;
// @ts-ignore TS doesn't recognize the overloads correctly
tracer.startActiveSpan = (...startActiveSpanArgs)=>{
const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore();
if (!workUnitStore) {
// @ts-ignore TS doesn't recognize the overloads correctly
return originalStartActiveSpan.apply(tracer, startActiveSpanArgs);
}
let fnIdx = 0;
if (startActiveSpanArgs.length === 2 && typeof startActiveSpanArgs[1] === 'function') {
fnIdx = 1;
} else if (startActiveSpanArgs.length === 3 && typeof startActiveSpanArgs[2] === 'function') {
fnIdx = 2;
} else if (startActiveSpanArgs.length > 3 && typeof startActiveSpanArgs[3] === 'function') {
fnIdx = 3;
}
if (fnIdx) {
const originalFn = startActiveSpanArgs[fnIdx];
if ((0, _clientandserverreferences.isUseCacheFunction)(originalFn)) {
console.error('A Cache Function (`use cache`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.');
}
startActiveSpanArgs[fnIdx] = withWorkUnitContext(workUnitStore, originalFn);
}
return _workunitasyncstorageexternal.workUnitAsyncStorage.exit(()=>{
// @ts-ignore TS doesn't recognize the overloads correctly
return originalStartActiveSpan.apply(tracer, startActiveSpanArgs);
});
};
WeakTracers.add(tracer);
return tracer;
};
}
const WeakTracers = new WeakSet();
function withWorkUnitContext(workUnitStore, fn) {
return (...args)=>_workunitasyncstorageexternal.workUnitAsyncStorage.run(workUnitStore, fn, ...args);
}
//# sourceMappingURL=instrumentation-node-extensions.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export declare function isPostpone(error: any): boolean;

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 @@
{"version":3,"sources":["../../../../src/server/lib/router-utils/is-postpone.ts"],"sourcesContent":["const REACT_POSTPONE_TYPE: symbol = Symbol.for('react.postpone')\n\nexport function isPostpone(error: any): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n error.$$typeof === REACT_POSTPONE_TYPE\n )\n}\n"],"names":["isPostpone","REACT_POSTPONE_TYPE","Symbol","for","error","$$typeof"],"mappings":";;;;+BAEgBA;;;eAAAA;;;AAFhB,MAAMC,sBAA8BC,OAAOC,GAAG,CAAC;AAExC,SAASH,WAAWI,KAAU;IACnC,OACE,OAAOA,UAAU,YACjBA,UAAU,QACVA,MAAMC,QAAQ,KAAKJ;AAEvB","ignoreList":[0]}

View File

@@ -0,0 +1,4 @@
import type { IncomingMessage, ServerResponse } from 'http';
import type { NextUrlWithParsedQuery } from '../../request-meta';
import { Duplex } from 'stream';
export declare function proxyRequest(req: IncomingMessage, res: ServerResponse | Duplex, parsedUrl: NextUrlWithParsedQuery, upgradeHead?: Buffer, reqBody?: any, proxyTimeout?: number | null): Promise<boolean>;

View File

@@ -0,0 +1,118 @@
"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");
const _stream = require("stream");
const _detachedpromise = require("../../../lib/detached-promise");
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 || ''
}
});
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);
});
const detached = new _detachedpromise.DetachedPromise();
proxy.on('error', (err)=>{
console.error(`Failed to proxy ${target}`, err);
if (!finished) {
finished = true;
detached.reject(err);
if (!res.destroyed) {
if (!(res instanceof _stream.Duplex)) {
res.statusCode = 500;
}
res.end('Internal Server Error');
}
}
});
// If upgrade head is present or the response is a Duplex stream, treat as
// WebSocket request.
if (upgradeHead || res instanceof _stream.Duplex) {
proxy.on('proxyReqWs', (proxyReq)=>{
proxyReq.on('close', ()=>{
if (!finished) {
finished = true;
detached.resolve(true);
}
});
});
proxy.ws(req, res, upgradeHead);
detached.resolve(true);
} else {
proxy.on('proxyReq', (proxyReq)=>{
proxyReq.on('close', ()=>{
if (!finished) {
finished = true;
detached.resolve(true);
}
});
});
proxy.web(req, res, {
buffer: reqBody
});
}
// When the proxy finishes proxying the request, shut down the proxy.
return detached.promise.finally(()=>{
proxy.close();
});
}
//# sourceMappingURL=proxy-request.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,20 @@
import type { FsOutput } from './filesystem';
import type { IncomingMessage, ServerResponse } from 'http';
import type { NextConfigRuntime } from '../../config-shared';
import type { RenderServer, initialize } from '../router-server';
import type { UnwrapPromise } from '../../../lib/coalesced-function';
import type { NextUrlWithParsedQuery } from '../../request-meta';
export declare function getResolveRoutes(fsChecker: UnwrapPromise<ReturnType<typeof import('./filesystem').setupFsCheck>>, config: NextConfigRuntime, opts: Parameters<typeof initialize>[0], renderServer: RenderServer, renderServerOpts: Parameters<RenderServer['initialize']>[0], ensureMiddleware?: (url?: string) => Promise<void>): ({ req, res, isUpgradeReq, invokedOutputs, }: {
req: IncomingMessage;
res: ServerResponse;
isUpgradeReq: boolean;
signal: AbortSignal;
invokedOutputs?: Set<string>;
}) => Promise<{
finished: boolean;
statusCode?: number;
bodyStream?: ReadableStream | null;
resHeaders: Record<string, string | string[]> | null;
parsedUrl: NextUrlWithParsedQuery;
matchedOutput?: FsOutput | null;
}>;

View File

@@ -0,0 +1,608 @@
"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("../../normalizers/request/next-data");
const _basepath = require("../../normalizers/request/base-path");
const _requestmeta = require("../../request-meta");
const _preparedestination = require("../../../shared/lib/router/utils/prepare-destination");
const _approuterheaders = require("../../../client/components/app-router-headers");
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) {
let routes = null;
const calculateRoutes = ()=>{
return [
// _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];
// Refresh the routes every time in development mode, but only initialize them
// once in production. We don't need to recompute these every time unless the routes
// are changing like in development, and the performance can be costly.
if (!routes || opts.dev) {
routes = calculateRoutes();
}
// 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) {
const bodySizeLimit = config.experimental.proxyClientMaxBodySize;
(0, _requestmeta.addRequestMeta)(req, 'clonableBody', (0, _bodystreams.getCloneableBody)(req, bodySizeLimit));
}
const maybeAddTrailingSlash = (pathname)=>{
if (config.trailingSlash && !config.skipProxyUrlNormalize && !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);
let normalizedPath = parsedUrl.pathname || '/';
if (config.basePath && (0, _pathhasprefix.pathHasPrefix)(normalizedPath, config.basePath)) {
normalizedPath = (0, _removepathprefix.removePathPrefix)(normalizedPath, config.basePath);
} else if (config.assetPrefix && (0, _pathhasprefix.pathHasPrefix)(normalizedPath, config.assetPrefix)) {
normalizedPath = (0, _removepathprefix.removePathPrefix)(normalizedPath, config.assetPrefix);
}
initialLocaleResult = (0, _normalizelocalepath.normalizeLocalePath)(normalizedPath, 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;
(0, _requestmeta.addRequestMeta)(req, 'defaultLocale', defaultLocale);
(0, _requestmeta.addRequestMeta)(req, 'locale', initialLocaleResult.detectedLocale || defaultLocale);
// ensure locale is present for resolving routes
if (!initialLocaleResult.detectedLocale && !initialLocaleResult.pathname.startsWith('/_next/')) {
parsedUrl.pathname = (0, _addpathprefix.addPathPrefix)(initialLocaleResult.pathname === '/' ? `/${defaultLocale}` : (0, _addpathprefix.addPathPrefix)(initialLocaleResult.pathname || '', `/${defaultLocale}`), hadBasePath ? config.basePath : '');
if (hadTrailingSlash) {
parsedUrl.pathname = maybeAddTrailingSlash(parsedUrl.pathname);
}
}
}
const checkLocaleApi = (pathname)=>{
if (config.i18n && pathname === urlNoQuery && (initialLocaleResult == null ? void 0 : initialLocaleResult.detectedLocale) && (0, _pathhasprefix.pathHasPrefix)(initialLocaleResult.pathname, '/api')) {
return true;
}
};
async function checkTrue() {
const pathname = parsedUrl.pathname || '/';
if (checkLocaleApi(pathname)) {
return;
}
if (!(invokedOutputs == null ? void 0 : invokedOutputs.has(pathname))) {
const output = await fsChecker.getItem(pathname);
if (output) {
if (config.useFileSystemPublicRoutes || didRewrite || output.type !== 'appFile' && output.type !== 'pageFile') {
return output;
}
}
}
const dynamicRoutes = fsChecker.getDynamicRoutes();
let curPathname = parsedUrl.pathname;
if (config.basePath) {
if (!(0, _pathhasprefix.pathHasPrefix)(curPathname || '', config.basePath)) {
return;
}
curPathname = (curPathname == null ? void 0 : curPathname.substring(config.basePath.length)) || '/';
}
const localeResult = fsChecker.handleLocale(curPathname || '');
for (const route of dynamicRoutes){
// when resolving fallback: false the
// render worker may return a no-fallback response
// which signals we need to continue resolving.
// TODO: optimize this to collect static paths
// to use at the routing layer
if (invokedOutputs == null ? void 0 : invokedOutputs.has(route.page)) {
continue;
}
const params = route.match(localeResult.pathname);
if (params) {
const pageOutput = await fsChecker.getItem((0, _addpathprefix.addPathPrefix)(route.page, config.basePath || ''));
// i18n locales aren't matched for app dir
if ((pageOutput == null ? void 0 : pageOutput.type) === 'appFile' && (initialLocaleResult == null ? void 0 : initialLocaleResult.detectedLocale)) {
continue;
}
if (pageOutput && (curPathname == null ? void 0 : curPathname.startsWith('/_next/data'))) {
(0, _requestmeta.addRequestMeta)(req, 'isNextDataReq', true);
}
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)
};
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;
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;
(0, _requestmeta.addRequestMeta)(req, 'isNextDataReq', true);
normalized = normalizers.data.normalize(normalized, true);
}
if (config.i18n) {
const curLocaleResult = (0, _normalizelocalepath.normalizeLocalePath)(normalized, config.i18n.locales);
if (curLocaleResult.detectedLocale) {
(0, _requestmeta.addRequestMeta)(req, 'locale', curLocaleResult.detectedLocale);
}
}
// If we updated the pathname, and it had a base path, re-add the
// base path.
if (updated) {
if (hadBasePath) {
normalized = normalized === '/' ? config.basePath : _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) {
(0, _requestmeta.addRequestMeta)(req, 'locale', output.locale);
}
return {
parsedUrl,
resHeaders,
finished: true,
matchedOutput
};
}
}
}
if (!opts.minimalMode && route.name === 'middleware') {
const match = fsChecker.getMiddlewareMatchers();
let maybeDecodedPathname = parsedUrl.pathname || '/';
try {
maybeDecodedPathname = decodeURIComponent(maybeDecodedPathname);
} catch {
/* non-fatal we can't decode so can't match it */ }
if (// @ts-expect-error BaseNextRequest stuff
(match == null ? void 0 : match(parsedUrl.pathname, req, parsedUrl.query)) || (match == null ? void 0 : match(maybeDecodedPathname, // @ts-expect-error BaseNextRequest stuff
req, parsedUrl.query))) {
if (ensureMiddleware) {
await ensureMiddleware(req.url);
}
const serverResult = await (renderServer == null ? void 0 : renderServer.initialize(renderServerOpts));
if (!serverResult) {
throw Object.defineProperty(new Error(`Failed to initialize render server "middleware"`), "__NEXT_ERROR_CODE", {
value: "E222",
enumerable: false,
configurable: true
});
}
(0, _requestmeta.addRequestMeta)(req, 'invokePath', '');
(0, _requestmeta.addRequestMeta)(req, 'invokeOutput', '');
(0, _requestmeta.addRequestMeta)(req, 'invokeQuery', {});
(0, _requestmeta.addRequestMeta)(req, 'middlewareInvoke', true);
if (opts.dev) {
(0, _requestmeta.addRequestMeta)(req, 'devRequestTimingMiddlewareStart', process.hrtime.bigint());
}
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();
}
});
}
} finally{
if (opts.dev) {
(0, _requestmeta.addRequestMeta)(req, 'devRequestTimingMiddlewareEnd', process.hrtime.bigint());
}
}
} 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;
}
// for set-cookie, the header shouldn't be added to the response
// as it's only needed for the request to the middleware function.
if (key === 'x-middleware-set-cookie') {
req.headers[key] = value;
continue;
}
if (value) {
resHeaders[key] = value;
req.headers[key] = value;
}
}
if (middlewareHeaders['x-middleware-rewrite']) {
const value = middlewareHeaders['x-middleware-rewrite'];
const destination = (0, _relativizeurl.getRelativeURL)(value, initUrl);
resHeaders['x-middleware-rewrite'] = destination;
parsedUrl = _url.default.parse(destination, true);
if (parsedUrl.protocol) {
return {
parsedUrl,
resHeaders,
finished: true
};
}
if (config.i18n) {
const curLocaleResult = (0, _normalizelocalepath.normalizeLocalePath)(parsedUrl.pathname || '', config.i18n.locales);
if (curLocaleResult.detectedLocale) {
(0, _requestmeta.addRequestMeta)(req, 'locale', curLocaleResult.detectedLocale);
}
}
}
if (middlewareHeaders['location']) {
const value = middlewareHeaders['location'];
// Only process Location header as a redirect if it has a proper redirect status
// This prevents a Location header with non-redirect status from being treated as a redirect
const isRedirectStatus = _redirectstatus.allowedStatusCodes.has(middlewareRes.status);
if (isRedirectStatus) {
// Process as redirect: update parsedUrl and convert to relative URL
const rel = (0, _relativizeurl.getRelativeURL)(value, initUrl);
resHeaders['location'] = rel;
parsedUrl = _url.default.parse(rel, true);
return {
parsedUrl,
resHeaders,
finished: true,
statusCode: middlewareRes.status
};
} else {
// Not a redirect: just pass through the Location header
resHeaders['location'] = value;
return {
parsedUrl,
resHeaders,
finished: true,
bodyStream,
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);
// @ts-expect-error // custom ParsedUrl
const unsafeParsedUrl = parsedDestination;
return {
finished: true,
parsedUrl: unsafeParsedUrl,
resHeaders: null,
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) {
var _config_experimental_clientParamParsingOrigins;
let rewriteParams = params;
const { parsedDestination } = (0, _preparedestination.prepareDestination)({
appendParamsToQuery: true,
destination: route.destination,
params: rewriteParams,
query: parsedUrl.query
});
// Check to see if this is a non-relative rewrite. If it is, we need
// to check to see if it's an allowed origin to receive the rewritten
// headers.
const parsedDestinationOrigin = parsedDestination.origin;
const isAllowedOrigin = parsedDestinationOrigin ? (_config_experimental_clientParamParsingOrigins = config.experimental.clientParamParsingOrigins) == null ? void 0 : _config_experimental_clientParamParsingOrigins.some((origin)=>new RegExp(origin).test(parsedDestinationOrigin)) : false;
// Set the rewrite headers only if this is a RSC request.
if (req.headers[_approuterheaders.RSC_HEADER] === '1' && (!parsedDestination.origin || isAllowedOrigin)) {
// We set the rewritten path and query headers on the response now
// that we know that the it's not an external rewrite.
if (parsedUrl.pathname !== parsedDestination.pathname) {
res.setHeader(_approuterheaders.NEXT_REWRITTEN_PATH_HEADER, parsedDestination.pathname);
}
if (parsedUrl.search !== parsedDestination.search) {
res.setHeader(_approuterheaders.NEXT_REWRITTEN_QUERY_HEADER, // remove the leading ? from the search
parsedDestination.search.slice(1));
}
}
if (parsedDestination.protocol) {
// @ts-expect-error // custom ParsedUrl
const unsafeParsedUrl = parsedDestination;
return {
parsedUrl: unsafeParsedUrl,
resHeaders: null,
finished: true
};
}
if (config.i18n) {
const curLocaleResult = (0, _normalizelocalepath.normalizeLocalePath)((0, _removepathprefix.removePathPrefix)(parsedDestination.pathname, config.basePath), config.i18n.locales);
if (curLocaleResult.detectedLocale) {
(0, _requestmeta.addRequestMeta)(req, 'locale', curLocaleResult.detectedLocale);
}
}
didRewrite = true;
parsedUrl.pathname = parsedDestination.pathname;
Object.assign(parsedUrl.query, parsedDestination.query);
}
// handle check: true
if (route.check) {
const output = await checkTrue();
if (output) {
return {
parsedUrl,
resHeaders,
finished: true,
matchedOutput: output
};
}
}
}
}
for (const route of routes){
const result = await handleRoute(route);
if (result) {
return result;
}
}
return {
finished,
parsedUrl,
resHeaders,
matchedOutput
};
}
return resolveRoutes;
}
//# sourceMappingURL=resolve-routes.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,72 @@
import { type Group } from '../../../shared/lib/router/utils/route-regex';
import type { NextConfigComplete } from '../../config-shared';
interface RouteInfo {
path: string;
groups: {
[groupName: string]: Group;
};
}
export interface RouteTypesManifest {
appRoutes: Record<string, RouteInfo>;
pageRoutes: Record<string, RouteInfo>;
layoutRoutes: Record<string, RouteInfo & {
slots: string[];
}>;
appRouteHandlerRoutes: Record<string, RouteInfo>;
/** Map of redirect source => RouteInfo */
redirectRoutes: Record<string, RouteInfo>;
/** Map of rewrite source => RouteInfo */
rewriteRoutes: Record<string, RouteInfo>;
/** File paths for validation */
appPagePaths: Set<string>;
pagesRouterPagePaths: Set<string>;
layoutPaths: Set<string>;
appRouteHandlers: Set<string>;
pageApiRoutes: Set<string>;
/** Direct mapping from file paths to routes for validation */
filePathToRoute: Map<string, string>;
}
export declare function convertCustomRouteSource(source: string): string[];
/**
* Extracts route parameters from a route pattern
*/
export declare function extractRouteParams(route: string): {
[groupName: string]: Group;
};
/**
* Creates a route types manifest from processed route data
* (used for both build and dev)
*/
export declare function createRouteTypesManifest({ dir, pageRoutes, appRoutes, appRouteHandlers, pageApiRoutes, layoutRoutes, slots, redirects, rewrites, validatorFilePath, }: {
dir: string;
pageRoutes: Array<{
route: string;
filePath: string;
}>;
appRoutes: Array<{
route: string;
filePath: string;
}>;
appRouteHandlers: Array<{
route: string;
filePath: string;
}>;
pageApiRoutes: Array<{
route: string;
filePath: string;
}>;
layoutRoutes: Array<{
route: string;
filePath: string;
}>;
slots: Array<{
name: string;
parent: string;
}>;
redirects?: NextConfigComplete['redirects'];
rewrites?: NextConfigComplete['rewrites'];
validatorFilePath?: string;
}): Promise<RouteTypesManifest>;
export declare function writeRouteTypesManifest(manifest: RouteTypesManifest, filePath: string, config: NextConfigComplete): Promise<void>;
export declare function writeValidatorFile(manifest: RouteTypesManifest, filePath: string): Promise<void>;
export {};

View File

@@ -0,0 +1,286 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
convertCustomRouteSource: null,
createRouteTypesManifest: null,
extractRouteParams: null,
writeRouteTypesManifest: null,
writeValidatorFile: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
convertCustomRouteSource: function() {
return convertCustomRouteSource;
},
createRouteTypesManifest: function() {
return createRouteTypesManifest;
},
extractRouteParams: function() {
return extractRouteParams;
},
writeRouteTypesManifest: function() {
return writeRouteTypesManifest;
},
writeValidatorFile: function() {
return writeValidatorFile;
}
});
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _routeregex = require("../../../shared/lib/router/utils/route-regex");
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
const _typegen = require("./typegen");
const _trytoparsepath = require("../../../lib/try-to-parse-path");
const _interceptionroutes = require("../../../shared/lib/router/utils/interception-routes");
const _entryconstants = require("../../../shared/lib/entry-constants");
const _normalizepathsep = require("../../../shared/lib/page-path/normalize-path-sep");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function convertCustomRouteSource(source) {
const parseResult = (0, _trytoparsepath.tryToParsePath)(source);
if (parseResult.error || !parseResult.tokens) {
// Fallback to original source if parsing fails
return source.startsWith('/') ? [
source
] : [
'/' + source
];
}
const possibleNormalizedRoutes = [
''
];
let slugCnt = 1;
function append(suffix) {
for(let i = 0; i < possibleNormalizedRoutes.length; i++){
possibleNormalizedRoutes[i] += suffix;
}
}
function fork(suffix) {
const currentLength = possibleNormalizedRoutes.length;
for(let i = 0; i < currentLength; i++){
possibleNormalizedRoutes.push(possibleNormalizedRoutes[i] + suffix);
}
}
for (const token of parseResult.tokens){
if (typeof token === 'object') {
// Make sure the slug is always named.
const slug = token.name || (slugCnt++ === 1 ? 'slug' : `slug${slugCnt}`);
if (token.modifier === '*') {
append(`${token.prefix}[[...${slug}]]`);
} else if (token.modifier === '+') {
append(`${token.prefix}[...${slug}]`);
} else if (token.modifier === '') {
if (token.pattern === '[^\\/#\\?]+?') {
// A safe slug
append(`${token.prefix}[${slug}]`);
} else if (token.pattern === '.*') {
// An optional catch-all slug
append(`${token.prefix}[[...${slug}]]`);
} else if (token.pattern === '.+') {
// A catch-all slug
append(`${token.prefix}[...${slug}]`);
} else {
// Other regex patterns are not supported. Skip this route.
return [];
}
} else if (token.modifier === '?') {
if (/^[a-zA-Z0-9_/]*$/.test(token.pattern)) {
// An optional slug with plain text only, fork the route.
append(token.prefix);
fork(token.pattern);
} else {
// Optional modifier `?` and regex patterns are not supported.
return [];
}
}
} else if (typeof token === 'string') {
append(token);
}
}
// Ensure leading slash
return possibleNormalizedRoutes.map((route)=>route.startsWith('/') ? route : '/' + route);
}
function extractRouteParams(route) {
const regex = (0, _routeregex.getRouteRegex)(route);
return regex.groups;
}
/**
* Resolves an intercepting route to its canonical equivalent
* Example: /gallery/test/(..)photo/[id] -> /gallery/photo/[id]
*/ function resolveInterceptingRoute(route) {
// Reuse centralized interception route normalization logic
try {
if (!(0, _interceptionroutes.isInterceptionRouteAppPath)(route)) return route;
const { interceptedRoute } = (0, _interceptionroutes.extractInterceptionRouteInformation)(route);
return interceptedRoute;
} catch {
// If parsing fails, fall back to the original route
return route;
}
}
async function createRouteTypesManifest({ dir, pageRoutes, appRoutes, appRouteHandlers, pageApiRoutes, layoutRoutes, slots, redirects, rewrites, validatorFilePath }) {
// Helper function to calculate the correct relative path
const getRelativePath = (filePath)=>{
if (validatorFilePath) {
// For validator generation, calculate path relative to validator directory
return (0, _normalizepathsep.normalizePathSep)(_path.default.relative(_path.default.dirname(validatorFilePath), filePath));
}
// For other uses, calculate path relative to project directory
return (0, _normalizepathsep.normalizePathSep)(_path.default.relative(dir, filePath));
};
const manifest = {
appRoutes: {},
pageRoutes: {},
layoutRoutes: {},
appRouteHandlerRoutes: {},
redirectRoutes: {},
rewriteRoutes: {},
appRouteHandlers: new Set(appRouteHandlers.map(({ filePath })=>getRelativePath(filePath))),
pageApiRoutes: new Set(pageApiRoutes.map(({ filePath })=>getRelativePath(filePath))),
appPagePaths: new Set(appRoutes.map(({ filePath })=>getRelativePath(filePath))),
pagesRouterPagePaths: new Set(pageRoutes.map(({ filePath })=>getRelativePath(filePath))),
layoutPaths: new Set(layoutRoutes.map(({ filePath })=>getRelativePath(filePath))),
filePathToRoute: new Map([
...appRoutes.map(({ route, filePath })=>[
getRelativePath(filePath),
resolveInterceptingRoute(route)
]),
...layoutRoutes.map(({ route, filePath })=>[
getRelativePath(filePath),
resolveInterceptingRoute(route)
]),
...appRouteHandlers.map(({ route, filePath })=>[
getRelativePath(filePath),
resolveInterceptingRoute(route)
]),
...pageRoutes.map(({ route, filePath })=>[
getRelativePath(filePath),
route
]),
...pageApiRoutes.map(({ route, filePath })=>[
getRelativePath(filePath),
route
])
])
};
// Process page routes
for (const { route, filePath } of pageRoutes){
manifest.pageRoutes[route] = {
path: getRelativePath(filePath),
groups: extractRouteParams(route)
};
}
// Process layout routes (exclude internal app error/not-found layouts)
for (const { route, filePath } of layoutRoutes){
if (route === _entryconstants.UNDERSCORE_GLOBAL_ERROR_ROUTE || route === _entryconstants.UNDERSCORE_NOT_FOUND_ROUTE) continue;
// Use the resolved route (for interception routes, this gives us the canonical route)
const resolvedRoute = resolveInterceptingRoute(route);
if (!manifest.layoutRoutes[resolvedRoute]) {
manifest.layoutRoutes[resolvedRoute] = {
path: getRelativePath(filePath),
groups: extractRouteParams(resolvedRoute),
slots: []
};
}
}
// Process slots
for (const slot of slots){
if (manifest.layoutRoutes[slot.parent]) {
manifest.layoutRoutes[slot.parent].slots.push(slot.name);
}
}
// Process app routes (exclude internal app routes)
for (const { route, filePath } of appRoutes){
if (route === _entryconstants.UNDERSCORE_GLOBAL_ERROR_ROUTE || route === _entryconstants.UNDERSCORE_NOT_FOUND_ROUTE) continue;
// Don't include metadata routes or pages
if (!filePath.endsWith('page.ts') && !filePath.endsWith('page.tsx') && !filePath.endsWith('.mdx') && !filePath.endsWith('.md')) {
continue;
}
// Use the resolved route (for interception routes, this gives us the canonical route)
const resolvedRoute = resolveInterceptingRoute(route);
if (!manifest.appRoutes[resolvedRoute]) {
manifest.appRoutes[resolvedRoute] = {
path: getRelativePath(filePath),
groups: extractRouteParams(resolvedRoute)
};
}
}
// Process app route handlers
for (const { route, filePath } of appRouteHandlers){
// Use the resolved route (for interception routes, this gives us the canonical route)
const resolvedRoute = resolveInterceptingRoute(route);
if (!manifest.appRouteHandlerRoutes[resolvedRoute]) {
manifest.appRouteHandlerRoutes[resolvedRoute] = {
path: getRelativePath(filePath),
groups: extractRouteParams(resolvedRoute)
};
}
}
// Process redirects
if (typeof redirects === 'function') {
const rd = await redirects();
for (const item of rd){
const possibleRoutes = convertCustomRouteSource(item.source);
for (const route of possibleRoutes){
manifest.redirectRoutes[route] = {
path: route,
groups: extractRouteParams(route)
};
}
}
}
// Process rewrites
if (typeof rewrites === 'function') {
const rw = await rewrites();
const allSources = Array.isArray(rw) ? rw : [
...(rw == null ? void 0 : rw.beforeFiles) || [],
...(rw == null ? void 0 : rw.afterFiles) || [],
...(rw == null ? void 0 : rw.fallback) || []
];
for (const item of allSources){
const possibleRoutes = convertCustomRouteSource(item.source);
for (const route of possibleRoutes){
manifest.rewriteRoutes[route] = {
path: route,
groups: extractRouteParams(route)
};
}
}
}
return manifest;
}
async function writeRouteTypesManifest(manifest, filePath, config) {
const dirname = _path.default.dirname(filePath);
if (!_fs.default.existsSync(dirname)) {
await _fs.default.promises.mkdir(dirname, {
recursive: true
});
}
// Write the main routes.d.ts file
await _fs.default.promises.writeFile(filePath, (0, _typegen.generateRouteTypesFile)(manifest));
// Write the link.d.ts file if typedRoutes is enabled
if (config.typedRoutes === true) {
const linkTypesPath = _path.default.join(dirname, 'link.d.ts');
await _fs.default.promises.writeFile(linkTypesPath, (0, _typegen.generateLinkTypesFile)(manifest));
}
}
async function writeValidatorFile(manifest, filePath) {
const dirname = _path.default.dirname(filePath);
if (!_fs.default.existsSync(dirname)) {
await _fs.default.promises.mkdir(dirname, {
recursive: true
});
}
await _fs.default.promises.writeFile(filePath, (0, _typegen.generateValidatorFile)(manifest));
}
//# sourceMappingURL=route-types-utils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,32 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { NextConfigRuntime } from '../../config-shared';
import type { UrlWithParsedQuery } from 'node:url';
import type { ServerCacheStatus } from '../../../next-devtools/dev-overlay/cache-indicator';
export type RevalidateFn = (config: {
urlPath: string;
revalidateHeaders: {
[key: string]: string | string[];
};
opts: {
unstable_onlyGenerated?: boolean;
};
}) => Promise<void>;
export type RouterServerContext = Record<string, {
hostname?: string;
revalidate?: RevalidateFn;
render404?: (req: IncomingMessage, res: ServerResponse, parsedUrl?: UrlWithParsedQuery, setHeaders?: boolean) => Promise<void>;
nextConfig?: NextConfigRuntime;
isCustomServer?: boolean;
experimentalTestProxy?: boolean;
logErrorWithOriginalStack?: (err: unknown, type: string) => void;
setIsrStatus?: (key: string, value: boolean | undefined) => void;
setReactDebugChannel?: (debugChannel: {
readable: ReadableStream<Uint8Array>;
}, htmlRequestId: string, requestId: string) => void;
setCacheStatus?: (status: ServerCacheStatus, htmlRequestId: string) => void;
sendErrorsToBrowser?: (errorsRscStream: ReadableStream<Uint8Array>, htmlRequestId: string) => void;
}>;
export declare const RouterServerContextSymbol: unique symbol;
export declare const routerServerGlobal: typeof globalThis & {
[RouterServerContextSymbol]?: RouterServerContext;
};

View File

@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
RouterServerContextSymbol: null,
routerServerGlobal: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
RouterServerContextSymbol: function() {
return RouterServerContextSymbol;
},
routerServerGlobal: function() {
return routerServerGlobal;
}
});
const RouterServerContextSymbol = Symbol.for('@next/router-server-methods');
const routerServerGlobal = globalThis;
//# sourceMappingURL=router-server-context.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/lib/router-utils/router-server-context.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { NextConfigRuntime } from '../../config-shared'\nimport type { UrlWithParsedQuery } from 'node:url'\nimport type { ServerCacheStatus } from '../../../next-devtools/dev-overlay/cache-indicator'\n\nexport type RevalidateFn = (config: {\n urlPath: string\n revalidateHeaders: { [key: string]: string | string[] }\n opts: { unstable_onlyGenerated?: boolean }\n}) => Promise<void>\n\n// The RouterServerContext contains instance specific\n// information that isn't available/relevant when\n// deployed in serverless environments, the key is\n// the relative project dir this allows separate contexts\n// when running multiple next instances in same process\nexport type RouterServerContext = Record<\n string,\n {\n // hostname the server is started with\n hostname?: string\n // revalidate function to bypass going through network\n // to invoke revalidate request (uses mocked req/res)\n revalidate?: RevalidateFn\n // function to render the 404 page\n render404?: (\n req: IncomingMessage,\n res: ServerResponse,\n parsedUrl?: UrlWithParsedQuery,\n setHeaders?: boolean\n ) => Promise<void>\n // exposing nextConfig for dev mode specifically\n nextConfig?: NextConfigRuntime\n // whether running in custom server mode\n isCustomServer?: boolean\n // whether test proxy is enabled\n experimentalTestProxy?: boolean\n // allow dev server to log with original stack\n logErrorWithOriginalStack?: (err: unknown, type: string) => void\n // allow setting ISR status in dev\n setIsrStatus?: (key: string, value: boolean | undefined) => void\n setReactDebugChannel?: (\n debugChannel: { readable: ReadableStream<Uint8Array> },\n htmlRequestId: string,\n requestId: string\n ) => void\n setCacheStatus?: (status: ServerCacheStatus, htmlRequestId: string) => void\n sendErrorsToBrowser?: (\n errorsRscStream: ReadableStream<Uint8Array>,\n htmlRequestId: string\n ) => void\n }\n>\n\nexport const RouterServerContextSymbol = Symbol.for(\n '@next/router-server-methods'\n)\n\nexport const routerServerGlobal = globalThis as typeof globalThis & {\n [RouterServerContextSymbol]?: RouterServerContext\n}\n"],"names":["RouterServerContextSymbol","routerServerGlobal","Symbol","for","globalThis"],"mappings":";;;;;;;;;;;;;;;IAsDaA,yBAAyB;eAAzBA;;IAIAC,kBAAkB;eAAlBA;;;AAJN,MAAMD,4BAA4BE,OAAOC,GAAG,CACjD;AAGK,MAAMF,qBAAqBG","ignoreList":[0]}

View File

@@ -0,0 +1,59 @@
import type { NextConfigComplete } from '../../config-shared';
import type { UnwrapPromise } from '../../../lib/coalesced-function';
import type { ProxyMatcher } from '../../../build/analysis/get-page-static-info';
import type { RoutesManifest } from '../../../build';
import type { MiddlewareRouteMatch } from '../../../shared/lib/router/utils/middleware-route-matcher';
import type { PropagateToWorkersField } from './types';
import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types';
import type { Telemetry } from '../../../telemetry/storage';
import type { IncomingMessage, ServerResponse } from 'http';
import type { LazyRenderServerInstance } from '../router-server';
export type SetupOpts = {
renderServer: LazyRenderServerInstance;
dir: string;
turbo?: boolean;
appDir?: string;
pagesDir?: string;
telemetry: Telemetry;
isCustomServer?: boolean;
fsChecker: UnwrapPromise<ReturnType<typeof import('./filesystem').setupFsCheck>>;
nextConfig: NextConfigComplete;
port: number;
onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined;
resetFetch: () => void;
};
export interface DevRoutesManifest {
version: number;
caseSensitive: RoutesManifest['caseSensitive'];
basePath: RoutesManifest['basePath'];
rewrites: RoutesManifest['rewrites'];
redirects: RoutesManifest['redirects'];
headers: RoutesManifest['headers'];
i18n: RoutesManifest['i18n'];
skipProxyUrlNormalize: RoutesManifest['skipProxyUrlNormalize'];
}
export type ServerFields = {
actualMiddlewareFile?: string | undefined;
actualInstrumentationHookFile?: string | undefined;
appPathRoutes?: Record<string, string | string[]>;
middleware?: {
page: string;
match: MiddlewareRouteMatch;
matchers?: ProxyMatcher[];
} | undefined;
hasAppNotFound?: boolean;
interceptionRoutes?: ReturnType<typeof import('./filesystem').buildCustomRoute>[];
setIsrStatus?: (key: string, value: boolean | undefined) => void;
resetFetch?: () => void;
};
export declare function propagateServerField(opts: SetupOpts, field: PropagateToWorkersField, args: any): Promise<void>;
export declare function setupDevBundler(opts: SetupOpts): Promise<{
serverFields: ServerFields;
hotReloader: NextJsHotReloaderInterface;
requestHandler: (req: IncomingMessage, res: ServerResponse) => Promise<{
finished: boolean;
}>;
logErrorWithOriginalStack: (err: unknown, type?: "unhandledRejection" | "uncaughtException" | "warning" | "app-dir") => void;
ensureMiddleware(requestUrl?: string): Promise<void>;
}>;
export type DevBundler = Awaited<ReturnType<typeof setupDevBundler>>;

View File

@@ -0,0 +1,970 @@
"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 _installbindings = require("../../../build/swc/install-bindings");
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 _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 _shared = require("../../../trace/shared");
const _findpagefile = require("../find-page-file");
const _events = require("../../../telemetry/events");
const _utils = require("../../../shared/lib/router/utils");
const _sortbypageexts = require("../../../build/sort-by-page-exts");
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 _shared1 = require("../../../build/webpack/plugins/next-types-plugin/shared");
const _hotreloadertypes = require("../../dev/hot-reloader-types");
const _pagetypes = require("../../../lib/page-types");
const _encryptionutilsserver = require("../../app-render/encryption-utils-server");
const _ismetadataroute = require("../../../lib/metadata/is-metadata-route");
const _getmetadataroute = require("../../../lib/metadata/get-metadata-route");
const _jsconfigpathsplugin = require("../../../build/webpack/plugins/jsconfig-paths-plugin");
const _store = require("../../../build/output/store");
const _utils2 = require("../../../shared/lib/turbopack/utils");
const _defineenv = require("../../../build/define-env");
const _internalerror = require("../../../shared/lib/turbopack/internal-error");
const _normalizepath = require("../../../lib/normalize-path");
const _constants1 = require("../../../lib/constants");
const _routetypesutils = require("./route-types-utils");
const _cachelifetypeutils = require("./cache-life-type-utils");
const _segment = require("../../../shared/lib/segment");
const _ensureleadingslash = require("../../../shared/lib/page-path/ensure-leading-slash");
const _lockfile = require("../../../build/lockfile");
const _magicidentifier = require("../../../shared/lib/magic-identifier");
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) {
const verifyResult = await (0, _verifytypescriptsetup.verifyTypeScriptSetup)({
dir: opts.dir,
distDir: opts.nextConfig.distDir,
typeCheckPreflight: false,
tsconfigPath: opts.nextConfig.typescript.tsconfigPath,
disableStaticImages: opts.nextConfig.images.disableStaticImages,
hasAppDir: !!opts.appDir,
hasPagesDir: !!opts.pagesDir,
isolatedDevBuild: opts.nextConfig.experimental.isolatedDevBuild,
appDir: opts.appDir,
pagesDir: opts.pagesDir
});
if (verifyResult.version) {
return true;
}
return false;
}
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, resetFetch } = opts;
const { useFileSystemPublicRoutes } = nextConfig;
const distDir = _path.default.join(opts.dir, opts.nextConfig.distDir);
(0, _shared.setGlobal)('distDir', distDir);
(0, _shared.setGlobal)('phase', _constants.PHASE_DEVELOPMENT_SERVER);
let lockfile;
if (opts.nextConfig.experimental.lockDistDir) {
_fs.default.mkdirSync(distDir, {
recursive: true
});
lockfile = await _lockfile.Lockfile.acquireWithRetriesOrExit(_path.default.join(distDir, 'lock'), 'next dev');
}
const validFileMatcher = (0, _findpagefile.createValidFileMatcher)(nextConfig.pageExtensions, appDir);
const serverFields = {};
// Update logging state once based on next.config.js when initializing
_store.store.setState({
logging: nextConfig.logging !== false
});
const hotReloader = opts.turbo ? await (async ()=>{
const createHotReloaderTurbopack = require('../../dev/hot-reloader-turbopack').createHotReloaderTurbopack;
return await createHotReloaderTurbopack(opts, serverFields, distDir, resetFetch, lockfile);
})() : await (async ()=>{
const HotReloader = process.env.NEXT_RSPACK ? require('../../dev/hot-reloader-rspack').default : require('../../dev/hot-reloader-webpack').default;
return new HotReloader(opts.dir, {
isSrcDir: opts.isSrcDir,
appDir,
pagesDir,
distDir,
config: opts.nextConfig,
buildId: 'development',
encryptionKey: await (0, _encryptionutilsserver.generateEncryptionKeyBase64)({
isBuild: false,
distDir
}),
telemetry: opts.telemetry,
rewrites: opts.fsChecker.rewrites,
previewProps: opts.fsChecker.prerenderManifest.preview,
resetFetch,
lockfile,
onDevServerCleanup: opts.onDevServerCleanup
});
})();
await hotReloader.start();
// have to write this after starting hot-reloader since that
// cleans the dist dir
const distTypesDir = _path.default.join(distDir, 'types');
await (0, _routetypesutils.writeRouteTypesManifest)({
appRoutes: {},
pageRoutes: {},
layoutRoutes: {},
appRouteHandlerRoutes: {},
redirectRoutes: {},
rewriteRoutes: {},
appPagePaths: new Set(),
pagesRouterPagePaths: new Set(),
layoutPaths: new Set(),
appRouteHandlers: new Set(),
pageApiRoutes: new Set(),
filePathToRoute: new Map()
}, _path.default.join(distTypesDir, 'routes.d.ts'), opts.nextConfig);
const routesManifestPath = _path.default.join(distDir, _constants.ROUTES_MANIFEST);
const routesManifest = {
version: 3,
caseSensitive: !!nextConfig.experimental.caseSensitiveRoutes,
basePath: nextConfig.basePath,
rewrites: opts.fsChecker.rewrites,
redirects: opts.fsChecker.redirects,
headers: opts.fsChecker.headers,
i18n: nextConfig.i18n || undefined,
skipProxyUrlNormalize: nextConfig.skipProxyUrlNormalize
};
await _fs.default.promises.writeFile(routesManifestPath, JSON.stringify(routesManifest));
const prerenderManifestPath = _path.default.join(distDir, _constants.PRERENDER_MANIFEST);
await _fs.default.promises.writeFile(prerenderManifestPath, JSON.stringify(opts.fsChecker.prerenderManifest, null, 2));
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({
// Watchpack default is 200ms which adds 200ms of dead time on bootup.
aggregateTimeout: 5,
ignored: (pathname)=>{
return !files.some((file)=>file.startsWith(pathname)) && !directories.some((d)=>pathname.startsWith(d) || d.startsWith(pathname));
}
});
const fileWatchTimes = new Map();
let enabledTypeScript = await verifyTypeScript(opts);
let previousClientRouterFilters;
let previousConflictingPagePaths = new Set();
const routeTypesFilePath = _path.default.join(distDir, 'types', 'routes.d.ts');
const validatorFilePath = _path.default.join(distDir, 'types', 'validator.ts');
let initialWatchTime = performance.now() + performance.timeOrigin;
wp.on('aggregated', async ()=>{
var _serverFields_middleware, _serverFields_middleware1;
let writeEnvDefinitions = false;
let typescriptStatusFromLastAggregation = enabledTypeScript;
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();
const appRouteHandlers = [];
const pageApiRoutes = [];
const pageRoutes = [];
const appRoutes = [];
const layoutRoutes = [];
const slots = [];
let envChange = false;
let tsconfigChange = false;
let conflictingPageChange = 0;
let hasRootAppNotFound = false;
const { appFiles, pageFiles, staticMetadataFiles } = opts.fsChecker;
appFiles.clear();
pageFiles.clear();
staticMetadataFiles.clear();
_shared1.devPageFiles.clear();
const sortedKnownFiles = [
...knownFiles.keys()
].sort((0, _sortbypageexts.sortByPageExts)(nextConfig.pageExtensions));
let proxyFilePath;
let middlewareFilePath;
for (const fileName of sortedKnownFiles){
if (!files.includes(fileName) && !directories.some((d)=>fileName.startsWith(d))) {
continue;
}
const { name: fileBaseName, dir: fileDir } = _path.default.parse(fileName);
const isAtConventionLevel = fileDir === dir || fileDir === _path.default.join(dir, 'src');
if (isAtConventionLevel && fileBaseName === _constants1.MIDDLEWARE_FILENAME) {
middlewareFilePath = fileName;
}
if (isAtConventionLevel && fileBaseName === _constants1.PROXY_FILENAME) {
proxyFilePath = fileName;
}
if (middlewareFilePath) {
if (proxyFilePath) {
const cwd = process.cwd();
throw Object.defineProperty(new Error(`Both ${_constants1.MIDDLEWARE_FILENAME} file "./${_path.default.relative(cwd, middlewareFilePath)}" and ${_constants1.PROXY_FILENAME} file "./${_path.default.relative(cwd, proxyFilePath)}" are detected. Please use "./${_path.default.relative(cwd, proxyFilePath)}" only. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`), "__NEXT_ERROR_CODE", {
value: "E900",
enumerable: false,
configurable: true
});
}
_log.warnOnce(`The "${_constants1.MIDDLEWARE_FILENAME}" file convention is deprecated. Please use "${_constants1.PROXY_FILENAME}" instead. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`);
}
const meta = knownFiles.get(fileName);
const watchTime = fileWatchTimes.get(fileName);
const nextWatchTime = meta == null ? void 0 : meta.timestamp;
// If the file is showing up for the first time or the meta.timestamp is changed since last time
// Files that were created before we started watching are not considered changed.
// If any file was created by Next.js while booting, we assume those changes
// are handled in the bootstrap phase.
// Files that existed before we booted should be handled during bootstrapping.
const fileChanged = watchTime === undefined && (nextWatchTime === undefined || nextWatchTime >= initialWatchTime) || watchTime && watchTime !== nextWatchTime;
fileWatchTimes.set(fileName, nextWatchTime);
if (envFiles.includes(fileName)) {
if (fileChanged) {
envChange = true;
}
continue;
}
if (tsconfigPaths.includes(fileName)) {
if (fileName.endsWith('tsconfig.json')) {
enabledTypeScript = true;
}
if (fileChanged) {
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 getStaticInfoIncludingLayouts = require('../../../build/get-static-info-including-layouts').getStaticInfoIncludingLayouts;
const staticInfo = await 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)) {
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 && appDir && (0, _ismetadataroute.isMetadataRouteFile)(fileName.replace(appDir, ''), nextConfig.pageExtensions, true)) {
const getPageStaticInfo = require('../../../build/analysis/get-page-static-info').getPageStaticInfo;
const staticInfo = await getPageStaticInfo({
pageFilePath: fileName,
nextConfig: {},
page: pageName,
isDev: true,
pageType: _pagetypes.PAGE_TYPES.APP
});
pageName = (0, _getmetadataroute.normalizeMetadataPageToRoute)(pageName, !!(staticInfo.generateSitemaps || staticInfo.generateImageMetadata));
}
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;
}
// Ignore files/directories starting with `_` in the app directory
if ((0, _normalizepathsep.normalizePathSep)(pageName).includes('/_')) {
continue;
}
// Record parallel route slots for layout typing
// May run multiple times (e.g. if a parallel route
// has both a layout and a page, and children) but that's fine
const segments = (0, _normalizepathsep.normalizePathSep)(pageName).split('/');
for(let i = segments.length - 1; i >= 0; i--){
const segment = segments[i];
if ((0, _segment.isParallelRouteSegment)(segment)) {
const parentPath = (0, _apppaths.normalizeAppPath)(segments.slice(0, i).join('/'));
const slotName = segment.slice(1);
// check if the slot already exists
if (slots.some((s)=>s.name === slotName && s.parent === parentPath)) continue;
slots.push({
name: slotName,
parent: parentPath
});
break;
}
}
// Record layouts
if (validFileMatcher.isAppLayoutPage(fileName)) {
layoutRoutes.push({
route: (0, _ensureleadingslash.ensureLeadingSlash)((0, _apppaths.normalizeAppPath)((0, _normalizepathsep.normalizePathSep)(pageName)).replace(/\/layout$/, '')),
filePath: fileName
});
}
if (!validFileMatcher.isAppRouterPage(fileName)) {
continue;
}
const originalPageName = pageName;
pageName = (0, _apppaths.normalizeAppPath)(pageName).replace(/%5F/g, '_');
if (!appPaths[pageName]) {
appPaths[pageName] = [];
}
appPaths[pageName].push(opts.turbo ? originalPageName.replace(/%5F/g, '_') : originalPageName);
if (useFileSystemPublicRoutes) {
// Static metadata files will be served from filesystem.
if (appDir && (0, _ismetadataroute.isStaticMetadataFile)(fileName.replace(appDir, ''))) {
staticMetadataFiles.set(pageName, fileName);
} else {
appFiles.add(pageName);
}
}
if (validFileMatcher.isAppRouterRoute(fileName)) {
appRouteHandlers.push({
route: (0, _normalizepathsep.normalizePathSep)(pageName),
filePath: fileName
});
} else {
appRoutes.push({
route: (0, _normalizepathsep.normalizePathSep)(pageName),
filePath: fileName
});
}
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);
}
if (pageName.startsWith('/api/')) {
pageApiRoutes.push({
route: (0, _normalizepathsep.normalizePathSep)(pageName),
filePath: fileName
});
} else {
pageRoutes.push({
route: (0, _normalizepathsep.normalizePathSep)(pageName),
filePath: fileName
});
}
}
// Record pages
if (isAppPath) {
appPageFilePaths.set(pageName, fileName);
} else {
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(Object.defineProperty(new Error(errorMessage), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
}));
} 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 (envChange || tsconfigChange) {
if (envChange) {
writeEnvDefinitions = true;
await propagateServerField(opts, 'loadEnvConfig', [
{
dev: true,
forceReload: true
}
]);
}
if (hotReloader.turbopackProject) {
var _opts_nextConfig_turbopack;
const hasRewrites = opts.fsChecker.rewrites.afterFiles.length > 0 || opts.fsChecker.rewrites.beforeFiles.length > 0 || opts.fsChecker.rewrites.fallback.length > 0;
const rootPath = ((_opts_nextConfig_turbopack = opts.nextConfig.turbopack) == null ? void 0 : _opts_nextConfig_turbopack.root) || opts.nextConfig.outputFileTracingRoot || opts.dir;
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,
projectPath: opts.dir,
rewrites: opts.fsChecker.rewrites
}),
rootPath,
projectPath: (0, _normalizepath.normalizePath)(_path.default.relative(rootPath, dir))
});
} else {
var _hotReloader_activeWebpackConfigs;
let tsconfigResult;
// This is not relevant for Turbopack because tsconfig/jsconfig is handled internally.
if (tsconfigChange) {
try {
const loadJsConfig = require('../../../build/load-jsconfig').default;
tsconfigResult = await loadJsConfig(dir, nextConfig);
} catch (_) {
/* do we want to log if there are syntax errors in tsconfig while editing? */ }
}
(_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 instanceof _jsconfigpathsplugin.JsConfigPathsPlugin && 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 == null ? void 0 : currentResolvedBaseUrl.baseUrl));
if (resolvedBaseUrl) {
if (resolvedBaseUrl.baseUrl !== (currentResolvedBaseUrl == null ? void 0 : 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, _defineenv.getDefineEnv)({
isTurbopack: false,
clientRouterFilters,
config: nextConfig,
dev: true,
distDir,
fetchCacheKeyPrefix: opts.nextConfig.experimental.fetchCacheKeyPrefix,
hasRewrites,
isClient,
isEdgeServer,
isNodeServer,
middlewareMatchers: undefined,
projectPath: opts.dir,
rewrites: opts.fsChecker.rewrites
});
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(Object.defineProperty(new _utils1.NestedMiddlewareError(nestedMiddleware, dir, pagesDir || appDir), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
}).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.getNamedRouteRegex)(page, {
prefixRouteKeys: true
});
return {
regex: regex.re.toString(),
namedRegex: regex.namedRegex,
routeKeys: regex.routeKeys,
match: (0, _routematcher.getRouteMatcher)(regex),
page
};
});
const dataRoutes = [];
for (const page of sortedRoutes){
const route = (0, _builddataroute.buildDataRoute)(page, 'development');
const routeRegex = (0, _routeregex.getNamedRouteRegex)(route.page, {
prefixRouteKeys: true
});
dataRoutes.push({
...route,
regex: routeRegex.re.toString(),
namedRegex: routeRegex.namedRegex,
routeKeys: routeRegex.routeKeys,
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);
// For Turbopack ADDED_PAGE and REMOVED_PAGE are implemented in hot-reloader-turbopack.ts
// in order to avoid a race condition where ADDED_PAGE and REMOVED_PAGE are sent before Turbopack picked up the file change.
if (!opts.turbo) {
// Reload the matchers. The filesystem would have been written to,
// and the matchers need to re-scan it to update the router.
// Reloading the matchers should happen before `ADDED_PAGE` or `REMOVED_PAGE` is sent over the websocket
// otherwise it sends the event too early.
await propagateServerField(opts, 'reloadMatchers', undefined);
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({
type: _hotreloadertypes.HMR_MESSAGE_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE,
data: [
{
devPagesManifest: true
}
]
});
addedRoutes.forEach((route)=>{
hotReloader.send({
type: _hotreloadertypes.HMR_MESSAGE_SENT_TO_BROWSER.ADDED_PAGE,
data: [
route
]
});
});
removedRoutes.forEach((route)=>{
hotReloader.send({
type: _hotreloadertypes.HMR_MESSAGE_SENT_TO_BROWSER.REMOVED_PAGE,
data: [
route
]
});
});
}
}
prevSortedRoutes = sortedRoutes;
if (enabledTypeScript) {
var _nextConfig_experimental;
// Using === false to make the check clearer.
if (typescriptStatusFromLastAggregation === false) {
// 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 (writeEnvDefinitions && ((_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.typedEnv)) {
// TODO: The call to propagateServerField 'loadEnvConfig' causes the env to be loaded twice on env file changes.
const loadEnvConfig = require('@next/env').loadEnvConfig;
const { loadedEnvFiles } = loadEnvConfig(dir, process.env.NODE_ENV === 'development', // Silent as it's the second time `loadEnvConfig` is called in this pass.
undefined, true);
const createEnvDefinitions = require('../experimental/create-env-definitions').createEnvDefinitions;
await createEnvDefinitions({
distDir,
loadedEnvFiles: [
...loadedEnvFiles,
{
path: nextConfig.configFileName,
env: nextConfig.env,
contents: ''
}
]
});
}
const routeTypesManifest = await (0, _routetypesutils.createRouteTypesManifest)({
dir,
pageRoutes,
appRoutes,
layoutRoutes,
slots,
redirects: opts.nextConfig.redirects,
rewrites: opts.nextConfig.rewrites,
// Ensure relative paths in validator.ts are computed from validatorFilePath,
// matching behavior of build and CLI typegen.
validatorFilePath,
appRouteHandlers,
pageApiRoutes
});
await (0, _routetypesutils.writeRouteTypesManifest)(routeTypesManifest, routeTypesFilePath, opts.nextConfig);
await (0, _routetypesutils.writeValidatorFile)(routeTypesManifest, validatorFilePath);
// Generate cache-life types if cacheLife config exists
const cacheLifeFilePath = _path.default.join(distTypesDir, 'cache-life.d.ts');
(0, _cachelifetypeutils.writeCacheLifeTypes)(opts.nextConfig.cacheLife, cacheLifeFilePath);
}
if (!resolved) {
resolve();
resolved = true;
}
} catch (e) {
if (!resolved) {
reject(e);
resolved = true;
} else {
_log.warn('Failed to reload dynamic routes:', e);
}
}
});
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_CLIENT_MIDDLEWARE_MANIFEST}`;
opts.fsChecker.devVirtualFsItems.add(devMiddlewareManifestPath);
const devTurbopackMiddlewareManifestPath = `/_next/${_constants.CLIENT_STATIC_FILES_PATH}/development/${_constants.TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST}`;
opts.fsChecker.devVirtualFsItems.add(devTurbopackMiddlewareManifestPath);
async function requestHandler(req, res) {
var _parsedUrl_pathname, _parsedUrl_pathname1, _parsedUrl_pathname2;
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', _constants1.JSON_CONTENT_TYPE_HEADER);
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)) || ((_parsedUrl_pathname2 = parsedUrl.pathname) == null ? void 0 : _parsedUrl_pathname2.includes(devTurbopackMiddlewareManifestPath))) {
var _serverFields_middleware;
res.statusCode = 200;
res.setHeader('Content-Type', _constants1.JSON_CONTENT_TYPE_HEADER);
res.end(JSON.stringify(((_serverFields_middleware = serverFields.middleware) == null ? void 0 : _serverFields_middleware.matchers) || []));
return {
finished: true
};
}
return {
finished: false
};
}
function logErrorWithOriginalStack(err, type) {
if (err instanceof Error) {
err.message = (0, _magicidentifier.deobfuscateText)(err.message);
}
if (err instanceof _utils2.ModuleBuildError) {
// Errors that may come from issues from the user's code
_log.error(err.message);
} else if (err instanceof _internalerror.TurbopackInternalError) {
// An internal Turbopack error that has been handled by next-swc, written
// to disk and a simplified message shown to user on the Rust side.
} else if (type === 'warning') {
_log.warn(err);
} else if (type === 'app-dir') {
_log.error(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) {
var _opts_nextConfig_experimental;
const isSrcDir = _path.default.relative(opts.dir, opts.pagesDir || opts.appDir || '').startsWith('src');
await (0, _installbindings.installBindings)((_opts_nextConfig_experimental = opts.nextConfig.experimental) == null ? void 0 : _opts_nextConfig_experimental.useWasmBinary);
const result = await startWatcher({
...opts,
isSrcDir
});
opts.telemetry.record((0, _events.eventCliSession)(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
})
}));
// Track build features for dev server here:
opts.telemetry.record({
eventName: _events.EVENT_BUILD_FEATURE_USAGE,
payload: {
featureName: 'turbopackFileSystemCache',
invocationCount: (0, _utils2.isFileSystemCacheEnabledForDev)(opts.nextConfig) ? 1 : 0
}
});
return result;
}
// Returns a trace rewritten through Turbopack's sourcemaps
//# sourceMappingURL=setup-dev-bundler.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
import type { RouteTypesManifest } from './route-types-utils';
export declare function generateLinkTypesFile(routesManifest: RouteTypesManifest): string;
export declare function generateValidatorFile(routesManifest: RouteTypesManifest): string;
export declare function generateRouteTypesFile(routesManifest: RouteTypesManifest): string;

View File

@@ -0,0 +1,613 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
generateLinkTypesFile: null,
generateRouteTypesFile: null,
generateValidatorFile: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
generateLinkTypesFile: function() {
return generateLinkTypesFile;
},
generateRouteTypesFile: function() {
return generateRouteTypesFile;
},
generateValidatorFile: function() {
return generateValidatorFile;
}
});
const _isdynamic = require("../../../shared/lib/router/utils/is-dynamic");
function generateRouteTypes(routesManifest) {
const appRoutes = Object.keys(routesManifest.appRoutes).sort();
const pageRoutes = Object.keys(routesManifest.pageRoutes).sort();
const layoutRoutes = Object.keys(routesManifest.layoutRoutes).sort();
const redirectRoutes = Object.keys(routesManifest.redirectRoutes).sort();
const rewriteRoutes = Object.keys(routesManifest.rewriteRoutes).sort();
let result = '';
// Generate AppRoutes union type (pages only)
if (appRoutes.length > 0) {
result += `type AppRoutes = ${appRoutes.map((route)=>JSON.stringify(route)).join(' | ')}\n`;
} else {
result += 'type AppRoutes = never\n';
}
// Generate AppRouteHandlerRoutes union type for route handlers
const appRouteHandlerRoutes = Object.keys(routesManifest.appRouteHandlerRoutes).sort();
const hasAppRouteHandlers = appRouteHandlerRoutes.length > 0;
if (hasAppRouteHandlers) {
result += `type AppRouteHandlerRoutes = ${appRouteHandlerRoutes.map((route)=>JSON.stringify(route)).join(' | ')}\n`;
}
// Generate PageRoutes union type
if (pageRoutes.length > 0) {
result += `type PageRoutes = ${pageRoutes.map((route)=>JSON.stringify(route)).join(' | ')}\n`;
} else {
result += 'type PageRoutes = never\n';
}
// Generate LayoutRoutes union type
if (layoutRoutes.length > 0) {
result += `type LayoutRoutes = ${layoutRoutes.map((route)=>JSON.stringify(route)).join(' | ')}\n`;
} else {
result += 'type LayoutRoutes = never\n';
}
// Generate RedirectRoutes union type
if (redirectRoutes.length > 0) {
result += `type RedirectRoutes = ${redirectRoutes.map((route)=>JSON.stringify(route)).join(' | ')}\n`;
} else {
result += 'type RedirectRoutes = never\n';
}
// Generate RewriteRoutes union type
if (rewriteRoutes.length > 0) {
result += `type RewriteRoutes = ${rewriteRoutes.map((route)=>JSON.stringify(route)).join(' | ')}\n`;
} else {
result += 'type RewriteRoutes = never\n';
}
// Only include AppRouteHandlerRoutes in Routes union if there are actual route handlers
const routeUnionParts = [
'AppRoutes',
'PageRoutes',
'LayoutRoutes',
'RedirectRoutes',
'RewriteRoutes'
];
if (hasAppRouteHandlers) {
routeUnionParts.push('AppRouteHandlerRoutes');
}
result += `type Routes = ${routeUnionParts.join(' | ')}\n`;
return result;
}
function generateParamTypes(routesManifest) {
const allRoutes = {
...routesManifest.appRoutes,
...routesManifest.appRouteHandlerRoutes,
...routesManifest.pageRoutes,
...routesManifest.layoutRoutes,
...routesManifest.redirectRoutes,
...routesManifest.rewriteRoutes
};
let paramTypes = 'interface ParamMap {\n';
// Sort routes deterministically for consistent output
const sortedRoutes = Object.entries(allRoutes).sort(([a], [b])=>a.localeCompare(b));
for (const [route, routeInfo] of sortedRoutes){
const { groups } = routeInfo;
// For static routes (no dynamic segments), we can produce an empty parameter map.
if (!(0, _isdynamic.isDynamicRoute)(route) || Object.keys(groups ?? {}).length === 0) {
paramTypes += ` ${JSON.stringify(route)}: {}\n`;
continue;
}
let paramType = '{';
// Process each group based on its properties
for (const [key, group] of Object.entries(groups)){
const escapedKey = JSON.stringify(key);
if (group.repeat) {
// Catch-all parameters
if (group.optional) {
paramType += ` ${escapedKey}?: string[];`;
} else {
paramType += ` ${escapedKey}: string[];`;
}
} else {
// Regular parameters
if (group.optional) {
paramType += ` ${escapedKey}?: string;`;
} else {
paramType += ` ${escapedKey}: string;`;
}
}
}
paramType += ' }';
paramTypes += ` ${JSON.stringify(route)}: ${paramType}\n`;
}
paramTypes += '}\n';
return paramTypes;
}
function generateLayoutSlotMap(routesManifest) {
let slotMap = 'interface LayoutSlotMap {\n';
// Sort routes deterministically for consistent output
const sortedLayoutRoutes = Object.entries(routesManifest.layoutRoutes).sort(([a], [b])=>a.localeCompare(b));
for (const [route, routeInfo] of sortedLayoutRoutes){
if ('slots' in routeInfo) {
const slots = routeInfo.slots.sort();
if (slots.length > 0) {
slotMap += ` ${JSON.stringify(route)}: ${slots.map((slot)=>JSON.stringify(slot)).join(' | ')}\n`;
} else {
slotMap += ` ${JSON.stringify(route)}: never\n`;
}
} else {
slotMap += ` ${JSON.stringify(route)}: never\n`;
}
}
slotMap += '}\n';
return slotMap;
}
// Helper function to format routes to route types (matches the plugin logic exactly)
function formatRouteToRouteType(route) {
const isDynamic = (0, _isdynamic.isDynamicRoute)(route);
if (isDynamic) {
route = route.split('/').map((part)=>{
if (part.startsWith('[') && part.endsWith(']')) {
if (part.startsWith('[...')) {
// /[...slug]
return `\${CatchAllSlug<T>}`;
} else if (part.startsWith('[[...') && part.endsWith(']]')) {
// /[[...slug]]
return `\${OptionalCatchAllSlug<T>}`;
}
// /[slug]
return `\${SafeSlug<T>}`;
}
return part;
}).join('/');
}
return {
isDynamic,
routeType: route
};
}
// Helper function to serialize route types (matches the plugin logic exactly)
function serializeRouteTypes(routeTypes) {
// route collection is not deterministic, this makes the output of the file deterministic
return routeTypes.sort().map((route)=>`\n | \`${route}\``).join('');
}
function generateLinkTypesFile(routesManifest) {
// Generate serialized static and dynamic routes for the internal namespace
// Build a unified set of routes across app/pages/redirect/rewrite as well as
// app route handlers and Pages Router API routes.
const allRoutesSet = new Set([
...Object.keys(routesManifest.appRoutes),
...Object.keys(routesManifest.pageRoutes),
...Object.keys(routesManifest.redirectRoutes),
...Object.keys(routesManifest.rewriteRoutes),
// Allow linking to App Route Handlers (e.g. `/logout/route.ts`)
...Object.keys(routesManifest.appRouteHandlerRoutes),
// Allow linking to Pages Router API routes (e.g. `/api/*`)
...Array.from(routesManifest.pageApiRoutes)
]);
const staticRouteTypes = [];
const dynamicRouteTypes = [];
// Process each route using the same logic as the plugin
for (const route of allRoutesSet){
const { isDynamic, routeType } = formatRouteToRouteType(route);
if (isDynamic) {
dynamicRouteTypes.push(routeType);
} else {
staticRouteTypes.push(routeType);
}
}
const serializedStaticRouteTypes = serializeRouteTypes(staticRouteTypes);
const serializedDynamicRouteTypes = serializeRouteTypes(dynamicRouteTypes);
// If both StaticRoutes and DynamicRoutes are empty, fallback to type 'string & {}'.
const routeTypesFallback = !serializedStaticRouteTypes && !serializedDynamicRouteTypes ? 'string & {}' : '';
return `// This file is generated automatically by Next.js
// Do not edit this file manually
// Type definitions for Next.js routes
/**
* Internal types used by the Next.js router and Link component.
* These types are not meant to be used directly.
* @internal
*/
declare namespace __next_route_internal_types__ {
type SearchOrHash = \`?\${string}\` | \`#\${string}\`
type WithProtocol = \`\${string}:\${string}\`
type Suffix = '' | SearchOrHash
type SafeSlug<S extends string> = S extends \`\${string}/\${string}\`
? never
: S extends \`\${string}\${SearchOrHash}\`
? never
: S extends ''
? never
: S
type CatchAllSlug<S extends string> = S extends \`\${string}\${SearchOrHash}\`
? never
: S extends ''
? never
: S
type OptionalCatchAllSlug<S extends string> =
S extends \`\${string}\${SearchOrHash}\` ? never : S
type StaticRoutes = ${serializedStaticRouteTypes || 'never'}
type DynamicRoutes<T extends string = string> = ${serializedDynamicRouteTypes || 'never'}
type RouteImpl<T> = ${routeTypesFallback || `
${// This keeps autocompletion working for static routes.
'| StaticRoutes'}
| SearchOrHash
| WithProtocol
| \`\${StaticRoutes}\${SearchOrHash}\`
| (T extends \`\${DynamicRoutes<infer _>}\${Suffix}\` ? T : never)
`}
}
declare module 'next' {
export { default } from 'next/types.js'
export * from 'next/types.js'
export type Route<T extends string = string> =
__next_route_internal_types__.RouteImpl<T>
}
declare module 'next/link' {
export { useLinkStatus } from 'next/dist/client/link.js'
import type { LinkProps as OriginalLinkProps } from 'next/dist/client/link.js'
import type { AnchorHTMLAttributes, DetailedHTMLProps } from 'react'
import type { UrlObject } from 'url'
type LinkRestProps = Omit<
Omit<
DetailedHTMLProps<
AnchorHTMLAttributes<HTMLAnchorElement>,
HTMLAnchorElement
>,
keyof OriginalLinkProps
> &
OriginalLinkProps,
'href'
>
export type LinkProps<RouteInferType> = LinkRestProps & {
/**
* The path or URL to navigate to. This is the only required prop. It can also be an object.
* @see https://nextjs.org/docs/api-reference/next/link
*/
href: __next_route_internal_types__.RouteImpl<RouteInferType> | UrlObject
}
export default function Link<RouteType>(props: LinkProps<RouteType>): JSX.Element
}
declare module 'next/navigation' {
export * from 'next/dist/client/components/navigation.js'
import type { NavigateOptions, AppRouterInstance as OriginalAppRouterInstance } from 'next/dist/shared/lib/app-router-context.shared-runtime.js'
import type { RedirectType } from 'next/dist/client/components/redirect-error.js'
interface AppRouterInstance extends OriginalAppRouterInstance {
/**
* Navigate to the provided href.
* Pushes a new history entry.
*/
push<RouteType>(href: __next_route_internal_types__.RouteImpl<RouteType>, options?: NavigateOptions): void
/**
* Navigate to the provided href.
* Replaces the current history entry.
*/
replace<RouteType>(href: __next_route_internal_types__.RouteImpl<RouteType>, options?: NavigateOptions): void
/**
* Prefetch the provided href.
*/
prefetch<RouteType>(href: __next_route_internal_types__.RouteImpl<RouteType>): void
}
export function useRouter(): AppRouterInstance;
/**
* This function allows you to redirect the user to another URL. It can be used in
* [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),
* [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and
* [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
*
* - In a Server Component, this will insert a meta tag to redirect the user to the target page.
* - In a Route Handler or Server Action, it will serve a 307/303 to the caller.
* - In a Server Action, type defaults to 'push' and 'replace' elsewhere.
*
* Read more: [Next.js Docs: redirect](https://nextjs.org/docs/app/api-reference/functions/redirect)
*/
export function redirect<RouteType>(
/** The URL to redirect to */
url: __next_route_internal_types__.RouteImpl<RouteType>,
type?: RedirectType
): never;
/**
* This function allows you to redirect the user to another URL. It can be used in
* [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),
* [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and
* [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
*
* - In a Server Component, this will insert a meta tag to redirect the user to the target page.
* - In a Route Handler or Server Action, it will serve a 308/303 to the caller.
*
* Read more: [Next.js Docs: redirect](https://nextjs.org/docs/app/api-reference/functions/redirect)
*/
export function permanentRedirect<RouteType>(
/** The URL to redirect to */
url: __next_route_internal_types__.RouteImpl<RouteType>,
type?: RedirectType
): never;
}
declare module 'next/form' {
import type { FormProps as OriginalFormProps } from 'next/dist/client/form.js'
type FormRestProps = Omit<OriginalFormProps, 'action'>
export type FormProps<RouteInferType> = {
/**
* \`action\` can be either a \`string\` or a function.
* - If \`action\` is a string, it will be interpreted as a path or URL to navigate to when the form is submitted.
* The path will be prefetched when the form becomes visible.
* - If \`action\` is a function, it will be called when the form is submitted. See the [React docs](https://react.dev/reference/react-dom/components/form#props) for more.
*/
action: __next_route_internal_types__.RouteImpl<RouteInferType> | ((formData: FormData) => void)
} & FormRestProps
export default function Form<RouteType>(props: FormProps<RouteType>): JSX.Element
}
`;
}
function generateValidatorFile(routesManifest) {
const generateValidations = (paths, type, pathToRouteMap)=>paths.sort()// Only validate TypeScript files - JavaScript files have too many type inference limitations
.filter((filePath)=>filePath.endsWith('.ts') || filePath.endsWith('.tsx')).filter(// Don't include metadata routes or pages
// (e.g. /manifest.webmanifest)
(filePath)=>type !== 'AppPageConfig' || filePath.endsWith('page.ts') || filePath.endsWith('page.tsx')).map((filePath)=>{
// Keep the file extension for TypeScript imports to support node16 module resolution
const importPath = filePath;
const route = pathToRouteMap == null ? void 0 : pathToRouteMap.get(filePath);
const typeWithRoute = route && (type === 'AppPageConfig' || type === 'LayoutConfig' || type === 'RouteHandlerConfig') ? `${type}<${JSON.stringify(route)}>` : type;
// NOTE: we previously used `satisfies` here, but it's not supported by TypeScript 4.8 and below.
// If we ever raise the TS minimum version, we can switch back.
return `// Validate ${filePath}
{
type __IsExpected<Specific extends ${typeWithRoute}> = Specific
const handler = {} as typeof import(${JSON.stringify(importPath.replace(/\.tsx?$/, '.js'))})
type __Check = __IsExpected<typeof handler>
// @ts-ignore
type __Unused = __Check
}`;
}).join('\n\n');
// Use direct mappings from the manifest
// Generate validations for different route types
const appPageValidations = generateValidations(Array.from(routesManifest.appPagePaths).sort(), 'AppPageConfig', routesManifest.filePathToRoute);
const appRouteHandlerValidations = generateValidations(Array.from(routesManifest.appRouteHandlers).sort(), 'RouteHandlerConfig', routesManifest.filePathToRoute);
const pagesRouterPageValidations = generateValidations(Array.from(routesManifest.pagesRouterPagePaths).sort(), 'PagesPageConfig');
const pagesApiRouteValidations = generateValidations(Array.from(routesManifest.pageApiRoutes).sort(), 'ApiRouteConfig');
const layoutValidations = generateValidations(Array.from(routesManifest.layoutPaths).sort(), 'LayoutConfig', routesManifest.filePathToRoute);
const hasAppRouteHandlers = Object.keys(routesManifest.appRouteHandlerRoutes).length > 0;
// Build type definitions based on what's actually used
let typeDefinitions = '';
if (appPageValidations) {
typeDefinitions += `type AppPageConfig<Route extends AppRoutes = AppRoutes> = {
default: React.ComponentType<{ params: Promise<ParamMap[Route]> } & any> | ((props: { params: Promise<ParamMap[Route]> } & any) => React.ReactNode | Promise<React.ReactNode> | never | void | Promise<void>)
generateStaticParams?: (props: { params: ParamMap[Route] }) => Promise<any[]> | any[]
generateMetadata?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: ResolvingMetadata
) => Promise<any> | any
generateViewport?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: ResolvingViewport
) => Promise<any> | any
metadata?: any
viewport?: any
}
`;
}
if (pagesRouterPageValidations) {
typeDefinitions += `type PagesPageConfig = {
default: React.ComponentType<any> | ((props: any) => React.ReactNode | Promise<React.ReactNode> | never | void)
getStaticProps?: (context: any) => Promise<any> | any
getStaticPaths?: (context: any) => Promise<any> | any
getServerSideProps?: (context: any) => Promise<any> | any
getInitialProps?: (context: any) => Promise<any> | any
/**
* Segment configuration for legacy Pages Router pages.
* Validated at build-time by parsePagesSegmentConfig.
*/
config?: {
maxDuration?: number
runtime?: 'edge' | 'experimental-edge' | 'nodejs' | string // necessary unless config is exported as const
regions?: string[]
}
}
`;
}
if (layoutValidations) {
typeDefinitions += `type LayoutConfig<Route extends LayoutRoutes = LayoutRoutes> = {
default: React.ComponentType<LayoutProps<Route>> | ((props: LayoutProps<Route>) => React.ReactNode | Promise<React.ReactNode> | never | void | Promise<void>)
generateStaticParams?: (props: { params: ParamMap[Route] }) => Promise<any[]> | any[]
generateMetadata?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: ResolvingMetadata
) => Promise<any> | any
generateViewport?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: ResolvingViewport
) => Promise<any> | any
metadata?: any
viewport?: any
}
`;
}
if (appRouteHandlerValidations) {
typeDefinitions += `type RouteHandlerConfig<Route extends AppRouteHandlerRoutes = AppRouteHandlerRoutes> = {
GET?: (request: NextRequest, context: { params: Promise<ParamMap[Route]> }) => Promise<Response | void> | Response | void
POST?: (request: NextRequest, context: { params: Promise<ParamMap[Route]> }) => Promise<Response | void> | Response | void
PUT?: (request: NextRequest, context: { params: Promise<ParamMap[Route]> }) => Promise<Response | void> | Response | void
PATCH?: (request: NextRequest, context: { params: Promise<ParamMap[Route]> }) => Promise<Response | void> | Response | void
DELETE?: (request: NextRequest, context: { params: Promise<ParamMap[Route]> }) => Promise<Response | void> | Response | void
HEAD?: (request: NextRequest, context: { params: Promise<ParamMap[Route]> }) => Promise<Response | void> | Response | void
OPTIONS?: (request: NextRequest, context: { params: Promise<ParamMap[Route]> }) => Promise<Response | void> | Response | void
}
`;
}
if (pagesApiRouteValidations) {
typeDefinitions += `type ApiRouteConfig = {
default: (req: any, res: any) => ReturnType<NextApiHandler>
config?: {
api?: {
bodyParser?: boolean | { sizeLimit?: string }
responseLimit?: string | number | boolean
externalResolver?: boolean
}
runtime?: 'edge' | 'experimental-edge' | 'nodejs' | string // necessary unless config is exported as const
maxDuration?: number
}
}
`;
}
// Build import statement based on what's actually needed
const routeImports = [];
// Only import AppRoutes if there are app pages
if (appPageValidations) {
routeImports.push('AppRoutes');
}
// Only import LayoutRoutes if there are layouts
if (layoutValidations) {
routeImports.push('LayoutRoutes');
}
// Only import ParamMap if there are routes that use it
if (appPageValidations || layoutValidations || appRouteHandlerValidations) {
routeImports.push('ParamMap');
}
if (hasAppRouteHandlers) {
routeImports.push('AppRouteHandlerRoutes');
}
const routeImportStatement = routeImports.length > 0 ? `import type { ${routeImports.join(', ')} } from "./routes.js"` : '';
const nextRequestImport = hasAppRouteHandlers ? "import type { NextRequest } from 'next/server.js'\n" : '';
// Conditionally import types from next/types, merged into a single statement
const nextTypes = [];
if (pagesApiRouteValidations) {
nextTypes.push('NextApiHandler');
}
if (appPageValidations || layoutValidations) {
nextTypes.push('ResolvingMetadata', 'ResolvingViewport');
}
const nextTypesImport = nextTypes.length > 0 ? `import type { ${nextTypes.join(', ')} } from "next/types.js"\n` : '';
return `// This file is generated automatically by Next.js
// Do not edit this file manually
// This file validates that all pages and layouts export the correct types
${routeImportStatement}
${nextTypesImport}${nextRequestImport}
${typeDefinitions}
${appPageValidations}
${appRouteHandlerValidations}
${pagesRouterPageValidations}
${pagesApiRouteValidations}
${layoutValidations}
`;
}
function generateRouteTypesFile(routesManifest) {
const routeTypes = generateRouteTypes(routesManifest);
const paramTypes = generateParamTypes(routesManifest);
const layoutSlotMap = generateLayoutSlotMap(routesManifest);
const hasAppRouteHandlers = Object.keys(routesManifest.appRouteHandlerRoutes).length > 0;
// Build export statement based on what's actually generated
const routeExports = [
'AppRoutes',
'PageRoutes',
'LayoutRoutes',
'RedirectRoutes',
'RewriteRoutes',
'ParamMap'
];
if (hasAppRouteHandlers) {
routeExports.push('AppRouteHandlerRoutes');
}
const exportStatement = `export type { ${routeExports.join(', ')} }`;
const routeContextInterface = hasAppRouteHandlers ? `
/**
* Context for Next.js App Router route handlers
* @example
* \`\`\`tsx
* export async function GET(request: NextRequest, context: RouteContext<'/api/users/[id]'>) {
* const { id } = await context.params
* return Response.json({ id })
* }
* \`\`\`
*/
interface RouteContext<AppRouteHandlerRoute extends AppRouteHandlerRoutes> {
params: Promise<ParamMap[AppRouteHandlerRoute]>
}` : '';
return `// This file is generated automatically by Next.js
// Do not edit this file manually
${routeTypes}
${paramTypes}
export type ParamsOf<Route extends Routes> = ParamMap[Route]
${layoutSlotMap}
${exportStatement}
declare global {
/**
* Props for Next.js App Router page components
* @example
* \`\`\`tsx
* export default function Page(props: PageProps<'/blog/[slug]'>) {
* const { slug } = await props.params
* return <div>Blog post: {slug}</div>
* }
* \`\`\`
*/
interface PageProps<AppRoute extends AppRoutes> {
params: Promise<ParamMap[AppRoute]>
searchParams: Promise<Record<string, string | string[] | undefined>>
}
/**
* Props for Next.js App Router layout components
* @example
* \`\`\`tsx
* export default function Layout(props: LayoutProps<'/dashboard'>) {
* return <div>{props.children}</div>
* }
* \`\`\`
*/
type LayoutProps<LayoutRoute extends LayoutRoutes> = {
params: Promise<ParamMap[LayoutRoute]>
children: React.ReactNode
} & {
[K in LayoutSlotMap[LayoutRoute]]: React.ReactNode
}${routeContextInterface}
}
`;
}
//# sourceMappingURL=typegen.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export type PropagateToWorkersField = 'actualMiddlewareFile' | 'actualInstrumentationHookFile' | 'reloadMatchers' | 'loadEnvConfig' | 'appPathRoutes' | 'middleware' | 'renderOpts';

View File

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

View File

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