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

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

View File

@@ -0,0 +1,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>;

View File

@@ -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)(cacheMaxMemorySize)) {
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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/helpers/create-incremental-cache.ts"],"sourcesContent":["import path from 'path'\nimport { IncrementalCache } from '../../server/lib/incremental-cache'\nimport { hasNextSupport } from '../../server/ci-info'\nimport { nodeFs } from '../../server/lib/node-fs-methods'\nimport { interopDefault } from '../../lib/interop-default'\nimport { formatDynamicImportPath } from '../../lib/format-dynamic-import-path'\nimport {\n initializeCacheHandlers,\n setCacheHandler,\n} from '../../server/use-cache/handlers'\n\nexport async function createIncrementalCache({\n cacheHandler,\n cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n distDir,\n dir,\n flushToDisk,\n cacheHandlers,\n requestHeaders,\n}: {\n cacheHandler?: string\n cacheMaxMemorySize: number\n fetchCacheKeyPrefix?: string\n distDir: string\n dir: string\n flushToDisk?: boolean\n requestHeaders?: Record<string, string | string[] | undefined>\n cacheHandlers?: Record<string, string | undefined>\n}) {\n // Custom cache handler overrides.\n let CacheHandler: any\n if (cacheHandler) {\n CacheHandler = interopDefault(\n await import(formatDynamicImportPath(dir, cacheHandler)).then(\n (mod) => mod.default || mod\n )\n )\n }\n\n if (cacheHandlers && initializeCacheHandlers(cacheMaxMemorySize)) {\n for (const [kind, handler] of Object.entries(cacheHandlers)) {\n if (!handler) continue\n\n setCacheHandler(\n kind,\n interopDefault(\n await import(formatDynamicImportPath(dir, handler)).then(\n (mod) => mod.default || mod\n )\n )\n )\n }\n }\n\n const incrementalCache = new IncrementalCache({\n dev: false,\n requestHeaders: requestHeaders || {},\n flushToDisk,\n maxMemoryCacheSize: cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n getPrerenderManifest: () => ({\n version: 4,\n routes: {},\n dynamicRoutes: {},\n preview: {\n previewModeEncryptionKey: '',\n previewModeId: '',\n previewModeSigningKey: '',\n },\n notFoundRoutes: [],\n }),\n fs: nodeFs,\n serverDistDir: path.join(distDir, 'server'),\n CurCacheHandler: CacheHandler,\n minimalMode: hasNextSupport,\n })\n\n ;(globalThis as any).__incrementalCache = incrementalCache\n\n return incrementalCache\n}\n"],"names":["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,EAACb,qBAAqB;QAChE,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","ignoreList":[0]}

View File

@@ -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;

View File

@@ -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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/helpers/get-params.ts"],"sourcesContent":["import {\n type RouteMatchFn,\n getRouteMatcher,\n} from '../../shared/lib/router/utils/route-matcher'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\n\n// The last page and matcher that this function handled.\nlet last: {\n page: string\n matcher: RouteMatchFn\n} | null = null\n\n/**\n * Gets the params for the provided page.\n * @param page the page that contains dynamic path parameters\n * @param pathname the pathname to match\n * @returns the matches that were found, throws otherwise\n */\nexport function getParams(page: string, pathname: string) {\n // Because this is often called on the output of `getStaticPaths` or similar\n // where the `page` here doesn't change, this will \"remember\" the last page\n // it created the RegExp for. If it matches, it'll just re-use it.\n let matcher: RouteMatchFn\n if (last?.page === page) {\n matcher = last.matcher\n } else {\n matcher = getRouteMatcher(getRouteRegex(page))\n }\n\n const params = matcher(pathname)\n if (!params) {\n throw new Error(\n `The provided export path '${pathname}' doesn't match the '${page}' page.\\nRead more: https://nextjs.org/docs/messages/export-path-mismatch`\n )\n }\n\n return params\n}\n"],"names":["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","ignoreList":[0]}

View File

@@ -0,0 +1 @@
export declare const isDynamicUsageError: (err: unknown) => boolean;

View File

@@ -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

View File

@@ -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","ignoreList":[0]}

View File

@@ -0,0 +1,8 @@
import type { ExportAppResult, ExportAppOptions } from './types';
import { type StaticWorker } from '../build';
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, staticWorker?: StaticWorker): Promise<ExportAppResult | null>;

753
apps/public-web/node_modules/next/dist/export/index.js generated vendored Normal file
View File

@@ -0,0 +1,753 @@
"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 _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");
const _worker = require("../lib/worker");
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, staticWorker) {
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, {
debugPrerender: options.debugPrerender
}));
const distDir = (0, _path.join)(dir, nextConfig.distDir);
const telemetry = options.buildExport ? null : new _storage.Telemetry({
distDir
});
if (telemetry) {
telemetry.record((0, _events.eventCliSession)(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,
cacheComponents: nextConfig.cacheComponents ?? false,
trailingSlash: nextConfig.trailingSlash,
locales: i18n == null ? void 0 : i18n.locales,
locale: i18n == null ? void 0 : i18n.defaultLocale,
defaultLocale: i18n == null ? void 0 : i18n.defaultLocale,
domainLocales: i18n == null ? void 0 : i18n.domains,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
// Exported pages do not currently support dynamic HTML.
supportsDynamicResponse: false,
crossOrigin: nextConfig.crossOrigin,
optimizeCss: nextConfig.experimental.optimizeCss,
nextConfigOutput: nextConfig.output,
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,
largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverActions: nextConfig.experimental.serverActions,
serverComponents: enabledDirectories.app,
cacheLifeProfiles: nextConfig.cacheLife,
nextFontManifest: require((0, _path.join)(distDir, 'server', `${_constants1.NEXT_FONT_MANIFEST}.json`)),
images: nextConfig.images,
deploymentId: nextConfig.deploymentId,
htmlLimitedBots: nextConfig.htmlLimitedBots.source,
experimental: {
clientTraceMetadata: nextConfig.experimental.clientTraceMetadata,
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
clientParamParsingOrigins: nextConfig.experimental.clientParamParsingOrigins,
dynamicOnHover: nextConfig.experimental.dynamicOnHover ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts
},
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
hasReadableErrorStacks: nextConfig.experimental.serverSourceMaps === true && // TODO(NDX-531): Checking (and setting) the minify flags should be
// unnecessary once name mapping is fixed.
(process.env.TURBOPACK ? nextConfig.experimental.turbopackMinify === false : nextConfig.experimental.serverMinification === false) && nextConfig.enablePrerenderSourceMaps === true
};
globalThis.__NEXT_DATA__ = {
nextExport: true
};
const exportPathMap = await span.traceChild('run-export-path-map').traceAsyncFn(async ()=>{
const exportMap = await nextConfig.exportPathMap(defaultPathMap, {
dev: false,
dir,
outDir,
distDir,
buildId
});
return exportMap;
});
// During static export, remove export 404/500 of pages router
// when only app router presents
if (!options.buildExport && options.appDirOnly) {
delete exportPathMap['/404'];
delete exportPathMap['/500'];
}
// only add missing 404 page when `buildExport` is false
if (!options.buildExport && !options.appDirOnly) {
// only add missing /404 if not specified in `exportPathMap`
if (!exportPathMap['/404']) {
exportPathMap['/404'] = {
page: '/_error'
};
}
/**
* exports 404.html for backwards compat
* E.g. GitHub Pages, GitLab Pages, Cloudflare Pages, Netlify
*/ if (!exportPathMap['/404.html'] && exportPathMap['/404']) {
// alias /404.html to /404 to be compatible with custom 404 / _error page
exportPathMap['/404.html'] = exportPathMap['/404'];
}
}
const allExportPaths = [];
const seenExportPaths = new Set();
const fallbackEnabledPages = new Set();
for (const [path, entry] of Object.entries(exportPathMap)){
// make sure to prevent duplicates
const normalizedPath = (0, _denormalizepagepath.denormalizePagePath)((0, _normalizepagepath.normalizePagePath)(path));
if (seenExportPaths.has(normalizedPath)) {
continue;
}
seenExportPaths.add(normalizedPath);
if (!entry._isAppDir && (0, _isapiroute.isAPIRoute)(entry.page)) {
hasApiRoutes = true;
continue;
}
allExportPaths.push({
...entry,
path: normalizedPath
});
if (prerenderManifest && !options.buildExport) {
const prerenderInfo = prerenderManifest.dynamicRoutes[entry.page];
if (prerenderInfo && prerenderInfo.fallback !== false) {
fallbackEnabledPages.add(entry.page);
}
}
}
if (allExportPaths.length === 0) {
if (!prerenderManifest) {
return null;
}
}
if (fallbackEnabledPages.size > 0) {
throw Object.defineProperty(new ExportError(`Found pages with \`fallback\` enabled:\n${[
...fallbackEnabledPages
].join('\n')}\n${_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 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 exportPagesInBatches = async (worker, exportPaths, renderResumeDataCachesByPage)=>{
// Batch filtered pages into smaller batches, and call the export worker on
// each batch. We've set a default minimum of 25 pages per batch to ensure
// that even setups with only a few static pages can leverage a shared
// incremental cache, however this value can be configured.
const minPageCountPerBatch = nextConfig.experimental.staticGenerationMinPagesPerWorker ?? 25;
// Calculate the number of workers needed to ensure each batch has at least
// minPageCountPerBatch pages.
const numWorkers = Math.min(options.numWorkers, Math.ceil(exportPaths.length / minPageCountPerBatch));
// Calculate the page count per batch based on the number of workers.
const pageCountPerBatch = Math.ceil(exportPaths.length / numWorkers);
const batches = Array.from({
length: numWorkers
}, (_, i)=>exportPaths.slice(i * pageCountPerBatch, (i + 1) * pageCountPerBatch));
// Distribute remaining pages.
const remainingPages = exportPaths.slice(numWorkers * pageCountPerBatch);
remainingPages.forEach((page, index)=>{
batches[index % batches.length].push(page);
});
return (await Promise.all(batches.map(async (batch)=>worker.exportPages({
buildId,
exportPaths: batch,
parentSpanId: span.getId(),
pagesDataDir,
renderOpts,
options,
dir,
distDir,
outDir,
nextConfig,
cacheHandler: nextConfig.cacheHandler,
cacheMaxMemorySize: nextConfig.cacheMaxMemorySize,
fetchCache: true,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
renderResumeDataCachesByPage
})))).flat();
};
let initialPhaseExportPaths = [];
const finalPhaseExportPaths = [];
if (renderOpts.cacheComponents) {
for (const exportPath of allExportPaths){
if (exportPath._allowEmptyStaticShell) {
finalPhaseExportPaths.push(exportPath);
} else {
initialPhaseExportPaths.push(exportPath);
}
}
} else {
initialPhaseExportPaths = allExportPaths;
}
const totalExportPaths = initialPhaseExportPaths.length + finalPhaseExportPaths.length;
let worker = null;
let results = [];
if (totalExportPaths > 0) {
const progress = (0, _progress.createProgress)(totalExportPaths, options.statusMessage ?? `Exporting using ${options.numWorkers} worker${options.numWorkers > 1 ? 's' : ''}`);
if (staticWorker) {
// TODO: progress shouldn't rely on "activity" event sent from `exportPage`.
staticWorker.setOnActivity(progress.run);
staticWorker.setOnActivityAbort(progress.clear);
worker = staticWorker;
} else {
worker = (0, _build.createStaticWorker)(nextConfig, {
debuggerPortOffset: (0, _worker.getNextBuildDebuggerPortOffset)({
kind: 'export-page'
}),
numberOfWorkers: options.numWorkers,
progress
});
}
results = await exportPagesInBatches(worker, initialPhaseExportPaths);
if (finalPhaseExportPaths.length > 0) {
const renderResumeDataCachesByPage = {};
for (const { page, result } of results){
if (!result) {
continue;
}
if ('renderResumeDataCache' in result && result.renderResumeDataCache) {
// The last RDC for each page is used. We only need one. It should have
// all the entries that the fallback shell also needs. We don't need to
// merge them per page.
renderResumeDataCachesByPage[page] = result.renderResumeDataCache;
// Remove the RDC string from the result so that it can be garbage
// collected, when there are more results for the same page.
result.renderResumeDataCache = undefined;
}
}
const finalPhaseResults = await exportPagesInBatches(worker, finalPhaseExportPaths, renderResumeDataCachesByPage);
results.push(...finalPhaseResults);
}
}
const collector = {
byPath: new Map(),
byPage: new Map(),
ssgNotFoundPaths: new Set(),
turborepoAccessTraceResults: new Map()
};
const failedExportAttemptsByPage = new Map();
for (const { result, path, page, pageKey } of results){
if (!result) continue;
if ('error' in result) {
failedExportAttemptsByPage.set(pageKey, true);
continue;
}
if (result.turborepoAccessTraceResult) {
var _collector_turborepoAccessTraceResults;
(_collector_turborepoAccessTraceResults = collector.turborepoAccessTraceResults) == null ? void 0 : _collector_turborepoAccessTraceResults.set(path, _turborepoaccesstrace.TurborepoAccessTraceResult.fromSerialized(result.turborepoAccessTraceResult));
}
if (options.buildExport) {
// Update path info by path.
const info = collector.byPath.get(path) ?? {};
if (result.cacheControl) {
info.cacheControl = result.cacheControl;
}
if (typeof result.metadata !== 'undefined') {
info.metadata = result.metadata;
}
if (typeof result.hasEmptyStaticShell !== 'undefined') {
info.hasEmptyStaticShell = result.hasEmptyStaticShell;
}
if (typeof result.hasPostponed !== 'undefined') {
info.hasPostponed = result.hasPostponed;
}
if (typeof result.fetchMetrics !== 'undefined') {
info.fetchMetrics = result.fetchMetrics;
}
collector.byPath.set(path, info);
// Update not found.
if (result.ssgNotFound === true) {
collector.ssgNotFoundPaths.add(path);
}
// Update durations.
const durations = collector.byPage.get(page) ?? {
durationsByPath: new Map()
};
durations.durationsByPath.set(path, result.duration);
collector.byPage.set(page, durations);
}
}
// Export mode provide static outputs that are not compatible with PPR mode.
if (!options.buildExport && nextConfig.experimental.ppr) {
// TODO: add message
throw Object.defineProperty(new Error('Invariant: PPR cannot be enabled in export mode'), "__NEXT_ERROR_CODE", {
value: "E54",
enumerable: false,
configurable: true
});
}
// copy prerendered routes to outDir
if (!options.buildExport && prerenderManifest) {
await Promise.all(Object.keys(prerenderManifest.routes).map(async (unnormalizedRoute)=>{
// Special handling: map app /_not-found to 404.html (and 404/index.html when trailingSlash)
if (unnormalizedRoute === '/_not-found') {
const { srcRoute } = prerenderManifest.routes[unnormalizedRoute];
const appPageName = mapAppRouteToPage.get(srcRoute || '');
const pageName = appPageName || srcRoute || unnormalizedRoute;
const isAppPath = Boolean(appPageName);
const route = (0, _normalizepagepath.normalizePagePath)(unnormalizedRoute);
const pagePath = (0, _require.getPagePath)(pageName, distDir, undefined, isAppPath);
const distPagesDir = (0, _path.join)(pagePath, pageName.slice(1).split('/').map(()=>'..').join('/'));
const orig = (0, _path.join)(distPagesDir, route);
const htmlSrc = `${orig}.html`;
// write 404.html at root
const htmlDest404 = (0, _path.join)(outDir, '404.html');
await _fs.promises.mkdir((0, _path.dirname)(htmlDest404), {
recursive: true
});
await _fs.promises.copyFile(htmlSrc, htmlDest404);
// When trailingSlash, also write 404/index.html
if (subFolders) {
const htmlDest404Index = (0, _path.join)(outDir, '404', 'index.html');
await _fs.promises.mkdir((0, _path.dirname)(htmlDest404Index), {
recursive: true
});
await _fs.promises.copyFile(htmlSrc, htmlDest404Index);
}
}
// Skip 500.html in static export
if (unnormalizedRoute === '/_global-error') {
return;
}
const { srcRoute } = prerenderManifest.routes[unnormalizedRoute];
const appPageName = mapAppRouteToPage.get(srcRoute || '');
const pageName = appPageName || srcRoute || unnormalizedRoute;
const isAppPath = Boolean(appPageName);
const isAppRouteHandler = appPageName && (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 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);
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 (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();
}
// Clean up activity listeners for progress.
if (staticWorker) {
staticWorker.setOnActivity(undefined);
staticWorker.setOnActivityAbort(undefined);
}
if (!staticWorker && worker) {
await worker.end();
}
return collector;
}
async function collectSegmentPaths(segmentsDirectory) {
const results = [];
await collectSegmentPathsImpl(segmentsDirectory, segmentsDirectory, results);
return results;
}
async function collectSegmentPathsImpl(segmentsDirectory, directory, results) {
const segmentFiles = await _fs.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, staticWorker) {
const nextExportSpan = span.traceChild('next-export');
return nextExportSpan.traceAsyncFn(async ()=>{
return await exportAppImpl(dir, options, nextExportSpan, staticWorker);
});
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
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 { OpaqueFallbackRouteParams } 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';
/**
* 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: OpaqueFallbackRouteParams | null, partialRenderOpts: Omit<RenderOpts, keyof RequestLifecycleOpts>, htmlFilepath: string, debugOutput: boolean, isDynamicError: boolean, fileWriter: MultiFileWriter, sharedContext: AppSharedContext): Promise<ExportRouteResult>;

View File

@@ -0,0 +1,201 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "exportAppPage", {
enumerable: true,
get: function() {
return exportAppPage;
}
});
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");
const _resumedatacache = require("../../server/resume-data-cache/resume-data-cache");
const _entryconstants = require("../../shared/lib/entry-constants");
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;
let isDefaultGlobalError = false;
// If the page is `/_not-found`, then we should update the page to be `/404`.
if (page === _entryconstants.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY) {
isDefaultNotFound = true;
pathname = '/404';
}
// If the page is `/_global-error`, then we should update the page to be `/500`.
if (page === _entryconstants.UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY) {
isDefaultGlobalError = true;
pathname = '/500';
}
try {
const result = await (0, _modulerender.lazyRenderAppPage)(new _node.NodeNextRequest(req), new _node.NodeNextResponse(res), pathname, query, fallbackRouteParams, renderOpts, undefined, sharedContext);
const html = result.toUnchunkedString();
// TODO(after): if we abort a prerender because of an error in an after-callback
// we should probably communicate that better (and not log the error twice)
await afterRunner.executeAfter();
const { metadata } = result;
const { flightData, cacheControl = {
revalidate: false,
expire: undefined
}, postponed, fetchTags, fetchMetrics, segmentData, renderResumeDataCache } = metadata;
// Ensure we don't postpone without having PPR enabled.
if (postponed && !renderOpts.experimental.isRoutePPREnabled) {
throw Object.defineProperty(new Error('Invariant: page postponed without PPR being enabled'), "__NEXT_ERROR_CODE", {
value: "E156",
enumerable: false,
configurable: true
});
}
if (cacheControl.revalidate === 0) {
if (isDynamicError) {
throw Object.defineProperty(new Error(`Page with dynamic = "error" encountered dynamic data method on ${path}.`), "__NEXT_ERROR_CODE", {
value: "E388",
enumerable: false,
configurable: true
});
}
const { staticBailoutInfo = {} } = metadata;
if (debugOutput && (staticBailoutInfo == null ? void 0 : staticBailoutInfo.description)) {
logDynamicUsageWarning({
path,
description: staticBailoutInfo.description,
stack: staticBailoutInfo.stack
});
}
return {
cacheControl,
fetchMetrics
};
}
// If page data isn't available, it means that the page couldn't be rendered
// properly so long as we don't have unknown route params. When a route doesn't
// have unknown route params, there will not be any flight data.
if (!flightData) {
if (!fallbackRouteParams || fallbackRouteParams.size === 0 || renderOpts.cacheComponents) {
throw Object.defineProperty(new Error(`Invariant: failed to get page data for ${path}`), "__NEXT_ERROR_CODE", {
value: "E194",
enumerable: false,
configurable: true
});
}
} else {
// If PPR is enabled, we want to emit a segment prefetch files
// 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) {
// 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 (isDefaultGlobalError) {
// Override the default /_global-error page status code to 500
status = 500;
} else if (isNonSuccessfulStatusCode && !isParallelRoute) {
// If it's parallel route the status from mock response is 404
status = res.statusCode;
}
// Writing the request metadata to a file.
const meta = {
status,
headers,
postponed,
segmentPaths
};
fileWriter.append(htmlFilepath.replace(/\.html$/, _constants.NEXT_META_SUFFIX), JSON.stringify(meta, null, 2));
return {
// Filter the metadata if the environment does not have next support.
metadata: _ciinfo.hasNextSupport ? meta : {
segmentPaths: meta.segmentPaths
},
hasEmptyStaticShell: Boolean(postponed) && html === '',
hasPostponed: Boolean(postponed),
cacheControl,
fetchMetrics,
renderResumeDataCache: renderResumeDataCache ? await (0, _resumedatacache.stringifyResumeDataCache)(renderResumeDataCache, renderOpts.cacheComponents) : undefined
};
} 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

File diff suppressed because one or more lines are too long

View File

@@ -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, cacheComponents: boolean, experimental: Required<Pick<ExperimentalConfig, 'authInterrupts'>>, buildId: string): Promise<ExportRouteResult>;

View File

@@ -0,0 +1,144 @@
"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 _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, cacheComponents, experimental, buildId) {
// Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}`;
// Adapt the request and response to the Next.js request and response.
const request = _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: {
cacheComponents,
experimental,
nextExport: true,
supportsDynamicResponse: false,
incrementalCache,
waitUntil: afterRunner.context.waitUntil,
onClose: afterRunner.context.onClose,
onAfterTaskError: afterRunner.context.onTaskError,
cacheLifeProfiles
},
sharedContext: {
buildId
}
};
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 cacheComponents is enabled because we
// expect that anything dynamic in the GET handler will make it dynamic
// and thus avoid the cache surprises that led to us removing static gen
// unless specifically opted into
cacheComponents !== true) {
return {
cacheControl: {
revalidate: 0,
expire: undefined
}
};
}
const response = await 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

File diff suppressed because one or more lines are too long

View File

@@ -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, pagesDataDir: string, buildExport: boolean, isDynamic: boolean, sharedContext: PagesSharedContext, renderContext: PagesRenderContext, hasOrigQueryValues: boolean, renderOpts: RenderOpts, components: LoadComponentsReturnType, fileWriter: MultiFileWriter): Promise<ExportRouteResult | undefined>;

View File

@@ -0,0 +1,91 @@
"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 _constants = require("../../lib/constants");
const _bailouttocsr = require("../../shared/lib/lazy-dynamic/bailout-to-csr");
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, pagesDataDir, buildExport, isDynamic, sharedContext, renderContext, hasOrigQueryValues, renderOpts, components, fileWriter) {
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, _constants.HTML_CONTENT_TYPE_HEADER);
if (hasOrigQueryValues) {
throw Object.defineProperty(new Error(`\nError: you provided query values for ${path} which is an auto-exported page. These can not be applied since the page can no longer be re-rendered on the server. To disable auto-export for this page add \`getInitialProps\`\n`), "__NEXT_ERROR_CODE", {
value: "E505",
enumerable: false,
configurable: true
});
}
} else {
/**
* This sets environment variable to be used at the time of SSR by head.tsx.
* Using this from process.env allows targeting SSR by calling
* `process.env.__NEXT_OPTIMIZE_CSS`.
*/ if (renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true);
}
try {
renderResult = await (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 html = renderResult && !renderResult.isNull ? renderResult.toUnchunkedString() : '';
const metadata = (renderResult == null ? void 0 : renderResult.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 (!ssgNotFound) {
// don't attempt writing to disk if getStaticProps returned not found
fileWriter.append(htmlFilepath, html);
}
return {
cacheControl: metadata.cacheControl ?? {
revalidate: false,
expire: undefined
},
ssgNotFound
};
}
//# sourceMappingURL=pages.js.map

File diff suppressed because one or more lines are too long

View File

@@ -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;
};

View File

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

View File

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

View File

@@ -0,0 +1,136 @@
import type { RenderOptsPartial as AppRenderOptsPartial } from '../server/app-render/types';
import type { RenderOptsPartial as PagesRenderOptsPartial } from '../server/render';
import type { GenericComponentMod, LoadComponentsReturnType } from '../server/load-components';
import type { OutgoingHttpHeaders } from 'http';
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';
import type { RenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache';
import type { StaticWorker } from '../build';
export type ExportPathEntry = ExportPathMap[keyof ExportPathMap] & {
path: string;
};
export interface ExportPagesInput {
buildId: string;
exportPaths: ExportPathEntry[];
parentSpanId: number;
dir: string;
distDir: string;
outDir: string;
pagesDataDir: string;
renderOpts: WorkerRenderOptsPartial;
nextConfig: NextConfigComplete;
cacheMaxMemorySize: NextConfigComplete['cacheMaxMemorySize'];
fetchCache: boolean | undefined;
cacheHandler: string | undefined;
fetchCacheKeyPrefix: string | undefined;
options: ExportAppOptions;
renderResumeDataCachesByPage: Record<string, string> | undefined;
}
export interface ExportPageInput {
buildId: string;
exportPath: ExportPathEntry;
distDir: string;
outDir: string;
pagesDataDir: string;
renderOpts: WorkerRenderOptsPartial;
trailingSlash?: boolean;
buildExport?: boolean;
subFolders?: boolean;
optimizeCss: any;
disableOptimizedLoading: any;
parentSpanId: number;
httpAgentOptions: NextConfigComplete['httpAgentOptions'];
debugOutput?: boolean;
nextConfigOutput?: NextConfigComplete['output'];
enableExperimentalReact?: boolean;
sriEnabled: boolean;
renderResumeDataCache: RenderResumeDataCache | undefined;
}
export type ExportRouteResult = {
cacheControl: CacheControl;
metadata?: Partial<RouteMetadata>;
ssgNotFound?: boolean;
hasEmptyStaticShell?: boolean;
hasPostponed?: boolean;
fetchMetrics?: FetchMetrics;
renderResumeDataCache?: string;
} | {
error: boolean;
};
export type ExportPageResult = ExportRouteResult & {
duration: number;
turborepoAccessTraceResult?: SerializableTurborepoAccessTraceResult;
};
export type ExportPagesResult = {
result: ExportPageResult | undefined;
path: string;
page: string;
pageKey: string;
}[];
export type WorkerRenderOptsPartial = PagesRenderOptsPartial & AppRenderOptsPartial;
export type WorkerRenderOpts<NextModule extends GenericComponentMod = GenericComponentMod> = WorkerRenderOptsPartial & LoadComponentsReturnType<NextModule>;
export interface ExportAppOptions {
staticWorker?: StaticWorker;
outdir: string;
enabledDirectories: NextEnabledDirectories;
silent?: boolean;
debugOutput?: boolean;
debugPrerender?: boolean;
pages?: string[];
buildExport: boolean;
statusMessage?: string;
nextConfig?: NextConfigComplete;
hasOutdirFromCli?: boolean;
numWorkers: number;
appDirOnly: boolean;
}
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 static shell when using PPR.
*/
hasEmptyStaticShell?: 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>;
};

View File

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

View File

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

View File

@@ -0,0 +1,2 @@
import type { NextConfigComplete } from '../server/config-shared';
export declare function hasCustomExportOutput(config: NextConfigComplete): boolean;

24
apps/public-web/node_modules/next/dist/export/utils.js generated vendored Normal file
View File

@@ -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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/export/utils.ts"],"sourcesContent":["import type { NextConfigComplete } from '../server/config-shared'\n\nexport function hasCustomExportOutput(config: NextConfigComplete) {\n // In the past, a user had to run \"next build\" to generate\n // \".next\" (or whatever the distDir) followed by \"next export\"\n // to generate \"out\" (or whatever the outDir). However, when\n // \"output: export\" is configured, \"next build\" does both steps.\n // So the user-configured distDir is actually the outDir.\n // We'll do some custom logic when meeting this condition.\n // e.g.\n // Will set config.distDir to .next to make sure the manifests\n // are still reading from temporary .next directory.\n return config.output === 'export' && config.distDir !== '.next'\n}\n"],"names":["hasCustomExportOutput","config","output","distDir"],"mappings":";;;;+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","ignoreList":[0]}

View File

@@ -0,0 +1,3 @@
import type { ExportPagesInput, ExportPagesResult } from './types';
import '../server/node-environment';
export declare function exportPages(input: ExportPagesInput): Promise<ExportPagesResult>;

429
apps/public-web/node_modules/next/dist/export/worker.js generated vendored Normal file
View File

@@ -0,0 +1,429 @@
"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 _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");
const _resumedatacache = require("../server/resume-data-cache/resume-data-cache");
const _globalbehaviors = require("../server/node-environment-extensions/global-behaviors");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
process.env.NEXT_IS_EXPORT_WORKER = 'true';
globalThis.__NEXT_DATA__ = {
nextExport: true
};
class TimeoutError extends Error {
constructor(...args){
super(...args), this.code = 'NEXT_EXPORT_TIMEOUT_ERROR';
}
}
class ExportPageError extends Error {
constructor(...args){
super(...args), this.code = 'NEXT_EXPORT_PAGE_ERROR';
}
}
async function exportPageImpl(input, fileWriter) {
var _req_url;
const { exportPath, distDir, pagesDataDir, buildExport = false, subFolders = false, optimizeCss, disableOptimizedLoading, debugOutput = false, enableExperimentalReact, trailingSlash, sriEnabled, renderOpts: commonRenderOpts, outDir: commonOutDir, buildId, renderResumeDataCache } = input;
if (enableExperimentalReact) {
process.env.__NEXT_EXPERIMENTAL_REACT = 'true';
}
const { path, page, // The parameters that are currently unknown.
_fallbackRouteParams = [], // Check if this is an `app/` page.
_isAppDir: isAppDir = false, // Check if this should error when dynamic usage is detected.
_isDynamicError: isDynamicError = false, // If this page supports partial prerendering, then we need to pass that to
// the renderOpts.
_isRoutePPREnabled: isRoutePPREnabled, // Configure the rendering of the page to allow that an empty static shell
// is generated while rendering using PPR and Cache Components.
_allowEmptyStaticShell: allowEmptyStaticShell = false, // Pull the original query out.
query: originalQuery = {} } = exportPath;
const fallbackRouteParams = (0, _fallbackparams.createOpaqueFallbackRouteParams)(_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') : commonOutDir;
const filePath = (0, _normalizepagepath.normalizePagePath)(path);
let updatedPath = exportPath._ssgPath || path;
let locale = exportPath._locale || commonRenderOpts.locale;
if (commonRenderOpts.locale) {
const localePathResult = (0, _normalizelocalepath.normalizeLocalePath)(path, commonRenderOpts.locales);
if (localePathResult.detectedLocale) {
updatedPath = localePathResult.pathname;
locale = localePathResult.detectedLocale;
}
}
// We need to show a warning if they try to provide query values
// for an auto-exported page since they won't be available
const hasOrigQueryValues = Object.keys(originalQuery).length > 0;
// Check if the page is a specified dynamic route
const { pathname: nonLocalizedPath } = (0, _normalizelocalepath.normalizeLocalePath)(path, commonRenderOpts.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 && commonRenderOpts.domainLocales && commonRenderOpts.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);
}
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,
needsManifestsForLegacyReasons: true
});
// Handle App Routes.
if (isAppDir && (0, _isapprouteroute.isAppRouteRoute)(page)) {
return (0, _approute.exportAppRoute)(req, res, params, page, components.routeModule, commonRenderOpts.incrementalCache, commonRenderOpts.cacheLifeProfiles, htmlFilepath, fileWriter, commonRenderOpts.cacheComponents, commonRenderOpts.experimental, buildId);
}
const renderOpts = {
...components,
...commonRenderOpts,
params,
optimizeCss,
disableOptimizedLoading,
locale,
supportsDynamicResponse: false,
// During the export phase in next build, we always enable the streaming metadata since if there's
// any dynamic access in metadata we can determine it in the build phase.
// If it's static, then it won't affect anything.
// If it's dynamic, then it can be handled when request hits the route.
serveStreamingMetadata: true,
allowEmptyStaticShell,
experimental: {
...commonRenderOpts.experimental,
isRoutePPREnabled
},
renderResumeDataCache
};
// Handle App Pages
if (isAppDir) {
const sharedContext = {
buildId
};
return (0, _apppage.exportAppPage)(req, res, page, path, pathname, query, fallbackRouteParams, renderOpts, htmlFilepath, debugOutput, isDynamicError, fileWriter, sharedContext);
} else {
const sharedContext = {
buildId,
deploymentId: commonRenderOpts.deploymentId,
customServer: undefined
};
const renderContext = {
isFallback: exportPath._pagesFallback ?? false,
isDraftMode: false,
developmentNotFoundSourcePage: undefined
};
return (0, _pages.exportPagesPage)(req, res, path, page, query, params, htmlFilepath, htmlFilename, pagesDataDir, buildExport, isDynamic, sharedContext, renderContext, hasOrigQueryValues, renderOpts, components, fileWriter);
}
}
async function exportPages(input) {
const { exportPaths, dir, distDir, outDir, cacheHandler, cacheMaxMemorySize, fetchCacheKeyPrefix, pagesDataDir, renderOpts, nextConfig, options, renderResumeDataCachesByPage = {} } = input;
(0, _globalbehaviors.installGlobalBehaviors)(nextConfig);
if (nextConfig.enablePrerenderSourceMaps) {
try {
// Same as `next dev`
// Limiting the stack trace to a useful amount of frames is handled by ignore-listing.
// TODO: How high can we go without severely impacting CPU/memory?
Error.stackTraceLimit = 50;
} catch {}
}
// If the fetch cache was enabled, we need to create an incremental
// cache instance for this page.
const incrementalCache = await (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.cacheHandlers
});
renderOpts.incrementalCache = incrementalCache;
const maxConcurrency = nextConfig.experimental.staticGenerationMaxConcurrency ?? 8;
const results = [];
const exportPageWithRetry = async (exportPath, maxAttempts)=>{
var // Also tests for `inspect-brk`
_process_env_NODE_OPTIONS;
const { page, path } = exportPath;
const pageKey = page !== path ? `${page}: ${path}` : path;
let attempt = 0;
let result;
const hasDebuggerAttached = (_process_env_NODE_OPTIONS = process.env.NODE_OPTIONS) == null ? void 0 : _process_env_NODE_OPTIONS.includes('--inspect');
const renderResumeDataCache = renderResumeDataCachesByPage[page] ? (0, _resumedatacache.createRenderResumeDataCache)(renderResumeDataCachesByPage[page]) : undefined;
while(attempt < maxAttempts){
try {
var _nextConfig_experimental_sri;
result = await Promise.race([
exportPage({
exportPath,
distDir,
outDir,
pagesDataDir,
renderOpts,
trailingSlash: nextConfig.trailingSlash,
subFolders: nextConfig.trailingSlash && !options.buildExport,
buildExport: options.buildExport,
optimizeCss: nextConfig.experimental.optimizeCss,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
parentSpanId: input.parentSpanId,
httpAgentOptions: nextConfig.httpAgentOptions,
debugOutput: options.debugOutput,
enableExperimentalReact: (0, _needsexperimentalreact.needsExperimentalReact)(nextConfig),
sriEnabled: Boolean((_nextConfig_experimental_sri = nextConfig.experimental.sri) == null ? void 0 : _nextConfig_experimental_sri.algorithm),
buildId: input.buildId,
renderResumeDataCache
}),
hasDebuggerAttached ? new Promise(()=>{}) : new Promise((_, reject)=>{
setTimeout(()=>{
reject(new TimeoutError());
}, nextConfig.staticPageGenerationTimeout * 1000);
})
]);
// If there was an error in the export, throw it immediately. In the catch block, we might retry the export,
// or immediately fail the build, depending on user configuration. We might also continue on and attempt other pages.
if (result && 'error' in result) {
throw new ExportPageError();
}
break;
} catch (err) {
// The only error that should be caught here is an ExportError, as `exportPage` doesn't throw and instead returns an object with an `error` property.
// This is an overly cautious check to ensure that we don't accidentally catch an unexpected error.
if (!(err instanceof ExportPageError || err instanceof TimeoutError)) {
throw err;
}
if (err instanceof TimeoutError) {
// If the export times out, we will restart the worker up to 3 times.
maxAttempts = 3;
}
// We've reached the maximum number of attempts
if (attempt >= maxAttempts - 1) {
// Log a message if we've reached the maximum number of attempts.
// We only care to do this if maxAttempts was configured.
if (maxAttempts > 1) {
console.info(`Failed to build ${pageKey} after ${maxAttempts} attempts.`);
}
// If prerenderEarlyExit is enabled, we'll exit the build immediately.
if (nextConfig.experimental.prerenderEarlyExit) {
console.error(`Export encountered an error on ${pageKey}, exiting the build.`);
process.exit(1);
} else {
// Otherwise, this is a no-op. The build will continue, and a summary of failed pages will be displayed at the end.
}
} else {
// Otherwise, we have more attempts to make. Wait before retrying
if (err instanceof TimeoutError) {
console.info(`Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}) because it took more than ${nextConfig.staticPageGenerationTimeout} seconds. Retrying again shortly.`);
} else {
console.info(`Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}). Retrying again shortly.`);
}
// Exponential backoff with random jitter to avoid thundering herd on retries
const baseDelay = 500 // 500ms
;
const maxDelay = 2000 // 2 seconds
;
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
const jitter = Math.random() * 0.3 * delay // Add up to 30% random jitter
;
await new Promise((r)=>setTimeout(r, delay + jitter));
}
}
attempt++;
}
return {
result,
path,
page,
pageKey
};
};
for(let i = 0; i < exportPaths.length; i += maxConcurrency){
const subset = exportPaths.slice(i, i + maxConcurrency);
const subsetResults = await Promise.all(subset.map((exportPath)=>exportPageWithRetry(exportPath, nextConfig.experimental.staticGenerationRetryCount ?? 1)));
results.push(...subsetResults);
}
return results;
}
async function exportPage(input) {
(0, _trace.trace)('export-page', input.parentSpanId).setAttribute('path', input.exportPath.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.exportPath.path}". Read more: https://nextjs.org/docs/messages/prerender-error`);
// bailoutToCSRError errors should not leak to the user as they are not actionable; they're
// a framework signal
if (!(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.
// TODO: Always log the full error. ignore-listing will take care of hiding internal stacks.
if ((0, _staticgenerationbailout.isStaticGenBailoutError)(err)) {
if (err.message) {
console.error(`Error: ${err.message}`);
}
} else {
console.error(err);
}
}
return {
error: true,
duration: Date.now() - start
};
}
// Notify the parent process that we processed a page (used by the progress activity indicator)
process.send == null ? void 0 : process.send.call(process, [
3,
{
type: 'activity'
}
]);
// Otherwise we can return the result.
return {
...result,
duration: Date.now() - start,
turborepoAccessTraceResult: turborepoAccessTraceResult.serialize()
};
}
process.on('unhandledRejection', (err)=>{
// if it's a postpone error, it'll be handled later
// when the postponed promise is actually awaited.
if ((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

File diff suppressed because one or more lines are too long