Initial boiler plate project

This commit is contained in:
2024-09-24 03:52:46 +00:00
parent 6120b2d6c3
commit 154b93e267
10034 changed files with 2079352 additions and 2 deletions

View File

@ -0,0 +1,43 @@
import path from "path";
import { IncrementalCache } from "../../server/lib/incremental-cache";
import { hasNextSupport } from "../../telemetry/ci-info";
import { nodeFs } from "../../server/lib/node-fs-methods";
import { interopDefault } from "../../lib/interop-default";
import { formatDynamicImportPath } from "../../lib/format-dynamic-import-path";
export async function createIncrementalCache({ cacheHandler, cacheMaxMemorySize, fetchCacheKeyPrefix, distDir, dir, enabledDirectories, experimental, flushToDisk }) {
// Custom cache handler overrides.
let CacheHandler;
if (cacheHandler) {
CacheHandler = interopDefault(await import(formatDynamicImportPath(dir, cacheHandler)).then((mod)=>mod.default || mod));
}
const incrementalCache = new IncrementalCache({
dev: false,
requestHeaders: {},
flushToDisk,
fetchCache: true,
maxMemoryCacheSize: cacheMaxMemorySize,
fetchCacheKeyPrefix,
getPrerenderManifest: ()=>({
version: 4,
routes: {},
dynamicRoutes: {},
preview: {
previewModeEncryptionKey: "",
previewModeId: "",
previewModeSigningKey: ""
},
notFoundRoutes: []
}),
fs: nodeFs,
pagesDir: enabledDirectories.pages,
appDir: enabledDirectories.app,
serverDistDir: path.join(distDir, "server"),
CurCacheHandler: CacheHandler,
minimalMode: hasNextSupport,
experimental
});
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"],"names":["path","IncrementalCache","hasNextSupport","nodeFs","interopDefault","formatDynamicImportPath","createIncrementalCache","cacheHandler","cacheMaxMemorySize","fetchCacheKeyPrefix","distDir","dir","enabledDirectories","experimental","flushToDisk","CacheHandler","then","mod","default","incrementalCache","dev","requestHeaders","fetchCache","maxMemoryCacheSize","getPrerenderManifest","version","routes","dynamicRoutes","preview","previewModeEncryptionKey","previewModeId","previewModeSigningKey","notFoundRoutes","fs","pagesDir","pages","appDir","app","serverDistDir","join","CurCacheHandler","minimalMode","globalThis","__incrementalCache"],"mappings":"AAEA,OAAOA,UAAU,OAAM;AACvB,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,cAAc,QAAQ,0BAAyB;AACxD,SAASC,MAAM,QAAQ,mCAAkC;AACzD,SAASC,cAAc,QAAQ,4BAA2B;AAC1D,SAASC,uBAAuB,QAAQ,uCAAsC;AAE9E,OAAO,eAAeC,uBAAuB,EAC3CC,YAAY,EACZC,kBAAkB,EAClBC,mBAAmB,EACnBC,OAAO,EACPC,GAAG,EACHC,kBAAkB,EAClBC,YAAY,EACZC,WAAW,EAUZ;IACC,kCAAkC;IAClC,IAAIC;IACJ,IAAIR,cAAc;QAChBQ,eAAeX,eACb,MAAM,MAAM,CAACC,wBAAwBM,KAAKJ,eAAeS,IAAI,CAC3D,CAACC,MAAQA,IAAIC,OAAO,IAAID;IAG9B;IAEA,MAAME,mBAAmB,IAAIlB,iBAAiB;QAC5CmB,KAAK;QACLC,gBAAgB,CAAC;QACjBP;QACAQ,YAAY;QACZC,oBAAoBf;QACpBC;QACAe,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,IAAI9B;QACJ+B,UAAUtB,mBAAmBuB,KAAK;QAClCC,QAAQxB,mBAAmByB,GAAG;QAC9BC,eAAetC,KAAKuC,IAAI,CAAC7B,SAAS;QAClC8B,iBAAiBzB;QACjB0B,aAAavC;QACbW;IACF;IAEE6B,WAAmBC,kBAAkB,GAAGxB;IAE1C,OAAOA;AACT"}

View File

@ -0,0 +1,27 @@
import { getRouteMatcher } from "../../shared/lib/router/utils/route-matcher";
import { getRouteRegex } from "../../shared/lib/router/utils/route-regex";
// The last page and matcher that this function handled.
let last = null;
/**
* Gets the params for the provided page.
* @param page the page that contains dynamic path parameters
* @param pathname the pathname to match
* @returns the matches that were found, throws otherwise
*/ export function getParams(page, pathname) {
// Because this is often called on the output of `getStaticPaths` or similar
// where the `page` here doesn't change, this will "remember" the last page
// it created the RegExp for. If it matches, it'll just re-use it.
let matcher;
if ((last == null ? void 0 : last.page) === page) {
matcher = last.matcher;
} else {
matcher = getRouteMatcher(getRouteRegex(page));
}
const params = matcher(pathname);
if (!params) {
throw new Error(`The provided export path '${pathname}' doesn't match the '${page}' page.\nRead more: https://nextjs.org/docs/messages/export-path-mismatch`);
}
return params;
}
//# sourceMappingURL=get-params.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/helpers/get-params.ts"],"names":["getRouteMatcher","getRouteRegex","last","getParams","page","pathname","matcher","params","Error"],"mappings":"AAAA,SAEEA,eAAe,QACV,8CAA6C;AACpD,SAASC,aAAa,QAAQ,4CAA2C;AAEzE,wDAAwD;AACxD,IAAIC,OAGO;AAEX;;;;;CAKC,GACD,OAAO,SAASC,UAAUC,IAAY,EAAEC,QAAgB;IACtD,4EAA4E;IAC5E,2EAA2E;IAC3E,kEAAkE;IAClE,IAAIC;IACJ,IAAIJ,CAAAA,wBAAAA,KAAME,IAAI,MAAKA,MAAM;QACvBE,UAAUJ,KAAKI,OAAO;IACxB,OAAO;QACLA,UAAUN,gBAAgBC,cAAcG;IAC1C;IAEA,MAAMG,SAASD,QAAQD;IACvB,IAAI,CAACE,QAAQ;QACX,MAAM,IAAIC,MACR,CAAC,0BAA0B,EAAEH,SAAS,qBAAqB,EAAED,KAAK,yEAAyE,CAAC;IAEhJ;IAEA,OAAOG;AACT"}

View File

@ -0,0 +1,6 @@
import { isDynamicServerError } from "../../client/components/hooks-server-context";
import { isBailoutToCSRError } from "../../shared/lib/lazy-dynamic/bailout-to-csr";
import { isNavigationSignalError } from "./is-navigation-signal-error";
export const isDynamicUsageError = (err)=>isDynamicServerError(err) || isBailoutToCSRError(err) || isNavigationSignalError(err);
//# sourceMappingURL=is-dynamic-usage-error.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/helpers/is-dynamic-usage-error.ts"],"names":["isDynamicServerError","isBailoutToCSRError","isNavigationSignalError","isDynamicUsageError","err"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,+CAA8C;AACnF,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,uBAAuB,QAAQ,+BAA8B;AAEtE,OAAO,MAAMC,sBAAsB,CAACC,MAClCJ,qBAAqBI,QACrBH,oBAAoBG,QACpBF,wBAAwBE,KAAI"}

View File

@ -0,0 +1,9 @@
import { isNotFoundError } from "../../client/components/not-found";
import { isRedirectError } from "../../client/components/redirect";
/**
* Returns true if the error is a navigation signal error. These errors are
* thrown by user code to perform navigation operations and interrupt the React
* render.
*/ export const isNavigationSignalError = (err)=>isNotFoundError(err) || isRedirectError(err);
//# sourceMappingURL=is-navigation-signal-error.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/helpers/is-navigation-signal-error.ts"],"names":["isNotFoundError","isRedirectError","isNavigationSignalError","err"],"mappings":"AAAA,SAASA,eAAe,QAAQ,oCAAmC;AACnE,SAASC,eAAe,QAAQ,mCAAkC;AAElE;;;;CAIC,GACD,OAAO,MAAMC,0BAA0B,CAACC,MACtCH,gBAAgBG,QAAQF,gBAAgBE,KAAI"}

555
node_modules/next/dist/esm/export/index.js generated vendored Normal file
View File

@ -0,0 +1,555 @@
import { bold, yellow } from "../lib/picocolors";
import findUp from "next/dist/compiled/find-up";
import { existsSync, promises as fs } from "fs";
import "../server/require-hook";
import { Worker } from "../lib/worker";
import { dirname, join, resolve, sep } from "path";
import { formatAmpMessages } from "../build/output/index";
import * as Log from "../build/output/log";
import { RSC_SUFFIX, SSG_FALLBACK_EXPORT_ERROR } from "../lib/constants";
import { recursiveCopy } from "../lib/recursive-copy";
import { BUILD_ID_FILE, CLIENT_PUBLIC_FILES_PATH, CLIENT_STATIC_FILES_PATH, EXPORT_DETAIL, EXPORT_MARKER, NEXT_FONT_MANIFEST, MIDDLEWARE_MANIFEST, PAGES_MANIFEST, PHASE_EXPORT, PRERENDER_MANIFEST, SERVER_DIRECTORY, SERVER_REFERENCE_MANIFEST, APP_PATH_ROUTES_MANIFEST } from "../shared/lib/constants";
import loadConfig from "../server/config";
import { eventCliSession } from "../telemetry/events";
import { hasNextSupport } from "../telemetry/ci-info";
import { Telemetry } from "../telemetry/storage";
import { normalizePagePath } from "../shared/lib/page-path/normalize-page-path";
import { denormalizePagePath } from "../shared/lib/page-path/denormalize-page-path";
import { loadEnvConfig } from "@next/env";
import { isAPIRoute } from "../lib/is-api-route";
import { getPagePath } from "../server/require";
import { isAppRouteRoute } from "../lib/is-app-route-route";
import { isAppPageRoute } from "../lib/is-app-page-route";
import isError from "../lib/is-error";
import { needsExperimentalReact } from "../lib/needs-experimental-react";
import { formatManifest } from "../build/manifests/formatter/format-manifest";
import { validateRevalidate } from "../server/lib/patch-fetch";
import { TurborepoAccessTraceResult } from "../build/turborepo-access-trace";
import { createProgress } from "../build/progress";
export class ExportError extends Error {
constructor(...args){
super(...args);
this.code = "NEXT_EXPORT_ERROR";
}
}
function setupWorkers(options, nextConfig) {
if (options.exportPageWorker) {
return {
pages: options.exportPageWorker,
app: options.exportAppPageWorker,
end: options.endWorker || (()=>Promise.resolve())
};
}
const threads = options.threads || nextConfig.experimental.cpus;
if (!options.silent && !options.buildExport) {
Log.info(`Launching ${threads} workers`);
}
const timeout = (nextConfig == null ? void 0 : nextConfig.staticPageGenerationTimeout) || 0;
let infoPrinted = false;
const worker = new Worker(require.resolve("./worker"), {
timeout: timeout * 1000,
onRestart: (_method, [{ path }], attempts)=>{
if (attempts >= 3) {
throw new ExportError(`Static page generation for ${path} is still timing out after 3 attempts. See more info here https://nextjs.org/docs/messages/static-page-generation-timeout`);
}
Log.warn(`Restarted static page generation for ${path} because it took more than ${timeout} seconds`);
if (!infoPrinted) {
Log.warn("See more info here https://nextjs.org/docs/messages/static-page-generation-timeout");
infoPrinted = true;
}
},
maxRetries: 0,
numWorkers: threads,
enableWorkerThreads: nextConfig.experimental.workerThreads,
exposedMethods: [
"default"
]
});
return {
pages: worker.default,
end: async ()=>{
await worker.end();
}
};
}
export async function exportAppImpl(dir, options, span) {
var _nextConfig_amp, _nextConfig_experimental_amp, _nextConfig_experimental_amp1;
dir = resolve(dir);
// attempt to load global env values so they are available in next.config.js
span.traceChild("load-dotenv").traceFn(()=>loadEnvConfig(dir, false, Log));
const { enabledDirectories } = options;
const nextConfig = options.nextConfig || await span.traceChild("load-next-config").traceAsyncFn(()=>loadConfig(PHASE_EXPORT, dir));
const distDir = join(dir, nextConfig.distDir);
const telemetry = options.buildExport ? null : new Telemetry({
distDir
});
if (telemetry) {
telemetry.record(eventCliSession(distDir, nextConfig, {
webpackVersion: null,
cliCommand: "export",
isSrcDir: null,
hasNowJson: !!await findUp("now.json", {
cwd: dir
}),
isCustomServer: null,
turboFlag: false,
pagesDir: null,
appDir: null
}));
}
const subFolders = nextConfig.trailingSlash && !options.buildExport;
if (!options.silent && !options.buildExport) {
Log.info(`using build directory: ${distDir}`);
}
const buildIdFile = join(distDir, BUILD_ID_FILE);
if (!existsSync(buildIdFile)) {
throw 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`);
}
const customRoutes = [
"rewrites",
"redirects",
"headers"
].filter((config)=>typeof nextConfig[config] === "function");
if (!hasNextSupport && !options.buildExport && customRoutes.length > 0) {
Log.warn(`rewrites, redirects, and headers are not applied when exporting your application, detected (${customRoutes.join(", ")}). See more info here: https://nextjs.org/docs/messages/export-no-custom-routes`);
}
const buildId = await fs.readFile(buildIdFile, "utf8");
const pagesManifest = !options.pages && require(join(distDir, SERVER_DIRECTORY, PAGES_MANIFEST));
let prerenderManifest;
try {
prerenderManifest = require(join(distDir, PRERENDER_MANIFEST));
} catch {}
let appRoutePathManifest;
try {
appRoutePathManifest = require(join(distDir, APP_PATH_ROUTES_MANIFEST));
} catch (err) {
if (isError(err) && (err.code === "ENOENT" || err.code === "MODULE_NOT_FOUND")) {
// the manifest doesn't exist which will happen when using
// "pages" dir instead of "app" dir.
appRoutePathManifest = undefined;
} else {
// the manifest is malformed (invalid json)
throw err;
}
}
const excludedPrerenderRoutes = new Set();
const pages = options.pages || Object.keys(pagesManifest);
const defaultPathMap = {};
let hasApiRoutes = false;
for (const page of pages){
// _document and _app are not real pages
// _error is exported as 404.html later on
// API Routes are Node.js functions
if (isAPIRoute(page)) {
hasApiRoutes = true;
continue;
}
if (page === "/_document" || page === "/_app" || page === "/_error") {
continue;
}
// iSSG pages that are dynamic should not export templated version by
// default. In most cases, this would never work. There is no server that
// could run `getStaticProps`. If users make their page work lazily, they
// can manually add it to the `exportPathMap`.
if (prerenderManifest == null ? void 0 : prerenderManifest.dynamicRoutes[page]) {
excludedPrerenderRoutes.add(page);
continue;
}
defaultPathMap[page] = {
page
};
}
const mapAppRouteToPage = new Map();
if (!options.buildExport && appRoutePathManifest) {
for (const [pageName, routePath] of Object.entries(appRoutePathManifest)){
mapAppRouteToPage.set(routePath, pageName);
if (isAppPageRoute(pageName) && !(prerenderManifest == null ? void 0 : prerenderManifest.routes[routePath]) && !(prerenderManifest == null ? void 0 : prerenderManifest.dynamicRoutes[routePath])) {
defaultPathMap[routePath] = {
page: pageName,
_isAppDir: true
};
}
}
}
// Initialize the output directory
const outDir = options.outdir;
if (outDir === join(dir, "public")) {
throw 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`);
}
if (outDir === join(dir, "static")) {
throw 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`);
}
await fs.rm(outDir, {
recursive: true,
force: true
});
await fs.mkdir(join(outDir, "_next", buildId), {
recursive: true
});
await fs.writeFile(join(distDir, EXPORT_DETAIL), formatManifest({
version: 1,
outDirectory: outDir,
success: false
}), "utf8");
// Copy static directory
if (!options.buildExport && existsSync(join(dir, "static"))) {
if (!options.silent) {
Log.info('Copying "static" directory');
}
await span.traceChild("copy-static-directory").traceAsyncFn(()=>recursiveCopy(join(dir, "static"), join(outDir, "static")));
}
// Copy .next/static directory
if (!options.buildExport && existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))) {
if (!options.silent) {
Log.info('Copying "static build" directory');
}
await span.traceChild("copy-next-static-directory").traceAsyncFn(()=>recursiveCopy(join(distDir, CLIENT_STATIC_FILES_PATH), join(outDir, "_next", CLIENT_STATIC_FILES_PATH)));
}
// Get the exportPathMap from the config file
if (typeof nextConfig.exportPathMap !== "function") {
nextConfig.exportPathMap = async (defaultMap)=>{
return defaultMap;
};
}
const { i18n, images: { loader = "default", unoptimized } } = nextConfig;
if (i18n && !options.buildExport) {
throw 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`);
}
if (!options.buildExport) {
const { isNextImageImported } = await span.traceChild("is-next-image-imported").traceAsyncFn(()=>fs.readFile(join(distDir, EXPORT_MARKER), "utf8").then((text)=>JSON.parse(text)).catch(()=>({})));
if (isNextImageImported && loader === "default" && !unoptimized && !hasNextSupport) {
throw 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`);
}
}
let serverActionsManifest;
if (enabledDirectories.app) {
serverActionsManifest = require(join(distDir, SERVER_DIRECTORY, SERVER_REFERENCE_MANIFEST + ".json"));
if (nextConfig.output === "export") {
if (Object.keys(serverActionsManifest.node).length > 0 || Object.keys(serverActionsManifest.edge).length > 0) {
throw new ExportError(`Server Actions are not supported with static export.`);
}
}
}
// Start the rendering process
const renderOpts = {
previewProps: prerenderManifest == null ? void 0 : prerenderManifest.preview,
buildId,
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,
optimizeFonts: nextConfig.optimizeFonts,
largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverActions: nextConfig.experimental.serverActions,
serverComponents: enabledDirectories.app,
nextFontManifest: require(join(distDir, "server", `${NEXT_FONT_MANIFEST}.json`)),
images: nextConfig.images,
...enabledDirectories.app ? {
serverActionsManifest
} : {},
strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.deploymentId,
experimental: {
ppr: nextConfig.experimental.ppr === true,
missingSuspenseWithCSRBailout: nextConfig.experimental.missingSuspenseWithCSRBailout === true,
swrDelta: nextConfig.experimental.swrDelta
}
};
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig;
if (Object.keys(publicRuntimeConfig).length > 0) {
renderOpts.runtimeConfig = publicRuntimeConfig;
}
globalThis.__NEXT_DATA__ = {
nextExport: true
};
const exportPathMap = await span.traceChild("run-export-path-map").traceAsyncFn(async ()=>{
const exportMap = await nextConfig.exportPathMap(defaultPathMap, {
dev: false,
dir,
outDir,
distDir,
buildId
});
return exportMap;
});
// only add missing 404 page when `buildExport` is false
if (!options.buildExport) {
// only add missing /404 if not specified in `exportPathMap`
if (!exportPathMap["/404"]) {
exportPathMap["/404"] = {
page: "/_error"
};
}
/**
* exports 404.html for backwards compat
* E.g. GitHub Pages, GitLab Pages, Cloudflare Pages, Netlify
*/ if (!exportPathMap["/404.html"]) {
// alias /404.html to /404 to be compatible with custom 404 / _error page
exportPathMap["/404.html"] = exportPathMap["/404"];
}
}
// make sure to prevent duplicates
const exportPaths = [
...new Set(Object.keys(exportPathMap).map((path)=>denormalizePagePath(normalizePagePath(path))))
];
const filteredPaths = exportPaths.filter((route)=>exportPathMap[route]._isAppDir || // Remove API routes
!isAPIRoute(exportPathMap[route].page));
if (filteredPaths.length !== exportPaths.length) {
hasApiRoutes = true;
}
if (filteredPaths.length === 0) {
return null;
}
if (prerenderManifest && !options.buildExport) {
const fallbackEnabledPages = new Set();
for (const path of Object.keys(exportPathMap)){
const page = exportPathMap[path].page;
const prerenderInfo = prerenderManifest.dynamicRoutes[page];
if (prerenderInfo && prerenderInfo.fallback !== false) {
fallbackEnabledPages.add(page);
}
}
if (fallbackEnabledPages.size > 0) {
throw new ExportError(`Found pages with \`fallback\` enabled:\n${[
...fallbackEnabledPages
].join("\n")}\n${SSG_FALLBACK_EXPORT_ERROR}\n`);
}
}
let hasMiddleware = false;
if (!options.buildExport) {
try {
const middlewareManifest = require(join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST));
hasMiddleware = Object.keys(middlewareManifest.middleware).length > 0;
} catch {}
// Warn if the user defines a path for an API page
if (hasApiRoutes || hasMiddleware) {
if (nextConfig.output === "export") {
Log.warn(yellow(`Statically exporting a Next.js application via \`next export\` disables API routes and middleware.`) + `\n` + yellow(`This command is meant for static-only hosts, and is` + " " + bold(`not necessary to make your application static.`)) + `\n` + yellow(`Pages in your application without server-side data dependencies will be automatically statically exported by \`next build\`, including pages powered by \`getStaticProps\`.`) + `\n` + yellow(`Learn more: https://nextjs.org/docs/messages/api-routes-static-export`));
}
}
}
const progress = !options.silent && createProgress(filteredPaths.length, options.statusMessage || "Exporting");
const pagesDataDir = options.buildExport ? outDir : join(outDir, "_next/data", buildId);
const ampValidations = {};
const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH);
// Copy public directory
if (!options.buildExport && existsSync(publicDir)) {
if (!options.silent) {
Log.info('Copying "public" directory');
}
await span.traceChild("copy-public-directory").traceAsyncFn(()=>recursiveCopy(publicDir, outDir, {
filter (path) {
// Exclude paths used by pages
return !exportPathMap[path];
}
}));
}
const workers = setupWorkers(options, nextConfig);
const results = await Promise.all(filteredPaths.map(async (path)=>{
const pathMap = exportPathMap[path];
const exportPage = workers[pathMap._isAppDir ? "app" : "pages"];
if (!exportPage) {
throw new Error("Invariant: Undefined export worker for app dir, this is a bug in Next.js.");
}
const pageExportSpan = span.traceChild("export-page");
pageExportSpan.setAttribute("path", path);
const result = await pageExportSpan.traceAsyncFn(async ()=>{
var _nextConfig_experimental_amp;
return await exportPage({
dir,
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,
subFolders,
buildExport: options.buildExport,
optimizeFonts: nextConfig.optimizeFonts,
optimizeCss: nextConfig.experimental.optimizeCss,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
parentSpanId: pageExportSpan.getId(),
httpAgentOptions: nextConfig.httpAgentOptions,
debugOutput: options.debugOutput,
cacheMaxMemorySize: nextConfig.cacheMaxMemorySize,
fetchCache: true,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
cacheHandler: nextConfig.cacheHandler,
enableExperimentalReact: needsExperimentalReact(nextConfig),
enabledDirectories
});
});
if (nextConfig.experimental.prerenderEarlyExit) {
if (result && "error" in result) {
throw new Error(`Export encountered an error on ${path}, exiting due to prerenderEarlyExit: true being set`);
}
}
if (progress) progress();
return {
result,
path
};
}));
const errorPaths = [];
let renderError = false;
let hadValidationError = false;
const collector = {
byPath: new Map(),
byPage: new Map(),
ssgNotFoundPaths: new Set(),
turborepoAccessTraceResults: new Map()
};
for (const { result, path } of results){
if (!result) continue;
const { page } = exportPathMap[path];
if (result.turborepoAccessTraceResult) {
var _collector_turborepoAccessTraceResults;
(_collector_turborepoAccessTraceResults = collector.turborepoAccessTraceResults) == null ? void 0 : _collector_turborepoAccessTraceResults.set(path, TurborepoAccessTraceResult.fromSerialized(result.turborepoAccessTraceResult));
}
// Capture any render errors.
if ("error" in result) {
renderError = true;
errorPaths.push(page !== path ? `${page}: ${path}` : path);
continue;
}
// 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 (typeof result.revalidate !== "undefined") {
info.revalidate = validateRevalidate(result.revalidate, path);
}
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;
}
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);
}
}
const endWorkerPromise = workers.end();
// Export mode provide static outputs that are not compatible with PPR mode.
if (!options.buildExport && nextConfig.experimental.ppr) {
// TODO: add message
throw new Error("Invariant: PPR cannot be enabled in export mode");
}
// copy prerendered routes to outDir
if (!options.buildExport && prerenderManifest) {
await Promise.all(Object.keys(prerenderManifest.routes).map(async (route)=>{
const { srcRoute } = prerenderManifest.routes[route];
const appPageName = mapAppRouteToPage.get(srcRoute || "");
const pageName = appPageName || srcRoute || route;
const isAppPath = Boolean(appPageName);
const isAppRouteHandler = appPageName && isAppRouteRoute(appPageName);
// returning notFound: true from getStaticProps will not
// output html/json files during the build
if (prerenderManifest.notFoundRoutes.includes(route)) {
return;
}
route = normalizePagePath(route);
const pagePath = getPagePath(pageName, distDir, undefined, isAppPath);
const distPagesDir = join(pagePath, // strip leading / and then recurse number of nested dirs
// to place from base folder
pageName.slice(1).split("/").map(()=>"..").join("/"));
const orig = join(distPagesDir, route);
const handlerSrc = `${orig}.body`;
const handlerDest = join(outDir, route);
if (isAppRouteHandler && existsSync(handlerSrc)) {
await fs.mkdir(dirname(handlerDest), {
recursive: true
});
await fs.copyFile(handlerSrc, handlerDest);
return;
}
const htmlDest = join(outDir, `${route}${subFolders && route !== "/index" ? `${sep}index` : ""}.html`);
const ampHtmlDest = join(outDir, `${route}.amp${subFolders ? `${sep}index` : ""}.html`);
const jsonDest = isAppPath ? join(outDir, `${route}${subFolders && route !== "/index" ? `${sep}index` : ""}.txt`) : join(pagesDataDir, `${route}.json`);
await fs.mkdir(dirname(htmlDest), {
recursive: true
});
await fs.mkdir(dirname(jsonDest), {
recursive: true
});
const htmlSrc = `${orig}.html`;
const jsonSrc = `${orig}${isAppPath ? RSC_SUFFIX : ".json"}`;
await fs.copyFile(htmlSrc, htmlDest);
await fs.copyFile(jsonSrc, jsonDest);
if (existsSync(`${orig}.amp.html`)) {
await fs.mkdir(dirname(ampHtmlDest), {
recursive: true
});
await fs.copyFile(`${orig}.amp.html`, ampHtmlDest);
}
}));
}
if (Object.keys(ampValidations).length) {
console.log(formatAmpMessages(ampValidations));
}
if (hadValidationError) {
throw new ExportError(`AMP Validation caused the export to fail. https://nextjs.org/docs/messages/amp-export-validation`);
}
if (renderError) {
throw new ExportError(`Export encountered errors on following paths:\n\t${errorPaths.sort().join("\n ")}`);
}
await fs.writeFile(join(distDir, EXPORT_DETAIL), formatManifest({
version: 1,
outDirectory: outDir,
success: true
}), "utf8");
if (telemetry) {
await telemetry.flush();
}
await endWorkerPromise;
return collector;
}
export default async function exportApp(dir, options, span) {
const nextExportSpan = span.traceChild("next-export");
return nextExportSpan.traceAsyncFn(async ()=>{
return await exportAppImpl(dir, options, nextExportSpan);
});
}
//# sourceMappingURL=index.js.map

1
node_modules/next/dist/esm/export/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

126
node_modules/next/dist/esm/export/routes/app-page.js generated vendored Normal file
View File

@ -0,0 +1,126 @@
import { isDynamicUsageError } from "../helpers/is-dynamic-usage-error";
import { NEXT_CACHE_TAGS_HEADER, NEXT_META_SUFFIX, RSC_PREFETCH_SUFFIX, RSC_SUFFIX } from "../../lib/constants";
import { hasNextSupport } from "../../telemetry/ci-info";
import { lazyRenderAppPage } from "../../server/future/route-modules/app-page/module.render";
import { isBailoutToCSRError } from "../../shared/lib/lazy-dynamic/bailout-to-csr";
export var ExportedAppPageFiles;
(function(ExportedAppPageFiles) {
ExportedAppPageFiles["HTML"] = "HTML";
ExportedAppPageFiles["FLIGHT"] = "FLIGHT";
ExportedAppPageFiles["PREFETCH_FLIGHT"] = "PREFETCH_FLIGHT";
ExportedAppPageFiles["META"] = "META";
ExportedAppPageFiles["POSTPONED"] = "POSTPONED";
})(ExportedAppPageFiles || (ExportedAppPageFiles = {}));
export async function exportAppPage(req, res, page, path, pathname, query, renderOpts, htmlFilepath, debugOutput, isDynamicError, fileWriter) {
let isDefaultNotFound = false;
// If the page is `/_not-found`, then we should update the page to be `/404`.
// UNDERSCORE_NOT_FOUND_ROUTE value used here, however we don't want to import it here as it causes constants to be inlined which we don't want here.
if (page === "/_not-found/page") {
isDefaultNotFound = true;
pathname = "/404";
}
try {
const result = await lazyRenderAppPage(req, res, pathname, query, renderOpts);
const html = result.toUnchunkedString();
const { metadata } = result;
const { flightData, revalidate = false, postponed, fetchTags } = metadata;
// Ensure we don't postpone without having PPR enabled.
if (postponed && !renderOpts.experimental.ppr) {
throw new Error("Invariant: page postponed without PPR being enabled");
}
if (revalidate === 0) {
if (isDynamicError) {
throw new Error(`Page with dynamic = "error" encountered dynamic data method on ${path}.`);
}
const { staticBailoutInfo = {} } = metadata;
if (revalidate === 0 && debugOutput && (staticBailoutInfo == null ? void 0 : staticBailoutInfo.description)) {
logDynamicUsageWarning({
path,
description: staticBailoutInfo.description,
stack: staticBailoutInfo.stack
});
}
return {
revalidate: 0
};
} else if (!flightData) {
throw new Error(`Invariant: failed to get page data for ${path}`);
} else if (renderOpts.experimental.ppr) {
// If PPR is enabled, we should emit the flight data as the prefetch
// payload.
await fileWriter("PREFETCH_FLIGHT", htmlFilepath.replace(/\.html$/, RSC_PREFETCH_SUFFIX), flightData);
} else {
// Writing the RSC payload to a file if we don't have PPR enabled.
await fileWriter("FLIGHT", htmlFilepath.replace(/\.html$/, RSC_SUFFIX), flightData);
}
const headers = {
...metadata.headers
};
// When PPR is enabled, we should grab the headers from the mocked response
// and add it to the headers.
if (renderOpts.experimental.ppr) {
Object.assign(headers, res.getHeaders());
}
if (fetchTags) {
headers[NEXT_CACHE_TAGS_HEADER] = fetchTags;
}
// Writing static HTML to a file.
await fileWriter("HTML", htmlFilepath, html ?? "", "utf8");
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.ppr ? 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
};
await fileWriter("META", htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX), JSON.stringify(meta, null, 2));
return {
// Only include the metadata if the environment has next support.
metadata: hasNextSupport ? meta : undefined,
hasEmptyPrelude: Boolean(postponed) && html === "",
hasPostponed: Boolean(postponed),
revalidate
};
} catch (err) {
if (!isDynamicUsageError(err)) {
throw err;
}
// If enabled, we should fail rendering if a client side rendering bailout
// occurred at the page level.
if (renderOpts.experimental.missingSuspenseWithCSRBailout && isBailoutToCSRError(err)) {
throw err;
}
if (debugOutput) {
const { dynamicUsageDescription, dynamicUsageStack } = renderOpts.store;
logDynamicUsageWarning({
path,
description: dynamicUsageDescription,
stack: dynamicUsageStack
});
}
return {
revalidate: 0
};
}
}
function logDynamicUsageWarning({ path, description, stack }) {
const errMessage = new Error(`Static generation failed due to dynamic usage on ${path}, reason: ${description}`);
if (stack) {
errMessage.stack = errMessage.message + stack.substring(stack.indexOf("\n"));
}
console.warn(errMessage);
}
//# sourceMappingURL=app-page.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/routes/app-page.ts"],"names":["isDynamicUsageError","NEXT_CACHE_TAGS_HEADER","NEXT_META_SUFFIX","RSC_PREFETCH_SUFFIX","RSC_SUFFIX","hasNextSupport","lazyRenderAppPage","isBailoutToCSRError","ExportedAppPageFiles","exportAppPage","req","res","page","path","pathname","query","renderOpts","htmlFilepath","debugOutput","isDynamicError","fileWriter","isDefaultNotFound","result","html","toUnchunkedString","metadata","flightData","revalidate","postponed","fetchTags","experimental","ppr","Error","staticBailoutInfo","description","logDynamicUsageWarning","stack","replace","headers","Object","assign","getHeaders","isParallelRoute","test","isNonSuccessfulStatusCode","statusCode","status","undefined","meta","JSON","stringify","hasEmptyPrelude","Boolean","hasPostponed","err","missingSuspenseWithCSRBailout","dynamicUsageDescription","dynamicUsageStack","store","errMessage","message","substring","indexOf","console","warn"],"mappings":"AAUA,SAASA,mBAAmB,QAAQ,oCAAmC;AACvE,SACEC,sBAAsB,EACtBC,gBAAgB,EAChBC,mBAAmB,EACnBC,UAAU,QACL,sBAAqB;AAC5B,SAASC,cAAc,QAAQ,0BAAyB;AACxD,SAASC,iBAAiB,QAAQ,2DAA0D;AAC5F,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AY,CAACyB,6BAA6B,IACrDhD,oBAAoB+C,MACpB;YACA,MAAMA;QACR;QAEA,IAAIpC,aAAa;YACf,MAAM,EAAEsC,uBAAuB,EAAEC,iBAAiB,EAAE,GAAG,AAACzC,WACrD0C,KAAK;YAERvB,uBAAuB;gBACrBtB;gBACAqB,aAAasB;gBACbpB,OAAOqB;YACT;QACF;QAEA,OAAO;YAAE9B,YAAY;QAAE;IACzB;AACF;AAEA,SAASQ,uBAAuB,EAC9BtB,IAAI,EACJqB,WAAW,EACXE,KAAK,EAKN;IACC,MAAMuB,aAAa,IAAI3B,MACrB,CAAC,iDAAiD,EAAEnB,KAAK,UAAU,EAAEqB,YAAY,CAAC;IAGpF,IAAIE,OAAO;QACTuB,WAAWvB,KAAK,GAAGuB,WAAWC,OAAO,GAAGxB,MAAMyB,SAAS,CAACzB,MAAM0B,OAAO,CAAC;IACxE;IAEAC,QAAQC,IAAI,CAACL;AACf"}

95
node_modules/next/dist/esm/export/routes/app-route.js generated vendored Normal file
View File

@ -0,0 +1,95 @@
import { join } from "path";
import { NEXT_BODY_SUFFIX, NEXT_CACHE_TAGS_HEADER, NEXT_META_SUFFIX } from "../../lib/constants";
import { NodeNextRequest } from "../../server/base-http/node";
import { RouteModuleLoader } from "../../server/future/helpers/module-loader/route-module-loader";
import { NextRequestAdapter, signalFromNodeResponse } from "../../server/web/spec-extension/adapters/next-request";
import { toNodeOutgoingHttpHeaders } from "../../server/web/utils";
import { isDynamicUsageError } from "../helpers/is-dynamic-usage-error";
import { SERVER_DIRECTORY } from "../../shared/lib/constants";
import { hasNextSupport } from "../../telemetry/ci-info";
export var ExportedAppRouteFiles;
(function(ExportedAppRouteFiles) {
ExportedAppRouteFiles["BODY"] = "BODY";
ExportedAppRouteFiles["META"] = "META";
})(ExportedAppRouteFiles || (ExportedAppRouteFiles = {}));
export async function exportAppRoute(req, res, params, page, incrementalCache, distDir, htmlFilepath, fileWriter) {
// Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}`;
// Adapt the request and response to the Next.js request and response.
const request = NextRequestAdapter.fromNodeNextRequest(new NodeNextRequest(req), signalFromNodeResponse(res));
// 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: {
ppr: false
},
originalPathname: page,
nextExport: true,
supportsDynamicResponse: false,
incrementalCache
}
};
if (hasNextSupport) {
context.renderOpts.isRevalidate = true;
}
// This is a route handler, which means it has it's handler in the
// bundled file already, we should just use that.
const filename = join(distDir, SERVER_DIRECTORY, "app", page);
try {
var _context_renderOpts_store;
// Route module loading and handling.
const module = await RouteModuleLoader.load(filename);
const response = await module.handle(request, context);
const isValidStatus = response.status < 400 || response.status === 404;
if (!isValidStatus) {
return {
revalidate: 0
};
}
const blob = await response.blob();
const revalidate = typeof ((_context_renderOpts_store = context.renderOpts.store) == null ? void 0 : _context_renderOpts_store.revalidate) === "undefined" ? false : context.renderOpts.store.revalidate;
const headers = toNodeOutgoingHttpHeaders(response.headers);
const cacheTags = context.renderOpts.fetchTags;
if (cacheTags) {
headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;
}
if (!headers["content-type"] && blob.type) {
headers["content-type"] = blob.type;
}
// Writing response body to a file.
const body = Buffer.from(await blob.arrayBuffer());
await fileWriter("BODY", htmlFilepath.replace(/\.html$/, NEXT_BODY_SUFFIX), body, "utf8");
// Write the request metadata to a file.
const meta = {
status: response.status,
headers
};
await fileWriter("META", htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX), JSON.stringify(meta));
return {
revalidate: revalidate,
metadata: meta
};
} catch (err) {
if (!isDynamicUsageError(err)) {
throw err;
}
return {
revalidate: 0
};
}
}
//# sourceMappingURL=app-route.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/routes/app-route.ts"],"names":["join","NEXT_BODY_SUFFIX","NEXT_CACHE_TAGS_HEADER","NEXT_META_SUFFIX","NodeNextRequest","RouteModuleLoader","NextRequestAdapter","signalFromNodeResponse","toNodeOutgoingHttpHeaders","isDynamicUsageError","SERVER_DIRECTORY","hasNextSupport","ExportedAppRouteFiles","exportAppRoute","req","res","params","page","incrementalCache","distDir","htmlFilepath","fileWriter","url","request","fromNodeNextRequest","context","prerenderManifest","version","routes","dynamicRoutes","preview","previewModeEncryptionKey","previewModeId","previewModeSigningKey","notFoundRoutes","renderOpts","experimental","ppr","originalPathname","nextExport","supportsDynamicResponse","isRevalidate","filename","module","load","response","handle","isValidStatus","status","revalidate","blob","store","headers","cacheTags","fetchTags","type","body","Buffer","from","arrayBuffer","replace","meta","JSON","stringify","metadata","err"],"mappings":"AAKA,SAASA,IAAI,QAAQ,OAAM;AAC3B,SACEC,gBAAgB,EAChBC,sBAAsB,EACtBC,gBAAgB,QACX,sBAAqB;AAC5B,SAASC,eAAe,QAAQ,8BAA6B;AAC7D,SAASC,iBAAiB,QAAQ,gEAA+D;AACjG,SACEC,kBAAkB,EAClBC,sBAAsB,QACjB,wDAAuD;AAC9D,SAASC,yBAAyB,QAAQ,yBAAwB;AAKlE,SAASC,mBAAmB,QAAQ,oCAAmC;AACvE,SAASC,gBAAgB,QAAQ,6BAA4B;AAC7D,SAASC,cAAc,QAAQ,0BAAyB;;UAEtCC;;;GAAAA,0BAAAA;AAKlB,OAAO,eAAeC,eACpBC,GAAkB,EAClBC,GAAmB,EACnBC,MAAwD,EACxDC,IAAY,EACZC,gBAA8C,EAC9CC,OAAe,EACfC,YAAoB,EACpBC,UAAsB;IAEtB,mCAAmC;IACnCP,IAAIQ,GAAG,GAAG,CAAC,qBAAqB,EAAER,IAAIQ,GAAG,CAAC,CAAC;IAE3C,sEAAsE;IACtE,MAAMC,UAAUjB,mBAAmBkB,mBAAmB,CACpD,IAAIpB,gBAAgBU,MACpBP,uBAAuBQ;IAGzB,oEAAoE;IACpE,6CAA6C;IAC7C,MAAMU,UAAu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AAW;QAC/C,MAAMtC,mBAEJD,aAAawC,OAAO,CAAC,WAAW3D,mBAChCuD,MACA;QAGF,wCAAwC;QACxC,MAAMK,OAAO;YAAEb,QAAQH,SAASG,MAAM;YAAEI;QAAQ;QAChD,MAAM/B,mBAEJD,aAAawC,OAAO,CAAC,WAAWzD,mBAChC2D,KAAKC,SAAS,CAACF;QAGjB,OAAO;YACLZ,YAAYA;YACZe,UAAUH;QACZ;IACF,EAAE,OAAOI,KAAK;QACZ,IAAI,CAACxD,oBAAoBwD,MAAM;YAC7B,MAAMA;QACR;QAEA,OAAO;YAAEhB,YAAY;QAAE;IACzB;AACF"}

124
node_modules/next/dist/esm/export/routes/pages.js generated vendored Normal file
View File

@ -0,0 +1,124 @@
import RenderResult from "../../server/render-result";
import { join } from "path";
import { isInAmpMode } from "../../shared/lib/amp-mode";
import { NEXT_DATA_SUFFIX, SERVER_PROPS_EXPORT_ERROR } from "../../lib/constants";
import { isBailoutToCSRError } from "../../shared/lib/lazy-dynamic/bailout-to-csr";
import AmpHtmlValidator from "next/dist/compiled/amphtml-validator";
import { FileType, fileExists } from "../../lib/file-exists";
import { lazyRenderPagesPage } from "../../server/future/route-modules/pages/module.render";
export var ExportedPagesFiles;
(function(ExportedPagesFiles) {
ExportedPagesFiles["HTML"] = "HTML";
ExportedPagesFiles["DATA"] = "DATA";
ExportedPagesFiles["AMP_HTML"] = "AMP_HTML";
ExportedPagesFiles["AMP_DATA"] = "AMP_PAGE_DATA";
})(ExportedPagesFiles || (ExportedPagesFiles = {}));
export async function exportPages(req, res, path, page, query, htmlFilepath, htmlFilename, ampPath, subFolders, outDir, ampValidatorPath, pagesDataDir, buildExport, isDynamic, 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"
};
const inAmpMode = isInAmpMode(ampState);
const hybridAmp = ampState.hybrid;
if (components.getServerSideProps) {
throw new Error(`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`);
}
// for non-dynamic SSG pages we should have already
// prerendered the file
if (!buildExport && components.getStaticProps && !isDynamic) {
return;
}
if (components.getStaticProps && !htmlFilepath.endsWith(".html")) {
// make sure it ends with .html if the name contains a dot
htmlFilepath += ".html";
htmlFilename += ".html";
}
let renderResult;
if (typeof components.Component === "string") {
renderResult = RenderResult.fromStatic(components.Component);
if (hasOrigQueryValues) {
throw 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`);
}
} else {
/**
* This sets environment variable to be used at the time of static export by head.tsx.
* Using this from process.env allows targeting SSR by calling
* `process.env.__NEXT_OPTIMIZE_FONTS`.
* TODO(prateekbh@): Remove this when experimental.optimizeFonts are being cleaned up.
*/ if (renderOpts.optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(renderOpts.optimizeFonts);
}
if (renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true);
}
try {
renderResult = await lazyRenderPagesPage(req, res, page, query, renderOpts);
} catch (err) {
if (!isBailoutToCSRError(err)) throw err;
}
}
const ssgNotFound = renderResult == null ? void 0 : renderResult.metadata.isNotFound;
const ampValidations = [];
const validateAmp = async (rawAmpHtml, ampPageName, validatorPath)=>{
const validator = await AmpHtmlValidator.getInstance(validatorPath);
const result = validator.validateString(rawAmpHtml);
const errors = result.errors.filter((e)=>e.severity === "ERROR");
const warnings = result.errors.filter((e)=>e.severity !== "ERROR");
if (warnings.length || errors.length) {
ampValidations.push({
page: ampPageName,
result: {
errors,
warnings
}
});
}
};
const html = renderResult && !renderResult.isNull ? renderResult.toUnchunkedString() : "";
let ampRenderResult;
if (inAmpMode && !renderOpts.ampSkipValidation) {
if (!ssgNotFound) {
await validateAmp(html, path, ampValidatorPath);
}
} else if (hybridAmp) {
const ampHtmlFilename = subFolders ? join(ampPath, "index.html") : `${ampPath}.html`;
const ampHtmlFilepath = join(outDir, ampHtmlFilename);
const exists = await fileExists(ampHtmlFilepath, FileType.File);
if (!exists) {
try {
ampRenderResult = await lazyRenderPagesPage(req, res, page, {
...query,
amp: "1"
}, renderOpts);
} catch (err) {
if (!isBailoutToCSRError(err)) throw err;
}
const ampHtml = ampRenderResult && !ampRenderResult.isNull ? ampRenderResult.toUnchunkedString() : "";
if (!renderOpts.ampSkipValidation) {
await validateAmp(ampHtml, page + "?amp=1", ampValidatorPath);
}
await fileWriter("AMP_HTML", ampHtmlFilepath, ampHtml, "utf8");
}
}
const metadata = (renderResult == null ? void 0 : renderResult.metadata) || (ampRenderResult == null ? void 0 : ampRenderResult.metadata) || {};
if (metadata.pageData) {
const dataFile = join(pagesDataDir, htmlFilename.replace(/\.html$/, NEXT_DATA_SUFFIX));
await fileWriter("DATA", dataFile, JSON.stringify(metadata.pageData), "utf8");
if (hybridAmp) {
await fileWriter("AMP_PAGE_DATA", dataFile.replace(/\.json$/, ".amp.json"), JSON.stringify(metadata.pageData), "utf8");
}
}
if (!ssgNotFound) {
// don't attempt writing to disk if getStaticProps returned not found
await fileWriter("HTML", htmlFilepath, html, "utf8");
}
return {
ampValidations,
revalidate: metadata.revalidate ?? false,
ssgNotFound
};
}
//# sourceMappingURL=pages.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/routes/pages.ts"],"names":["RenderResult","join","isInAmpMode","NEXT_DATA_SUFFIX","SERVER_PROPS_EXPORT_ERROR","isBailoutToCSRError","AmpHtmlValidator","FileType","fileExists","lazyRenderPagesPage","ExportedPagesFiles","exportPages","req","res","path","page","query","htmlFilepath","htmlFilename","ampPath","subFolders","outDir","ampValidatorPath","pagesDataDir","buildExport","isDynamic","hasOrigQueryValues","renderOpts","components","fileWriter","ampState","ampFirst","pageConfig","amp","hasQuery","Boolean","hybrid","inAmpMode","hybridAmp","getServerSideProps","Error","getStaticProps","endsWith","renderResult","Component","fromStatic","optimizeFonts","process","env","__NEXT_OPTIMIZE_FONTS","JSON","stringify","optimizeCss","__NEXT_OPTIMIZE_CSS","err","ssgNotFound","metadata","isNotFound","ampValidations","validateAmp","rawAmpHtml","ampPageName","validatorPath","validator","getInstance","result","validateString","errors","filter","e","severity","warnings","length","push","html","isNull","toUnchunkedString","ampRenderResult","ampSkipValidation","ampHtmlFilename","ampHtmlFilepath","exists","File","ampHtml","pageData","dataFile","replace","revalidate"],"mappings":"AAMA,OAAOA,kBAAkB,6BAA4B;AACrD,SAASC,IAAI,QAAQ,OAAM;AAK3B,SAASC,WAAW,QAAQ,4BAA2B;AACvD,SACEC,gBAAgB,EAChBC,yBAAyB,QACpB,sBAAqB;AAC5B,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,OAAOC,sBAAsB,uCAAsC;AACnE,SAASC,QAAQ,EAAEC,UAAU,QAAQ,wBAAuB;AAC5D,SAASC,mBAAmB,QAAQ,wDAAuD;;UAEzEC;;;;;GAAAA,uBAAAA;AAOlB,OAAO,eAAeC,YACpBC,GAAkB,EAClBC,GAAmB,EACnBC,IAAY,EACZC,IAAY,EACZC,KAAyB,EACzBC,YAAoB,EACpBC,YAAoB,EACpBC,OAAe,EACfC,UAAmB,EACnBC,MAAc,EACdC,gBAAoC,EACpCC,YAAoB,EACpBC,WAAoB,EACpBC,SAAkB,EAClBC,kBAA2B,EAC3BC,UAAsB,EACtBC,UAAoC,EACpCC,UAAsB;QAGVD,wBAEFA;IAHV,MAAME,WAAW;QACfC,UAAUH,EAAAA,yBAAAA,WAAWI,UAAU,qBAArBJ,uBAAuBK,GAAG,MAAK;QACzCC,UAAUC,QAAQnB,MAAMiB,GAAG;QAC3BG,QAAQR,EAAAA,0BAAAA,WAAWI,UAAU,qBAArBJ,wBAAuBK,GAAG,MAAK;IACzC;IAEA,MAAMI,YAAYnC,YAAY4B;IAC9B,MAA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;IACzE,IAAIA,SAAS4B,QAAQ,EAAE;QACrB,MAAMC,WAAWpF,KACfsB,cACAL,aAAaoE,OAAO,CAAC,WAAWnF;QAGlC,MAAM0B,mBAEJwD,UACAnC,KAAKC,SAAS,CAACK,SAAS4B,QAAQ,GAChC;QAGF,IAAI9C,WAAW;YACb,MAAMT,4BAEJwD,SAASC,OAAO,CAAC,WAAW,cAC5BpC,KAAKC,SAAS,CAACK,SAAS4B,QAAQ,GAChC;QAEJ;IACF;IAEA,IAAI,CAAC7B,aAAa;QAChB,qEAAqE;QACrE,MAAM1B,mBAAoCZ,cAAcyD,MAAM;IAChE;IAEA,OAAO;QACLhB;QACA6B,YAAY/B,SAAS+B,UAAU,IAAI;QACnChC;IACF;AACF"}

3
node_modules/next/dist/esm/export/routes/types.js generated vendored Normal file
View File

@ -0,0 +1,3 @@
export { };
//# sourceMappingURL=types.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/routes/types.ts"],"names":[],"mappings":"AAEA,WAIC"}

3
node_modules/next/dist/esm/export/types.js generated vendored Normal file
View File

@ -0,0 +1,3 @@
export { };
//# sourceMappingURL=types.js.map

1
node_modules/next/dist/esm/export/types.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/export/types.ts"],"names":[],"mappings":"AA8KA,WAIoC"}

14
node_modules/next/dist/esm/export/utils.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
export function hasCustomExportOutput(config) {
// In the past, a user had to run "next build" to generate
// ".next" (or whatever the distDir) followed by "next export"
// to generate "out" (or whatever the outDir). However, when
// "output: export" is configured, "next build" does both steps.
// So the user-configured distDir is actually the outDir.
// We'll do some custom logic when meeting this condition.
// e.g.
// Will set config.distDir to .next to make sure the manifests
// are still reading from temporary .next directory.
return config.output === "export" && config.distDir !== ".next";
}
//# sourceMappingURL=utils.js.map

1
node_modules/next/dist/esm/export/utils.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/export/utils.ts"],"names":["hasCustomExportOutput","config","output","distDir"],"mappings":"AAEA,OAAO,SAASA,sBAAsBC,MAA0B;IAC9D,0DAA0D;IAC1D,8DAA8D;IAC9D,4DAA4D;IAC5D,gEAAgE;IAChE,yDAAyD;IACzD,0DAA0D;IAC1D,OAAO;IACP,8DAA8D;IAC9D,oDAAoD;IACpD,OAAOA,OAAOC,MAAM,KAAK,YAAYD,OAAOE,OAAO,KAAK;AAC1D"}

263
node_modules/next/dist/esm/export/worker.js generated vendored Normal file
View File

@ -0,0 +1,263 @@
import "../server/node-environment";
process.env.NEXT_IS_EXPORT_WORKER = "true";
import { extname, join, dirname, sep } from "path";
import fs from "fs/promises";
import { loadComponents } from "../server/load-components";
import { isDynamicRoute } from "../shared/lib/router/utils/is-dynamic";
import { normalizePagePath } from "../shared/lib/page-path/normalize-page-path";
import { requireFontManifest } from "../server/require";
import { normalizeLocalePath } from "../shared/lib/i18n/normalize-locale-path";
import { trace } from "../trace";
import { setHttpClientAndAgentOptions } from "../server/setup-http-agent-env";
import isError from "../lib/is-error";
import { addRequestMeta } from "../server/request-meta";
import { normalizeAppPath } from "../shared/lib/router/utils/app-paths";
import { createRequestResponseMocks } from "../server/lib/mock-request";
import { isAppRouteRoute } from "../lib/is-app-route-route";
import { hasNextSupport } from "../telemetry/ci-info";
import { exportAppRoute } from "./routes/app-route";
import { exportAppPage } from "./routes/app-page";
import { exportPages } from "./routes/pages";
import { getParams } from "./helpers/get-params";
import { createIncrementalCache } from "./helpers/create-incremental-cache";
import { isPostpone } from "../server/lib/router-utils/is-postpone";
import { isDynamicUsageError } from "./helpers/is-dynamic-usage-error";
import { isBailoutToCSRError } from "../shared/lib/lazy-dynamic/bailout-to-csr";
import { turborepoTraceAccess, TurborepoAccessTraceResult } from "../build/turborepo-access-trace";
const envConfig = require("../shared/lib/runtime-config.external");
globalThis.__NEXT_DATA__ = {
nextExport: true
};
async function exportPageImpl(input, fileWriter) {
const { dir, path, pathMap, distDir, pagesDataDir, buildExport = false, serverRuntimeConfig, subFolders = false, optimizeFonts, optimizeCss, disableOptimizedLoading, debugOutput = false, cacheMaxMemorySize, fetchCache, fetchCacheKeyPrefix, cacheHandler, enableExperimentalReact, ampValidatorPath, trailingSlash, enabledDirectories } = input;
if (enableExperimentalReact) {
process.env.__NEXT_EXPERIMENTAL_REACT = "true";
}
const { page, // Check if this is an `app/` page.
_isAppDir: isAppDir = false, // TODO: use this when we've re-enabled app prefetching https://github.com/vercel/next.js/pull/58609
// // Check if this is an `app/` prefix request.
// _isAppPrefetch: isAppPrefetch = false,
// Check if this should error when dynamic usage is detected.
_isDynamicError: isDynamicError = false, // Pull the original query out.
query: originalQuery = {} } = pathMap;
try {
var _req_url;
let query = {
...originalQuery
};
const pathname = normalizeAppPath(page);
const isDynamic = isDynamicRoute(page);
const outDir = isAppDir ? join(distDir, "server/app") : input.outDir;
let params;
const filePath = normalizePagePath(path);
const ampPath = `${filePath}.amp`;
let renderAmpPath = ampPath;
let updatedPath = query.__nextSsgPath || path;
delete query.__nextSsgPath;
let locale = query.__nextLocale || input.renderOpts.locale;
delete query.__nextLocale;
if (input.renderOpts.locale) {
const localePathResult = normalizeLocalePath(path, input.renderOpts.locales);
if (localePathResult.detectedLocale) {
updatedPath = localePathResult.pathname;
locale = localePathResult.detectedLocale;
if (locale === input.renderOpts.defaultLocale) {
renderAmpPath = `${normalizePagePath(updatedPath)}.amp`;
}
}
}
// We need to show a warning if they try to provide query values
// for an auto-exported page since they won't be available
const hasOrigQueryValues = Object.keys(originalQuery).length > 0;
// Check if the page is a specified dynamic route
const { pathname: nonLocalizedPath } = normalizeLocalePath(path, input.renderOpts.locales);
if (isDynamic && page !== nonLocalizedPath) {
const normalizedPage = isAppDir ? normalizeAppPath(page) : page;
params = getParams(normalizedPage, updatedPath);
if (params) {
query = {
...query,
...params
};
}
}
const { req, res } = createRequestResponseMocks({
url: updatedPath
});
// If this is a status code page, then set the response code.
for (const statusCode of [
404,
500
]){
if ([
`/${statusCode}`,
`/${statusCode}.html`,
`/${statusCode}/index.html`
].some((p)=>p === updatedPath || `/${locale}${p}` === updatedPath)) {
res.statusCode = statusCode;
}
}
// Ensure that the URL has a trailing slash if it's configured.
if (trailingSlash && !((_req_url = req.url) == null ? void 0 : _req_url.endsWith("/"))) {
req.url += "/";
}
if (locale && buildExport && input.renderOpts.domainLocales && input.renderOpts.domainLocales.some((dl)=>{
var _dl_locales;
return dl.defaultLocale === locale || ((_dl_locales = dl.locales) == null ? void 0 : _dl_locales.includes(locale || ""));
})) {
addRequestMeta(req, "isLocaleDomain", true);
}
envConfig.setConfig({
serverRuntimeConfig,
publicRuntimeConfig: input.renderOpts.runtimeConfig
});
const getHtmlFilename = (p)=>subFolders ? `${p}${sep}index.html` : `${p}.html`;
let htmlFilename = getHtmlFilename(filePath);
// dynamic routes can provide invalid extensions e.g. /blog/[...slug] returns an
// extension of `.slug]`
const pageExt = isDynamic || isAppDir ? "" : extname(page);
const pathExt = isDynamic || isAppDir ? "" : extname(path);
// force output 404.html for backwards compat
if (path === "/404.html") {
htmlFilename = path;
} else if (pageExt !== pathExt && pathExt !== "") {
const isBuiltinPaths = [
"/500",
"/404"
].some((p)=>p === path || p === path + ".html");
// If the ssg path has .html extension, and it's not builtin paths, use it directly
// Otherwise, use that as the filename instead
const isHtmlExtPath = !isBuiltinPaths && path.endsWith(".html");
htmlFilename = isHtmlExtPath ? getHtmlFilename(path) : path;
} else if (path === "/") {
// If the path is the root, just use index.html
htmlFilename = "index.html";
}
const baseDir = join(outDir, dirname(htmlFilename));
let htmlFilepath = join(outDir, htmlFilename);
await fs.mkdir(baseDir, {
recursive: true
});
// If the fetch cache was enabled, we need to create an incremental
// cache instance for this page.
const incrementalCache = isAppDir && fetchCache ? await createIncrementalCache({
cacheHandler,
cacheMaxMemorySize,
fetchCacheKeyPrefix,
distDir,
dir,
enabledDirectories,
// PPR is not available for Pages.
experimental: {
ppr: false
},
// skip writing to disk in minimal mode for now, pending some
// changes to better support it
flushToDisk: !hasNextSupport
}) : undefined;
// Handle App Routes.
if (isAppDir && isAppRouteRoute(page)) {
return await exportAppRoute(req, res, params, page, incrementalCache, distDir, htmlFilepath, fileWriter);
}
const components = await loadComponents({
distDir,
page,
isAppPath: isAppDir
});
const renderOpts = {
...components,
...input.renderOpts,
ampPath: renderAmpPath,
params,
optimizeFonts,
optimizeCss,
disableOptimizedLoading,
fontManifest: optimizeFonts ? requireFontManifest(distDir) : undefined,
locale,
supportsDynamicResponse: false,
originalPathname: page
};
if (hasNextSupport) {
renderOpts.isRevalidate = true;
}
// Handle App Pages
if (isAppDir) {
// Set the incremental cache on the renderOpts, that's how app page's
// consume it.
renderOpts.incrementalCache = incrementalCache;
return await exportAppPage(req, res, page, path, pathname, query, renderOpts, htmlFilepath, debugOutput, isDynamicError, fileWriter);
}
return await exportPages(req, res, path, page, query, htmlFilepath, htmlFilename, ampPath, subFolders, outDir, ampValidatorPath, pagesDataDir, buildExport, isDynamic, hasOrigQueryValues, renderOpts, components, fileWriter);
} catch (err) {
console.error(`\nError occurred prerendering page "${path}". Read more: https://nextjs.org/docs/messages/prerender-error\n`);
if (!isBailoutToCSRError(err)) {
console.error(isError(err) && err.stack ? err.stack : err);
}
return {
error: true
};
}
}
export default async function exportPage(input) {
// Configure the http agent.
setHttpClientAndAgentOptions({
httpAgentOptions: input.httpAgentOptions
});
const files = [];
const baseFileWriter = async (type, path, content, encodingOptions = "utf-8")=>{
await fs.mkdir(dirname(path), {
recursive: true
});
await fs.writeFile(path, content, encodingOptions);
files.push({
type,
path
});
};
const exportPageSpan = trace("export-page-worker", input.parentSpanId);
const start = Date.now();
const turborepoAccessTraceResult = new TurborepoAccessTraceResult();
// Export the page.
const result = await exportPageSpan.traceAsyncFn(()=>turborepoTraceAccess(()=>exportPageImpl(input, baseFileWriter), turborepoAccessTraceResult));
// 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,
files: []
};
}
// Otherwise we can return the result.
return {
duration: Date.now() - start,
files,
ampValidations: result.ampValidations,
revalidate: result.revalidate,
metadata: result.metadata,
ssgNotFound: result.ssgNotFound,
hasEmptyPrelude: result.hasEmptyPrelude,
hasPostponed: result.hasPostponed,
turborepoAccessTraceResult: turborepoAccessTraceResult.serialize()
};
}
process.on("unhandledRejection", (err)=>{
// if it's a postpone error, it'll be handled later
// when the postponed promise is actually awaited.
if (isPostpone(err)) {
return;
}
// we don't want to log these errors
if (isDynamicUsageError(err)) {
return;
}
console.error(err);
});
process.on("rejectionHandled", ()=>{
// It is ok to await a Promise late in Next.js as it allows for better
// prefetching patterns to avoid waterfalls. We ignore logging these.
// We should've already errored in anyway unhandledRejection.
});
//# sourceMappingURL=worker.js.map

1
node_modules/next/dist/esm/export/worker.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long