Initial commit
This commit is contained in:
Generated
Vendored
+46
@@ -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()) {
|
||||
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
|
||||
Generated
Vendored
+1
@@ -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()) {\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,2BAA2B;QAC9C,KAAK,MAAM,CAACe,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"}
|
||||
+31
@@ -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
@@ -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"}
|
||||
Generated
Vendored
+7
@@ -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
|
||||
Generated
Vendored
+1
@@ -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"}
|
||||
+615
@@ -0,0 +1,615 @@
|
||||
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 { formatAmpMessages } from '../build/output/index';
|
||||
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 { 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/generate-interception-routes-rewrites';
|
||||
import { extractInfoFromServerReferenceId } from '../shared/lib/server-reference-info';
|
||||
import { convertSegmentPathToStaticExportFilename } from '../shared/lib/segment-cache/segment-value-encoding';
|
||||
export class ExportError extends Error {
|
||||
constructor(...args){
|
||||
super(...args), this.code = 'NEXT_EXPORT_ERROR';
|
||||
}
|
||||
}
|
||||
async function exportAppImpl(dir, options, span) {
|
||||
var _nextConfig_amp, _nextConfig_experimental_amp, _nextConfig_experimental_amp1;
|
||||
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));
|
||||
const distDir = join(dir, nextConfig.distDir);
|
||||
const telemetry = options.buildExport ? null : new Telemetry({
|
||||
distDir
|
||||
});
|
||||
if (telemetry) {
|
||||
telemetry.record(eventCliSession(distDir, 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,
|
||||
nextExport: true,
|
||||
assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
|
||||
distDir,
|
||||
dev: false,
|
||||
basePath: nextConfig.basePath,
|
||||
trailingSlash: nextConfig.trailingSlash,
|
||||
canonicalBase: ((_nextConfig_amp = nextConfig.amp) == null ? void 0 : _nextConfig_amp.canonicalBase) || '',
|
||||
ampSkipValidation: ((_nextConfig_experimental_amp = nextConfig.experimental.amp) == null ? void 0 : _nextConfig_experimental_amp.skipValidation) || false,
|
||||
ampOptimizerConfig: ((_nextConfig_experimental_amp1 = nextConfig.experimental.amp) == null ? void 0 : _nextConfig_experimental_amp1.optimizer) || undefined,
|
||||
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.experimental.cacheLife,
|
||||
nextFontManifest: require(join(distDir, 'server', `${NEXT_FONT_MANIFEST}.json`)),
|
||||
images: nextConfig.images,
|
||||
...enabledDirectories.app ? {
|
||||
serverActionsManifest
|
||||
} : {},
|
||||
strictNextHead: nextConfig.experimental.strictNextHead ?? true,
|
||||
deploymentId: nextConfig.deploymentId,
|
||||
htmlLimitedBots: nextConfig.htmlLimitedBots.source,
|
||||
experimental: {
|
||||
clientTraceMetadata: nextConfig.experimental.clientTraceMetadata,
|
||||
expireTime: nextConfig.expireTime,
|
||||
dynamicIO: nextConfig.experimental.dynamicIO ?? false,
|
||||
clientSegmentCache: nextConfig.experimental.clientSegmentCache === 'client-only' ? 'client-only' : Boolean(nextConfig.experimental.clientSegmentCache),
|
||||
dynamicOnHover: nextConfig.experimental.dynamicOnHover ?? false,
|
||||
inlineCss: nextConfig.experimental.inlineCss ?? false,
|
||||
authInterrupts: !!nextConfig.experimental.authInterrupts
|
||||
},
|
||||
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength
|
||||
};
|
||||
const { publicRuntimeConfig } = nextConfig;
|
||||
if (Object.keys(publicRuntimeConfig).length > 0) {
|
||||
renderOpts.runtimeConfig = publicRuntimeConfig;
|
||||
}
|
||||
// We need this for server rendering the Link component.
|
||||
;
|
||||
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;
|
||||
});
|
||||
// only add missing 404 page when `buildExport` is false
|
||||
if (!options.buildExport) {
|
||||
// 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']) {
|
||||
// alias /404.html to /404 to be compatible with custom 404 / _error page
|
||||
exportPathMap['/404.html'] = exportPathMap['/404'];
|
||||
}
|
||||
}
|
||||
// make sure to prevent duplicates
|
||||
const exportPaths = [
|
||||
...new Set(Object.keys(exportPathMap).map((path)=>denormalizePagePath(normalizePagePath(path))))
|
||||
];
|
||||
const filteredPaths = exportPaths.filter((route)=>exportPathMap[route]._isAppDir || // Remove API routes
|
||||
!isAPIRoute(exportPathMap[route].page));
|
||||
if (filteredPaths.length !== exportPaths.length) {
|
||||
hasApiRoutes = true;
|
||||
}
|
||||
if (filteredPaths.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (prerenderManifest && !options.buildExport) {
|
||||
const fallbackEnabledPages = new Set();
|
||||
for (const path of Object.keys(exportPathMap)){
|
||||
const page = exportPathMap[path].page;
|
||||
const prerenderInfo = prerenderManifest.dynamicRoutes[page];
|
||||
if (prerenderInfo && prerenderInfo.fallback !== false) {
|
||||
fallbackEnabledPages.add(page);
|
||||
}
|
||||
}
|
||||
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 ampValidations = {};
|
||||
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 failedExportAttemptsByPage = new Map();
|
||||
// Chunk filtered pages into smaller groups, and call the export worker on each group.
|
||||
// We've set a default minimum of 25 pages per chunk to ensure that even setups
|
||||
// with only a few static pages can leverage a shared incremental cache, however this
|
||||
// value can be configured.
|
||||
const minChunkSize = nextConfig.experimental.staticGenerationMinPagesPerWorker ?? 25;
|
||||
// Calculate the number of workers needed to ensure each chunk has at least minChunkSize pages
|
||||
const numWorkers = Math.min(options.numWorkers, Math.ceil(filteredPaths.length / minChunkSize));
|
||||
// Calculate the chunk size based on the number of workers
|
||||
const chunkSize = Math.ceil(filteredPaths.length / numWorkers);
|
||||
const chunks = Array.from({
|
||||
length: numWorkers
|
||||
}, (_, i)=>filteredPaths.slice(i * chunkSize, (i + 1) * chunkSize));
|
||||
// Distribute remaining pages
|
||||
const remainingPages = filteredPaths.slice(numWorkers * chunkSize);
|
||||
remainingPages.forEach((page, index)=>{
|
||||
chunks[index % chunks.length].push(page);
|
||||
});
|
||||
const progress = createProgress(filteredPaths.length, options.statusMessage || 'Exporting');
|
||||
const worker = createStaticWorker(nextConfig, progress);
|
||||
const results = (await Promise.all(chunks.map((paths)=>worker.exportPages({
|
||||
buildId,
|
||||
paths,
|
||||
exportPathMap,
|
||||
parentSpanId: span.getId(),
|
||||
pagesDataDir,
|
||||
renderOpts,
|
||||
options,
|
||||
dir,
|
||||
distDir,
|
||||
outDir,
|
||||
nextConfig,
|
||||
cacheHandler: nextConfig.cacheHandler,
|
||||
cacheMaxMemorySize: nextConfig.cacheMaxMemorySize,
|
||||
fetchCache: true,
|
||||
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix
|
||||
})))).flat();
|
||||
let hadValidationError = false;
|
||||
const collector = {
|
||||
byPath: new Map(),
|
||||
byPage: new Map(),
|
||||
ssgNotFoundPaths: new Set(),
|
||||
turborepoAccessTraceResults: new Map()
|
||||
};
|
||||
for (const { result, path, pageKey } of results){
|
||||
if (!result) continue;
|
||||
if ('error' in result) {
|
||||
failedExportAttemptsByPage.set(pageKey, true);
|
||||
continue;
|
||||
}
|
||||
const { page } = exportPathMap[path];
|
||||
if (result.turborepoAccessTraceResult) {
|
||||
var _collector_turborepoAccessTraceResults;
|
||||
(_collector_turborepoAccessTraceResults = collector.turborepoAccessTraceResults) == null ? void 0 : _collector_turborepoAccessTraceResults.set(path, TurborepoAccessTraceResult.fromSerialized(result.turborepoAccessTraceResult));
|
||||
}
|
||||
// Capture any amp validations.
|
||||
if (result.ampValidations) {
|
||||
for (const validation of result.ampValidations){
|
||||
ampValidations[validation.page] = validation.result;
|
||||
hadValidationError ||= validation.result.errors.length > 0;
|
||||
}
|
||||
}
|
||||
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.hasEmptyPrelude !== 'undefined') {
|
||||
info.hasEmptyPrelude = result.hasEmptyPrelude;
|
||||
}
|
||||
if (typeof result.hasPostponed !== 'undefined') {
|
||||
info.hasPostponed = result.hasPostponed;
|
||||
}
|
||||
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)=>{
|
||||
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 ampHtmlDest = join(outDir, `${route}.amp${subFolders ? `${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);
|
||||
if (existsSync(`${orig}.amp.html`)) {
|
||||
await fs.mkdir(dirname(ampHtmlDest), {
|
||||
recursive: true
|
||||
});
|
||||
await fs.copyFile(`${orig}.amp.html`, ampHtmlDest);
|
||||
}
|
||||
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 (Object.keys(ampValidations).length) {
|
||||
console.log(formatAmpMessages(ampValidations));
|
||||
}
|
||||
if (hadValidationError) {
|
||||
throw Object.defineProperty(new ExportError(`AMP Validation caused the export to fail. https://nextjs.org/docs/messages/amp-export-validation`), "__NEXT_ERROR_CODE", {
|
||||
value: "E596",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
if (failedExportAttemptsByPage.size > 0) {
|
||||
const failedPages = Array.from(failedExportAttemptsByPage.keys());
|
||||
throw Object.defineProperty(new ExportError(`Export encountered errors on following paths:\n\t${failedPages.sort().join('\n\t')}`), "__NEXT_ERROR_CODE", {
|
||||
value: "E535",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
await fs.writeFile(join(distDir, EXPORT_DETAIL), formatManifest({
|
||||
version: 1,
|
||||
outDirectory: outDir,
|
||||
success: true
|
||||
}), 'utf8');
|
||||
if (telemetry) {
|
||||
await telemetry.flush();
|
||||
}
|
||||
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) {
|
||||
const nextExportSpan = span.traceChild('next-export');
|
||||
return nextExportSpan.traceAsyncFn(async ()=>{
|
||||
return await exportAppImpl(dir, options, nextExportSpan);
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+213
@@ -0,0 +1,213 @@
|
||||
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error';
|
||||
import { NEXT_CACHE_TAGS_HEADER, NEXT_META_SUFFIX, RSC_PREFETCH_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';
|
||||
export async function prospectiveRenderAppPage(req, res, page, pathname, query, fallbackRouteParams, partialRenderOpts, sharedContext) {
|
||||
const afterRunner = new AfterRunner();
|
||||
// If the page is `/_not-found`, then we should update the page to be `/404`.
|
||||
// UNDERSCORE_NOT_FOUND_ROUTE value used here, however we don't want to import it here as it causes constants to be inlined which we don't want here.
|
||||
if (page === '/_not-found/page') {
|
||||
pathname = '/404';
|
||||
}
|
||||
try {
|
||||
await lazyRenderAppPage(new NodeNextRequest(req), new NodeNextResponse(res), pathname, query, fallbackRouteParams, {
|
||||
...partialRenderOpts,
|
||||
waitUntil: afterRunner.context.waitUntil,
|
||||
onClose: afterRunner.context.onClose,
|
||||
onAfterTaskError: afterRunner.context.onTaskError
|
||||
}, undefined, false, sharedContext);
|
||||
// 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();
|
||||
} 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 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;
|
||||
// If the page is `/_not-found`, then we should update the page to be `/404`.
|
||||
// UNDERSCORE_NOT_FOUND_ROUTE value used here, however we don't want to import it here as it causes constants to be inlined which we don't want here.
|
||||
if (page === '/_not-found/page') {
|
||||
isDefaultNotFound = true;
|
||||
pathname = '/404';
|
||||
}
|
||||
try {
|
||||
const result = await lazyRenderAppPage(new NodeNextRequest(req), new NodeNextResponse(res), pathname, query, fallbackRouteParams, renderOpts, undefined, false, 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 } = 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.
|
||||
if (!flightData && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {
|
||||
throw Object.defineProperty(new Error(`Invariant: failed to get page data for ${path}`), "__NEXT_ERROR_CODE", {
|
||||
value: "E194",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
if (flightData) {
|
||||
// If PPR is enabled, we want to emit a prefetch rsc file for the page
|
||||
// instead of the standard rsc. This is because the standard rsc will
|
||||
// contain the dynamic data. We do this if any routes have PPR enabled so
|
||||
// that the cache read/write is the same.
|
||||
if (renderOpts.experimental.isRoutePPREnabled) {
|
||||
// If PPR is enabled, we should emit the flight data as the prefetch
|
||||
// payload.
|
||||
// TODO: This will eventually be replaced by the per-segment prefetch
|
||||
// output below.
|
||||
fileWriter.append(htmlFilepath.replace(/\.html$/, RSC_PREFETCH_SUFFIX), flightData);
|
||||
} else {
|
||||
// Writing the RSC payload to a file if we don't have PPR enabled.
|
||||
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 (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
|
||||
};
|
||||
fileWriter.append(htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX), JSON.stringify(meta, null, 2));
|
||||
return {
|
||||
// Only include the metadata if the environment has next support.
|
||||
metadata: hasNextSupport ? meta : undefined,
|
||||
hasEmptyPrelude: Boolean(postponed) && html === '',
|
||||
hasPostponed: Boolean(postponed),
|
||||
cacheControl,
|
||||
fetchMetrics
|
||||
};
|
||||
} 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
|
||||
+1
File diff suppressed because one or more lines are too long
+125
@@ -0,0 +1,125 @@
|
||||
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 { hasNextSupport } from '../../server/ci-info';
|
||||
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, 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,
|
||||
prerenderManifest: {
|
||||
version: 4,
|
||||
routes: {},
|
||||
dynamicRoutes: {},
|
||||
preview: {
|
||||
previewModeEncryptionKey: '',
|
||||
previewModeId: '',
|
||||
previewModeSigningKey: ''
|
||||
},
|
||||
notFoundRoutes: []
|
||||
},
|
||||
renderOpts: {
|
||||
experimental,
|
||||
nextExport: true,
|
||||
supportsDynamicResponse: false,
|
||||
incrementalCache,
|
||||
waitUntil: afterRunner.context.waitUntil,
|
||||
onClose: afterRunner.context.onClose,
|
||||
onAfterTaskError: afterRunner.context.onTaskError,
|
||||
cacheLifeProfiles
|
||||
},
|
||||
sharedContext: {
|
||||
buildId
|
||||
}
|
||||
};
|
||||
if (hasNextSupport) {
|
||||
context.renderOpts.isRevalidate = true;
|
||||
}
|
||||
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 dynamicIO 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
|
||||
experimental.dynamicIO !== 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
|
||||
+1
File diff suppressed because one or more lines are too long
+137
@@ -0,0 +1,137 @@
|
||||
import RenderResult from '../../server/render-result';
|
||||
import { join } from 'path';
|
||||
import { isInAmpMode } from '../../shared/lib/amp-mode';
|
||||
import { NEXT_DATA_SUFFIX, SERVER_PROPS_EXPORT_ERROR } from '../../lib/constants';
|
||||
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';
|
||||
import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator';
|
||||
import { FileType, fileExists } from '../../lib/file-exists';
|
||||
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, ampPath, subFolders, outDir, ampValidatorPath, pagesDataDir, buildExport, isDynamic, sharedContext, renderContext, hasOrigQueryValues, renderOpts, components, fileWriter) {
|
||||
var _components_pageConfig, _components_pageConfig1;
|
||||
const ampState = {
|
||||
ampFirst: ((_components_pageConfig = components.pageConfig) == null ? void 0 : _components_pageConfig.amp) === true,
|
||||
hasQuery: Boolean(query.amp),
|
||||
hybrid: ((_components_pageConfig1 = components.pageConfig) == null ? void 0 : _components_pageConfig1.amp) === 'hybrid'
|
||||
};
|
||||
if (!ampValidatorPath) {
|
||||
ampValidatorPath = require.resolve('next/dist/compiled/amphtml-validator/validator_wasm.js');
|
||||
}
|
||||
const inAmpMode = isInAmpMode(ampState);
|
||||
const hybridAmp = ampState.hybrid;
|
||||
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);
|
||||
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 ampValidations = [];
|
||||
const validateAmp = async (rawAmpHtml, ampPageName, validatorPath)=>{
|
||||
const validator = await AmpHtmlValidator.getInstance(validatorPath);
|
||||
const result = validator.validateString(rawAmpHtml);
|
||||
const errors = result.errors.filter((e)=>e.severity === 'ERROR');
|
||||
const warnings = result.errors.filter((e)=>e.severity !== 'ERROR');
|
||||
if (warnings.length || errors.length) {
|
||||
ampValidations.push({
|
||||
page: ampPageName,
|
||||
result: {
|
||||
errors,
|
||||
warnings
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
const html = renderResult && !renderResult.isNull ? renderResult.toUnchunkedString() : '';
|
||||
let ampRenderResult;
|
||||
if (inAmpMode && !renderOpts.ampSkipValidation) {
|
||||
if (!ssgNotFound) {
|
||||
await validateAmp(html, path, ampValidatorPath);
|
||||
}
|
||||
} else if (hybridAmp) {
|
||||
const ampHtmlFilename = subFolders ? join(ampPath, 'index.html') : `${ampPath}.html`;
|
||||
const ampHtmlFilepath = join(outDir, ampHtmlFilename);
|
||||
const exists = await fileExists(ampHtmlFilepath, FileType.File);
|
||||
if (!exists) {
|
||||
try {
|
||||
ampRenderResult = await lazyRenderPagesPage(req, res, page, {
|
||||
...searchAndDynamicParams,
|
||||
amp: '1'
|
||||
}, renderOpts, sharedContext, renderContext);
|
||||
} catch (err) {
|
||||
if (!isBailoutToCSRError(err)) throw err;
|
||||
}
|
||||
const ampHtml = ampRenderResult && !ampRenderResult.isNull ? ampRenderResult.toUnchunkedString() : '';
|
||||
if (!renderOpts.ampSkipValidation) {
|
||||
await validateAmp(ampHtml, page + '?amp=1', ampValidatorPath);
|
||||
}
|
||||
fileWriter.append(ampHtmlFilepath, ampHtml);
|
||||
}
|
||||
}
|
||||
const metadata = (renderResult == null ? void 0 : renderResult.metadata) || (ampRenderResult == null ? void 0 : ampRenderResult.metadata) || {};
|
||||
if (metadata.pageData) {
|
||||
const dataFile = join(pagesDataDir, htmlFilename.replace(/\.html$/, NEXT_DATA_SUFFIX));
|
||||
fileWriter.append(dataFile, JSON.stringify(metadata.pageData));
|
||||
if (hybridAmp) {
|
||||
fileWriter.append(dataFile.replace(/\.json$/, '.amp.json'), JSON.stringify(metadata.pageData));
|
||||
}
|
||||
}
|
||||
if (!ssgNotFound) {
|
||||
// don't attempt writing to disk if getStaticProps returned not found
|
||||
fileWriter.append(htmlFilepath, html);
|
||||
}
|
||||
return {
|
||||
ampValidations,
|
||||
cacheControl: metadata.cacheControl ?? {
|
||||
revalidate: false,
|
||||
expire: undefined
|
||||
},
|
||||
ssgNotFound
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=pages.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+3
@@ -0,0 +1,3 @@
|
||||
export { };
|
||||
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/export/routes/types.ts"],"sourcesContent":["import type { OutgoingHttpHeaders } from 'node:http'\n\nexport type RouteMetadata = {\n status: number | undefined\n headers: OutgoingHttpHeaders | undefined\n postponed: string | undefined\n segmentPaths: Array<string> | undefined\n}\n"],"names":[],"mappings":"AAEA,WAKC"}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export { };
|
||||
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -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 { LoadComponentsReturnType } from '../server/load-components'\nimport type { OutgoingHttpHeaders } from 'http'\nimport type AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'\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'\n\nexport interface AmpValidation {\n page: string\n result: {\n errors: AmpHtmlValidator.ValidationError[]\n warnings: AmpHtmlValidator.ValidationError[]\n }\n}\n\ntype PathMap = ExportPathMap[keyof ExportPathMap]\n\nexport interface ExportPagesInput {\n buildId: string\n paths: string[]\n exportPathMap: ExportPathMap\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'] | undefined\n fetchCache: boolean | undefined\n cacheHandler: string | undefined\n fetchCacheKeyPrefix: string | undefined\n options: ExportAppOptions\n}\n\nexport interface ExportPageInput {\n buildId: string\n path: string\n pathMap: PathMap\n distDir: string\n outDir: string\n pagesDataDir: string\n renderOpts: WorkerRenderOptsPartial\n ampValidatorPath?: string\n trailingSlash?: boolean\n buildExport?: boolean\n serverRuntimeConfig: { [key: string]: any }\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}\n\nexport type ExportRouteResult =\n | {\n ampValidations?: AmpValidation[]\n cacheControl: CacheControl\n metadata?: Partial<RouteMetadata>\n ssgNotFound?: boolean\n hasEmptyPrelude?: boolean\n hasPostponed?: boolean\n fetchMetrics?: FetchMetrics\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 pageKey: string\n}[]\n\nexport type WorkerRenderOptsPartial = PagesRenderOptsPartial &\n AppRenderOptsPartial\n\nexport type WorkerRenderOpts = WorkerRenderOptsPartial &\n LoadComponentsReturnType\n\nexport interface ExportAppOptions {\n outdir: string\n enabledDirectories: NextEnabledDirectories\n silent?: boolean\n debugOutput?: boolean\n pages?: string[]\n buildExport: boolean\n statusMessage?: string\n nextConfig?: NextConfigComplete\n hasOutdirFromCli?: boolean\n numWorkers: number\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 prelude when using PPR.\n */\n hasEmptyPrelude?: boolean\n /**\n * If the page has postponed when using PPR.\n */\n hasPostponed?: 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":"AAyHA,WA0CC"}
|
||||
+14
@@ -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
@@ -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"}
|
||||
+425
@@ -0,0 +1,425 @@
|
||||
import '../server/node-environment';
|
||||
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 isError from '../lib/is-error';
|
||||
import { addRequestMeta } from '../server/request-meta';
|
||||
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths';
|
||||
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, prospectiveRenderAppPage } 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 { getFallbackRouteParams } 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';
|
||||
const envConfig = require('../shared/lib/runtime-config.external');
|
||||
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 { path, pathMap, distDir, pagesDataDir, buildExport = false, serverRuntimeConfig, subFolders = false, optimizeCss, disableOptimizedLoading, debugOutput = false, enableExperimentalReact, ampValidatorPath, trailingSlash, sriEnabled } = input;
|
||||
if (enableExperimentalReact) {
|
||||
process.env.__NEXT_EXPERIMENTAL_REACT = 'true';
|
||||
}
|
||||
const { 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, // If this is a prospective render, we don't actually want to persist the
|
||||
// result, we just want to use it to error the build if there's a problem.
|
||||
_isProspectiveRender: isProspectiveRender = false, // Pull the original query out.
|
||||
query: originalQuery = {} } = pathMap;
|
||||
const fallbackRouteParams = getFallbackRouteParams(_fallbackRouteParams);
|
||||
let query = {
|
||||
...originalQuery
|
||||
};
|
||||
const pathname = normalizeAppPath(page);
|
||||
const isDynamic = isDynamicRoute(page);
|
||||
const outDir = isAppDir ? join(distDir, 'server/app') : input.outDir;
|
||||
const filePath = normalizePagePath(path);
|
||||
const ampPath = `${filePath}.amp`;
|
||||
let renderAmpPath = ampPath;
|
||||
let updatedPath = pathMap._ssgPath || path;
|
||||
let locale = pathMap._locale || input.renderOpts.locale;
|
||||
if (input.renderOpts.locale) {
|
||||
const localePathResult = normalizeLocalePath(path, input.renderOpts.locales);
|
||||
if (localePathResult.detectedLocale) {
|
||||
updatedPath = localePathResult.pathname;
|
||||
locale = localePathResult.detectedLocale;
|
||||
if (locale === input.renderOpts.defaultLocale) {
|
||||
renderAmpPath = `${normalizePagePath(updatedPath)}.amp`;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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, input.renderOpts.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 += '/';
|
||||
}
|
||||
if (locale && buildExport && input.renderOpts.domainLocales && input.renderOpts.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);
|
||||
}
|
||||
envConfig.setConfig({
|
||||
serverRuntimeConfig,
|
||||
publicRuntimeConfig: input.renderOpts.runtimeConfig
|
||||
});
|
||||
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
|
||||
});
|
||||
// Handle App Routes.
|
||||
if (isAppDir && isAppRouteRoute(page)) {
|
||||
return exportAppRoute(req, res, params, page, components.routeModule, input.renderOpts.incrementalCache, input.renderOpts.cacheLifeProfiles, htmlFilepath, fileWriter, input.renderOpts.experimental, input.buildId);
|
||||
}
|
||||
const renderOpts = {
|
||||
...components,
|
||||
...input.renderOpts,
|
||||
ampPath: renderAmpPath,
|
||||
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,
|
||||
experimental: {
|
||||
...input.renderOpts.experimental,
|
||||
isRoutePPREnabled
|
||||
}
|
||||
};
|
||||
if (hasNextSupport) {
|
||||
renderOpts.isRevalidate = true;
|
||||
}
|
||||
// Handle App Pages
|
||||
if (isAppDir) {
|
||||
const sharedContext = {
|
||||
buildId: input.buildId
|
||||
};
|
||||
// If this is a prospective render, don't return any metrics or revalidate
|
||||
// timings as we aren't persisting this render (it was only to error).
|
||||
if (isProspectiveRender) {
|
||||
return prospectiveRenderAppPage(req, res, page, pathname, query, fallbackRouteParams, renderOpts, sharedContext);
|
||||
}
|
||||
return exportAppPage(req, res, page, path, pathname, query, fallbackRouteParams, renderOpts, htmlFilepath, debugOutput, isDynamicError, fileWriter, sharedContext);
|
||||
}
|
||||
const sharedContext = {
|
||||
buildId: input.buildId,
|
||||
deploymentId: input.renderOpts.deploymentId,
|
||||
customServer: undefined
|
||||
};
|
||||
const renderContext = {
|
||||
isFallback: pathMap._pagesFallback ?? false,
|
||||
isDraftMode: false,
|
||||
developmentNotFoundSourcePage: undefined
|
||||
};
|
||||
return exportPagesPage(req, res, path, page, query, params, htmlFilepath, htmlFilename, ampPath, subFolders, outDir, ampValidatorPath, pagesDataDir, buildExport, isDynamic, sharedContext, renderContext, hasOrigQueryValues, renderOpts, components, fileWriter);
|
||||
}
|
||||
export async function exportPages(input) {
|
||||
const { exportPathMap, paths, dir, distDir, outDir, cacheHandler, cacheMaxMemorySize, fetchCacheKeyPrefix, pagesDataDir, renderOpts, nextConfig, options } = input;
|
||||
// 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.experimental.cacheHandlers
|
||||
});
|
||||
renderOpts.incrementalCache = incrementalCache;
|
||||
const maxConcurrency = nextConfig.experimental.staticGenerationMaxConcurrency ?? 8;
|
||||
const results = [];
|
||||
const exportPageWithRetry = async (path, maxAttempts)=>{
|
||||
const pathMap = exportPathMap[path];
|
||||
const { page } = exportPathMap[path];
|
||||
const pageKey = page !== path ? `${page}: ${path}` : path;
|
||||
let attempt = 0;
|
||||
let result;
|
||||
while(attempt < maxAttempts){
|
||||
try {
|
||||
var _nextConfig_experimental_amp, _nextConfig_experimental_sri;
|
||||
result = await Promise.race([
|
||||
exportPage({
|
||||
path,
|
||||
pathMap,
|
||||
distDir,
|
||||
outDir,
|
||||
pagesDataDir,
|
||||
renderOpts,
|
||||
ampValidatorPath: ((_nextConfig_experimental_amp = nextConfig.experimental.amp) == null ? void 0 : _nextConfig_experimental_amp.validator) || undefined,
|
||||
trailingSlash: nextConfig.trailingSlash,
|
||||
serverRuntimeConfig: nextConfig.serverRuntimeConfig,
|
||||
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
|
||||
}),
|
||||
// If exporting the page takes longer than the timeout, reject the 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,
|
||||
pageKey
|
||||
};
|
||||
};
|
||||
for(let i = 0; i < paths.length; i += maxConcurrency){
|
||||
const subset = paths.slice(i, i + maxConcurrency);
|
||||
const subsetResults = await Promise.all(subset.map((path)=>exportPageWithRetry(path, nextConfig.experimental.staticGenerationRetryCount ?? 1)));
|
||||
results.push(...subsetResults);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
async function exportPage(input) {
|
||||
trace('export-page', input.parentSpanId).setAttribute('path', input.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.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.
|
||||
if (isStaticGenBailoutError(err)) {
|
||||
if (err.message) {
|
||||
console.error(`Error: ${err.message}`);
|
||||
}
|
||||
} else if (isError(err) && err.stack) {
|
||||
console.error(err.stack);
|
||||
} 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 {
|
||||
duration: Date.now() - start,
|
||||
ampValidations: result.ampValidations,
|
||||
cacheControl: result.cacheControl,
|
||||
metadata: result.metadata,
|
||||
ssgNotFound: result.ssgNotFound,
|
||||
hasEmptyPrelude: result.hasEmptyPrelude,
|
||||
hasPostponed: result.hasPostponed,
|
||||
turborepoAccessTraceResult: turborepoAccessTraceResult.serialize(),
|
||||
fetchMetrics: result.fetchMetrics
|
||||
};
|
||||
}
|
||||
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
|
||||
+1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user