added fonts
This commit is contained in:
1 parent
4134e3a234
commit
142d2986b6
9079 files changed
+1498421
-2
No files matched your search
+11
@@ -0,0 +1,11 @@
|
||||
import { IncrementalCache } from '../../server/lib/incremental-cache';
|
||||
export declare function createIncrementalCache({ cacheHandler, cacheMaxMemorySize, fetchCacheKeyPrefix, distDir, dir, flushToDisk, cacheHandlers, requestHeaders, }: {
|
||||
cacheHandler?: string;
|
||||
cacheMaxMemorySize?: number;
|
||||
fetchCacheKeyPrefix?: string;
|
||||
distDir: string;
|
||||
dir: string;
|
||||
flushToDisk?: boolean;
|
||||
requestHeaders?: Record<string, string | string[] | undefined>;
|
||||
cacheHandlers?: Record<string, string | undefined>;
|
||||
}): Promise<IncrementalCache>;
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "createIncrementalCache", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return createIncrementalCache;
|
||||
}
|
||||
});
|
||||
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
|
||||
const _incrementalcache = require("../../server/lib/incremental-cache");
|
||||
const _ciinfo = require("../../server/ci-info");
|
||||
const _nodefsmethods = require("../../server/lib/node-fs-methods");
|
||||
const _interopdefault = require("../../lib/interop-default");
|
||||
const _formatdynamicimportpath = require("../../lib/format-dynamic-import-path");
|
||||
const _handlers = require("../../server/use-cache/handlers");
|
||||
function _interop_require_default(obj) {
|
||||
return obj && obj.__esModule ? obj : {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
async function createIncrementalCache({ cacheHandler, cacheMaxMemorySize, fetchCacheKeyPrefix, distDir, dir, flushToDisk, cacheHandlers, requestHeaders }) {
|
||||
// Custom cache handler overrides.
|
||||
let CacheHandler;
|
||||
if (cacheHandler) {
|
||||
CacheHandler = (0, _interopdefault.interopDefault)(await import((0, _formatdynamicimportpath.formatDynamicImportPath)(dir, cacheHandler)).then((mod)=>mod.default || mod));
|
||||
}
|
||||
if (cacheHandlers && (0, _handlers.initializeCacheHandlers)()) {
|
||||
for (const [kind, handler] of Object.entries(cacheHandlers)){
|
||||
if (!handler) continue;
|
||||
(0, _handlers.setCacheHandler)(kind, (0, _interopdefault.interopDefault)(await import((0, _formatdynamicimportpath.formatDynamicImportPath)(dir, handler)).then((mod)=>mod.default || mod)));
|
||||
}
|
||||
}
|
||||
const incrementalCache = new _incrementalcache.IncrementalCache({
|
||||
dev: false,
|
||||
requestHeaders: requestHeaders || {},
|
||||
flushToDisk,
|
||||
maxMemoryCacheSize: cacheMaxMemorySize,
|
||||
fetchCacheKeyPrefix,
|
||||
getPrerenderManifest: ()=>({
|
||||
version: 4,
|
||||
routes: {},
|
||||
dynamicRoutes: {},
|
||||
preview: {
|
||||
previewModeEncryptionKey: '',
|
||||
previewModeId: '',
|
||||
previewModeSigningKey: ''
|
||||
},
|
||||
notFoundRoutes: []
|
||||
}),
|
||||
fs: _nodefsmethods.nodeFs,
|
||||
serverDistDir: _path.default.join(distDir, 'server'),
|
||||
CurCacheHandler: CacheHandler,
|
||||
minimalMode: _ciinfo.hasNextSupport
|
||||
});
|
||||
globalThis.__incrementalCache = incrementalCache;
|
||||
return incrementalCache;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=create-incremental-cache.js.map
|
||||
+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":["createIncrementalCache","cacheHandler","cacheMaxMemorySize","fetchCacheKeyPrefix","distDir","dir","flushToDisk","cacheHandlers","requestHeaders","CacheHandler","interopDefault","formatDynamicImportPath","then","mod","default","initializeCacheHandlers","kind","handler","Object","entries","setCacheHandler","incrementalCache","IncrementalCache","dev","maxMemoryCacheSize","getPrerenderManifest","version","routes","dynamicRoutes","preview","previewModeEncryptionKey","previewModeId","previewModeSigningKey","notFoundRoutes","fs","nodeFs","serverDistDir","path","join","CurCacheHandler","minimalMode","hasNextSupport","globalThis","__incrementalCache"],"mappings":";;;;+BAWsBA;;;eAAAA;;;6DAXL;kCACgB;wBACF;+BACR;gCACQ;yCACS;0BAIjC;;;;;;AAEA,eAAeA,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,eAAeC,IAAAA,8BAAc,EAC3B,MAAM,MAAM,CAACC,IAAAA,gDAAuB,EAACN,KAAKJ,eAAeW,IAAI,CAC3D,CAACC,MAAQA,IAAIC,OAAO,IAAID;IAG9B;IAEA,IAAIN,iBAAiBQ,IAAAA,iCAAuB,KAAI;QAC9C,KAAK,MAAM,CAACC,MAAMC,QAAQ,IAAIC,OAAOC,OAAO,CAACZ,eAAgB;YAC3D,IAAI,CAACU,SAAS;YAEdG,IAAAA,yBAAe,EACbJ,MACAN,IAAAA,8BAAc,EACZ,MAAM,MAAM,CAACC,IAAAA,gDAAuB,EAACN,KAAKY,UAAUL,IAAI,CACtD,CAACC,MAAQA,IAAIC,OAAO,IAAID;QAIhC;IACF;IAEA,MAAMQ,mBAAmB,IAAIC,kCAAgB,CAAC;QAC5CC,KAAK;QACLf,gBAAgBA,kBAAkB,CAAC;QACnCF;QACAkB,oBAAoBtB;QACpBC;QACAsB,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,IAAIC,qBAAM;QACVC,eAAeC,aAAI,CAACC,IAAI,CAAClC,SAAS;QAClCmC,iBAAiB9B;QACjB+B,aAAaC,sBAAc;IAC7B;IAEEC,WAAmBC,kBAAkB,GAAGtB;IAE1C,OAAOA;AACT"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* 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 declare function getParams(page: string, pathname: string): import("../../server/request/params").Params;
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "getParams", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return getParams;
|
||||
}
|
||||
});
|
||||
const _routematcher = require("../../shared/lib/router/utils/route-matcher");
|
||||
const _routeregex = require("../../shared/lib/router/utils/route-regex");
|
||||
// The last page and matcher that this function handled.
|
||||
let last = null;
|
||||
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 = (0, _routematcher.getRouteMatcher)((0, _routeregex.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":["getParams","last","page","pathname","matcher","getRouteMatcher","getRouteRegex","params","Error"],"mappings":";;;;+BAkBgBA;;;eAAAA;;;8BAfT;4BACuB;AAE9B,wDAAwD;AACxD,IAAIC,OAGO;AAQJ,SAASD,UAAUE,IAAY,EAAEC,QAAgB;IACtD,4EAA4E;IAC5E,2EAA2E;IAC3E,kEAAkE;IAClE,IAAIC;IACJ,IAAIH,CAAAA,wBAAAA,KAAMC,IAAI,MAAKA,MAAM;QACvBE,UAAUH,KAAKG,OAAO;IACxB,OAAO;QACLA,UAAUC,IAAAA,6BAAe,EAACC,IAAAA,yBAAa,EAACJ;IAC1C;IAEA,MAAMK,SAASH,QAAQD;IACvB,IAAI,CAACI,QAAQ;QACX,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,0BAA0B,EAAEL,SAAS,qBAAqB,EAAED,KAAK,yEAAyE,CAAC,GADxI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,OAAOK;AACT"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare const isDynamicUsageError: (err: unknown) => boolean;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "isDynamicUsageError", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return isDynamicUsageError;
|
||||
}
|
||||
});
|
||||
const _hooksservercontext = require("../../client/components/hooks-server-context");
|
||||
const _bailouttocsr = require("../../shared/lib/lazy-dynamic/bailout-to-csr");
|
||||
const _isnextroutererror = require("../../client/components/is-next-router-error");
|
||||
const _dynamicrendering = require("../../server/app-render/dynamic-rendering");
|
||||
const isDynamicUsageError = (err)=>(0, _hooksservercontext.isDynamicServerError)(err) || (0, _bailouttocsr.isBailoutToCSRError)(err) || (0, _isnextroutererror.isNextRouterError)(err) || (0, _dynamicrendering.isDynamicPostpone)(err);
|
||||
|
||||
//# sourceMappingURL=is-dynamic-usage-error.js.map
|
||||
+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":["isDynamicUsageError","err","isDynamicServerError","isBailoutToCSRError","isNextRouterError","isDynamicPostpone"],"mappings":";;;;+BAKaA;;;eAAAA;;;oCALwB;8BACD;mCACF;kCACA;AAE3B,MAAMA,sBAAsB,CAACC,MAClCC,IAAAA,wCAAoB,EAACD,QACrBE,IAAAA,iCAAmB,EAACF,QACpBG,IAAAA,oCAAiB,EAACH,QAClBI,IAAAA,mCAAiB,EAACJ"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import type { ExportAppResult, ExportAppOptions } from './types';
|
||||
import '../server/require-hook';
|
||||
import type { Span } from '../trace';
|
||||
export declare class ExportError extends Error {
|
||||
code: string;
|
||||
}
|
||||
export default function exportApp(dir: string, options: ExportAppOptions, span: Span): Promise<ExportAppResult | null>;
|
||||
+684
@@ -0,0 +1,684 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
ExportError: null,
|
||||
default: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
ExportError: function() {
|
||||
return ExportError;
|
||||
},
|
||||
default: function() {
|
||||
return exportApp;
|
||||
}
|
||||
});
|
||||
const _build = require("../build");
|
||||
const _picocolors = require("../lib/picocolors");
|
||||
const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up"));
|
||||
const _fs = require("fs");
|
||||
require("../server/require-hook");
|
||||
const _path = require("path");
|
||||
const _index = require("../build/output/index");
|
||||
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../build/output/log"));
|
||||
const _constants = require("../lib/constants");
|
||||
const _recursivecopy = require("../lib/recursive-copy");
|
||||
const _constants1 = require("../shared/lib/constants");
|
||||
const _config = /*#__PURE__*/ _interop_require_default(require("../server/config"));
|
||||
const _events = require("../telemetry/events");
|
||||
const _ciinfo = require("../server/ci-info");
|
||||
const _storage = require("../telemetry/storage");
|
||||
const _normalizepagepath = require("../shared/lib/page-path/normalize-page-path");
|
||||
const _denormalizepagepath = require("../shared/lib/page-path/denormalize-page-path");
|
||||
const _env = require("@next/env");
|
||||
const _isapiroute = require("../lib/is-api-route");
|
||||
const _require = require("../server/require");
|
||||
const _isapprouteroute = require("../lib/is-app-route-route");
|
||||
const _isapppageroute = require("../lib/is-app-page-route");
|
||||
const _iserror = /*#__PURE__*/ _interop_require_default(require("../lib/is-error"));
|
||||
const _formatmanifest = require("../build/manifests/formatter/format-manifest");
|
||||
const _turborepoaccesstrace = require("../build/turborepo-access-trace");
|
||||
const _progress = require("../build/progress");
|
||||
const _generateinterceptionroutesrewrites = require("../lib/generate-interception-routes-rewrites");
|
||||
const _serverreferenceinfo = require("../shared/lib/server-reference-info");
|
||||
const _segmentvalueencoding = require("../shared/lib/segment-cache/segment-value-encoding");
|
||||
function _interop_require_default(obj) {
|
||||
return obj && obj.__esModule ? obj : {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
function _getRequireWildcardCache(nodeInterop) {
|
||||
if (typeof WeakMap !== "function") return null;
|
||||
var cacheBabelInterop = new WeakMap();
|
||||
var cacheNodeInterop = new WeakMap();
|
||||
return (_getRequireWildcardCache = function(nodeInterop) {
|
||||
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
|
||||
})(nodeInterop);
|
||||
}
|
||||
function _interop_require_wildcard(obj, nodeInterop) {
|
||||
if (!nodeInterop && obj && obj.__esModule) {
|
||||
return obj;
|
||||
}
|
||||
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
|
||||
return {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
var cache = _getRequireWildcardCache(nodeInterop);
|
||||
if (cache && cache.has(obj)) {
|
||||
return cache.get(obj);
|
||||
}
|
||||
var newObj = {
|
||||
__proto__: null
|
||||
};
|
||||
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
|
||||
for(var key in obj){
|
||||
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
|
||||
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
|
||||
if (desc && (desc.get || desc.set)) {
|
||||
Object.defineProperty(newObj, key, desc);
|
||||
} else {
|
||||
newObj[key] = obj[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
newObj.default = obj;
|
||||
if (cache) {
|
||||
cache.set(obj, newObj);
|
||||
}
|
||||
return newObj;
|
||||
}
|
||||
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 = (0, _path.resolve)(dir);
|
||||
// attempt to load global env values so they are available in next.config.js
|
||||
span.traceChild('load-dotenv').traceFn(()=>(0, _env.loadEnvConfig)(dir, false, _log));
|
||||
const { enabledDirectories } = options;
|
||||
const nextConfig = options.nextConfig || await span.traceChild('load-next-config').traceAsyncFn(()=>(0, _config.default)(_constants1.PHASE_EXPORT, dir));
|
||||
const distDir = (0, _path.join)(dir, nextConfig.distDir);
|
||||
const telemetry = options.buildExport ? null : new _storage.Telemetry({
|
||||
distDir
|
||||
});
|
||||
if (telemetry) {
|
||||
telemetry.record((0, _events.eventCliSession)(distDir, nextConfig, {
|
||||
webpackVersion: null,
|
||||
cliCommand: 'export',
|
||||
isSrcDir: null,
|
||||
hasNowJson: !!await (0, _findup.default)('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 = (0, _path.join)(distDir, _constants1.BUILD_ID_FILE);
|
||||
if (!(0, _fs.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 (!_ciinfo.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.promises.readFile(buildIdFile, 'utf8');
|
||||
const pagesManifest = !options.pages && require((0, _path.join)(distDir, _constants1.SERVER_DIRECTORY, _constants1.PAGES_MANIFEST));
|
||||
let prerenderManifest;
|
||||
try {
|
||||
prerenderManifest = require((0, _path.join)(distDir, _constants1.PRERENDER_MANIFEST));
|
||||
} catch {}
|
||||
let appRoutePathManifest;
|
||||
try {
|
||||
appRoutePathManifest = require((0, _path.join)(distDir, _constants1.APP_PATH_ROUTES_MANIFEST));
|
||||
} catch (err) {
|
||||
if ((0, _iserror.default)(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 ((0, _isapiroute.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 ((0, _isapppageroute.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 === (0, _path.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 === (0, _path.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.promises.rm(outDir, {
|
||||
recursive: true,
|
||||
force: true
|
||||
});
|
||||
await _fs.promises.mkdir((0, _path.join)(outDir, '_next', buildId), {
|
||||
recursive: true
|
||||
});
|
||||
await _fs.promises.writeFile((0, _path.join)(distDir, _constants1.EXPORT_DETAIL), (0, _formatmanifest.formatManifest)({
|
||||
version: 1,
|
||||
outDirectory: outDir,
|
||||
success: false
|
||||
}), 'utf8');
|
||||
// Copy static directory
|
||||
if (!options.buildExport && (0, _fs.existsSync)((0, _path.join)(dir, 'static'))) {
|
||||
if (!options.silent) {
|
||||
_log.info('Copying "static" directory');
|
||||
}
|
||||
await span.traceChild('copy-static-directory').traceAsyncFn(()=>(0, _recursivecopy.recursiveCopy)((0, _path.join)(dir, 'static'), (0, _path.join)(outDir, 'static')));
|
||||
}
|
||||
// Copy .next/static directory
|
||||
if (!options.buildExport && (0, _fs.existsSync)((0, _path.join)(distDir, _constants1.CLIENT_STATIC_FILES_PATH))) {
|
||||
if (!options.silent) {
|
||||
_log.info('Copying "static build" directory');
|
||||
}
|
||||
await span.traceChild('copy-next-static-directory').traceAsyncFn(()=>(0, _recursivecopy.recursiveCopy)((0, _path.join)(distDir, _constants1.CLIENT_STATIC_FILES_PATH), (0, _path.join)(outDir, '_next', _constants1.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.promises.readFile((0, _path.join)(distDir, _constants1.EXPORT_MARKER), 'utf8').then((text)=>JSON.parse(text)).catch(()=>({})));
|
||||
if (isNextImageImported && loader === 'default' && !unoptimized && !_ciinfo.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((0, _path.join)(distDir, _constants1.SERVER_DIRECTORY, _constants1.SERVER_REFERENCE_MANIFEST + '.json'));
|
||||
if (nextConfig.output === 'export') {
|
||||
var _routesManifest_rewrites_beforeFiles, _routesManifest_rewrites;
|
||||
const routesManifest = require((0, _path.join)(distDir, _constants1.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(_generateinterceptionroutesrewrites.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)=>(0, _serverreferenceinfo.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((0, _path.join)(distDir, 'server', `${_constants1.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,
|
||||
staleTimes: nextConfig.experimental.staleTimes,
|
||||
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)=>(0, _denormalizepagepath.denormalizePagePath)((0, _normalizepagepath.normalizePagePath)(path))))
|
||||
];
|
||||
const filteredPaths = exportPaths.filter((route)=>exportPathMap[route]._isAppDir || // Remove API routes
|
||||
!(0, _isapiroute.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${_constants.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((0, _path.join)(distDir, _constants1.SERVER_DIRECTORY, _constants1.MIDDLEWARE_MANIFEST));
|
||||
const functionsConfigManifest = require((0, _path.join)(distDir, _constants1.SERVER_DIRECTORY, _constants1.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((0, _picocolors.yellow)(`Statically exporting a Next.js application via \`next export\` disables API routes and middleware.`) + `\n` + (0, _picocolors.yellow)(`This command is meant for static-only hosts, and is` + ' ' + (0, _picocolors.bold)(`not necessary to make your application static.`)) + `\n` + (0, _picocolors.yellow)(`Pages in your application without server-side data dependencies will be automatically statically exported by \`next build\`, including pages powered by \`getStaticProps\`.`) + `\n` + (0, _picocolors.yellow)(`Learn more: https://nextjs.org/docs/messages/api-routes-static-export`));
|
||||
}
|
||||
}
|
||||
}
|
||||
const pagesDataDir = options.buildExport ? outDir : (0, _path.join)(outDir, '_next/data', buildId);
|
||||
const ampValidations = {};
|
||||
const publicDir = (0, _path.join)(dir, _constants1.CLIENT_PUBLIC_FILES_PATH);
|
||||
// Copy public directory
|
||||
if (!options.buildExport && (0, _fs.existsSync)(publicDir)) {
|
||||
if (!options.silent) {
|
||||
_log.info('Copying "public" directory');
|
||||
}
|
||||
await span.traceChild('copy-public-directory').traceAsyncFn(()=>(0, _recursivecopy.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 = (0, _progress.createProgress)(filteredPaths.length, options.statusMessage || 'Exporting');
|
||||
const worker = (0, _build.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, _turborepoaccesstrace.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 && (0, _isapprouteroute.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 = (0, _normalizepagepath.normalizePagePath)(unnormalizedRoute);
|
||||
const pagePath = (0, _require.getPagePath)(pageName, distDir, undefined, isAppPath);
|
||||
const distPagesDir = (0, _path.join)(pagePath, // strip leading / and then recurse number of nested dirs
|
||||
// to place from base folder
|
||||
pageName.slice(1).split('/').map(()=>'..').join('/'));
|
||||
const orig = (0, _path.join)(distPagesDir, route);
|
||||
const handlerSrc = `${orig}.body`;
|
||||
const handlerDest = (0, _path.join)(outDir, route);
|
||||
if (isAppRouteHandler && (0, _fs.existsSync)(handlerSrc)) {
|
||||
await _fs.promises.mkdir((0, _path.dirname)(handlerDest), {
|
||||
recursive: true
|
||||
});
|
||||
await _fs.promises.copyFile(handlerSrc, handlerDest);
|
||||
return;
|
||||
}
|
||||
const htmlDest = (0, _path.join)(outDir, `${route}${subFolders && route !== '/index' ? `${_path.sep}index` : ''}.html`);
|
||||
const ampHtmlDest = (0, _path.join)(outDir, `${route}.amp${subFolders ? `${_path.sep}index` : ''}.html`);
|
||||
const jsonDest = isAppPath ? (0, _path.join)(outDir, `${route}${subFolders && route !== '/index' ? `${_path.sep}index` : ''}.txt`) : (0, _path.join)(pagesDataDir, `${route}.json`);
|
||||
await _fs.promises.mkdir((0, _path.dirname)(htmlDest), {
|
||||
recursive: true
|
||||
});
|
||||
await _fs.promises.mkdir((0, _path.dirname)(jsonDest), {
|
||||
recursive: true
|
||||
});
|
||||
const htmlSrc = `${orig}.html`;
|
||||
const jsonSrc = `${orig}${isAppPath ? _constants.RSC_SUFFIX : '.json'}`;
|
||||
await _fs.promises.copyFile(htmlSrc, htmlDest);
|
||||
await _fs.promises.copyFile(jsonSrc, jsonDest);
|
||||
if ((0, _fs.existsSync)(`${orig}.amp.html`)) {
|
||||
await _fs.promises.mkdir((0, _path.dirname)(ampHtmlDest), {
|
||||
recursive: true
|
||||
});
|
||||
await _fs.promises.copyFile(`${orig}.amp.html`, ampHtmlDest);
|
||||
}
|
||||
const segmentsDir = `${orig}${_constants.RSC_SEGMENTS_DIR_SUFFIX}`;
|
||||
if (isAppPath && (0, _fs.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 = (0, _path.join)(outDir, unnormalizedRoute);
|
||||
const segmentPaths = await collectSegmentPaths(segmentsDir);
|
||||
await Promise.all(segmentPaths.map(async (segmentFileSrc)=>{
|
||||
const segmentPath = '/' + segmentFileSrc.slice(0, -_constants.RSC_SEGMENT_SUFFIX.length);
|
||||
const segmentFilename = (0, _segmentvalueencoding.convertSegmentPathToStaticExportFilename)(segmentPath);
|
||||
const segmentFileDest = (0, _path.join)(segmentsDirDest, segmentFilename);
|
||||
await _fs.promises.mkdir((0, _path.dirname)(segmentFileDest), {
|
||||
recursive: true
|
||||
});
|
||||
await _fs.promises.copyFile((0, _path.join)(segmentsDir, segmentFileSrc), segmentFileDest);
|
||||
}));
|
||||
}
|
||||
}));
|
||||
}
|
||||
if (Object.keys(ampValidations).length) {
|
||||
console.log((0, _index.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.promises.writeFile((0, _path.join)(distDir, _constants1.EXPORT_DETAIL), (0, _formatmanifest.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.promises.readdir(directory, {
|
||||
withFileTypes: true
|
||||
});
|
||||
await Promise.all(segmentFiles.map(async (segmentFile)=>{
|
||||
if (segmentFile.isDirectory()) {
|
||||
await collectSegmentPathsImpl(segmentsDirectory, (0, _path.join)(directory, segmentFile.name), results);
|
||||
return;
|
||||
}
|
||||
if (!segmentFile.name.endsWith(_constants.RSC_SEGMENT_SUFFIX)) {
|
||||
return;
|
||||
}
|
||||
results.push((0, _path.relative)(segmentsDirectory, (0, _path.join)(directory, segmentFile.name)));
|
||||
}));
|
||||
}
|
||||
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
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/export/index.ts"],"sourcesContent":["import type {\n ExportAppResult,\n ExportAppOptions,\n WorkerRenderOptsPartial,\n} from './types'\nimport { createStaticWorker, type PrerenderManifest } from '../build'\nimport type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'\n\nimport { bold, yellow } from '../lib/picocolors'\nimport findUp from 'next/dist/compiled/find-up'\nimport { existsSync, promises as fs } from 'fs'\n\nimport '../server/require-hook'\n\nimport { dirname, join, resolve, sep, relative } from 'path'\nimport { formatAmpMessages } from '../build/output/index'\nimport type { AmpPageStatus } from '../build/output/index'\nimport * as Log from '../build/output/log'\nimport {\n RSC_SEGMENT_SUFFIX,\n RSC_SEGMENTS_DIR_SUFFIX,\n RSC_SUFFIX,\n SSG_FALLBACK_EXPORT_ERROR,\n} from '../lib/constants'\nimport { recursiveCopy } from '../lib/recursive-copy'\nimport {\n BUILD_ID_FILE,\n CLIENT_PUBLIC_FILES_PATH,\n CLIENT_STATIC_FILES_PATH,\n EXPORT_DETAIL,\n EXPORT_MARKER,\n NEXT_FONT_MANIFEST,\n MIDDLEWARE_MANIFEST,\n PAGES_MANIFEST,\n PHASE_EXPORT,\n PRERENDER_MANIFEST,\n SERVER_DIRECTORY,\n SERVER_REFERENCE_MANIFEST,\n APP_PATH_ROUTES_MANIFEST,\n ROUTES_MANIFEST,\n FUNCTIONS_CONFIG_MANIFEST,\n} from '../shared/lib/constants'\nimport loadConfig from '../server/config'\nimport type { ExportPathMap } from '../server/config-shared'\nimport { eventCliSession } from '../telemetry/events'\nimport { hasNextSupport } from '../server/ci-info'\nimport { Telemetry } from '../telemetry/storage'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport { loadEnvConfig } from '@next/env'\nimport { isAPIRoute } from '../lib/is-api-route'\nimport { getPagePath } from '../server/require'\nimport type { Span } from '../trace'\nimport type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'\nimport { isAppRouteRoute } from '../lib/is-app-route-route'\nimport { isAppPageRoute } from '../lib/is-app-page-route'\nimport isError from '../lib/is-error'\nimport { formatManifest } from '../build/manifests/formatter/format-manifest'\nimport { TurborepoAccessTraceResult } from '../build/turborepo-access-trace'\nimport { createProgress } from '../build/progress'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites'\nimport type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'\nimport { extractInfoFromServerReferenceId } from '../shared/lib/server-reference-info'\nimport { convertSegmentPathToStaticExportFilename } from '../shared/lib/segment-cache/segment-value-encoding'\n\nexport class ExportError extends Error {\n code = 'NEXT_EXPORT_ERROR'\n}\n\nasync function exportAppImpl(\n dir: string,\n options: Readonly<ExportAppOptions>,\n span: Span\n): Promise<ExportAppResult | null> {\n dir = resolve(dir)\n\n // attempt to load global env values so they are available in next.config.js\n span.traceChild('load-dotenv').traceFn(() => loadEnvConfig(dir, false, Log))\n\n const { enabledDirectories } = options\n\n const nextConfig =\n options.nextConfig ||\n (await span\n .traceChild('load-next-config')\n .traceAsyncFn(() => loadConfig(PHASE_EXPORT, dir)))\n\n const distDir = join(dir, nextConfig.distDir)\n const telemetry = options.buildExport ? null : new Telemetry({ distDir })\n\n if (telemetry) {\n telemetry.record(\n eventCliSession(distDir, nextConfig, {\n webpackVersion: null,\n cliCommand: 'export',\n isSrcDir: null,\n hasNowJson: !!(await findUp('now.json', { cwd: dir })),\n isCustomServer: null,\n turboFlag: false,\n pagesDir: null,\n appDir: null,\n })\n )\n }\n\n const subFolders = nextConfig.trailingSlash && !options.buildExport\n\n if (!options.silent && !options.buildExport) {\n Log.info(`using build directory: ${distDir}`)\n }\n\n const buildIdFile = join(distDir, BUILD_ID_FILE)\n\n if (!existsSync(buildIdFile)) {\n throw new ExportError(\n `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`\n )\n }\n\n const customRoutes = ['rewrites', 'redirects', 'headers'].filter(\n (config) => typeof nextConfig[config] === 'function'\n )\n\n if (!hasNextSupport && !options.buildExport && customRoutes.length > 0) {\n Log.warn(\n `rewrites, redirects, and headers are not applied when exporting your application, detected (${customRoutes.join(\n ', '\n )}). See more info here: https://nextjs.org/docs/messages/export-no-custom-routes`\n )\n }\n\n const buildId = await fs.readFile(buildIdFile, 'utf8')\n\n const pagesLine truncated
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import type { ExportRouteResult } from '../types';
|
||||
import type { RenderOpts } from '../../server/app-render/types';
|
||||
import type { NextParsedUrlQuery } from '../../server/request-meta';
|
||||
import type { MockedRequest, MockedResponse } from '../../server/lib/mock-request';
|
||||
import type { FallbackRouteParams } from '../../server/request/fallback-params';
|
||||
import type { RequestLifecycleOpts } from '../../server/base-server';
|
||||
import type { AppSharedContext } from '../../server/app-render/app-render';
|
||||
import type { MultiFileWriter } from '../../lib/multi-file-writer';
|
||||
export declare function prospectiveRenderAppPage(req: MockedRequest, res: MockedResponse, page: string, pathname: string, query: NextParsedUrlQuery, fallbackRouteParams: FallbackRouteParams | null, partialRenderOpts: Omit<RenderOpts, keyof RequestLifecycleOpts>, sharedContext: AppSharedContext): Promise<undefined>;
|
||||
/**
|
||||
* Renders & exports a page associated with the /app directory
|
||||
*/
|
||||
export declare function exportAppPage(req: MockedRequest, res: MockedResponse, page: string, path: string, pathname: string, query: NextParsedUrlQuery, fallbackRouteParams: FallbackRouteParams | null, partialRenderOpts: Omit<RenderOpts, keyof RequestLifecycleOpts>, htmlFilepath: string, debugOutput: boolean, isDynamicError: boolean, fileWriter: MultiFileWriter, sharedContext: AppSharedContext): Promise<ExportRouteResult>;
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
exportAppPage: null,
|
||||
prospectiveRenderAppPage: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
exportAppPage: function() {
|
||||
return exportAppPage;
|
||||
},
|
||||
prospectiveRenderAppPage: function() {
|
||||
return prospectiveRenderAppPage;
|
||||
}
|
||||
});
|
||||
const _isdynamicusageerror = require("../helpers/is-dynamic-usage-error");
|
||||
const _constants = require("../../lib/constants");
|
||||
const _ciinfo = require("../../server/ci-info");
|
||||
const _modulerender = require("../../server/route-modules/app-page/module.render");
|
||||
const _bailouttocsr = require("../../shared/lib/lazy-dynamic/bailout-to-csr");
|
||||
const _node = require("../../server/base-http/node");
|
||||
const _approuterheaders = require("../../client/components/app-router-headers");
|
||||
const _runwithafter = require("../../server/after/run-with-after");
|
||||
async function prospectiveRenderAppPage(req, res, page, pathname, query, fallbackRouteParams, partialRenderOpts, sharedContext) {
|
||||
const afterRunner = new _runwithafter.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 (0, _modulerender.lazyRenderAppPage)(new _node.NodeNextRequest(req), new _node.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 (!(0, _isdynamicusageerror.isDynamicUsageError)(err)) {
|
||||
throw err;
|
||||
}
|
||||
// We should fail rendering if a client side rendering bailout
|
||||
// occurred at the page level.
|
||||
if ((0, _bailouttocsr.isBailoutToCSRError)(err)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
async function exportAppPage(req, res, page, path, pathname, query, fallbackRouteParams, partialRenderOpts, htmlFilepath, debugOutput, isDynamicError, fileWriter, sharedContext) {
|
||||
const afterRunner = new _runwithafter.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 (0, _modulerender.lazyRenderAppPage)(new _node.NodeNextRequest(req), new _node.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$/, _constants.RSC_PREFETCH_SUFFIX), flightData);
|
||||
} else {
|
||||
// Writing the RSC payload to a file if we don't have PPR enabled.
|
||||
fileWriter.append(htmlFilepath.replace(/\.html$/, _constants.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$/, _constants.RSC_SEGMENTS_DIR_SUFFIX);
|
||||
for (const [segmentPath, buffer] of segmentData){
|
||||
segmentPaths.push(segmentPath);
|
||||
const segmentDataFilePath = segmentsDir + segmentPath + _constants.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[_approuterheaders.NEXT_IS_PRERENDER_HEADER] = '1';
|
||||
if (fetchTags) {
|
||||
headers[_constants.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$/, _constants.NEXT_META_SUFFIX), JSON.stringify(meta, null, 2));
|
||||
return {
|
||||
// Only include the metadata if the environment has next support.
|
||||
metadata: _ciinfo.hasNextSupport ? meta : undefined,
|
||||
hasEmptyPrelude: Boolean(postponed) && html === '',
|
||||
hasPostponed: Boolean(postponed),
|
||||
cacheControl,
|
||||
fetchMetrics
|
||||
};
|
||||
} catch (err) {
|
||||
if (!(0, _isdynamicusageerror.isDynamicUsageError)(err)) {
|
||||
throw err;
|
||||
}
|
||||
// We should fail rendering if a client side rendering bailout
|
||||
// occurred at the page level.
|
||||
if ((0, _bailouttocsr.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
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/export/routes/app-page.ts"],"sourcesContent":["import type { OutgoingHttpHeaders } from 'node:http'\nimport type { ExportRouteResult } from '../types'\nimport type { RenderOpts } from '../../server/app-render/types'\nimport type { NextParsedUrlQuery } from '../../server/request-meta'\nimport type { RouteMetadata } from './types'\n\nimport type {\n MockedRequest,\n MockedResponse,\n} from '../../server/lib/mock-request'\nimport { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'\nimport {\n NEXT_CACHE_TAGS_HEADER,\n NEXT_META_SUFFIX,\n RSC_PREFETCH_SUFFIX,\n RSC_SUFFIX,\n RSC_SEGMENTS_DIR_SUFFIX,\n RSC_SEGMENT_SUFFIX,\n} from '../../lib/constants'\nimport { hasNextSupport } from '../../server/ci-info'\nimport { lazyRenderAppPage } from '../../server/route-modules/app-page/module.render'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'\nimport { NEXT_IS_PRERENDER_HEADER } from '../../client/components/app-router-headers'\nimport type { FetchMetrics } from '../../server/base-http'\nimport type { WorkStore } from '../../server/app-render/work-async-storage.external'\nimport type { FallbackRouteParams } from '../../server/request/fallback-params'\nimport { AfterRunner } from '../../server/after/run-with-after'\nimport type { RequestLifecycleOpts } from '../../server/base-server'\nimport type { AppSharedContext } from '../../server/app-render/app-render'\nimport type { MultiFileWriter } from '../../lib/multi-file-writer'\n\nexport async function prospectiveRenderAppPage(\n req: MockedRequest,\n res: MockedResponse,\n page: string,\n pathname: string,\n query: NextParsedUrlQuery,\n fallbackRouteParams: FallbackRouteParams | null,\n partialRenderOpts: Omit<RenderOpts, keyof RequestLifecycleOpts>,\n sharedContext: AppSharedContext\n): Promise<undefined> {\n const afterRunner = new AfterRunner()\n\n // If the page is `/_not-found`, then we should update the page to be `/404`.\n // 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.\n if (page === '/_not-found/page') {\n pathname = '/404'\n }\n\n try {\n await lazyRenderAppPage(\n new NodeNextRequest(req),\n new NodeNextResponse(res),\n pathname,\n query,\n fallbackRouteParams,\n {\n ...partialRenderOpts,\n waitUntil: afterRunner.context.waitUntil,\n onClose: afterRunner.context.onClose,\n onAfterTaskError: afterRunner.context.onTaskError,\n },\n undefined,\n false,\n sharedContext\n )\n\n // TODO(after): if we abort a prerender because of an error in an after-callback\n // we should probably communicate that better (and not log the error twice)\n await afterRunner.executeAfter()\n } catch (err) {\n if (!isDynamicUsageError(err)) {\n throw err\n }\n\n // We should fail rendering if a client side rendering bailout\n // occurred at the page level.\n if (isBailoutToCSRError(err)) {\n throw err\n }\n }\n}\n\n/**\n * Renders & exports a page associated with the /app directory\n */\nexport async function exportAppPage(\n req: MockedRequest,\n res: MockedResponse,\n page: string,\n path: string,\n pathname: string,\n query: NextParsedUrlQuery,\n fallbackRouteParams: FallbackRouteParams | null,\n partialRenderOpts: Omit<RenderOpts, keyof RequestLifecycleOpts>,\n htmlFilepath: string,\n debugOutput: boolean,\n isDynamicError: boolean,\n fileWriter: MultiFileWriter,\n sharedContext: AppSharedContext\n): Promise<ExportRouteResult> {\n const afterRunner = new AfterRunner()\n\n const renderOpts: RenderOpts = {\n ...partialRenderOpts,\n waitUntil: afterRunner.context.waitUntil,\n onClose: afterRunner.context.onClose,\n onAfterTaskError: afterRunner.context.onTaskError,\n }\n\n let isDefaultNotFound = false\n // If the page is `/_not-found`, then we should update the page to be `/404`.\n // 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.\n if (page === '/_not-found/page') {\n isDefaultNotFound = true\n pathname = '/404'\n }\n\n try {\n const result = await lazyRenderAppPage(\n new NodeNextRequest(req),\n new NodeNextResponse(res),\n pathname,\n query,\n fallbackRouteParams,\n renderOpts,\n undefined,\n false,\n sharedContext\n )\n\n const html = result.toUnchunkedString()\n\n // TODO(after): if we abort a prerender because of an error in an after-callback\n // we should probably communicate that better (and not log the error twice)\n await afterRunner.executeAfter()\n\n const { metadata } = result\n const {\n flightData,\n cacheControl = { revalidate: false, expire:Line truncated
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import type { ExportRouteResult } from '../types';
|
||||
import type AppRouteRouteModule from '../../server/route-modules/app-route/module';
|
||||
import type { IncrementalCache } from '../../server/lib/incremental-cache';
|
||||
import type { MockedRequest, MockedResponse } from '../../server/lib/mock-request';
|
||||
import type { ExperimentalConfig } from '../../server/config-shared';
|
||||
import type { Params } from '../../server/request/params';
|
||||
import type { MultiFileWriter } from '../../lib/multi-file-writer';
|
||||
export declare const enum ExportedAppRouteFiles {
|
||||
BODY = "BODY",
|
||||
META = "META"
|
||||
}
|
||||
export declare function exportAppRoute(req: MockedRequest, res: MockedResponse, params: Params | undefined, page: string, module: AppRouteRouteModule, incrementalCache: IncrementalCache | undefined, cacheLifeProfiles: undefined | {
|
||||
[profile: string]: import('../../server/use-cache/cache-life').CacheLife;
|
||||
}, htmlFilepath: string, fileWriter: MultiFileWriter, experimental: Required<Pick<ExperimentalConfig, 'dynamicIO' | 'authInterrupts'>>, buildId: string): Promise<ExportRouteResult>;
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
ExportedAppRouteFiles: null,
|
||||
exportAppRoute: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
ExportedAppRouteFiles: function() {
|
||||
return ExportedAppRouteFiles;
|
||||
},
|
||||
exportAppRoute: function() {
|
||||
return exportAppRoute;
|
||||
}
|
||||
});
|
||||
const _constants = require("../../lib/constants");
|
||||
const _node = require("../../server/base-http/node");
|
||||
const _nextrequest = require("../../server/web/spec-extension/adapters/next-request");
|
||||
const _utils = require("../../server/web/utils");
|
||||
const _isdynamicusageerror = require("../helpers/is-dynamic-usage-error");
|
||||
const _ciinfo = require("../../server/ci-info");
|
||||
const _isstaticgenenabled = require("../../server/route-modules/app-route/helpers/is-static-gen-enabled");
|
||||
const _ismetadataroute = require("../../lib/metadata/is-metadata-route");
|
||||
const _apppaths = require("../../shared/lib/router/utils/app-paths");
|
||||
const _runwithafter = require("../../server/after/run-with-after");
|
||||
var ExportedAppRouteFiles = /*#__PURE__*/ function(ExportedAppRouteFiles) {
|
||||
ExportedAppRouteFiles["BODY"] = "BODY";
|
||||
ExportedAppRouteFiles["META"] = "META";
|
||||
return ExportedAppRouteFiles;
|
||||
}({});
|
||||
async function exportAppRoute(req, res, params, page, module1, 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 = _nextrequest.NextRequestAdapter.fromNodeNextRequest(new _node.NodeNextRequest(req), (0, _nextrequest.signalFromNodeResponse)(res));
|
||||
const afterRunner = new _runwithafter.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 (_ciinfo.hasNextSupport) {
|
||||
context.renderOpts.isRevalidate = true;
|
||||
}
|
||||
try {
|
||||
const userland = module1.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 = (0, _apppaths.normalizeAppPath)(page) + '/route';
|
||||
const isPageMetadataRoute = (0, _ismetadataroute.isMetadataRoute)(routePath);
|
||||
if (!(0, _isstaticgenenabled.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 module1.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 >= _constants.INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;
|
||||
const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= _constants.INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;
|
||||
const headers = (0, _utils.toNodeOutgoingHttpHeaders)(response.headers);
|
||||
const cacheTags = context.renderOpts.collectedTags;
|
||||
if (cacheTags) {
|
||||
headers[_constants.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$/, _constants.NEXT_BODY_SUFFIX), body);
|
||||
// Write the request metadata to a file.
|
||||
const meta = {
|
||||
status: response.status,
|
||||
headers
|
||||
};
|
||||
fileWriter.append(htmlFilepath.replace(/\.html$/, _constants.NEXT_META_SUFFIX), JSON.stringify(meta));
|
||||
return {
|
||||
cacheControl: {
|
||||
revalidate,
|
||||
expire
|
||||
},
|
||||
metadata: meta
|
||||
};
|
||||
} catch (err) {
|
||||
if (!(0, _isdynamicusageerror.isDynamicUsageError)(err)) {
|
||||
throw err;
|
||||
}
|
||||
return {
|
||||
cacheControl: {
|
||||
revalidate: 0,
|
||||
expire: undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-route.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/export/routes/app-route.ts"],"sourcesContent":["import type { ExportRouteResult } from '../types'\nimport type AppRouteRouteModule from '../../server/route-modules/app-route/module'\nimport type { AppRouteRouteHandlerContext } from '../../server/route-modules/app-route/module'\nimport type { IncrementalCache } from '../../server/lib/incremental-cache'\n\nimport {\n INFINITE_CACHE,\n NEXT_BODY_SUFFIX,\n NEXT_CACHE_TAGS_HEADER,\n NEXT_META_SUFFIX,\n} from '../../lib/constants'\nimport { NodeNextRequest } from '../../server/base-http/node'\nimport {\n NextRequestAdapter,\n signalFromNodeResponse,\n} from '../../server/web/spec-extension/adapters/next-request'\nimport { toNodeOutgoingHttpHeaders } from '../../server/web/utils'\nimport type {\n MockedRequest,\n MockedResponse,\n} from '../../server/lib/mock-request'\nimport { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'\nimport { hasNextSupport } from '../../server/ci-info'\nimport { isStaticGenEnabled } from '../../server/route-modules/app-route/helpers/is-static-gen-enabled'\nimport type { ExperimentalConfig } from '../../server/config-shared'\nimport { isMetadataRoute } from '../../lib/metadata/is-metadata-route'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport type { Params } from '../../server/request/params'\nimport { AfterRunner } from '../../server/after/run-with-after'\nimport type { MultiFileWriter } from '../../lib/multi-file-writer'\n\nexport const enum ExportedAppRouteFiles {\n BODY = 'BODY',\n META = 'META',\n}\n\nexport async function exportAppRoute(\n req: MockedRequest,\n res: MockedResponse,\n params: Params | undefined,\n page: string,\n module: AppRouteRouteModule,\n incrementalCache: IncrementalCache | undefined,\n cacheLifeProfiles:\n | undefined\n | {\n [profile: string]: import('../../server/use-cache/cache-life').CacheLife\n },\n htmlFilepath: string,\n fileWriter: MultiFileWriter,\n experimental: Required<\n Pick<ExperimentalConfig, 'dynamicIO' | 'authInterrupts'>\n >,\n buildId: string\n): Promise<ExportRouteResult> {\n // Ensure that the URL is absolute.\n req.url = `http://localhost:3000${req.url}`\n\n // Adapt the request and response to the Next.js request and response.\n const request = NextRequestAdapter.fromNodeNextRequest(\n new NodeNextRequest(req),\n signalFromNodeResponse(res)\n )\n\n const afterRunner = new AfterRunner()\n\n // Create the context for the handler. This contains the params from\n // the route and the context for the request.\n const context: AppRouteRouteHandlerContext = {\n params,\n prerenderManifest: {\n version: 4,\n routes: {},\n dynamicRoutes: {},\n preview: {\n previewModeEncryptionKey: '',\n previewModeId: '',\n previewModeSigningKey: '',\n },\n notFoundRoutes: [],\n },\n renderOpts: {\n experimental,\n nextExport: true,\n supportsDynamicResponse: false,\n incrementalCache,\n waitUntil: afterRunner.context.waitUntil,\n onClose: afterRunner.context.onClose,\n onAfterTaskError: afterRunner.context.onTaskError,\n cacheLifeProfiles,\n },\n sharedContext: {\n buildId,\n },\n }\n\n if (hasNextSupport) {\n context.renderOpts.isRevalidate = true\n }\n\n try {\n const userland = module.userland\n // we don't bail from the static optimization for\n // metadata routes, since it's app-route we can always append /route suffix.\n const routePath = normalizeAppPath(page) + '/route'\n const isPageMetadataRoute = isMetadataRoute(routePath)\n\n if (\n !isStaticGenEnabled(userland) &&\n !isPageMetadataRoute &&\n // We don't disable static gen when dynamicIO is enabled because we\n // expect that anything dynamic in the GET handler will make it dynamic\n // and thus avoid the cache surprises that led to us removing static gen\n // unless specifically opted into\n experimental.dynamicIO !== true\n ) {\n return { cacheControl: { revalidate: 0, expire: undefined } }\n }\n\n const response = await module.handle(request, context)\n\n const isValidStatus = response.status < 400 || response.status === 404\n if (!isValidStatus) {\n return { cacheControl: { revalidate: 0, expire: undefined } }\n }\n\n const blob = await response.blob()\n\n // TODO(after): if we abort a prerender because of an error in an after-callback\n // we should probably communicate that better (and not log the error twice)\n await afterRunner.executeAfter()\n\n const revalidate =\n typeof context.renderOpts.collectedRevalidate === 'undefined' ||\n context.renderOpts.collectedRevalidate >= INFINITE_CACHE\n ? false\n : context.renderOpts.collectedRevalidate\n\n const expire =\n typeof context.renderOpts.collectedExpire === 'undefined' ||\n context.renderOpts.cLine truncated
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import type { ExportRouteResult } from '../types';
|
||||
import type { PagesRenderContext, PagesSharedContext, RenderOpts } from '../../server/render';
|
||||
import type { LoadComponentsReturnType } from '../../server/load-components';
|
||||
import type { NextParsedUrlQuery } from '../../server/request-meta';
|
||||
import type { Params } from '../../server/request/params';
|
||||
import type { MockedRequest, MockedResponse } from '../../server/lib/mock-request';
|
||||
import type { MultiFileWriter } from '../../lib/multi-file-writer';
|
||||
/**
|
||||
* Renders & exports a page associated with the /pages directory
|
||||
*/
|
||||
export declare function exportPagesPage(req: MockedRequest, res: MockedResponse, path: string, page: string, query: NextParsedUrlQuery, params: Params | undefined, htmlFilepath: string, htmlFilename: string, ampPath: string, subFolders: boolean, outDir: string, ampValidatorPath: string | undefined, pagesDataDir: string, buildExport: boolean, isDynamic: boolean, sharedContext: PagesSharedContext, renderContext: PagesRenderContext, hasOrigQueryValues: boolean, renderOpts: RenderOpts, components: LoadComponentsReturnType, fileWriter: MultiFileWriter): Promise<ExportRouteResult | undefined>;
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "exportPagesPage", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return exportPagesPage;
|
||||
}
|
||||
});
|
||||
const _renderresult = /*#__PURE__*/ _interop_require_default(require("../../server/render-result"));
|
||||
const _path = require("path");
|
||||
const _ampmode = require("../../shared/lib/amp-mode");
|
||||
const _constants = require("../../lib/constants");
|
||||
const _bailouttocsr = require("../../shared/lib/lazy-dynamic/bailout-to-csr");
|
||||
const _amphtmlvalidator = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/amphtml-validator"));
|
||||
const _fileexists = require("../../lib/file-exists");
|
||||
const _modulerender = require("../../server/route-modules/pages/module.render");
|
||||
function _interop_require_default(obj) {
|
||||
return obj && obj.__esModule ? obj : {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
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 = (0, _ampmode.isInAmpMode)(ampState);
|
||||
const hybridAmp = ampState.hybrid;
|
||||
if (components.getServerSideProps) {
|
||||
throw Object.defineProperty(new Error(`Error for page ${page}: ${_constants.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.default.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 (0, _modulerender.lazyRenderPagesPage)(req, res, page, searchAndDynamicParams, renderOpts, sharedContext, renderContext);
|
||||
} catch (err) {
|
||||
if (!(0, _bailouttocsr.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.default.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 ? (0, _path.join)(ampPath, 'index.html') : `${ampPath}.html`;
|
||||
const ampHtmlFilepath = (0, _path.join)(outDir, ampHtmlFilename);
|
||||
const exists = await (0, _fileexists.fileExists)(ampHtmlFilepath, _fileexists.FileType.File);
|
||||
if (!exists) {
|
||||
try {
|
||||
ampRenderResult = await (0, _modulerender.lazyRenderPagesPage)(req, res, page, {
|
||||
...searchAndDynamicParams,
|
||||
amp: '1'
|
||||
}, renderOpts, sharedContext, renderContext);
|
||||
} catch (err) {
|
||||
if (!(0, _bailouttocsr.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 = (0, _path.join)(pagesDataDir, htmlFilename.replace(/\.html$/, _constants.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
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/export/routes/pages.ts"],"sourcesContent":["import type { ExportRouteResult } from '../types'\nimport type {\n PagesRenderContext,\n PagesSharedContext,\n RenderOpts,\n} from '../../server/render'\nimport type { LoadComponentsReturnType } from '../../server/load-components'\nimport type { AmpValidation } from '../types'\nimport type { NextParsedUrlQuery } from '../../server/request-meta'\nimport type { Params } from '../../server/request/params'\n\nimport RenderResult from '../../server/render-result'\nimport { join } from 'path'\nimport type {\n MockedRequest,\n MockedResponse,\n} from '../../server/lib/mock-request'\nimport { isInAmpMode } from '../../shared/lib/amp-mode'\nimport {\n NEXT_DATA_SUFFIX,\n SERVER_PROPS_EXPORT_ERROR,\n} from '../../lib/constants'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'\nimport { FileType, fileExists } from '../../lib/file-exists'\nimport { lazyRenderPagesPage } from '../../server/route-modules/pages/module.render'\nimport type { MultiFileWriter } from '../../lib/multi-file-writer'\n\n/**\n * Renders & exports a page associated with the /pages directory\n */\nexport async function exportPagesPage(\n req: MockedRequest,\n res: MockedResponse,\n path: string,\n page: string,\n query: NextParsedUrlQuery,\n params: Params | undefined,\n htmlFilepath: string,\n htmlFilename: string,\n ampPath: string,\n subFolders: boolean,\n outDir: string,\n ampValidatorPath: string | undefined,\n pagesDataDir: string,\n buildExport: boolean,\n isDynamic: boolean,\n sharedContext: PagesSharedContext,\n renderContext: PagesRenderContext,\n hasOrigQueryValues: boolean,\n renderOpts: RenderOpts,\n components: LoadComponentsReturnType,\n fileWriter: MultiFileWriter\n): Promise<ExportRouteResult | undefined> {\n const ampState = {\n ampFirst: components.pageConfig?.amp === true,\n hasQuery: Boolean(query.amp),\n hybrid: components.pageConfig?.amp === 'hybrid',\n }\n\n if (!ampValidatorPath) {\n ampValidatorPath = require.resolve(\n 'next/dist/compiled/amphtml-validator/validator_wasm.js'\n )\n }\n\n const inAmpMode = isInAmpMode(ampState)\n const hybridAmp = ampState.hybrid\n\n if (components.getServerSideProps) {\n throw new Error(`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`)\n }\n\n // for non-dynamic SSG pages we should have already\n // prerendered the file\n if (!buildExport && components.getStaticProps && !isDynamic) {\n return\n }\n\n // Pages router merges page params (e.g. [lang]) with query params\n // primarily to support them both being accessible on `useRouter().query`.\n // If we extracted dynamic params from the path, we need to merge them\n // back into the query object.\n const searchAndDynamicParams = {\n ...query,\n ...params,\n }\n\n if (components.getStaticProps && !htmlFilepath.endsWith('.html')) {\n // make sure it ends with .html if the name contains a dot\n htmlFilepath += '.html'\n htmlFilename += '.html'\n }\n\n let renderResult: RenderResult | undefined\n\n if (typeof components.Component === 'string') {\n renderResult = RenderResult.fromStatic(components.Component)\n\n if (hasOrigQueryValues) {\n throw new Error(\n `\\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`\n )\n }\n } else {\n /**\n * This sets environment variable to be used at the time of SSR by head.tsx.\n * Using this from process.env allows targeting SSR by calling\n * `process.env.__NEXT_OPTIMIZE_CSS`.\n */\n if (renderOpts.optimizeCss) {\n process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)\n }\n try {\n renderResult = await lazyRenderPagesPage(\n req,\n res,\n page,\n searchAndDynamicParams,\n renderOpts,\n sharedContext,\n renderContext\n )\n } catch (err) {\n if (!isBailoutToCSRError(err)) throw err\n }\n }\n\n const ssgNotFound = renderResult?.metadata.isNotFound\n\n const ampValidations: AmpValidation[] = []\n\n const validateAmp = async (\n rawAmpHtml: string,\n ampPageName: string,\n validatorPath: string | undefined\n ) => {\n const validator = await AmpHtmlValidator.getInstance(validatorPath)\n const result = validator.validateString(rawAmpHtml)\n const errors = result.errors.filter((e) => e.severity === 'ERROR')\n const warnings = result.errors.filter((e) => e.severity !== 'ERROR')\n\n if (warnings.length || errors.length) {\n ampValidations.push({\n page: ampPageName,\n result: {\n errors,\n warnings,\n },\n })\n }\n }\n\n const html =\n renderResult && !rLine truncated
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import type { OutgoingHttpHeaders } from 'node:http';
|
||||
export type RouteMetadata = {
|
||||
status: number | undefined;
|
||||
headers: OutgoingHttpHeaders | undefined;
|
||||
postponed: string | undefined;
|
||||
segmentPaths: Array<string> | undefined;
|
||||
};
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":[],"names":[],"mappings":""}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
import type { RenderOptsPartial as AppRenderOptsPartial } from '../server/app-render/types';
|
||||
import type { RenderOptsPartial as PagesRenderOptsPartial } from '../server/render';
|
||||
import type { LoadComponentsReturnType } from '../server/load-components';
|
||||
import type { OutgoingHttpHeaders } from 'http';
|
||||
import type AmpHtmlValidator from 'next/dist/compiled/amphtml-validator';
|
||||
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared';
|
||||
import type { CacheControl } from '../server/lib/cache-control';
|
||||
import type { NextEnabledDirectories } from '../server/base-server';
|
||||
import type { SerializableTurborepoAccessTraceResult, TurborepoAccessTraceResult } from '../build/turborepo-access-trace';
|
||||
import type { FetchMetrics } from '../server/base-http';
|
||||
import type { RouteMetadata } from './routes/types';
|
||||
export interface AmpValidation {
|
||||
page: string;
|
||||
result: {
|
||||
errors: AmpHtmlValidator.ValidationError[];
|
||||
warnings: AmpHtmlValidator.ValidationError[];
|
||||
};
|
||||
}
|
||||
type PathMap = ExportPathMap[keyof ExportPathMap];
|
||||
export interface ExportPagesInput {
|
||||
buildId: string;
|
||||
paths: string[];
|
||||
exportPathMap: ExportPathMap;
|
||||
parentSpanId: number;
|
||||
dir: string;
|
||||
distDir: string;
|
||||
outDir: string;
|
||||
pagesDataDir: string;
|
||||
renderOpts: WorkerRenderOptsPartial;
|
||||
nextConfig: NextConfigComplete;
|
||||
cacheMaxMemorySize: NextConfigComplete['cacheMaxMemorySize'] | undefined;
|
||||
fetchCache: boolean | undefined;
|
||||
cacheHandler: string | undefined;
|
||||
fetchCacheKeyPrefix: string | undefined;
|
||||
options: ExportAppOptions;
|
||||
}
|
||||
export interface ExportPageInput {
|
||||
buildId: string;
|
||||
path: string;
|
||||
pathMap: PathMap;
|
||||
distDir: string;
|
||||
outDir: string;
|
||||
pagesDataDir: string;
|
||||
renderOpts: WorkerRenderOptsPartial;
|
||||
ampValidatorPath?: string;
|
||||
trailingSlash?: boolean;
|
||||
buildExport?: boolean;
|
||||
serverRuntimeConfig: {
|
||||
[key: string]: any;
|
||||
};
|
||||
subFolders?: boolean;
|
||||
optimizeCss: any;
|
||||
disableOptimizedLoading: any;
|
||||
parentSpanId: number;
|
||||
httpAgentOptions: NextConfigComplete['httpAgentOptions'];
|
||||
debugOutput?: boolean;
|
||||
nextConfigOutput?: NextConfigComplete['output'];
|
||||
enableExperimentalReact?: boolean;
|
||||
sriEnabled: boolean;
|
||||
}
|
||||
export type ExportRouteResult = {
|
||||
ampValidations?: AmpValidation[];
|
||||
cacheControl: CacheControl;
|
||||
metadata?: Partial<RouteMetadata>;
|
||||
ssgNotFound?: boolean;
|
||||
hasEmptyPrelude?: boolean;
|
||||
hasPostponed?: boolean;
|
||||
fetchMetrics?: FetchMetrics;
|
||||
} | {
|
||||
error: boolean;
|
||||
};
|
||||
export type ExportPageResult = ExportRouteResult & {
|
||||
duration: number;
|
||||
turborepoAccessTraceResult?: SerializableTurborepoAccessTraceResult;
|
||||
};
|
||||
export type ExportPagesResult = {
|
||||
result: ExportPageResult | undefined;
|
||||
path: string;
|
||||
pageKey: string;
|
||||
}[];
|
||||
export type WorkerRenderOptsPartial = PagesRenderOptsPartial & AppRenderOptsPartial;
|
||||
export type WorkerRenderOpts = WorkerRenderOptsPartial & LoadComponentsReturnType;
|
||||
export interface ExportAppOptions {
|
||||
outdir: string;
|
||||
enabledDirectories: NextEnabledDirectories;
|
||||
silent?: boolean;
|
||||
debugOutput?: boolean;
|
||||
pages?: string[];
|
||||
buildExport: boolean;
|
||||
statusMessage?: string;
|
||||
nextConfig?: NextConfigComplete;
|
||||
hasOutdirFromCli?: boolean;
|
||||
numWorkers: number;
|
||||
}
|
||||
export type ExportPageMetadata = {
|
||||
revalidate: number | false;
|
||||
metadata: {
|
||||
status?: number | undefined;
|
||||
headers?: OutgoingHttpHeaders | undefined;
|
||||
} | undefined;
|
||||
duration: number;
|
||||
};
|
||||
export type ExportAppResult = {
|
||||
/**
|
||||
* Page information keyed by path.
|
||||
*/
|
||||
byPath: Map<string, {
|
||||
/**
|
||||
* The cache control for the page.
|
||||
*/
|
||||
cacheControl?: CacheControl;
|
||||
/**
|
||||
* The metadata for the page.
|
||||
*/
|
||||
metadata?: Partial<RouteMetadata>;
|
||||
/**
|
||||
* If the page has an empty prelude when using PPR.
|
||||
*/
|
||||
hasEmptyPrelude?: boolean;
|
||||
/**
|
||||
* If the page has postponed when using PPR.
|
||||
*/
|
||||
hasPostponed?: boolean;
|
||||
fetchMetrics?: FetchMetrics;
|
||||
}>;
|
||||
/**
|
||||
* Durations for each page in milliseconds.
|
||||
*/
|
||||
byPage: Map<string, {
|
||||
durationsByPath: Map<string, number>;
|
||||
}>;
|
||||
/**
|
||||
* The paths that were not found during SSG.
|
||||
*/
|
||||
ssgNotFoundPaths: Set<string>;
|
||||
/**
|
||||
* Traced dependencies for each page.
|
||||
*/
|
||||
turborepoAccessTraceResults: Map<string, TurborepoAccessTraceResult>;
|
||||
};
|
||||
export {};
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":[],"names":[],"mappings":""}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { NextConfigComplete } from '../server/config-shared';
|
||||
export declare function hasCustomExportOutput(config: NextConfigComplete): boolean;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "hasCustomExportOutput", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return hasCustomExportOutput;
|
||||
}
|
||||
});
|
||||
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":";;;;+BAEgBA;;;eAAAA;;;AAAT,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"}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExportPagesInput, ExportPagesResult } from './types';
|
||||
import '../server/node-environment';
|
||||
export declare function exportPages(input: ExportPagesInput): Promise<ExportPagesResult>;
|
||||
+440
@@ -0,0 +1,440 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "exportPages", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return exportPages;
|
||||
}
|
||||
});
|
||||
require("../server/node-environment");
|
||||
const _path = require("path");
|
||||
const _promises = /*#__PURE__*/ _interop_require_default(require("fs/promises"));
|
||||
const _loadcomponents = require("../server/load-components");
|
||||
const _isdynamic = require("../shared/lib/router/utils/is-dynamic");
|
||||
const _normalizepagepath = require("../shared/lib/page-path/normalize-page-path");
|
||||
const _normalizelocalepath = require("../shared/lib/i18n/normalize-locale-path");
|
||||
const _trace = require("../trace");
|
||||
const _setuphttpagentenv = require("../server/setup-http-agent-env");
|
||||
const _iserror = /*#__PURE__*/ _interop_require_default(require("../lib/is-error"));
|
||||
const _requestmeta = require("../server/request-meta");
|
||||
const _apppaths = require("../shared/lib/router/utils/app-paths");
|
||||
const _mockrequest = require("../server/lib/mock-request");
|
||||
const _isapprouteroute = require("../lib/is-app-route-route");
|
||||
const _ciinfo = require("../server/ci-info");
|
||||
const _approute = require("./routes/app-route");
|
||||
const _apppage = require("./routes/app-page");
|
||||
const _pages = require("./routes/pages");
|
||||
const _getparams = require("./helpers/get-params");
|
||||
const _createincrementalcache = require("./helpers/create-incremental-cache");
|
||||
const _ispostpone = require("../server/lib/router-utils/is-postpone");
|
||||
const _isdynamicusageerror = require("./helpers/is-dynamic-usage-error");
|
||||
const _bailouttocsr = require("../shared/lib/lazy-dynamic/bailout-to-csr");
|
||||
const _turborepoaccesstrace = require("../build/turborepo-access-trace");
|
||||
const _fallbackparams = require("../server/request/fallback-params");
|
||||
const _needsexperimentalreact = require("../lib/needs-experimental-react");
|
||||
const _staticgenerationbailout = require("../client/components/static-generation-bailout");
|
||||
const _multifilewriter = require("../lib/multi-file-writer");
|
||||
function _interop_require_default(obj) {
|
||||
return obj && obj.__esModule ? obj : {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
process.env.NEXT_IS_EXPORT_WORKER = 'true';
|
||||
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 = (0, _fallbackparams.getFallbackRouteParams)(_fallbackRouteParams);
|
||||
let query = {
|
||||
...originalQuery
|
||||
};
|
||||
const pathname = (0, _apppaths.normalizeAppPath)(page);
|
||||
const isDynamic = (0, _isdynamic.isDynamicRoute)(page);
|
||||
const outDir = isAppDir ? (0, _path.join)(distDir, 'server/app') : input.outDir;
|
||||
const filePath = (0, _normalizepagepath.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 = (0, _normalizelocalepath.normalizeLocalePath)(path, input.renderOpts.locales);
|
||||
if (localePathResult.detectedLocale) {
|
||||
updatedPath = localePathResult.pathname;
|
||||
locale = localePathResult.detectedLocale;
|
||||
if (locale === input.renderOpts.defaultLocale) {
|
||||
renderAmpPath = `${(0, _normalizepagepath.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 } = (0, _normalizelocalepath.normalizeLocalePath)(path, input.renderOpts.locales);
|
||||
let params;
|
||||
if (isDynamic && page !== nonLocalizedPath) {
|
||||
const normalizedPage = isAppDir ? (0, _apppaths.normalizeAppPath)(page) : page;
|
||||
params = (0, _getparams.getParams)(normalizedPage, updatedPath);
|
||||
}
|
||||
const { req, res } = (0, _mockrequest.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 || ''));
|
||||
})) {
|
||||
(0, _requestmeta.addRequestMeta)(req, 'isLocaleDomain', true);
|
||||
}
|
||||
envConfig.setConfig({
|
||||
serverRuntimeConfig,
|
||||
publicRuntimeConfig: input.renderOpts.runtimeConfig
|
||||
});
|
||||
const getHtmlFilename = (p)=>subFolders ? `${p}${_path.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 ? '' : (0, _path.extname)(page);
|
||||
const pathExt = isDynamic || isAppDir ? '' : (0, _path.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 = (0, _path.join)(outDir, (0, _path.dirname)(htmlFilename));
|
||||
let htmlFilepath = (0, _path.join)(outDir, htmlFilename);
|
||||
await _promises.default.mkdir(baseDir, {
|
||||
recursive: true
|
||||
});
|
||||
const components = await (0, _loadcomponents.loadComponents)({
|
||||
distDir,
|
||||
page,
|
||||
isAppPath: isAppDir,
|
||||
isDev: false,
|
||||
sriEnabled
|
||||
});
|
||||
// Handle App Routes.
|
||||
if (isAppDir && (0, _isapprouteroute.isAppRouteRoute)(page)) {
|
||||
return (0, _approute.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 (_ciinfo.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 (0, _apppage.prospectiveRenderAppPage)(req, res, page, pathname, query, fallbackRouteParams, renderOpts, sharedContext);
|
||||
}
|
||||
return (0, _apppage.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 (0, _pages.exportPagesPage)(req, res, path, page, query, params, htmlFilepath, htmlFilename, ampPath, subFolders, outDir, ampValidatorPath, pagesDataDir, buildExport, isDynamic, sharedContext, renderContext, hasOrigQueryValues, renderOpts, components, fileWriter);
|
||||
}
|
||||
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 (0, _createincrementalcache.createIncrementalCache)({
|
||||
cacheHandler,
|
||||
cacheMaxMemorySize,
|
||||
fetchCacheKeyPrefix,
|
||||
distDir,
|
||||
dir,
|
||||
// skip writing to disk in minimal mode for now, pending some
|
||||
// changes to better support it
|
||||
flushToDisk: !_ciinfo.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: (0, _needsexperimentalreact.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) {
|
||||
(0, _trace.trace)('export-page', input.parentSpanId).setAttribute('path', input.path);
|
||||
// Configure the http agent.
|
||||
(0, _setuphttpagentenv.setHttpClientAndAgentOptions)({
|
||||
httpAgentOptions: input.httpAgentOptions
|
||||
});
|
||||
const fileWriter = new _multifilewriter.MultiFileWriter({
|
||||
writeFile: (filePath, data)=>_promises.default.writeFile(filePath, data),
|
||||
mkdir: (dir)=>_promises.default.mkdir(dir, {
|
||||
recursive: true
|
||||
})
|
||||
});
|
||||
const exportPageSpan = (0, _trace.trace)('export-page-worker', input.parentSpanId);
|
||||
const start = Date.now();
|
||||
const turborepoAccessTraceResult = new _turborepoaccesstrace.TurborepoAccessTraceResult();
|
||||
// Export the page.
|
||||
let result;
|
||||
try {
|
||||
result = await exportPageSpan.traceAsyncFn(()=>(0, _turborepoaccesstrace.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 (!(0, _bailouttocsr.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 ((0, _staticgenerationbailout.isStaticGenBailoutError)(err)) {
|
||||
if (err.message) {
|
||||
console.error(`Error: ${err.message}`);
|
||||
}
|
||||
} else if ((0, _iserror.default)(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 ((0, _ispostpone.isPostpone)(err)) {
|
||||
return;
|
||||
}
|
||||
// we don't want to log these errors
|
||||
if ((0, _isdynamicusageerror.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 ((0, _isdynamicusageerror.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
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/export/worker.ts"],"sourcesContent":["import type {\n ExportPagesInput,\n ExportPageInput,\n ExportPageResult,\n ExportRouteResult,\n WorkerRenderOpts,\n ExportPagesResult,\n} from './types'\n\nimport '../server/node-environment'\n\nprocess.env.NEXT_IS_EXPORT_WORKER = 'true'\n\nimport { extname, join, dirname, sep } from 'path'\nimport fs from 'fs/promises'\nimport { loadComponents } from '../server/load-components'\nimport { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { trace } from '../trace'\nimport { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'\nimport isError from '../lib/is-error'\nimport { addRequestMeta } from '../server/request-meta'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\n\nimport { createRequestResponseMocks } from '../server/lib/mock-request'\nimport { isAppRouteRoute } from '../lib/is-app-route-route'\nimport { hasNextSupport } from '../server/ci-info'\nimport { exportAppRoute } from './routes/app-route'\nimport { exportAppPage, prospectiveRenderAppPage } from './routes/app-page'\nimport { exportPagesPage } from './routes/pages'\nimport { getParams } from './helpers/get-params'\nimport { createIncrementalCache } from './helpers/create-incremental-cache'\nimport { isPostpone } from '../server/lib/router-utils/is-postpone'\nimport { isDynamicUsageError } from './helpers/is-dynamic-usage-error'\nimport { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr'\nimport {\n turborepoTraceAccess,\n TurborepoAccessTraceResult,\n} from '../build/turborepo-access-trace'\nimport type { Params } from '../server/request/params'\nimport {\n getFallbackRouteParams,\n type FallbackRouteParams,\n} from '../server/request/fallback-params'\nimport { needsExperimentalReact } from '../lib/needs-experimental-react'\nimport type { AppRouteRouteModule } from '../server/route-modules/app-route/module.compiled'\nimport { isStaticGenBailoutError } from '../client/components/static-generation-bailout'\nimport type { PagesRenderContext, PagesSharedContext } from '../server/render'\nimport type { AppSharedContext } from '../server/app-render/app-render'\nimport { MultiFileWriter } from '../lib/multi-file-writer'\n\nconst envConfig = require('../shared/lib/runtime-config.external')\n\n;(globalThis as any).__NEXT_DATA__ = {\n nextExport: true,\n}\n\nclass TimeoutError extends Error {\n code = 'NEXT_EXPORT_TIMEOUT_ERROR'\n}\n\nclass ExportPageError extends Error {\n code = 'NEXT_EXPORT_PAGE_ERROR'\n}\n\nasync function exportPageImpl(\n input: ExportPageInput,\n fileWriter: MultiFileWriter\n): Promise<ExportRouteResult | undefined> {\n const {\n path,\n pathMap,\n distDir,\n pagesDataDir,\n buildExport = false,\n serverRuntimeConfig,\n subFolders = false,\n optimizeCss,\n disableOptimizedLoading,\n debugOutput = false,\n enableExperimentalReact,\n ampValidatorPath,\n trailingSlash,\n sriEnabled,\n } = input\n\n if (enableExperimentalReact) {\n process.env.__NEXT_EXPERIMENTAL_REACT = 'true'\n }\n\n const {\n page,\n\n // The parameters that are currently unknown.\n _fallbackRouteParams = [],\n\n // Check if this is an `app/` page.\n _isAppDir: isAppDir = false,\n\n // Check if this should error when dynamic usage is detected.\n _isDynamicError: isDynamicError = false,\n\n // If this page supports partial prerendering, then we need to pass that to\n // the renderOpts.\n _isRoutePPREnabled: isRoutePPREnabled,\n\n // If this is a prospective render, we don't actually want to persist the\n // result, we just want to use it to error the build if there's a problem.\n _isProspectiveRender: isProspectiveRender = false,\n\n // Pull the original query out.\n query: originalQuery = {},\n } = pathMap\n\n const fallbackRouteParams: FallbackRouteParams | null =\n getFallbackRouteParams(_fallbackRouteParams)\n\n let query = { ...originalQuery }\n const pathname = normalizeAppPath(page)\n const isDynamic = isDynamicRoute(page)\n const outDir = isAppDir ? join(distDir, 'server/app') : input.outDir\n\n const filePath = normalizePagePath(path)\n const ampPath = `${filePath}.amp`\n let renderAmpPath = ampPath\n\n let updatedPath = pathMap._ssgPath || path\n let locale = pathMap._locale || input.renderOpts.locale\n\n if (input.renderOpts.locale) {\n const localePathResult = normalizeLocalePath(path, input.renderOpts.locales)\n\n if (localePathResult.detectedLocale) {\n updatedPath = localePathResult.pathname\n locale = localePathResult.detectedLocale\n\n if (locale === input.renderOpts.defaultLocale) {\n renderAmpPath = `${normalizePagePath(updatedPath)}.amp`\n }\n }\n }\n\n // We need to show a warLine truncated
|
||||
Reference in new issue
Block a user