This commit is contained in:
Kismet Hasanaj
2026-05-02 20:07:02 +02:00
parent ce8672e283
commit 34dc9aec52
9428 changed files with 1733330 additions and 0 deletions
+46
View File
@@ -0,0 +1,46 @@
import path from 'path';
import { IncrementalCache } from '../../server/lib/incremental-cache';
import { hasNextSupport } from '../../server/ci-info';
import { nodeFs } from '../../server/lib/node-fs-methods';
import { interopDefault } from '../../lib/interop-default';
import { formatDynamicImportPath } from '../../lib/format-dynamic-import-path';
import { initializeCacheHandlers, setCacheHandler } from '../../server/use-cache/handlers';
export async function createIncrementalCache({ cacheHandler, cacheMaxMemorySize, fetchCacheKeyPrefix, distDir, dir, flushToDisk, cacheHandlers, requestHeaders }) {
// Custom cache handler overrides.
let CacheHandler;
if (cacheHandler) {
CacheHandler = interopDefault(await import(formatDynamicImportPath(dir, cacheHandler)).then((mod)=>mod.default || mod));
}
if (cacheHandlers && initializeCacheHandlers(cacheMaxMemorySize)) {
for (const [kind, handler] of Object.entries(cacheHandlers)){
if (!handler) continue;
setCacheHandler(kind, interopDefault(await import(formatDynamicImportPath(dir, handler)).then((mod)=>mod.default || mod)));
}
}
const incrementalCache = new IncrementalCache({
dev: false,
requestHeaders: requestHeaders || {},
flushToDisk,
maxMemoryCacheSize: cacheMaxMemorySize,
fetchCacheKeyPrefix,
getPrerenderManifest: ()=>({
version: 4,
routes: {},
dynamicRoutes: {},
preview: {
previewModeEncryptionKey: '',
previewModeId: '',
previewModeSigningKey: ''
},
notFoundRoutes: []
}),
fs: nodeFs,
serverDistDir: path.join(distDir, 'server'),
CurCacheHandler: CacheHandler,
minimalMode: hasNextSupport
});
globalThis.__incrementalCache = incrementalCache;
return incrementalCache;
}
//# sourceMappingURL=create-incremental-cache.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/export/helpers/create-incremental-cache.ts"],"sourcesContent":["import path from 'path'\nimport { IncrementalCache } from '../../server/lib/incremental-cache'\nimport { hasNextSupport } from '../../server/ci-info'\nimport { nodeFs } from '../../server/lib/node-fs-methods'\nimport { interopDefault } from '../../lib/interop-default'\nimport { formatDynamicImportPath } from '../../lib/format-dynamic-import-path'\nimport {\n initializeCacheHandlers,\n setCacheHandler,\n} from '../../server/use-cache/handlers'\n\nexport async function createIncrementalCache({\n cacheHandler,\n cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n distDir,\n dir,\n flushToDisk,\n cacheHandlers,\n requestHeaders,\n}: {\n cacheHandler?: string\n cacheMaxMemorySize: number\n fetchCacheKeyPrefix?: string\n distDir: string\n dir: string\n flushToDisk?: boolean\n requestHeaders?: Record<string, string | string[] | undefined>\n cacheHandlers?: Record<string, string | undefined>\n}) {\n // Custom cache handler overrides.\n let CacheHandler: any\n if (cacheHandler) {\n CacheHandler = interopDefault(\n await import(formatDynamicImportPath(dir, cacheHandler)).then(\n (mod) => mod.default || mod\n )\n )\n }\n\n if (cacheHandlers && initializeCacheHandlers(cacheMaxMemorySize)) {\n for (const [kind, handler] of Object.entries(cacheHandlers)) {\n if (!handler) continue\n\n setCacheHandler(\n kind,\n interopDefault(\n await import(formatDynamicImportPath(dir, handler)).then(\n (mod) => mod.default || mod\n )\n )\n )\n }\n }\n\n const incrementalCache = new IncrementalCache({\n dev: false,\n requestHeaders: requestHeaders || {},\n flushToDisk,\n maxMemoryCacheSize: cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n getPrerenderManifest: () => ({\n version: 4,\n routes: {},\n dynamicRoutes: {},\n preview: {\n previewModeEncryptionKey: '',\n previewModeId: '',\n previewModeSigningKey: '',\n },\n notFoundRoutes: [],\n }),\n fs: nodeFs,\n serverDistDir: path.join(distDir, 'server'),\n CurCacheHandler: CacheHandler,\n minimalMode: hasNextSupport,\n })\n\n ;(globalThis as any).__incrementalCache = incrementalCache\n\n return incrementalCache\n}\n"],"names":["path","IncrementalCache","hasNextSupport","nodeFs","interopDefault","formatDynamicImportPath","initializeCacheHandlers","setCacheHandler","createIncrementalCache","cacheHandler","cacheMaxMemorySize","fetchCacheKeyPrefix","distDir","dir","flushToDisk","cacheHandlers","requestHeaders","CacheHandler","then","mod","default","kind","handler","Object","entries","incrementalCache","dev","maxMemoryCacheSize","getPrerenderManifest","version","routes","dynamicRoutes","preview","previewModeEncryptionKey","previewModeId","previewModeSigningKey","notFoundRoutes","fs","serverDistDir","join","CurCacheHandler","minimalMode","globalThis","__incrementalCache"],"mappings":"AAAA,OAAOA,UAAU,OAAM;AACvB,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,MAAM,QAAQ,mCAAkC;AACzD,SAASC,cAAc,QAAQ,4BAA2B;AAC1D,SAASC,uBAAuB,QAAQ,uCAAsC;AAC9E,SACEC,uBAAuB,EACvBC,eAAe,QACV,kCAAiC;AAExC,OAAO,eAAeC,uBAAuB,EAC3CC,YAAY,EACZC,kBAAkB,EAClBC,mBAAmB,EACnBC,OAAO,EACPC,GAAG,EACHC,WAAW,EACXC,aAAa,EACbC,cAAc,EAUf;IACC,kCAAkC;IAClC,IAAIC;IACJ,IAAIR,cAAc;QAChBQ,eAAeb,eACb,MAAM,MAAM,CAACC,wBAAwBQ,KAAKJ,eAAeS,IAAI,CAC3D,CAACC,MAAQA,IAAIC,OAAO,IAAID;IAG9B;IAEA,IAAIJ,iBAAiBT,wBAAwBI,qBAAqB;QAChE,KAAK,MAAM,CAACW,MAAMC,QAAQ,IAAIC,OAAOC,OAAO,CAACT,eAAgB;YAC3D,IAAI,CAACO,SAAS;YAEdf,gBACEc,MACAjB,eACE,MAAM,MAAM,CAACC,wBAAwBQ,KAAKS,UAAUJ,IAAI,CACtD,CAACC,MAAQA,IAAIC,OAAO,IAAID;QAIhC;IACF;IAEA,MAAMM,mBAAmB,IAAIxB,iBAAiB;QAC5CyB,KAAK;QACLV,gBAAgBA,kBAAkB,CAAC;QACnCF;QACAa,oBAAoBjB;QACpBC;QACAiB,sBAAsB,IAAO,CAAA;gBAC3BC,SAAS;gBACTC,QAAQ,CAAC;gBACTC,eAAe,CAAC;gBAChBC,SAAS;oBACPC,0BAA0B;oBAC1BC,eAAe;oBACfC,uBAAuB;gBACzB;gBACAC,gBAAgB,EAAE;YACpB,CAAA;QACAC,IAAIlC;QACJmC,eAAetC,KAAKuC,IAAI,CAAC3B,SAAS;QAClC4B,iBAAiBvB;QACjBwB,aAAavC;IACf;IAEEwC,WAAmBC,kBAAkB,GAAGlB;IAE1C,OAAOA;AACT","ignoreList":[0]}
+31
View File
@@ -0,0 +1,31 @@
import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher';
import { getRouteRegex } from '../../shared/lib/router/utils/route-regex';
// The last page and matcher that this function handled.
let last = null;
/**
* Gets the params for the provided page.
* @param page the page that contains dynamic path parameters
* @param pathname the pathname to match
* @returns the matches that were found, throws otherwise
*/ export function getParams(page, pathname) {
// Because this is often called on the output of `getStaticPaths` or similar
// where the `page` here doesn't change, this will "remember" the last page
// it created the RegExp for. If it matches, it'll just re-use it.
let matcher;
if ((last == null ? void 0 : last.page) === page) {
matcher = last.matcher;
} else {
matcher = getRouteMatcher(getRouteRegex(page));
}
const params = matcher(pathname);
if (!params) {
throw Object.defineProperty(new Error(`The provided export path '${pathname}' doesn't match the '${page}' page.\nRead more: https://nextjs.org/docs/messages/export-path-mismatch`), "__NEXT_ERROR_CODE", {
value: "E20",
enumerable: false,
configurable: true
});
}
return params;
}
//# sourceMappingURL=get-params.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/export/helpers/get-params.ts"],"sourcesContent":["import {\n type RouteMatchFn,\n getRouteMatcher,\n} from '../../shared/lib/router/utils/route-matcher'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\n\n// The last page and matcher that this function handled.\nlet last: {\n page: string\n matcher: RouteMatchFn\n} | null = null\n\n/**\n * Gets the params for the provided page.\n * @param page the page that contains dynamic path parameters\n * @param pathname the pathname to match\n * @returns the matches that were found, throws otherwise\n */\nexport function getParams(page: string, pathname: string) {\n // Because this is often called on the output of `getStaticPaths` or similar\n // where the `page` here doesn't change, this will \"remember\" the last page\n // it created the RegExp for. If it matches, it'll just re-use it.\n let matcher: RouteMatchFn\n if (last?.page === page) {\n matcher = last.matcher\n } else {\n matcher = getRouteMatcher(getRouteRegex(page))\n }\n\n const params = matcher(pathname)\n if (!params) {\n throw new Error(\n `The provided export path '${pathname}' doesn't match the '${page}' page.\\nRead more: https://nextjs.org/docs/messages/export-path-mismatch`\n )\n }\n\n return params\n}\n"],"names":["getRouteMatcher","getRouteRegex","last","getParams","page","pathname","matcher","params","Error"],"mappings":"AAAA,SAEEA,eAAe,QACV,8CAA6C;AACpD,SAASC,aAAa,QAAQ,4CAA2C;AAEzE,wDAAwD;AACxD,IAAIC,OAGO;AAEX;;;;;CAKC,GACD,OAAO,SAASC,UAAUC,IAAY,EAAEC,QAAgB;IACtD,4EAA4E;IAC5E,2EAA2E;IAC3E,kEAAkE;IAClE,IAAIC;IACJ,IAAIJ,CAAAA,wBAAAA,KAAME,IAAI,MAAKA,MAAM;QACvBE,UAAUJ,KAAKI,OAAO;IACxB,OAAO;QACLA,UAAUN,gBAAgBC,cAAcG;IAC1C;IAEA,MAAMG,SAASD,QAAQD;IACvB,IAAI,CAACE,QAAQ;QACX,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,0BAA0B,EAAEH,SAAS,qBAAqB,EAAED,KAAK,yEAAyE,CAAC,GADxI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,OAAOG;AACT","ignoreList":[0]}
+7
View File
@@ -0,0 +1,7 @@
import { isDynamicServerError } from '../../client/components/hooks-server-context';
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';
import { isNextRouterError } from '../../client/components/is-next-router-error';
import { isDynamicPostpone } from '../../server/app-render/dynamic-rendering';
export const isDynamicUsageError = (err)=>isDynamicServerError(err) || isBailoutToCSRError(err) || isNextRouterError(err) || isDynamicPostpone(err);
//# sourceMappingURL=is-dynamic-usage-error.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/export/helpers/is-dynamic-usage-error.ts"],"sourcesContent":["import { isDynamicServerError } from '../../client/components/hooks-server-context'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from '../../client/components/is-next-router-error'\nimport { isDynamicPostpone } from '../../server/app-render/dynamic-rendering'\n\nexport const isDynamicUsageError = (err: unknown) =>\n isDynamicServerError(err) ||\n isBailoutToCSRError(err) ||\n isNextRouterError(err) ||\n isDynamicPostpone(err)\n"],"names":["isDynamicServerError","isBailoutToCSRError","isNextRouterError","isDynamicPostpone","isDynamicUsageError","err"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,+CAA8C;AACnF,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,iBAAiB,QAAQ,+CAA8C;AAChF,SAASC,iBAAiB,QAAQ,4CAA2C;AAE7E,OAAO,MAAMC,sBAAsB,CAACC,MAClCL,qBAAqBK,QACrBJ,oBAAoBI,QACpBH,kBAAkBG,QAClBF,kBAAkBE,KAAI","ignoreList":[0]}
+759
View File
@@ -0,0 +1,759 @@
import { createStaticWorker } from '../build';
import { bold, yellow } from '../lib/picocolors';
import findUp from 'next/dist/compiled/find-up';
import { existsSync, promises as fs } from 'fs';
import '../server/require-hook';
import { dirname, join, resolve, sep, relative } from 'path';
import * as Log from '../build/output/log';
import { RSC_SEGMENT_SUFFIX, RSC_SEGMENTS_DIR_SUFFIX, RSC_SUFFIX, SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants';
import { recursiveCopy } from '../lib/recursive-copy';
import { BUILD_ID_FILE, CLIENT_PUBLIC_FILES_PATH, CLIENT_STATIC_FILES_PATH, EXPORT_DETAIL, EXPORT_MARKER, NEXT_FONT_MANIFEST, MIDDLEWARE_MANIFEST, PAGES_MANIFEST, PHASE_EXPORT, PRERENDER_MANIFEST, SERVER_DIRECTORY, SERVER_REFERENCE_MANIFEST, APP_PATH_ROUTES_MANIFEST, ROUTES_MANIFEST, FUNCTIONS_CONFIG_MANIFEST } from '../shared/lib/constants';
import loadConfig from '../server/config';
import { parseMaxPostponedStateSize } from '../server/config-shared';
import { eventCliSession } from '../telemetry/events';
import { hasNextSupport } from '../server/ci-info';
import { Telemetry } from '../telemetry/storage';
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path';
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path';
import { loadEnvConfig } from '@next/env';
import { isAPIRoute } from '../lib/is-api-route';
import { getPagePath } from '../server/require';
import { isAppRouteRoute } from '../lib/is-app-route-route';
import { isAppPageRoute } from '../lib/is-app-page-route';
import isError from '../lib/is-error';
import { formatManifest } from '../build/manifests/formatter/format-manifest';
import { TurborepoAccessTraceResult } from '../build/turborepo-access-trace';
import { createProgress } from '../build/progress';
import { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite';
import { extractInfoFromServerReferenceId } from '../shared/lib/server-reference-info';
import { convertSegmentPathToStaticExportFilename } from '../shared/lib/segment-cache/segment-value-encoding';
import { getNextBuildDebuggerPortOffset } from '../lib/worker';
import { getParams } from './helpers/get-params';
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic';
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths';
export class ExportError extends Error {
constructor(...args){
super(...args), this.code = 'NEXT_EXPORT_ERROR';
}
}
/**
* Picks an RDC seed by matching on the params that are
* already known, so fallback shells use a seed that has already
* computed those known params.
*/ function buildRDCCacheByPage(results, finalPhaseExportPaths) {
const renderResumeDataCachesByPage = {};
const seedCandidatesByPage = new Map();
for (const { page, path, result } of results){
if (!result) {
continue;
}
if ('renderResumeDataCache' in result && result.renderResumeDataCache) {
// Collect all RDC seeds for this page so we can pick the best match
// for each fallback shell later (e.g. locale-specific variants).
const candidates = seedCandidatesByPage.get(page) ?? [];
candidates.push({
path,
renderResumeDataCache: result.renderResumeDataCache
});
seedCandidatesByPage.set(page, candidates);
// Remove the RDC string from the result so that it can be garbage
// collected, when there are more results for the same page.
result.renderResumeDataCache = undefined;
}
}
const getKnownParamsKey = (normalizedPage, path, fallbackParamNames)=>{
let params;
try {
params = getParams(normalizedPage, path);
} catch {
return null;
}
// Only keep params that are known, then sort
// for a stable key so we can match a compatible seed.
const entries = Object.entries(params).filter(([key])=>!fallbackParamNames.has(key));
entries.sort(([a], [b])=>a < b ? -1 : a > b ? 1 : 0);
return JSON.stringify(entries);
};
for (const exportPath of finalPhaseExportPaths){
const { page, path, _fallbackRouteParams = [] } = exportPath;
if (!isDynamicRoute(page)) {
continue;
}
// Normalize app pages before param matching.
const normalizedPage = normalizeAppPath(page);
const pageKey = page !== path ? `${page}: ${path}` : path;
const fallbackParamNames = new Set(_fallbackRouteParams.map((param)=>param.paramName));
// Build a key from the known params for this fallback shell so we can
// select a seed from a compatible prerendered route.
const targetKey = getKnownParamsKey(normalizedPage, path, fallbackParamNames);
if (!targetKey) {
continue;
}
const candidates = seedCandidatesByPage.get(page);
// No suitable candidates, so there's no RDC seed to select
if (!candidates || candidates.length === 0) {
continue;
}
let selected = null;
for (const candidate of candidates){
// Pick the seed whose known params match this fallback shell.
const candidateKey = getKnownParamsKey(normalizedPage, candidate.path, fallbackParamNames);
if (candidateKey === targetKey) {
selected = candidate.renderResumeDataCache;
break;
}
}
if (selected) {
renderResumeDataCachesByPage[pageKey] = selected;
}
}
return renderResumeDataCachesByPage;
}
async function exportAppImpl(dir, options, span, staticWorker) {
dir = resolve(dir);
// attempt to load global env values so they are available in next.config.js
span.traceChild('load-dotenv').traceFn(()=>loadEnvConfig(dir, false, Log));
const { enabledDirectories } = options;
const nextConfig = options.nextConfig || await span.traceChild('load-next-config').traceAsyncFn(()=>loadConfig(PHASE_EXPORT, dir, {
debugPrerender: options.debugPrerender
}));
const distDir = join(dir, nextConfig.distDir);
const telemetry = options.buildExport ? null : new Telemetry({
distDir
});
if (telemetry) {
telemetry.record(eventCliSession(nextConfig, {
webpackVersion: null,
cliCommand: 'export',
isSrcDir: null,
hasNowJson: !!await findUp('now.json', {
cwd: dir
}),
isCustomServer: null,
turboFlag: false,
pagesDir: null,
appDir: null
}));
}
const subFolders = nextConfig.trailingSlash && !options.buildExport;
if (!options.silent && !options.buildExport) {
Log.info(`using build directory: ${distDir}`);
}
const buildIdFile = join(distDir, BUILD_ID_FILE);
if (!existsSync(buildIdFile)) {
throw Object.defineProperty(new ExportError(`Could not find a production build in the '${distDir}' directory. Try building your app with 'next build' before starting the static export. https://nextjs.org/docs/messages/next-export-no-build-id`), "__NEXT_ERROR_CODE", {
value: "E610",
enumerable: false,
configurable: true
});
}
const customRoutes = [
'rewrites',
'redirects',
'headers'
].filter((config)=>typeof nextConfig[config] === 'function');
if (!hasNextSupport && !options.buildExport && customRoutes.length > 0) {
Log.warn(`rewrites, redirects, and headers are not applied when exporting your application, detected (${customRoutes.join(', ')}). See more info here: https://nextjs.org/docs/messages/export-no-custom-routes`);
}
const buildId = await fs.readFile(buildIdFile, 'utf8');
const pagesManifest = !options.pages && require(join(distDir, SERVER_DIRECTORY, PAGES_MANIFEST));
let prerenderManifest;
try {
prerenderManifest = require(join(distDir, PRERENDER_MANIFEST));
} catch {}
let appRoutePathManifest;
try {
appRoutePathManifest = require(join(distDir, APP_PATH_ROUTES_MANIFEST));
} catch (err) {
if (isError(err) && (err.code === 'ENOENT' || err.code === 'MODULE_NOT_FOUND')) {
// the manifest doesn't exist which will happen when using
// "pages" dir instead of "app" dir.
appRoutePathManifest = undefined;
} else {
// the manifest is malformed (invalid json)
throw err;
}
}
const excludedPrerenderRoutes = new Set();
const pages = options.pages || Object.keys(pagesManifest);
const defaultPathMap = {};
let hasApiRoutes = false;
for (const page of pages){
// _document and _app are not real pages
// _error is exported as 404.html later on
// API Routes are Node.js functions
if (isAPIRoute(page)) {
hasApiRoutes = true;
continue;
}
if (page === '/_document' || page === '/_app' || page === '/_error') {
continue;
}
// iSSG pages that are dynamic should not export templated version by
// default. In most cases, this would never work. There is no server that
// could run `getStaticProps`. If users make their page work lazily, they
// can manually add it to the `exportPathMap`.
if (prerenderManifest == null ? void 0 : prerenderManifest.dynamicRoutes[page]) {
excludedPrerenderRoutes.add(page);
continue;
}
defaultPathMap[page] = {
page
};
}
const mapAppRouteToPage = new Map();
if (!options.buildExport && appRoutePathManifest) {
for (const [pageName, routePath] of Object.entries(appRoutePathManifest)){
mapAppRouteToPage.set(routePath, pageName);
if (isAppPageRoute(pageName) && !(prerenderManifest == null ? void 0 : prerenderManifest.routes[routePath]) && !(prerenderManifest == null ? void 0 : prerenderManifest.dynamicRoutes[routePath])) {
defaultPathMap[routePath] = {
page: pageName,
_isAppDir: true
};
}
}
}
// Initialize the output directory
const outDir = options.outdir;
if (outDir === join(dir, 'public')) {
throw Object.defineProperty(new ExportError(`The 'public' directory is reserved in Next.js and can not be used as the export out directory. https://nextjs.org/docs/messages/can-not-output-to-public`), "__NEXT_ERROR_CODE", {
value: "E588",
enumerable: false,
configurable: true
});
}
if (outDir === join(dir, 'static')) {
throw Object.defineProperty(new ExportError(`The 'static' directory is reserved in Next.js and can not be used as the export out directory. https://nextjs.org/docs/messages/can-not-output-to-static`), "__NEXT_ERROR_CODE", {
value: "E548",
enumerable: false,
configurable: true
});
}
await fs.rm(outDir, {
recursive: true,
force: true
});
await fs.mkdir(join(outDir, '_next', buildId), {
recursive: true
});
await fs.writeFile(join(distDir, EXPORT_DETAIL), formatManifest({
version: 1,
outDirectory: outDir,
success: false
}), 'utf8');
// Copy static directory
if (!options.buildExport && existsSync(join(dir, 'static'))) {
if (!options.silent) {
Log.info('Copying "static" directory');
}
await span.traceChild('copy-static-directory').traceAsyncFn(()=>recursiveCopy(join(dir, 'static'), join(outDir, 'static')));
}
// Copy .next/static directory
if (!options.buildExport && existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))) {
if (!options.silent) {
Log.info('Copying "static build" directory');
}
await span.traceChild('copy-next-static-directory').traceAsyncFn(()=>recursiveCopy(join(distDir, CLIENT_STATIC_FILES_PATH), join(outDir, '_next', CLIENT_STATIC_FILES_PATH)));
}
// Get the exportPathMap from the config file
if (typeof nextConfig.exportPathMap !== 'function') {
nextConfig.exportPathMap = async (defaultMap)=>{
return defaultMap;
};
}
const { i18n, images: { loader = 'default', unoptimized } } = nextConfig;
if (i18n && !options.buildExport) {
throw Object.defineProperty(new ExportError(`i18n support is not compatible with next export. See here for more info on deploying: https://nextjs.org/docs/messages/export-no-custom-routes`), "__NEXT_ERROR_CODE", {
value: "E587",
enumerable: false,
configurable: true
});
}
if (!options.buildExport) {
const { isNextImageImported } = await span.traceChild('is-next-image-imported').traceAsyncFn(()=>fs.readFile(join(distDir, EXPORT_MARKER), 'utf8').then((text)=>JSON.parse(text)).catch(()=>({})));
if (isNextImageImported && loader === 'default' && !unoptimized && !hasNextSupport) {
throw Object.defineProperty(new ExportError(`Image Optimization using the default loader is not compatible with export.
Possible solutions:
- Use \`next start\` to run a server, which includes the Image Optimization API.
- Configure \`images.unoptimized = true\` in \`next.config.js\` to disable the Image Optimization API.
Read more: https://nextjs.org/docs/messages/export-image-api`), "__NEXT_ERROR_CODE", {
value: "E603",
enumerable: false,
configurable: true
});
}
}
let serverActionsManifest;
if (enabledDirectories.app) {
serverActionsManifest = require(join(distDir, SERVER_DIRECTORY, SERVER_REFERENCE_MANIFEST + '.json'));
if (nextConfig.output === 'export') {
var _routesManifest_rewrites_beforeFiles, _routesManifest_rewrites;
const routesManifest = require(join(distDir, ROUTES_MANIFEST));
// We already prevent rewrites earlier in the process, however Next.js will insert rewrites
// for interception routes so we need to check for that here.
if ((routesManifest == null ? void 0 : (_routesManifest_rewrites = routesManifest.rewrites) == null ? void 0 : (_routesManifest_rewrites_beforeFiles = _routesManifest_rewrites.beforeFiles) == null ? void 0 : _routesManifest_rewrites_beforeFiles.length) > 0) {
const hasInterceptionRouteRewrite = routesManifest.rewrites.beforeFiles.some(isInterceptionRouteRewrite);
if (hasInterceptionRouteRewrite) {
throw Object.defineProperty(new ExportError(`Intercepting routes are not supported with static export.\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features`), "__NEXT_ERROR_CODE", {
value: "E626",
enumerable: false,
configurable: true
});
}
}
const actionIds = [
...Object.keys(serverActionsManifest.node),
...Object.keys(serverActionsManifest.edge)
];
if (actionIds.some((actionId)=>extractInfoFromServerReferenceId(actionId).type === 'server-action')) {
throw Object.defineProperty(new ExportError(`Server Actions are not supported with static export.\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features`), "__NEXT_ERROR_CODE", {
value: "E625",
enumerable: false,
configurable: true
});
}
}
}
// Start the rendering process
const renderOpts = {
previewProps: prerenderManifest == null ? void 0 : prerenderManifest.preview,
isBuildTimePrerendering: true,
assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
distDir,
basePath: nextConfig.basePath,
cacheComponents: nextConfig.cacheComponents ?? false,
trailingSlash: nextConfig.trailingSlash,
locales: i18n == null ? void 0 : i18n.locales,
locale: i18n == null ? void 0 : i18n.defaultLocale,
defaultLocale: i18n == null ? void 0 : i18n.defaultLocale,
domainLocales: i18n == null ? void 0 : i18n.domains,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
// Exported pages do not currently support dynamic HTML.
supportsDynamicResponse: false,
crossOrigin: nextConfig.crossOrigin,
optimizeCss: nextConfig.experimental.optimizeCss,
nextConfigOutput: nextConfig.output,
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,
largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverActions: nextConfig.experimental.serverActions,
serverComponents: enabledDirectories.app,
cacheLifeProfiles: nextConfig.cacheLife,
nextFontManifest: require(join(distDir, 'server', `${NEXT_FONT_MANIFEST}.json`)),
images: nextConfig.images,
htmlLimitedBots: nextConfig.htmlLimitedBots.source,
experimental: {
clientTraceMetadata: nextConfig.experimental.clientTraceMetadata,
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
clientParamParsingOrigins: nextConfig.experimental.clientParamParsingOrigins,
dynamicOnHover: nextConfig.experimental.dynamicOnHover ?? false,
optimisticRouting: nextConfig.experimental.optimisticRouting ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false,
prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts,
cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(nextConfig.experimental.maxPostponedStateSize)
},
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength
};
globalThis.__NEXT_DATA__ = {
nextExport: true
};
const exportPathMap = await span.traceChild('run-export-path-map').traceAsyncFn(async ()=>{
const exportMap = await nextConfig.exportPathMap(defaultPathMap, {
dev: false,
dir,
outDir,
distDir,
buildId
});
return exportMap;
});
// During static export, remove export 404/500 of pages router
// when only app router presents
if (!options.buildExport && options.appDirOnly) {
delete exportPathMap['/404'];
delete exportPathMap['/500'];
}
// only add missing 404 page when `buildExport` is false
if (!options.buildExport && !options.appDirOnly) {
// only add missing /404 if not specified in `exportPathMap`
if (!exportPathMap['/404']) {
exportPathMap['/404'] = {
page: '/_error'
};
}
/**
* exports 404.html for backwards compat
* E.g. GitHub Pages, GitLab Pages, Cloudflare Pages, Netlify
*/ if (!exportPathMap['/404.html'] && exportPathMap['/404']) {
// alias /404.html to /404 to be compatible with custom 404 / _error page
exportPathMap['/404.html'] = exportPathMap['/404'];
}
}
const allExportPaths = [];
const seenExportPaths = new Set();
const fallbackEnabledPages = new Set();
for (const [path, entry] of Object.entries(exportPathMap)){
// make sure to prevent duplicates
const normalizedPath = denormalizePagePath(normalizePagePath(path));
if (seenExportPaths.has(normalizedPath)) {
continue;
}
seenExportPaths.add(normalizedPath);
if (!entry._isAppDir && isAPIRoute(entry.page)) {
hasApiRoutes = true;
continue;
}
allExportPaths.push({
...entry,
path: normalizedPath
});
if (prerenderManifest && !options.buildExport) {
const prerenderInfo = prerenderManifest.dynamicRoutes[entry.page];
if (prerenderInfo && prerenderInfo.fallback !== false) {
fallbackEnabledPages.add(entry.page);
}
}
}
if (allExportPaths.length === 0) {
if (!prerenderManifest) {
return null;
}
}
if (fallbackEnabledPages.size > 0) {
throw Object.defineProperty(new ExportError(`Found pages with \`fallback\` enabled:\n${[
...fallbackEnabledPages
].join('\n')}\n${SSG_FALLBACK_EXPORT_ERROR}\n`), "__NEXT_ERROR_CODE", {
value: "E533",
enumerable: false,
configurable: true
});
}
let hasMiddleware = false;
if (!options.buildExport) {
try {
var _functionsConfigManifest_functions;
const middlewareManifest = require(join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST));
const functionsConfigManifest = require(join(distDir, SERVER_DIRECTORY, FUNCTIONS_CONFIG_MANIFEST));
hasMiddleware = Object.keys(middlewareManifest.middleware).length > 0 || Boolean((_functionsConfigManifest_functions = functionsConfigManifest.functions) == null ? void 0 : _functionsConfigManifest_functions['/_middleware']);
} catch {}
// Warn if the user defines a path for an API page
if (hasApiRoutes || hasMiddleware) {
if (nextConfig.output === 'export') {
Log.warn(yellow(`Statically exporting a Next.js application via \`next export\` disables API routes and middleware.`) + `\n` + yellow(`This command is meant for static-only hosts, and is` + ' ' + bold(`not necessary to make your application static.`)) + `\n` + yellow(`Pages in your application without server-side data dependencies will be automatically statically exported by \`next build\`, including pages powered by \`getStaticProps\`.`) + `\n` + yellow(`Learn more: https://nextjs.org/docs/messages/api-routes-static-export`));
}
}
}
const pagesDataDir = options.buildExport ? outDir : join(outDir, '_next/data', buildId);
const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH);
// Copy public directory
if (!options.buildExport && existsSync(publicDir)) {
if (!options.silent) {
Log.info('Copying "public" directory');
}
await span.traceChild('copy-public-directory').traceAsyncFn(()=>recursiveCopy(publicDir, outDir, {
filter (path) {
// Exclude paths used by pages
return !exportPathMap[path];
}
}));
}
const exportPagesInBatches = async (worker, exportPaths, renderResumeDataCachesByPage)=>{
// Batch filtered pages into smaller batches, and call the export worker on
// each batch. We've set a default minimum of 25 pages per batch to ensure
// that even setups with only a few static pages can leverage a shared
// incremental cache, however this value can be configured.
const minPageCountPerBatch = nextConfig.experimental.staticGenerationMinPagesPerWorker ?? 25;
// Calculate the number of workers needed to ensure each batch has at least
// minPageCountPerBatch pages.
const numWorkers = Math.min(options.numWorkers, Math.ceil(exportPaths.length / minPageCountPerBatch));
// Calculate the page count per batch based on the number of workers.
const pageCountPerBatch = Math.ceil(exportPaths.length / numWorkers);
const batches = Array.from({
length: numWorkers
}, (_, i)=>exportPaths.slice(i * pageCountPerBatch, (i + 1) * pageCountPerBatch));
// Distribute remaining pages.
const remainingPages = exportPaths.slice(numWorkers * pageCountPerBatch);
remainingPages.forEach((page, index)=>{
batches[index % batches.length].push(page);
});
return (await Promise.all(batches.map(async (batch)=>worker.exportPages({
buildId,
deploymentId: nextConfig.deploymentId,
clientAssetToken: nextConfig.experimental.immutableAssetToken || nextConfig.deploymentId,
exportPaths: batch,
parentSpanId: span.getId(),
pagesDataDir,
renderOpts,
options,
dir,
distDir,
outDir,
nextConfig,
cacheHandler: nextConfig.cacheHandler,
cacheMaxMemorySize: nextConfig.cacheMaxMemorySize,
fetchCache: true,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
renderResumeDataCachesByPage
})))).flat();
};
let initialPhaseExportPaths = [];
const finalPhaseExportPaths = [];
if (renderOpts.cacheComponents) {
// Only run instant validation once per route, even if multiple param sets from generateStaticParams exist.
const routesWithInstantValidation = new Set();
for (const exportPath of allExportPaths){
if (exportPath._allowEmptyStaticShell) {
finalPhaseExportPaths.push(exportPath);
} else {
initialPhaseExportPaths.push(exportPath);
}
const route = exportPath.page;
if (!routesWithInstantValidation.has(route)) {
exportPath._runInstantValidation = true;
routesWithInstantValidation.add(route);
}
}
} else {
initialPhaseExportPaths = allExportPaths;
}
const totalExportPaths = initialPhaseExportPaths.length + finalPhaseExportPaths.length;
let worker = null;
let results = [];
if (totalExportPaths > 0) {
const progress = createProgress(totalExportPaths, options.statusMessage ?? `Exporting using ${options.numWorkers} worker${options.numWorkers > 1 ? 's' : ''}`);
if (staticWorker) {
// TODO: progress shouldn't rely on "activity" event sent from `exportPage`.
staticWorker.setOnActivity(progress.run);
staticWorker.setOnActivityAbort(progress.clear);
worker = staticWorker;
} else {
worker = createStaticWorker(nextConfig, {
debuggerPortOffset: getNextBuildDebuggerPortOffset({
kind: 'export-page'
}),
numberOfWorkers: options.numWorkers,
progress
});
}
results = await exportPagesInBatches(worker, initialPhaseExportPaths);
if (finalPhaseExportPaths.length > 0) {
const renderResumeDataCachesByPage = buildRDCCacheByPage(results, finalPhaseExportPaths);
const finalPhaseResults = await exportPagesInBatches(worker, finalPhaseExportPaths, renderResumeDataCachesByPage);
results.push(...finalPhaseResults);
}
}
const collector = {
byPath: new Map(),
byPage: new Map(),
ssgNotFoundPaths: new Set(),
turborepoAccessTraceResults: new Map()
};
const failedExportAttemptsByPage = new Map();
for (const { result, path, page, pageKey } of results){
if (!result) continue;
if ('error' in result) {
failedExportAttemptsByPage.set(pageKey, true);
continue;
}
if (result.turborepoAccessTraceResult) {
var _collector_turborepoAccessTraceResults;
(_collector_turborepoAccessTraceResults = collector.turborepoAccessTraceResults) == null ? void 0 : _collector_turborepoAccessTraceResults.set(path, TurborepoAccessTraceResult.fromSerialized(result.turborepoAccessTraceResult));
}
if (options.buildExport) {
// Update path info by path.
const info = collector.byPath.get(path) ?? {};
if (result.cacheControl) {
info.cacheControl = result.cacheControl;
}
if (typeof result.metadata !== 'undefined') {
info.metadata = result.metadata;
}
if (typeof result.hasEmptyStaticShell !== 'undefined') {
info.hasEmptyStaticShell = result.hasEmptyStaticShell;
}
if (typeof result.hasPostponed !== 'undefined') {
info.hasPostponed = result.hasPostponed;
}
if (typeof result.hasStaticRsc !== 'undefined') {
info.hasStaticRsc = result.hasStaticRsc;
}
if (typeof result.fetchMetrics !== 'undefined') {
info.fetchMetrics = result.fetchMetrics;
}
collector.byPath.set(path, info);
// Update not found.
if (result.ssgNotFound === true) {
collector.ssgNotFoundPaths.add(path);
}
// Update durations.
const durations = collector.byPage.get(page) ?? {
durationsByPath: new Map()
};
durations.durationsByPath.set(path, result.duration);
collector.byPage.set(page, durations);
}
}
// Export mode provide static outputs that are not compatible with PPR mode.
if (!options.buildExport && nextConfig.experimental.ppr) {
// TODO: add message
throw Object.defineProperty(new Error('Invariant: PPR cannot be enabled in export mode'), "__NEXT_ERROR_CODE", {
value: "E54",
enumerable: false,
configurable: true
});
}
// copy prerendered routes to outDir
if (!options.buildExport && prerenderManifest) {
await Promise.all(Object.keys(prerenderManifest.routes).map(async (unnormalizedRoute)=>{
// Special handling: map app /_not-found to 404.html (and 404/index.html when trailingSlash)
if (unnormalizedRoute === '/_not-found') {
const { srcRoute } = prerenderManifest.routes[unnormalizedRoute];
const appPageName = mapAppRouteToPage.get(srcRoute || '');
const pageName = appPageName || srcRoute || unnormalizedRoute;
const isAppPath = Boolean(appPageName);
const route = normalizePagePath(unnormalizedRoute);
const pagePath = getPagePath(pageName, distDir, undefined, isAppPath);
const distPagesDir = join(pagePath, pageName.slice(1).split('/').map(()=>'..').join('/'));
const orig = join(distPagesDir, route);
const htmlSrc = `${orig}.html`;
// write 404.html at root
const htmlDest404 = join(outDir, '404.html');
await fs.mkdir(dirname(htmlDest404), {
recursive: true
});
await fs.copyFile(htmlSrc, htmlDest404);
// When trailingSlash, also write 404/index.html
if (subFolders) {
const htmlDest404Index = join(outDir, '404', 'index.html');
await fs.mkdir(dirname(htmlDest404Index), {
recursive: true
});
await fs.copyFile(htmlSrc, htmlDest404Index);
}
}
// Skip 500.html in static export
if (unnormalizedRoute === '/_global-error') {
return;
}
const { srcRoute } = prerenderManifest.routes[unnormalizedRoute];
const appPageName = mapAppRouteToPage.get(srcRoute || '');
const pageName = appPageName || srcRoute || unnormalizedRoute;
const isAppPath = Boolean(appPageName);
const isAppRouteHandler = appPageName && isAppRouteRoute(appPageName);
// returning notFound: true from getStaticProps will not
// output html/json files during the build
if (prerenderManifest.notFoundRoutes.includes(unnormalizedRoute)) {
return;
}
// TODO: This rewrites /index/foo to /index/index/foo. Investigate and
// fix. I presume this was because normalizePagePath was designed for
// some other use case and then reused here for static exports without
// realizing the implications.
const route = normalizePagePath(unnormalizedRoute);
const pagePath = getPagePath(pageName, distDir, undefined, isAppPath);
const distPagesDir = join(pagePath, // strip leading / and then recurse number of nested dirs
// to place from base folder
pageName.slice(1).split('/').map(()=>'..').join('/'));
const orig = join(distPagesDir, route);
const handlerSrc = `${orig}.body`;
const handlerDest = join(outDir, route);
if (isAppRouteHandler && existsSync(handlerSrc)) {
await fs.mkdir(dirname(handlerDest), {
recursive: true
});
await fs.copyFile(handlerSrc, handlerDest);
return;
}
const htmlDest = join(outDir, `${route}${subFolders && route !== '/index' ? `${sep}index` : ''}.html`);
const jsonDest = isAppPath ? join(outDir, `${route}${subFolders && route !== '/index' ? `${sep}index` : ''}.txt`) : join(pagesDataDir, `${route}.json`);
await fs.mkdir(dirname(htmlDest), {
recursive: true
});
await fs.mkdir(dirname(jsonDest), {
recursive: true
});
const htmlSrc = `${orig}.html`;
const jsonSrc = `${orig}${isAppPath ? RSC_SUFFIX : '.json'}`;
await fs.copyFile(htmlSrc, htmlDest);
await fs.copyFile(jsonSrc, jsonDest);
const segmentsDir = `${orig}${RSC_SEGMENTS_DIR_SUFFIX}`;
if (isAppPath && existsSync(segmentsDir)) {
// Output a data file for each of this page's segments
//
// These files are requested by the client router's internal
// prefetcher, not the user directly. So we don't need to account for
// things like trailing slash handling.
//
// To keep the protocol simple, we can use the non-normalized route
// path instead of the normalized one (which, among other things,
// rewrites `/` to `/index`).
const segmentsDirDest = join(outDir, unnormalizedRoute);
const segmentPaths = await collectSegmentPaths(segmentsDir);
await Promise.all(segmentPaths.map(async (segmentFileSrc)=>{
const segmentPath = '/' + segmentFileSrc.slice(0, -RSC_SEGMENT_SUFFIX.length);
const segmentFilename = convertSegmentPathToStaticExportFilename(segmentPath);
const segmentFileDest = join(segmentsDirDest, segmentFilename);
await fs.mkdir(dirname(segmentFileDest), {
recursive: true
});
await fs.copyFile(join(segmentsDir, segmentFileSrc), segmentFileDest);
}));
}
}));
}
if (failedExportAttemptsByPage.size > 0) {
const failedPages = Array.from(failedExportAttemptsByPage.keys());
throw Object.defineProperty(new ExportError(`Export encountered errors on ${failedPages.length} ${failedPages.length === 1 ? 'path' : 'paths'}:\n\t${failedPages.sort().join('\n\t')}`), "__NEXT_ERROR_CODE", {
value: "E1053",
enumerable: false,
configurable: true
});
}
await fs.writeFile(join(distDir, EXPORT_DETAIL), formatManifest({
version: 1,
outDirectory: outDir,
success: true
}), 'utf8');
if (telemetry) {
await telemetry.flush();
}
// Clean up activity listeners for progress.
if (staticWorker) {
staticWorker.setOnActivity(undefined);
staticWorker.setOnActivityAbort(undefined);
}
if (!staticWorker && worker) {
await worker.end();
}
return collector;
}
async function collectSegmentPaths(segmentsDirectory) {
const results = [];
await collectSegmentPathsImpl(segmentsDirectory, segmentsDirectory, results);
return results;
}
async function collectSegmentPathsImpl(segmentsDirectory, directory, results) {
const segmentFiles = await fs.readdir(directory, {
withFileTypes: true
});
await Promise.all(segmentFiles.map(async (segmentFile)=>{
if (segmentFile.isDirectory()) {
await collectSegmentPathsImpl(segmentsDirectory, join(directory, segmentFile.name), results);
return;
}
if (!segmentFile.name.endsWith(RSC_SEGMENT_SUFFIX)) {
return;
}
results.push(relative(segmentsDirectory, join(directory, segmentFile.name)));
}));
}
export default async function exportApp(dir, options, span, staticWorker) {
const nextExportSpan = span.traceChild('next-export');
return nextExportSpan.traceAsyncFn(async ()=>{
return await exportAppImpl(dir, options, nextExportSpan, staticWorker);
});
}
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+199
View File
@@ -0,0 +1,199 @@
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error';
import { NEXT_CACHE_TAGS_HEADER, NEXT_META_SUFFIX, RSC_SUFFIX, RSC_SEGMENTS_DIR_SUFFIX, RSC_SEGMENT_SUFFIX } from '../../lib/constants';
import { hasNextSupport } from '../../server/ci-info';
import { lazyRenderAppPage } from '../../server/route-modules/app-page/module.render';
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node';
import { NEXT_IS_PRERENDER_HEADER } from '../../client/components/app-router-headers';
import { AfterRunner } from '../../server/after/run-with-after';
import { stringifyResumeDataCache } from '../../server/resume-data-cache/resume-data-cache';
import { UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY, UNDERSCORE_NOT_FOUND_ROUTE_ENTRY } from '../../shared/lib/entry-constants';
/**
* Renders & exports a page associated with the /app directory
*/ export async function exportAppPage(req, res, page, path, pathname, query, fallbackRouteParams, partialRenderOpts, htmlFilepath, debugOutput, isDynamicError, fileWriter, sharedContext) {
const afterRunner = new AfterRunner();
const renderOpts = {
...partialRenderOpts,
waitUntil: afterRunner.context.waitUntil,
onClose: afterRunner.context.onClose,
onAfterTaskError: afterRunner.context.onTaskError
};
let isDefaultNotFound = false;
let isDefaultGlobalError = false;
// If the page is `/_not-found`, then we should update the page to be `/404`.
if (page === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY) {
isDefaultNotFound = true;
pathname = '/404';
}
// If the page is `/_global-error`, then we should update the page to be `/500`.
if (page === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY) {
isDefaultGlobalError = true;
pathname = '/500';
}
try {
const result = await lazyRenderAppPage(new NodeNextRequest(req), new NodeNextResponse(res), pathname, query, fallbackRouteParams, renderOpts, undefined, sharedContext);
const html = result.toUnchunkedString();
// TODO(after): if we abort a prerender because of an error in an after-callback
// we should probably communicate that better (and not log the error twice)
await afterRunner.executeAfter();
const { metadata } = result;
const { flightData, cacheControl = {
revalidate: false,
expire: undefined
}, postponed, fetchTags, fetchMetrics, segmentData, prefetchHints, renderResumeDataCache } = metadata;
// Ensure we don't postpone without having PPR enabled.
if (postponed && !renderOpts.experimental.isRoutePPREnabled) {
throw Object.defineProperty(new Error('Invariant: page postponed without PPR being enabled'), "__NEXT_ERROR_CODE", {
value: "E156",
enumerable: false,
configurable: true
});
}
if (cacheControl.revalidate === 0) {
if (isDynamicError) {
throw Object.defineProperty(new Error(`Page with dynamic = "error" encountered dynamic data method on ${path}.`), "__NEXT_ERROR_CODE", {
value: "E388",
enumerable: false,
configurable: true
});
}
const { staticBailoutInfo = {} } = metadata;
if (debugOutput && (staticBailoutInfo == null ? void 0 : staticBailoutInfo.description)) {
logDynamicUsageWarning({
path,
description: staticBailoutInfo.description,
stack: staticBailoutInfo.stack
});
}
return {
cacheControl,
fetchMetrics
};
}
// If page data isn't available, it means that the page couldn't be rendered
// properly so long as we don't have unknown route params. When a route doesn't
// have unknown route params, there will not be any flight data.
let hasStaticRsc = false;
if (!flightData) {
if (!fallbackRouteParams || fallbackRouteParams.size === 0 || renderOpts.cacheComponents) {
throw Object.defineProperty(new Error(`Invariant: failed to get page data for ${path}`), "__NEXT_ERROR_CODE", {
value: "E194",
enumerable: false,
configurable: true
});
}
} else {
const hasFallbackParams = fallbackRouteParams != null && fallbackRouteParams.size > 0;
const shouldWriteRsc = !renderOpts.experimental.isRoutePPREnabled || !postponed && !hasFallbackParams;
hasStaticRsc = shouldWriteRsc;
// With PPR enabled, we normally skip writing .rsc because it may contain
// dynamic data. However, for fully static outputs (no postponed state and
// no fallback params), we can safely emit the route .rsc to support
// static navigations.
if (shouldWriteRsc) {
fileWriter.append(htmlFilepath.replace(/\.html$/, RSC_SUFFIX), flightData);
}
}
let segmentPaths;
if (segmentData) {
// Emit the per-segment prefetch data. We emit them as separate files
// so that the cache handler has the option to treat each as a
// separate entry.
segmentPaths = [];
const segmentsDir = htmlFilepath.replace(/\.html$/, RSC_SEGMENTS_DIR_SUFFIX);
for (const [segmentPath, buffer] of segmentData){
segmentPaths.push(segmentPath);
const segmentDataFilePath = segmentsDir + segmentPath + RSC_SEGMENT_SUFFIX;
fileWriter.append(segmentDataFilePath, buffer);
}
}
const headers = {
...metadata.headers
};
// If we're writing the file to disk, we know it's a prerender.
headers[NEXT_IS_PRERENDER_HEADER] = '1';
if (fetchTags) {
headers[NEXT_CACHE_TAGS_HEADER] = fetchTags;
}
// Writing static HTML to a file.
fileWriter.append(htmlFilepath, html);
const isParallelRoute = /\/@\w+/.test(page);
const isNonSuccessfulStatusCode = res.statusCode > 300;
// When PPR is enabled, we don't always send 200 for routes that have been
// pregenerated, so we should grab the status code from the mocked
// response.
let status = renderOpts.experimental.isRoutePPREnabled ? res.statusCode : undefined;
if (isDefaultNotFound) {
// Override the default /_not-found page status code to 404
status = 404;
} else if (isDefaultGlobalError) {
// Override the default /_global-error page status code to 500
status = 500;
} else if (isNonSuccessfulStatusCode && !isParallelRoute) {
// If it's parallel route the status from mock response is 404
status = res.statusCode;
}
// Writing the request metadata to a file.
const meta = {
status,
headers,
postponed,
segmentPaths,
prefetchHints
};
fileWriter.append(htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX), JSON.stringify(meta, null, 2));
return {
// Filter the metadata if the environment does not have next support.
metadata: hasNextSupport ? meta : {
segmentPaths: meta.segmentPaths,
prefetchHints: meta.prefetchHints
},
hasEmptyStaticShell: Boolean(postponed) && html === '',
hasPostponed: Boolean(postponed),
hasStaticRsc,
cacheControl,
fetchMetrics,
renderResumeDataCache: renderResumeDataCache ? await stringifyResumeDataCache(renderResumeDataCache, renderOpts.cacheComponents) : undefined
};
} catch (err) {
if (!isDynamicUsageError(err)) {
throw err;
}
// We should fail rendering if a client side rendering bailout
// occurred at the page level.
if (isBailoutToCSRError(err)) {
throw err;
}
let fetchMetrics;
if (debugOutput) {
const store = renderOpts.store;
const { dynamicUsageDescription, dynamicUsageStack } = store;
fetchMetrics = store.fetchMetrics;
logDynamicUsageWarning({
path,
description: dynamicUsageDescription ?? '',
stack: dynamicUsageStack
});
}
return {
cacheControl: {
revalidate: 0,
expire: undefined
},
fetchMetrics
};
}
}
function logDynamicUsageWarning({ path, description, stack }) {
const errMessage = Object.defineProperty(new Error(`Static generation failed due to dynamic usage on ${path}, reason: ${description}`), "__NEXT_ERROR_CODE", {
value: "E381",
enumerable: false,
configurable: true
});
if (stack) {
errMessage.stack = errMessage.message + stack.substring(stack.indexOf('\n'));
}
console.warn(errMessage);
}
//# sourceMappingURL=app-page.js.map
File diff suppressed because one or more lines are too long
+116
View File
@@ -0,0 +1,116 @@
import { INFINITE_CACHE, NEXT_BODY_SUFFIX, NEXT_CACHE_TAGS_HEADER, NEXT_META_SUFFIX } from '../../lib/constants';
import { NodeNextRequest } from '../../server/base-http/node';
import { NextRequestAdapter, signalFromNodeResponse } from '../../server/web/spec-extension/adapters/next-request';
import { toNodeOutgoingHttpHeaders } from '../../server/web/utils';
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error';
import { isStaticGenEnabled } from '../../server/route-modules/app-route/helpers/is-static-gen-enabled';
import { isMetadataRoute } from '../../lib/metadata/is-metadata-route';
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths';
import { AfterRunner } from '../../server/after/run-with-after';
export var ExportedAppRouteFiles = /*#__PURE__*/ function(ExportedAppRouteFiles) {
ExportedAppRouteFiles["BODY"] = "BODY";
ExportedAppRouteFiles["META"] = "META";
return ExportedAppRouteFiles;
}({});
export async function exportAppRoute(req, res, params, page, module, incrementalCache, cacheLifeProfiles, htmlFilepath, fileWriter, cacheComponents, experimental, buildId) {
// Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}`;
// Adapt the request and response to the Next.js request and response.
const request = NextRequestAdapter.fromNodeNextRequest(new NodeNextRequest(req), signalFromNodeResponse(res));
const afterRunner = new AfterRunner();
// Create the context for the handler. This contains the params from
// the route and the context for the request.
const context = {
params,
previewProps: {
previewModeEncryptionKey: '',
previewModeId: '',
previewModeSigningKey: ''
},
renderOpts: {
cacheComponents,
experimental,
isBuildTimePrerendering: true,
supportsDynamicResponse: false,
incrementalCache,
waitUntil: afterRunner.context.waitUntil,
onClose: afterRunner.context.onClose,
onAfterTaskError: afterRunner.context.onTaskError,
cacheLifeProfiles
},
sharedContext: {
buildId
}
};
try {
const userland = module.userland;
// we don't bail from the static optimization for
// metadata routes, since it's app-route we can always append /route suffix.
const routePath = normalizeAppPath(page) + '/route';
const isPageMetadataRoute = isMetadataRoute(routePath);
if (!isStaticGenEnabled(userland) && !isPageMetadataRoute && // We don't disable static gen when cacheComponents is enabled because we
// expect that anything dynamic in the GET handler will make it dynamic
// and thus avoid the cache surprises that led to us removing static gen
// unless specifically opted into
cacheComponents !== true) {
return {
cacheControl: {
revalidate: 0,
expire: undefined
}
};
}
const response = await module.handle(request, context);
const isValidStatus = response.status < 400 || response.status === 404;
if (!isValidStatus) {
return {
cacheControl: {
revalidate: 0,
expire: undefined
}
};
}
const blob = await response.blob();
// TODO(after): if we abort a prerender because of an error in an after-callback
// we should probably communicate that better (and not log the error twice)
await afterRunner.executeAfter();
const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;
const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;
const headers = toNodeOutgoingHttpHeaders(response.headers);
const cacheTags = context.renderOpts.collectedTags;
if (cacheTags) {
headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;
}
if (!headers['content-type'] && blob.type) {
headers['content-type'] = blob.type;
}
// Writing response body to a file.
const body = Buffer.from(await blob.arrayBuffer());
fileWriter.append(htmlFilepath.replace(/\.html$/, NEXT_BODY_SUFFIX), body);
// Write the request metadata to a file.
const meta = {
status: response.status,
headers
};
fileWriter.append(htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX), JSON.stringify(meta));
return {
cacheControl: {
revalidate,
expire
},
metadata: meta
};
} catch (err) {
if (!isDynamicUsageError(err)) {
throw err;
}
return {
cacheControl: {
revalidate: 0,
expire: undefined
}
};
}
}
//# sourceMappingURL=app-route.js.map
File diff suppressed because one or more lines are too long
+78
View File
@@ -0,0 +1,78 @@
import RenderResult from '../../server/render-result';
import { join } from 'path';
import { HTML_CONTENT_TYPE_HEADER, NEXT_DATA_SUFFIX, SERVER_PROPS_EXPORT_ERROR } from '../../lib/constants';
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';
import { lazyRenderPagesPage } from '../../server/route-modules/pages/module.render';
/**
* Renders & exports a page associated with the /pages directory
*/ export async function exportPagesPage(req, res, path, page, query, params, htmlFilepath, htmlFilename, pagesDataDir, buildExport, isDynamic, sharedContext, renderContext, hasOrigQueryValues, renderOpts, components, fileWriter) {
if (components.getServerSideProps) {
throw Object.defineProperty(new Error(`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`), "__NEXT_ERROR_CODE", {
value: "E15",
enumerable: false,
configurable: true
});
}
// for non-dynamic SSG pages we should have already
// prerendered the file
if (!buildExport && components.getStaticProps && !isDynamic) {
return;
}
// Pages router merges page params (e.g. [lang]) with query params
// primarily to support them both being accessible on `useRouter().query`.
// If we extracted dynamic params from the path, we need to merge them
// back into the query object.
const searchAndDynamicParams = {
...query,
...params
};
if (components.getStaticProps && !htmlFilepath.endsWith('.html')) {
// make sure it ends with .html if the name contains a dot
htmlFilepath += '.html';
htmlFilename += '.html';
}
let renderResult;
if (typeof components.Component === 'string') {
renderResult = RenderResult.fromStatic(components.Component, HTML_CONTENT_TYPE_HEADER);
if (hasOrigQueryValues) {
throw Object.defineProperty(new Error(`\nError: you provided query values for ${path} which is an auto-exported page. These can not be applied since the page can no longer be re-rendered on the server. To disable auto-export for this page add \`getInitialProps\`\n`), "__NEXT_ERROR_CODE", {
value: "E505",
enumerable: false,
configurable: true
});
}
} else {
/**
* This sets environment variable to be used at the time of SSR by head.tsx.
* Using this from process.env allows targeting SSR by calling
* `process.env.__NEXT_OPTIMIZE_CSS`.
*/ if (renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true);
}
try {
renderResult = await lazyRenderPagesPage(req, res, page, searchAndDynamicParams, renderOpts, sharedContext, renderContext);
} catch (err) {
if (!isBailoutToCSRError(err)) throw err;
}
}
const ssgNotFound = renderResult == null ? void 0 : renderResult.metadata.isNotFound;
const html = renderResult && !renderResult.isNull ? renderResult.toUnchunkedString() : '';
const metadata = (renderResult == null ? void 0 : renderResult.metadata) || {};
if (metadata.pageData) {
const dataFile = join(pagesDataDir, htmlFilename.replace(/\.html$/, NEXT_DATA_SUFFIX));
fileWriter.append(dataFile, JSON.stringify(metadata.pageData));
}
if (!ssgNotFound) {
// don't attempt writing to disk if getStaticProps returned not found
fileWriter.append(htmlFilepath, html);
}
return {
cacheControl: metadata.cacheControl ?? {
revalidate: false,
expire: undefined
},
ssgNotFound
};
}
//# sourceMappingURL=pages.js.map
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
export { };
//# sourceMappingURL=types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/export/routes/types.ts"],"sourcesContent":["import type { OutgoingHttpHeaders } from 'node:http'\nimport type { PrefetchHints } from '../../shared/lib/app-router-types'\n\nexport type RouteMetadata = {\n status: number | undefined\n headers: OutgoingHttpHeaders | undefined\n postponed: string | undefined\n segmentPaths: Array<string> | undefined\n prefetchHints: PrefetchHints | undefined\n}\n"],"names":[],"mappings":"AAGA,WAMC","ignoreList":[0]}
+3
View File
@@ -0,0 +1,3 @@
export { };
//# sourceMappingURL=types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/types.ts"],"sourcesContent":["import type { RenderOptsPartial as AppRenderOptsPartial } from '../server/app-render/types'\nimport type { RenderOptsPartial as PagesRenderOptsPartial } from '../server/render'\nimport type {\n GenericComponentMod,\n LoadComponentsReturnType,\n} from '../server/load-components'\nimport type { OutgoingHttpHeaders } from 'http'\nimport type { ExportPathMap, NextConfigComplete } from '../server/config-shared'\nimport type { CacheControl } from '../server/lib/cache-control'\nimport type { NextEnabledDirectories } from '../server/base-server'\nimport type {\n SerializableTurborepoAccessTraceResult,\n TurborepoAccessTraceResult,\n} from '../build/turborepo-access-trace'\nimport type { FetchMetrics } from '../server/base-http'\nimport type { RouteMetadata } from './routes/types'\nimport type { RenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'\nimport type { StaticWorker } from '../build'\n\nexport type ExportPathEntry = ExportPathMap[keyof ExportPathMap] & {\n path: string\n}\n\nexport interface ExportPagesInput {\n buildId: string\n deploymentId: string\n clientAssetToken: string\n exportPaths: ExportPathEntry[]\n parentSpanId: number\n dir: string\n distDir: string\n outDir: string\n pagesDataDir: string\n renderOpts: WorkerRenderOptsPartial\n nextConfig: NextConfigComplete\n cacheMaxMemorySize: NextConfigComplete['cacheMaxMemorySize']\n fetchCache: boolean | undefined\n cacheHandler: string | undefined\n fetchCacheKeyPrefix: string | undefined\n options: ExportAppOptions\n renderResumeDataCachesByPage: Record<string, string> | undefined\n}\n\nexport interface ExportPageInput {\n buildId: string\n deploymentId: string\n clientAssetToken: string\n exportPath: ExportPathEntry\n distDir: string\n outDir: string\n pagesDataDir: string\n renderOpts: WorkerRenderOptsPartial\n trailingSlash?: boolean\n buildExport?: boolean\n subFolders?: boolean\n optimizeCss: any\n disableOptimizedLoading: any\n parentSpanId: number\n httpAgentOptions: NextConfigComplete['httpAgentOptions']\n debugOutput?: boolean\n nextConfigOutput?: NextConfigComplete['output']\n enableExperimentalReact?: boolean\n sriEnabled: boolean\n renderResumeDataCache: RenderResumeDataCache | undefined\n}\n\nexport type ExportRouteResult =\n | {\n cacheControl: CacheControl\n metadata?: Partial<RouteMetadata>\n ssgNotFound?: boolean\n hasEmptyStaticShell?: boolean\n hasPostponed?: boolean\n hasStaticRsc?: boolean\n fetchMetrics?: FetchMetrics\n renderResumeDataCache?: string\n }\n | {\n error: boolean\n }\n\nexport type ExportPageResult = ExportRouteResult & {\n duration: number\n turborepoAccessTraceResult?: SerializableTurborepoAccessTraceResult\n}\n\nexport type ExportPagesResult = {\n result: ExportPageResult | undefined\n path: string\n page: string\n pageKey: string\n}[]\n\nexport type WorkerRenderOptsPartial = PagesRenderOptsPartial &\n AppRenderOptsPartial\n\nexport type WorkerRenderOpts<\n NextModule extends GenericComponentMod = GenericComponentMod,\n> = WorkerRenderOptsPartial & LoadComponentsReturnType<NextModule>\n\nexport interface ExportAppOptions {\n staticWorker?: StaticWorker\n outdir: string\n enabledDirectories: NextEnabledDirectories\n silent?: boolean\n debugOutput?: boolean\n debugPrerender?: boolean\n pages?: string[]\n buildExport: boolean\n statusMessage?: string\n nextConfig?: NextConfigComplete\n hasOutdirFromCli?: boolean\n numWorkers: number\n appDirOnly: boolean\n}\n\nexport type ExportPageMetadata = {\n revalidate: number | false\n metadata:\n | {\n status?: number | undefined\n headers?: OutgoingHttpHeaders | undefined\n }\n | undefined\n duration: number\n}\n\nexport type ExportAppResult = {\n /**\n * Page information keyed by path.\n */\n byPath: Map<\n string,\n {\n /**\n * The cache control for the page.\n */\n cacheControl?: CacheControl\n /**\n * The metadata for the page.\n */\n metadata?: Partial<RouteMetadata>\n /**\n * If the page has an empty static shell when using PPR.\n */\n hasEmptyStaticShell?: boolean\n /**\n * If the page has postponed when using PPR.\n */\n hasPostponed?: boolean\n /**\n * If the page emitted a static RSC payload.\n */\n hasStaticRsc?: boolean\n\n fetchMetrics?: FetchMetrics\n }\n >\n\n /**\n * Durations for each page in milliseconds.\n */\n byPage: Map<string, { durationsByPath: Map<string, number> }>\n\n /**\n * The paths that were not found during SSG.\n */\n ssgNotFoundPaths: Set<string>\n\n /**\n * Traced dependencies for each page.\n */\n turborepoAccessTraceResults: Map<string, TurborepoAccessTraceResult>\n}\n"],"names":[],"mappings":"AA+HA,WA8CC","ignoreList":[0]}
+14
View File
@@ -0,0 +1,14 @@
export function hasCustomExportOutput(config) {
// In the past, a user had to run "next build" to generate
// ".next" (or whatever the distDir) followed by "next export"
// to generate "out" (or whatever the outDir). However, when
// "output: export" is configured, "next build" does both steps.
// So the user-configured distDir is actually the outDir.
// We'll do some custom logic when meeting this condition.
// e.g.
// Will set config.distDir to .next to make sure the manifests
// are still reading from temporary .next directory.
return config.output === 'export' && config.distDir !== '.next';
}
//# sourceMappingURL=utils.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/utils.ts"],"sourcesContent":["import type { NextConfigComplete } from '../server/config-shared'\n\nexport function hasCustomExportOutput(config: NextConfigComplete) {\n // In the past, a user had to run \"next build\" to generate\n // \".next\" (or whatever the distDir) followed by \"next export\"\n // to generate \"out\" (or whatever the outDir). However, when\n // \"output: export\" is configured, \"next build\" does both steps.\n // So the user-configured distDir is actually the outDir.\n // We'll do some custom logic when meeting this condition.\n // e.g.\n // Will set config.distDir to .next to make sure the manifests\n // are still reading from temporary .next directory.\n return config.output === 'export' && config.distDir !== '.next'\n}\n"],"names":["hasCustomExportOutput","config","output","distDir"],"mappings":"AAEA,OAAO,SAASA,sBAAsBC,MAA0B;IAC9D,0DAA0D;IAC1D,8DAA8D;IAC9D,4DAA4D;IAC5D,gEAAgE;IAChE,yDAAyD;IACzD,0DAA0D;IAC1D,OAAO;IACP,8DAA8D;IAC9D,oDAAoD;IACpD,OAAOA,OAAOC,MAAM,KAAK,YAAYD,OAAOE,OAAO,KAAK;AAC1D","ignoreList":[0]}
+430
View File
@@ -0,0 +1,430 @@
import '../server/node-environment';
import { installBindings } from '../build/swc/install-bindings';
import { installCodeFrameSupport } from '../server/lib/install-code-frame';
process.env.NEXT_IS_EXPORT_WORKER = 'true';
import { extname, join, dirname, sep } from 'path';
import fs from 'fs/promises';
import { loadComponents } from '../server/load-components';
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic';
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path';
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path';
import { trace } from '../trace';
import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env';
import { addRequestMeta } from '../server/request-meta';
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths';
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash';
import { createRequestResponseMocks } from '../server/lib/mock-request';
import { isAppRouteRoute } from '../lib/is-app-route-route';
import { hasNextSupport } from '../server/ci-info';
import { exportAppRoute } from './routes/app-route';
import { exportAppPage } from './routes/app-page';
import { exportPagesPage } from './routes/pages';
import { getParams } from './helpers/get-params';
import { createIncrementalCache } from './helpers/create-incremental-cache';
import { isPostpone } from '../server/lib/router-utils/is-postpone';
import { isDynamicUsageError } from './helpers/is-dynamic-usage-error';
import { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr';
import { turborepoTraceAccess, TurborepoAccessTraceResult } from '../build/turborepo-access-trace';
import { createOpaqueFallbackRouteParams } from '../server/request/fallback-params';
import { needsExperimentalReact } from '../lib/needs-experimental-react';
import { isStaticGenBailoutError } from '../client/components/static-generation-bailout';
import { MultiFileWriter } from '../lib/multi-file-writer';
import { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache';
import { installGlobalBehaviors } from '../server/node-environment-extensions/global-behaviors';
globalThis.__NEXT_DATA__ = {
nextExport: true
};
class TimeoutError extends Error {
constructor(...args){
super(...args), this.code = 'NEXT_EXPORT_TIMEOUT_ERROR';
}
}
class ExportPageError extends Error {
constructor(...args){
super(...args), this.code = 'NEXT_EXPORT_PAGE_ERROR';
}
}
async function exportPageImpl(input, fileWriter) {
var _req_url;
const { exportPath, distDir, pagesDataDir, buildExport = false, subFolders = false, optimizeCss, disableOptimizedLoading, debugOutput = false, enableExperimentalReact, trailingSlash, sriEnabled, renderOpts: commonRenderOpts, outDir: commonOutDir, buildId, deploymentId, clientAssetToken, renderResumeDataCache } = input;
if (enableExperimentalReact) {
process.env.__NEXT_EXPERIMENTAL_REACT = 'true';
}
const { path, page, // The parameters that are currently unknown.
_fallbackRouteParams = [], // Check if this is an `app/` page.
_isAppDir: isAppDir = false, // Check if this should error when dynamic usage is detected.
_isDynamicError: isDynamicError = false, // If this page supports partial prerendering, then we need to pass that to
// the renderOpts.
_isRoutePPREnabled: isRoutePPREnabled, // Configure the rendering of the page to allow that an empty static shell
// is generated while rendering using PPR and Cache Components.
_allowEmptyStaticShell: allowEmptyStaticShell = false, // When true, attempt to run build-time instant validation for this export path.
_runInstantValidation: runInstantValidation = false, // Pull the original query out.
query: originalQuery = {} } = exportPath;
const fallbackRouteParams = createOpaqueFallbackRouteParams(_fallbackRouteParams);
let query = {
...originalQuery
};
const pathname = normalizeAppPath(page);
const isDynamic = isDynamicRoute(page);
const outDir = isAppDir ? join(distDir, 'server/app') : commonOutDir;
const filePath = normalizePagePath(path);
let updatedPath = exportPath._ssgPath || path;
let locale = exportPath._locale || commonRenderOpts.locale;
if (commonRenderOpts.locale) {
const localePathResult = normalizeLocalePath(path, commonRenderOpts.locales);
if (localePathResult.detectedLocale) {
updatedPath = localePathResult.pathname;
locale = localePathResult.detectedLocale;
}
}
// We need to show a warning if they try to provide query values
// for an auto-exported page since they won't be available
const hasOrigQueryValues = Object.keys(originalQuery).length > 0;
// Check if the page is a specified dynamic route
const { pathname: nonLocalizedPath } = normalizeLocalePath(path, commonRenderOpts.locales);
let params;
if (isDynamic && page !== nonLocalizedPath) {
const normalizedPage = isAppDir ? normalizeAppPath(page) : page;
params = getParams(normalizedPage, updatedPath);
}
const { req, res } = createRequestResponseMocks({
url: updatedPath
});
// If this is a status code page, then set the response code.
for (const statusCode of [
404,
500
]){
if ([
`/${statusCode}`,
`/${statusCode}.html`,
`/${statusCode}/index.html`
].some((p)=>p === updatedPath || `/${locale}${p}` === updatedPath)) {
res.statusCode = statusCode;
}
}
// Ensure that the URL has a trailing slash if it's configured.
if (trailingSlash && !((_req_url = req.url) == null ? void 0 : _req_url.endsWith('/'))) {
req.url += '/';
}
// Set the resolved pathname without trailing slash as request metadata.
addRequestMeta(req, 'resolvedPathname', removeTrailingSlash(updatedPath));
if (locale && buildExport && commonRenderOpts.domainLocales && commonRenderOpts.domainLocales.some((dl)=>{
var _dl_locales;
return dl.defaultLocale === locale || ((_dl_locales = dl.locales) == null ? void 0 : _dl_locales.includes(locale || ''));
})) {
addRequestMeta(req, 'isLocaleDomain', true);
}
const getHtmlFilename = (p)=>subFolders ? `${p}${sep}index.html` : `${p}.html`;
let htmlFilename = getHtmlFilename(filePath);
// dynamic routes can provide invalid extensions e.g. /blog/[...slug] returns an
// extension of `.slug]`
const pageExt = isDynamic || isAppDir ? '' : extname(page);
const pathExt = isDynamic || isAppDir ? '' : extname(path);
// force output 404.html for backwards compat
if (path === '/404.html') {
htmlFilename = path;
} else if (pageExt !== pathExt && pathExt !== '') {
const isBuiltinPaths = [
'/500',
'/404'
].some((p)=>p === path || p === path + '.html');
// If the ssg path has .html extension, and it's not builtin paths, use it directly
// Otherwise, use that as the filename instead
const isHtmlExtPath = !isBuiltinPaths && path.endsWith('.html');
htmlFilename = isHtmlExtPath ? getHtmlFilename(path) : path;
} else if (path === '/') {
// If the path is the root, just use index.html
htmlFilename = 'index.html';
}
const baseDir = join(outDir, dirname(htmlFilename));
let htmlFilepath = join(outDir, htmlFilename);
await fs.mkdir(baseDir, {
recursive: true
});
const components = await loadComponents({
distDir,
page,
isAppPath: isAppDir,
isDev: false,
sriEnabled,
needsManifestsForLegacyReasons: true
});
// Handle App Routes.
if (isAppDir && isAppRouteRoute(page)) {
return exportAppRoute(req, res, params, page, components.routeModule, commonRenderOpts.incrementalCache, commonRenderOpts.cacheLifeProfiles, htmlFilepath, fileWriter, commonRenderOpts.cacheComponents, commonRenderOpts.experimental, buildId);
}
const renderOpts = {
...components,
...commonRenderOpts,
params,
optimizeCss,
disableOptimizedLoading,
locale,
supportsDynamicResponse: false,
// During the export phase in next build, we always enable the streaming metadata since if there's
// any dynamic access in metadata we can determine it in the build phase.
// If it's static, then it won't affect anything.
// If it's dynamic, then it can be handled when request hits the route.
serveStreamingMetadata: true,
allowEmptyStaticShell,
runInstantValidation,
experimental: {
...commonRenderOpts.experimental,
isRoutePPREnabled
},
renderResumeDataCache
};
// Handle App Pages
if (isAppDir) {
const sharedContext = {
buildId,
deploymentId,
clientAssetToken
};
return exportAppPage(req, res, page, path, pathname, query, fallbackRouteParams, renderOpts, htmlFilepath, debugOutput, isDynamicError, fileWriter, sharedContext);
} else {
const sharedContext = {
buildId,
deploymentId,
clientAssetToken,
customServer: undefined
};
const renderContext = {
isFallback: exportPath._pagesFallback ?? false,
isDraftMode: false,
developmentNotFoundSourcePage: undefined
};
return exportPagesPage(req, res, path, page, query, params, htmlFilepath, htmlFilename, pagesDataDir, buildExport, isDynamic, sharedContext, renderContext, hasOrigQueryValues, renderOpts, components, fileWriter);
}
}
export async function exportPages(input) {
// Load native bindings in the worker process so that code frame rendering
// (which uses the native codeFrameColumns function) works during prerendering.
await installBindings();
installCodeFrameSupport();
const { exportPaths, dir, distDir, outDir, cacheHandler, cacheMaxMemorySize, fetchCacheKeyPrefix, pagesDataDir, renderOpts, nextConfig, options, renderResumeDataCachesByPage = {} } = input;
installGlobalBehaviors(nextConfig);
if (nextConfig.enablePrerenderSourceMaps) {
try {
// Same as `next dev`
// Limiting the stack trace to a useful amount of frames is handled by ignore-listing.
// TODO: How high can we go without severely impacting CPU/memory?
Error.stackTraceLimit = 50;
} catch {}
}
// If the fetch cache was enabled, we need to create an incremental
// cache instance for this page.
const incrementalCache = await createIncrementalCache({
cacheHandler,
cacheMaxMemorySize,
fetchCacheKeyPrefix,
distDir,
dir,
// skip writing to disk in minimal mode for now, pending some
// changes to better support it
flushToDisk: !hasNextSupport,
cacheHandlers: nextConfig.cacheHandlers
});
renderOpts.incrementalCache = incrementalCache;
const maxConcurrency = nextConfig.experimental.staticGenerationMaxConcurrency ?? 8;
const results = [];
const exportPageWithRetry = async (exportPath, maxAttempts)=>{
var // Also tests for `inspect-brk`
_process_env_NODE_OPTIONS;
const { page, path } = exportPath;
const pageKey = page !== path ? `${page}: ${path}` : path;
let attempt = 0;
let result;
const hasDebuggerAttached = (_process_env_NODE_OPTIONS = process.env.NODE_OPTIONS) == null ? void 0 : _process_env_NODE_OPTIONS.includes('--inspect');
const renderResumeDataCache = renderResumeDataCachesByPage[pageKey] ? createRenderResumeDataCache(renderResumeDataCachesByPage[pageKey], renderOpts.experimental.maxPostponedStateSizeBytes) : undefined;
while(attempt < maxAttempts){
try {
var _nextConfig_experimental_sri;
result = await Promise.race([
exportPage({
exportPath,
distDir,
outDir,
pagesDataDir,
renderOpts,
trailingSlash: nextConfig.trailingSlash,
subFolders: nextConfig.trailingSlash && !options.buildExport,
buildExport: options.buildExport,
optimizeCss: nextConfig.experimental.optimizeCss,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
parentSpanId: input.parentSpanId,
httpAgentOptions: nextConfig.httpAgentOptions,
debugOutput: options.debugOutput,
enableExperimentalReact: needsExperimentalReact(nextConfig),
sriEnabled: Boolean((_nextConfig_experimental_sri = nextConfig.experimental.sri) == null ? void 0 : _nextConfig_experimental_sri.algorithm),
buildId: input.buildId,
deploymentId: input.deploymentId,
clientAssetToken: input.clientAssetToken,
renderResumeDataCache
}),
hasDebuggerAttached ? new Promise(()=>{}) : new Promise((_, reject)=>{
setTimeout(()=>{
reject(new TimeoutError());
}, nextConfig.staticPageGenerationTimeout * 1000);
})
]);
// If there was an error in the export, throw it immediately. In the catch block, we might retry the export,
// or immediately fail the build, depending on user configuration. We might also continue on and attempt other pages.
if (result && 'error' in result) {
throw new ExportPageError();
}
break;
} catch (err) {
// The only error that should be caught here is an ExportError, as `exportPage` doesn't throw and instead returns an object with an `error` property.
// This is an overly cautious check to ensure that we don't accidentally catch an unexpected error.
if (!(err instanceof ExportPageError || err instanceof TimeoutError)) {
throw err;
}
if (err instanceof TimeoutError) {
// If the export times out, we will restart the worker up to 3 times.
maxAttempts = 3;
}
// We've reached the maximum number of attempts
if (attempt >= maxAttempts - 1) {
// Log a message if we've reached the maximum number of attempts.
// We only care to do this if maxAttempts was configured.
if (maxAttempts > 1) {
console.info(`Failed to build ${pageKey} after ${maxAttempts} attempts.`);
}
// If prerenderEarlyExit is enabled, we'll exit the build immediately.
if (nextConfig.experimental.prerenderEarlyExit) {
console.error(`Export encountered an error on ${pageKey}, exiting the build.`);
process.exit(1);
} else {
// Otherwise, this is a no-op. The build will continue, and a summary of failed pages will be displayed at the end.
}
} else {
// Otherwise, we have more attempts to make. Wait before retrying
if (err instanceof TimeoutError) {
console.info(`Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}) because it took more than ${nextConfig.staticPageGenerationTimeout} seconds. Retrying again shortly.`);
} else {
console.info(`Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}). Retrying again shortly.`);
}
// Exponential backoff with random jitter to avoid thundering herd on retries
const baseDelay = 500 // 500ms
;
const maxDelay = 2000 // 2 seconds
;
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
const jitter = Math.random() * 0.3 * delay // Add up to 30% random jitter
;
await new Promise((r)=>setTimeout(r, delay + jitter));
}
}
attempt++;
}
return {
result,
path,
page,
pageKey
};
};
for(let i = 0; i < exportPaths.length; i += maxConcurrency){
const subset = exportPaths.slice(i, i + maxConcurrency);
const subsetResults = await Promise.all(subset.map((exportPath)=>exportPageWithRetry(exportPath, nextConfig.experimental.staticGenerationRetryCount ?? 1)));
results.push(...subsetResults);
}
return results;
}
async function exportPage(input) {
trace('export-page', input.parentSpanId).setAttribute('path', input.exportPath.path);
// Configure the http agent.
setHttpClientAndAgentOptions({
httpAgentOptions: input.httpAgentOptions
});
const fileWriter = new MultiFileWriter({
writeFile: (filePath, data)=>fs.writeFile(filePath, data),
mkdir: (dir)=>fs.mkdir(dir, {
recursive: true
})
});
const exportPageSpan = trace('export-page-worker', input.parentSpanId);
const start = Date.now();
const turborepoAccessTraceResult = new TurborepoAccessTraceResult();
// Export the page.
let result;
try {
result = await exportPageSpan.traceAsyncFn(()=>turborepoTraceAccess(()=>exportPageImpl(input, fileWriter), turborepoAccessTraceResult));
// Wait for all the files to flush to disk.
await fileWriter.wait();
// If there was no result, then we can exit early.
if (!result) return;
// If there was an error, then we can exit early.
if ('error' in result) {
return {
error: result.error,
duration: Date.now() - start
};
}
} catch (err) {
console.error(`Error occurred prerendering page "${input.exportPath.path}". Read more: https://nextjs.org/docs/messages/prerender-error`);
// bailoutToCSRError errors should not leak to the user as they are not actionable; they're
// a framework signal
if (!isBailoutToCSRError(err)) {
// A static generation bailout error is a framework signal to fail static generation but
// and will encode a reason in the error message. If there is a message, we'll print it.
// Otherwise there's nothing to show as we don't want to leak an error internal error stack to the user.
// TODO: Always log the full error. ignore-listing will take care of hiding internal stacks.
if (isStaticGenBailoutError(err)) {
if (err.message) {
console.error(`Error: ${err.message}`);
}
} else {
console.error(err);
}
}
return {
error: true,
duration: Date.now() - start
};
}
// Notify the parent process that we processed a page (used by the progress activity indicator)
process.send == null ? void 0 : process.send.call(process, [
3,
{
type: 'activity'
}
]);
// Otherwise we can return the result.
return {
...result,
duration: Date.now() - start,
turborepoAccessTraceResult: turborepoAccessTraceResult.serialize()
};
}
process.on('unhandledRejection', (err)=>{
// if it's a postpone error, it'll be handled later
// when the postponed promise is actually awaited.
if (isPostpone(err)) {
return;
}
// we don't want to log these errors
if (isDynamicUsageError(err)) {
return;
}
console.error(err);
});
process.on('rejectionHandled', ()=>{
// It is ok to await a Promise late in Next.js as it allows for better
// prefetching patterns to avoid waterfalls. We ignore logging these.
// We should've already errored in anyway unhandledRejection.
});
const FATAL_UNHANDLED_NEXT_API_EXIT_CODE = 78;
process.on('uncaughtException', (err)=>{
if (isDynamicUsageError(err)) {
console.error('A Next.js API that uses exceptions to signal framework behavior was uncaught. This suggests improper usage of a Next.js API. The original error is printed below and the build will now exit.');
console.error(err);
process.exit(FATAL_UNHANDLED_NEXT_API_EXIT_CODE);
} else {
console.error(err);
}
});
//# sourceMappingURL=worker.js.map
File diff suppressed because one or more lines are too long