added fonts
This commit is contained in:
1 parent
4134e3a234
commit
142d2986b6
9079 files changed
+1498421
-2
No files matched your search
+213
@@ -0,0 +1,213 @@
|
||||
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error';
|
||||
import { NEXT_CACHE_TAGS_HEADER, NEXT_META_SUFFIX, RSC_PREFETCH_SUFFIX, RSC_SUFFIX, RSC_SEGMENTS_DIR_SUFFIX, RSC_SEGMENT_SUFFIX } from '../../lib/constants';
|
||||
import { hasNextSupport } from '../../server/ci-info';
|
||||
import { lazyRenderAppPage } from '../../server/route-modules/app-page/module.render';
|
||||
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';
|
||||
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node';
|
||||
import { NEXT_IS_PRERENDER_HEADER } from '../../client/components/app-router-headers';
|
||||
import { AfterRunner } from '../../server/after/run-with-after';
|
||||
export async function prospectiveRenderAppPage(req, res, page, pathname, query, fallbackRouteParams, partialRenderOpts, sharedContext) {
|
||||
const afterRunner = new AfterRunner();
|
||||
// If the page is `/_not-found`, then we should update the page to be `/404`.
|
||||
// UNDERSCORE_NOT_FOUND_ROUTE value used here, however we don't want to import it here as it causes constants to be inlined which we don't want here.
|
||||
if (page === '/_not-found/page') {
|
||||
pathname = '/404';
|
||||
}
|
||||
try {
|
||||
await lazyRenderAppPage(new NodeNextRequest(req), new NodeNextResponse(res), pathname, query, fallbackRouteParams, {
|
||||
...partialRenderOpts,
|
||||
waitUntil: afterRunner.context.waitUntil,
|
||||
onClose: afterRunner.context.onClose,
|
||||
onAfterTaskError: afterRunner.context.onTaskError
|
||||
}, undefined, false, sharedContext);
|
||||
// TODO(after): if we abort a prerender because of an error in an after-callback
|
||||
// we should probably communicate that better (and not log the error twice)
|
||||
await afterRunner.executeAfter();
|
||||
} catch (err) {
|
||||
if (!isDynamicUsageError(err)) {
|
||||
throw err;
|
||||
}
|
||||
// We should fail rendering if a client side rendering bailout
|
||||
// occurred at the page level.
|
||||
if (isBailoutToCSRError(err)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Renders & exports a page associated with the /app directory
|
||||
*/ export async function exportAppPage(req, res, page, path, pathname, query, fallbackRouteParams, partialRenderOpts, htmlFilepath, debugOutput, isDynamicError, fileWriter, sharedContext) {
|
||||
const afterRunner = new AfterRunner();
|
||||
const renderOpts = {
|
||||
...partialRenderOpts,
|
||||
waitUntil: afterRunner.context.waitUntil,
|
||||
onClose: afterRunner.context.onClose,
|
||||
onAfterTaskError: afterRunner.context.onTaskError
|
||||
};
|
||||
let isDefaultNotFound = false;
|
||||
// If the page is `/_not-found`, then we should update the page to be `/404`.
|
||||
// UNDERSCORE_NOT_FOUND_ROUTE value used here, however we don't want to import it here as it causes constants to be inlined which we don't want here.
|
||||
if (page === '/_not-found/page') {
|
||||
isDefaultNotFound = true;
|
||||
pathname = '/404';
|
||||
}
|
||||
try {
|
||||
const result = await lazyRenderAppPage(new NodeNextRequest(req), new NodeNextResponse(res), pathname, query, fallbackRouteParams, renderOpts, undefined, false, sharedContext);
|
||||
const html = result.toUnchunkedString();
|
||||
// TODO(after): if we abort a prerender because of an error in an after-callback
|
||||
// we should probably communicate that better (and not log the error twice)
|
||||
await afterRunner.executeAfter();
|
||||
const { metadata } = result;
|
||||
const { flightData, cacheControl = {
|
||||
revalidate: false,
|
||||
expire: undefined
|
||||
}, postponed, fetchTags, fetchMetrics, segmentData } = metadata;
|
||||
// Ensure we don't postpone without having PPR enabled.
|
||||
if (postponed && !renderOpts.experimental.isRoutePPREnabled) {
|
||||
throw Object.defineProperty(new Error('Invariant: page postponed without PPR being enabled'), "__NEXT_ERROR_CODE", {
|
||||
value: "E156",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
if (cacheControl.revalidate === 0) {
|
||||
if (isDynamicError) {
|
||||
throw Object.defineProperty(new Error(`Page with dynamic = "error" encountered dynamic data method on ${path}.`), "__NEXT_ERROR_CODE", {
|
||||
value: "E388",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
const { staticBailoutInfo = {} } = metadata;
|
||||
if (debugOutput && (staticBailoutInfo == null ? void 0 : staticBailoutInfo.description)) {
|
||||
logDynamicUsageWarning({
|
||||
path,
|
||||
description: staticBailoutInfo.description,
|
||||
stack: staticBailoutInfo.stack
|
||||
});
|
||||
}
|
||||
return {
|
||||
cacheControl,
|
||||
fetchMetrics
|
||||
};
|
||||
}
|
||||
// If page data isn't available, it means that the page couldn't be rendered
|
||||
// properly so long as we don't have unknown route params. When a route doesn't
|
||||
// have unknown route params, there will not be any flight data.
|
||||
if (!flightData && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {
|
||||
throw Object.defineProperty(new Error(`Invariant: failed to get page data for ${path}`), "__NEXT_ERROR_CODE", {
|
||||
value: "E194",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
if (flightData) {
|
||||
// If PPR is enabled, we want to emit a prefetch rsc file for the page
|
||||
// instead of the standard rsc. This is because the standard rsc will
|
||||
// contain the dynamic data. We do this if any routes have PPR enabled so
|
||||
// that the cache read/write is the same.
|
||||
if (renderOpts.experimental.isRoutePPREnabled) {
|
||||
// If PPR is enabled, we should emit the flight data as the prefetch
|
||||
// payload.
|
||||
// TODO: This will eventually be replaced by the per-segment prefetch
|
||||
// output below.
|
||||
fileWriter.append(htmlFilepath.replace(/\.html$/, RSC_PREFETCH_SUFFIX), flightData);
|
||||
} else {
|
||||
// Writing the RSC payload to a file if we don't have PPR enabled.
|
||||
fileWriter.append(htmlFilepath.replace(/\.html$/, RSC_SUFFIX), flightData);
|
||||
}
|
||||
}
|
||||
let segmentPaths;
|
||||
if (segmentData) {
|
||||
// Emit the per-segment prefetch data. We emit them as separate files
|
||||
// so that the cache handler has the option to treat each as a
|
||||
// separate entry.
|
||||
segmentPaths = [];
|
||||
const segmentsDir = htmlFilepath.replace(/\.html$/, RSC_SEGMENTS_DIR_SUFFIX);
|
||||
for (const [segmentPath, buffer] of segmentData){
|
||||
segmentPaths.push(segmentPath);
|
||||
const segmentDataFilePath = segmentsDir + segmentPath + RSC_SEGMENT_SUFFIX;
|
||||
fileWriter.append(segmentDataFilePath, buffer);
|
||||
}
|
||||
}
|
||||
const headers = {
|
||||
...metadata.headers
|
||||
};
|
||||
// If we're writing the file to disk, we know it's a prerender.
|
||||
headers[NEXT_IS_PRERENDER_HEADER] = '1';
|
||||
if (fetchTags) {
|
||||
headers[NEXT_CACHE_TAGS_HEADER] = fetchTags;
|
||||
}
|
||||
// Writing static HTML to a file.
|
||||
fileWriter.append(htmlFilepath, html ?? '');
|
||||
const isParallelRoute = /\/@\w+/.test(page);
|
||||
const isNonSuccessfulStatusCode = res.statusCode > 300;
|
||||
// When PPR is enabled, we don't always send 200 for routes that have been
|
||||
// pregenerated, so we should grab the status code from the mocked
|
||||
// response.
|
||||
let status = renderOpts.experimental.isRoutePPREnabled ? res.statusCode : undefined;
|
||||
if (isDefaultNotFound) {
|
||||
// Override the default /_not-found page status code to 404
|
||||
status = 404;
|
||||
} else if (isNonSuccessfulStatusCode && !isParallelRoute) {
|
||||
// If it's parallel route the status from mock response is 404
|
||||
status = res.statusCode;
|
||||
}
|
||||
// Writing the request metadata to a file.
|
||||
const meta = {
|
||||
status,
|
||||
headers,
|
||||
postponed,
|
||||
segmentPaths
|
||||
};
|
||||
fileWriter.append(htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX), JSON.stringify(meta, null, 2));
|
||||
return {
|
||||
// Only include the metadata if the environment has next support.
|
||||
metadata: hasNextSupport ? meta : undefined,
|
||||
hasEmptyPrelude: Boolean(postponed) && html === '',
|
||||
hasPostponed: Boolean(postponed),
|
||||
cacheControl,
|
||||
fetchMetrics
|
||||
};
|
||||
} catch (err) {
|
||||
if (!isDynamicUsageError(err)) {
|
||||
throw err;
|
||||
}
|
||||
// We should fail rendering if a client side rendering bailout
|
||||
// occurred at the page level.
|
||||
if (isBailoutToCSRError(err)) {
|
||||
throw err;
|
||||
}
|
||||
let fetchMetrics;
|
||||
if (debugOutput) {
|
||||
const store = renderOpts.store;
|
||||
const { dynamicUsageDescription, dynamicUsageStack } = store;
|
||||
fetchMetrics = store.fetchMetrics;
|
||||
logDynamicUsageWarning({
|
||||
path,
|
||||
description: dynamicUsageDescription ?? '',
|
||||
stack: dynamicUsageStack
|
||||
});
|
||||
}
|
||||
return {
|
||||
cacheControl: {
|
||||
revalidate: 0,
|
||||
expire: undefined
|
||||
},
|
||||
fetchMetrics
|
||||
};
|
||||
}
|
||||
}
|
||||
function logDynamicUsageWarning({ path, description, stack }) {
|
||||
const errMessage = Object.defineProperty(new Error(`Static generation failed due to dynamic usage on ${path}, reason: ${description}`), "__NEXT_ERROR_CODE", {
|
||||
value: "E381",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
if (stack) {
|
||||
errMessage.stack = errMessage.message + stack.substring(stack.indexOf('\n'));
|
||||
}
|
||||
console.warn(errMessage);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-page.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/export/routes/app-page.ts"],"sourcesContent":["import type { OutgoingHttpHeaders } from 'node:http'\nimport type { ExportRouteResult } from '../types'\nimport type { RenderOpts } from '../../server/app-render/types'\nimport type { NextParsedUrlQuery } from '../../server/request-meta'\nimport type { RouteMetadata } from './types'\n\nimport type {\n MockedRequest,\n MockedResponse,\n} from '../../server/lib/mock-request'\nimport { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'\nimport {\n NEXT_CACHE_TAGS_HEADER,\n NEXT_META_SUFFIX,\n RSC_PREFETCH_SUFFIX,\n RSC_SUFFIX,\n RSC_SEGMENTS_DIR_SUFFIX,\n RSC_SEGMENT_SUFFIX,\n} from '../../lib/constants'\nimport { hasNextSupport } from '../../server/ci-info'\nimport { lazyRenderAppPage } from '../../server/route-modules/app-page/module.render'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'\nimport { NEXT_IS_PRERENDER_HEADER } from '../../client/components/app-router-headers'\nimport type { FetchMetrics } from '../../server/base-http'\nimport type { WorkStore } from '../../server/app-render/work-async-storage.external'\nimport type { FallbackRouteParams } from '../../server/request/fallback-params'\nimport { AfterRunner } from '../../server/after/run-with-after'\nimport type { RequestLifecycleOpts } from '../../server/base-server'\nimport type { AppSharedContext } from '../../server/app-render/app-render'\nimport type { MultiFileWriter } from '../../lib/multi-file-writer'\n\nexport async function prospectiveRenderAppPage(\n req: MockedRequest,\n res: MockedResponse,\n page: string,\n pathname: string,\n query: NextParsedUrlQuery,\n fallbackRouteParams: FallbackRouteParams | null,\n partialRenderOpts: Omit<RenderOpts, keyof RequestLifecycleOpts>,\n sharedContext: AppSharedContext\n): Promise<undefined> {\n const afterRunner = new AfterRunner()\n\n // If the page is `/_not-found`, then we should update the page to be `/404`.\n // UNDERSCORE_NOT_FOUND_ROUTE value used here, however we don't want to import it here as it causes constants to be inlined which we don't want here.\n if (page === '/_not-found/page') {\n pathname = '/404'\n }\n\n try {\n await lazyRenderAppPage(\n new NodeNextRequest(req),\n new NodeNextResponse(res),\n pathname,\n query,\n fallbackRouteParams,\n {\n ...partialRenderOpts,\n waitUntil: afterRunner.context.waitUntil,\n onClose: afterRunner.context.onClose,\n onAfterTaskError: afterRunner.context.onTaskError,\n },\n undefined,\n false,\n sharedContext\n )\n\n // TODO(after): if we abort a prerender because of an error in an after-callback\n // we should probably communicate that better (and not log the error twice)\n await afterRunner.executeAfter()\n } catch (err) {\n if (!isDynamicUsageError(err)) {\n throw err\n }\n\n // We should fail rendering if a client side rendering bailout\n // occurred at the page level.\n if (isBailoutToCSRError(err)) {\n throw err\n }\n }\n}\n\n/**\n * Renders & exports a page associated with the /app directory\n */\nexport async function exportAppPage(\n req: MockedRequest,\n res: MockedResponse,\n page: string,\n path: string,\n pathname: string,\n query: NextParsedUrlQuery,\n fallbackRouteParams: FallbackRouteParams | null,\n partialRenderOpts: Omit<RenderOpts, keyof RequestLifecycleOpts>,\n htmlFilepath: string,\n debugOutput: boolean,\n isDynamicError: boolean,\n fileWriter: MultiFileWriter,\n sharedContext: AppSharedContext\n): Promise<ExportRouteResult> {\n const afterRunner = new AfterRunner()\n\n const renderOpts: RenderOpts = {\n ...partialRenderOpts,\n waitUntil: afterRunner.context.waitUntil,\n onClose: afterRunner.context.onClose,\n onAfterTaskError: afterRunner.context.onTaskError,\n }\n\n let isDefaultNotFound = false\n // If the page is `/_not-found`, then we should update the page to be `/404`.\n // UNDERSCORE_NOT_FOUND_ROUTE value used here, however we don't want to import it here as it causes constants to be inlined which we don't want here.\n if (page === '/_not-found/page') {\n isDefaultNotFound = true\n pathname = '/404'\n }\n\n try {\n const result = await lazyRenderAppPage(\n new NodeNextRequest(req),\n new NodeNextResponse(res),\n pathname,\n query,\n fallbackRouteParams,\n renderOpts,\n undefined,\n false,\n sharedContext\n )\n\n const html = result.toUnchunkedString()\n\n // TODO(after): if we abort a prerender because of an error in an after-callback\n // we should probably communicate that better (and not log the error twice)\n await afterRunner.executeAfter()\n\n const { metadata } = result\n const {\n flightData,\n cacheControl = { revalidate: false, expire:Line truncated
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import { INFINITE_CACHE, NEXT_BODY_SUFFIX, NEXT_CACHE_TAGS_HEADER, NEXT_META_SUFFIX } from '../../lib/constants';
|
||||
import { NodeNextRequest } from '../../server/base-http/node';
|
||||
import { NextRequestAdapter, signalFromNodeResponse } from '../../server/web/spec-extension/adapters/next-request';
|
||||
import { toNodeOutgoingHttpHeaders } from '../../server/web/utils';
|
||||
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error';
|
||||
import { hasNextSupport } from '../../server/ci-info';
|
||||
import { isStaticGenEnabled } from '../../server/route-modules/app-route/helpers/is-static-gen-enabled';
|
||||
import { isMetadataRoute } from '../../lib/metadata/is-metadata-route';
|
||||
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths';
|
||||
import { AfterRunner } from '../../server/after/run-with-after';
|
||||
export var ExportedAppRouteFiles = /*#__PURE__*/ function(ExportedAppRouteFiles) {
|
||||
ExportedAppRouteFiles["BODY"] = "BODY";
|
||||
ExportedAppRouteFiles["META"] = "META";
|
||||
return ExportedAppRouteFiles;
|
||||
}({});
|
||||
export async function exportAppRoute(req, res, params, page, module, incrementalCache, cacheLifeProfiles, htmlFilepath, fileWriter, experimental, buildId) {
|
||||
// Ensure that the URL is absolute.
|
||||
req.url = `http://localhost:3000${req.url}`;
|
||||
// Adapt the request and response to the Next.js request and response.
|
||||
const request = NextRequestAdapter.fromNodeNextRequest(new NodeNextRequest(req), signalFromNodeResponse(res));
|
||||
const afterRunner = new AfterRunner();
|
||||
// Create the context for the handler. This contains the params from
|
||||
// the route and the context for the request.
|
||||
const context = {
|
||||
params,
|
||||
prerenderManifest: {
|
||||
version: 4,
|
||||
routes: {},
|
||||
dynamicRoutes: {},
|
||||
preview: {
|
||||
previewModeEncryptionKey: '',
|
||||
previewModeId: '',
|
||||
previewModeSigningKey: ''
|
||||
},
|
||||
notFoundRoutes: []
|
||||
},
|
||||
renderOpts: {
|
||||
experimental,
|
||||
nextExport: true,
|
||||
supportsDynamicResponse: false,
|
||||
incrementalCache,
|
||||
waitUntil: afterRunner.context.waitUntil,
|
||||
onClose: afterRunner.context.onClose,
|
||||
onAfterTaskError: afterRunner.context.onTaskError,
|
||||
cacheLifeProfiles
|
||||
},
|
||||
sharedContext: {
|
||||
buildId
|
||||
}
|
||||
};
|
||||
if (hasNextSupport) {
|
||||
context.renderOpts.isRevalidate = true;
|
||||
}
|
||||
try {
|
||||
const userland = module.userland;
|
||||
// we don't bail from the static optimization for
|
||||
// metadata routes, since it's app-route we can always append /route suffix.
|
||||
const routePath = normalizeAppPath(page) + '/route';
|
||||
const isPageMetadataRoute = isMetadataRoute(routePath);
|
||||
if (!isStaticGenEnabled(userland) && !isPageMetadataRoute && // We don't disable static gen when dynamicIO is enabled because we
|
||||
// expect that anything dynamic in the GET handler will make it dynamic
|
||||
// and thus avoid the cache surprises that led to us removing static gen
|
||||
// unless specifically opted into
|
||||
experimental.dynamicIO !== true) {
|
||||
return {
|
||||
cacheControl: {
|
||||
revalidate: 0,
|
||||
expire: undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
const response = await module.handle(request, context);
|
||||
const isValidStatus = response.status < 400 || response.status === 404;
|
||||
if (!isValidStatus) {
|
||||
return {
|
||||
cacheControl: {
|
||||
revalidate: 0,
|
||||
expire: undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
const blob = await response.blob();
|
||||
// TODO(after): if we abort a prerender because of an error in an after-callback
|
||||
// we should probably communicate that better (and not log the error twice)
|
||||
await afterRunner.executeAfter();
|
||||
const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;
|
||||
const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;
|
||||
const headers = toNodeOutgoingHttpHeaders(response.headers);
|
||||
const cacheTags = context.renderOpts.collectedTags;
|
||||
if (cacheTags) {
|
||||
headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;
|
||||
}
|
||||
if (!headers['content-type'] && blob.type) {
|
||||
headers['content-type'] = blob.type;
|
||||
}
|
||||
// Writing response body to a file.
|
||||
const body = Buffer.from(await blob.arrayBuffer());
|
||||
fileWriter.append(htmlFilepath.replace(/\.html$/, NEXT_BODY_SUFFIX), body);
|
||||
// Write the request metadata to a file.
|
||||
const meta = {
|
||||
status: response.status,
|
||||
headers
|
||||
};
|
||||
fileWriter.append(htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX), JSON.stringify(meta));
|
||||
return {
|
||||
cacheControl: {
|
||||
revalidate,
|
||||
expire
|
||||
},
|
||||
metadata: meta
|
||||
};
|
||||
} catch (err) {
|
||||
if (!isDynamicUsageError(err)) {
|
||||
throw err;
|
||||
}
|
||||
return {
|
||||
cacheControl: {
|
||||
revalidate: 0,
|
||||
expire: undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-route.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/export/routes/app-route.ts"],"sourcesContent":["import type { ExportRouteResult } from '../types'\nimport type AppRouteRouteModule from '../../server/route-modules/app-route/module'\nimport type { AppRouteRouteHandlerContext } from '../../server/route-modules/app-route/module'\nimport type { IncrementalCache } from '../../server/lib/incremental-cache'\n\nimport {\n INFINITE_CACHE,\n NEXT_BODY_SUFFIX,\n NEXT_CACHE_TAGS_HEADER,\n NEXT_META_SUFFIX,\n} from '../../lib/constants'\nimport { NodeNextRequest } from '../../server/base-http/node'\nimport {\n NextRequestAdapter,\n signalFromNodeResponse,\n} from '../../server/web/spec-extension/adapters/next-request'\nimport { toNodeOutgoingHttpHeaders } from '../../server/web/utils'\nimport type {\n MockedRequest,\n MockedResponse,\n} from '../../server/lib/mock-request'\nimport { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'\nimport { hasNextSupport } from '../../server/ci-info'\nimport { isStaticGenEnabled } from '../../server/route-modules/app-route/helpers/is-static-gen-enabled'\nimport type { ExperimentalConfig } from '../../server/config-shared'\nimport { isMetadataRoute } from '../../lib/metadata/is-metadata-route'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport type { Params } from '../../server/request/params'\nimport { AfterRunner } from '../../server/after/run-with-after'\nimport type { MultiFileWriter } from '../../lib/multi-file-writer'\n\nexport const enum ExportedAppRouteFiles {\n BODY = 'BODY',\n META = 'META',\n}\n\nexport async function exportAppRoute(\n req: MockedRequest,\n res: MockedResponse,\n params: Params | undefined,\n page: string,\n module: AppRouteRouteModule,\n incrementalCache: IncrementalCache | undefined,\n cacheLifeProfiles:\n | undefined\n | {\n [profile: string]: import('../../server/use-cache/cache-life').CacheLife\n },\n htmlFilepath: string,\n fileWriter: MultiFileWriter,\n experimental: Required<\n Pick<ExperimentalConfig, 'dynamicIO' | 'authInterrupts'>\n >,\n buildId: string\n): Promise<ExportRouteResult> {\n // Ensure that the URL is absolute.\n req.url = `http://localhost:3000${req.url}`\n\n // Adapt the request and response to the Next.js request and response.\n const request = NextRequestAdapter.fromNodeNextRequest(\n new NodeNextRequest(req),\n signalFromNodeResponse(res)\n )\n\n const afterRunner = new AfterRunner()\n\n // Create the context for the handler. This contains the params from\n // the route and the context for the request.\n const context: AppRouteRouteHandlerContext = {\n params,\n prerenderManifest: {\n version: 4,\n routes: {},\n dynamicRoutes: {},\n preview: {\n previewModeEncryptionKey: '',\n previewModeId: '',\n previewModeSigningKey: '',\n },\n notFoundRoutes: [],\n },\n renderOpts: {\n experimental,\n nextExport: true,\n supportsDynamicResponse: false,\n incrementalCache,\n waitUntil: afterRunner.context.waitUntil,\n onClose: afterRunner.context.onClose,\n onAfterTaskError: afterRunner.context.onTaskError,\n cacheLifeProfiles,\n },\n sharedContext: {\n buildId,\n },\n }\n\n if (hasNextSupport) {\n context.renderOpts.isRevalidate = true\n }\n\n try {\n const userland = module.userland\n // we don't bail from the static optimization for\n // metadata routes, since it's app-route we can always append /route suffix.\n const routePath = normalizeAppPath(page) + '/route'\n const isPageMetadataRoute = isMetadataRoute(routePath)\n\n if (\n !isStaticGenEnabled(userland) &&\n !isPageMetadataRoute &&\n // We don't disable static gen when dynamicIO is enabled because we\n // expect that anything dynamic in the GET handler will make it dynamic\n // and thus avoid the cache surprises that led to us removing static gen\n // unless specifically opted into\n experimental.dynamicIO !== true\n ) {\n return { cacheControl: { revalidate: 0, expire: undefined } }\n }\n\n const response = await module.handle(request, context)\n\n const isValidStatus = response.status < 400 || response.status === 404\n if (!isValidStatus) {\n return { cacheControl: { revalidate: 0, expire: undefined } }\n }\n\n const blob = await response.blob()\n\n // TODO(after): if we abort a prerender because of an error in an after-callback\n // we should probably communicate that better (and not log the error twice)\n await afterRunner.executeAfter()\n\n const revalidate =\n typeof context.renderOpts.collectedRevalidate === 'undefined' ||\n context.renderOpts.collectedRevalidate >= INFINITE_CACHE\n ? false\n : context.renderOpts.collectedRevalidate\n\n const expire =\n typeof context.renderOpts.collectedExpire === 'undefined' ||\n context.renderOpts.cLine truncated
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
import RenderResult from '../../server/render-result';
|
||||
import { join } from 'path';
|
||||
import { isInAmpMode } from '../../shared/lib/amp-mode';
|
||||
import { NEXT_DATA_SUFFIX, SERVER_PROPS_EXPORT_ERROR } from '../../lib/constants';
|
||||
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';
|
||||
import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator';
|
||||
import { FileType, fileExists } from '../../lib/file-exists';
|
||||
import { lazyRenderPagesPage } from '../../server/route-modules/pages/module.render';
|
||||
/**
|
||||
* Renders & exports a page associated with the /pages directory
|
||||
*/ export async function exportPagesPage(req, res, path, page, query, params, htmlFilepath, htmlFilename, ampPath, subFolders, outDir, ampValidatorPath, pagesDataDir, buildExport, isDynamic, sharedContext, renderContext, hasOrigQueryValues, renderOpts, components, fileWriter) {
|
||||
var _components_pageConfig, _components_pageConfig1;
|
||||
const ampState = {
|
||||
ampFirst: ((_components_pageConfig = components.pageConfig) == null ? void 0 : _components_pageConfig.amp) === true,
|
||||
hasQuery: Boolean(query.amp),
|
||||
hybrid: ((_components_pageConfig1 = components.pageConfig) == null ? void 0 : _components_pageConfig1.amp) === 'hybrid'
|
||||
};
|
||||
if (!ampValidatorPath) {
|
||||
ampValidatorPath = require.resolve('next/dist/compiled/amphtml-validator/validator_wasm.js');
|
||||
}
|
||||
const inAmpMode = isInAmpMode(ampState);
|
||||
const hybridAmp = ampState.hybrid;
|
||||
if (components.getServerSideProps) {
|
||||
throw Object.defineProperty(new Error(`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`), "__NEXT_ERROR_CODE", {
|
||||
value: "E15",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
// for non-dynamic SSG pages we should have already
|
||||
// prerendered the file
|
||||
if (!buildExport && components.getStaticProps && !isDynamic) {
|
||||
return;
|
||||
}
|
||||
// Pages router merges page params (e.g. [lang]) with query params
|
||||
// primarily to support them both being accessible on `useRouter().query`.
|
||||
// If we extracted dynamic params from the path, we need to merge them
|
||||
// back into the query object.
|
||||
const searchAndDynamicParams = {
|
||||
...query,
|
||||
...params
|
||||
};
|
||||
if (components.getStaticProps && !htmlFilepath.endsWith('.html')) {
|
||||
// make sure it ends with .html if the name contains a dot
|
||||
htmlFilepath += '.html';
|
||||
htmlFilename += '.html';
|
||||
}
|
||||
let renderResult;
|
||||
if (typeof components.Component === 'string') {
|
||||
renderResult = RenderResult.fromStatic(components.Component);
|
||||
if (hasOrigQueryValues) {
|
||||
throw Object.defineProperty(new Error(`\nError: you provided query values for ${path} which is an auto-exported page. These can not be applied since the page can no longer be re-rendered on the server. To disable auto-export for this page add \`getInitialProps\`\n`), "__NEXT_ERROR_CODE", {
|
||||
value: "E505",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
} else {
|
||||
/**
|
||||
* This sets environment variable to be used at the time of SSR by head.tsx.
|
||||
* Using this from process.env allows targeting SSR by calling
|
||||
* `process.env.__NEXT_OPTIMIZE_CSS`.
|
||||
*/ if (renderOpts.optimizeCss) {
|
||||
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true);
|
||||
}
|
||||
try {
|
||||
renderResult = await lazyRenderPagesPage(req, res, page, searchAndDynamicParams, renderOpts, sharedContext, renderContext);
|
||||
} catch (err) {
|
||||
if (!isBailoutToCSRError(err)) throw err;
|
||||
}
|
||||
}
|
||||
const ssgNotFound = renderResult == null ? void 0 : renderResult.metadata.isNotFound;
|
||||
const ampValidations = [];
|
||||
const validateAmp = async (rawAmpHtml, ampPageName, validatorPath)=>{
|
||||
const validator = await AmpHtmlValidator.getInstance(validatorPath);
|
||||
const result = validator.validateString(rawAmpHtml);
|
||||
const errors = result.errors.filter((e)=>e.severity === 'ERROR');
|
||||
const warnings = result.errors.filter((e)=>e.severity !== 'ERROR');
|
||||
if (warnings.length || errors.length) {
|
||||
ampValidations.push({
|
||||
page: ampPageName,
|
||||
result: {
|
||||
errors,
|
||||
warnings
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
const html = renderResult && !renderResult.isNull ? renderResult.toUnchunkedString() : '';
|
||||
let ampRenderResult;
|
||||
if (inAmpMode && !renderOpts.ampSkipValidation) {
|
||||
if (!ssgNotFound) {
|
||||
await validateAmp(html, path, ampValidatorPath);
|
||||
}
|
||||
} else if (hybridAmp) {
|
||||
const ampHtmlFilename = subFolders ? join(ampPath, 'index.html') : `${ampPath}.html`;
|
||||
const ampHtmlFilepath = join(outDir, ampHtmlFilename);
|
||||
const exists = await fileExists(ampHtmlFilepath, FileType.File);
|
||||
if (!exists) {
|
||||
try {
|
||||
ampRenderResult = await lazyRenderPagesPage(req, res, page, {
|
||||
...searchAndDynamicParams,
|
||||
amp: '1'
|
||||
}, renderOpts, sharedContext, renderContext);
|
||||
} catch (err) {
|
||||
if (!isBailoutToCSRError(err)) throw err;
|
||||
}
|
||||
const ampHtml = ampRenderResult && !ampRenderResult.isNull ? ampRenderResult.toUnchunkedString() : '';
|
||||
if (!renderOpts.ampSkipValidation) {
|
||||
await validateAmp(ampHtml, page + '?amp=1', ampValidatorPath);
|
||||
}
|
||||
fileWriter.append(ampHtmlFilepath, ampHtml);
|
||||
}
|
||||
}
|
||||
const metadata = (renderResult == null ? void 0 : renderResult.metadata) || (ampRenderResult == null ? void 0 : ampRenderResult.metadata) || {};
|
||||
if (metadata.pageData) {
|
||||
const dataFile = join(pagesDataDir, htmlFilename.replace(/\.html$/, NEXT_DATA_SUFFIX));
|
||||
fileWriter.append(dataFile, JSON.stringify(metadata.pageData));
|
||||
if (hybridAmp) {
|
||||
fileWriter.append(dataFile.replace(/\.json$/, '.amp.json'), JSON.stringify(metadata.pageData));
|
||||
}
|
||||
}
|
||||
if (!ssgNotFound) {
|
||||
// don't attempt writing to disk if getStaticProps returned not found
|
||||
fileWriter.append(htmlFilepath, html);
|
||||
}
|
||||
return {
|
||||
ampValidations,
|
||||
cacheControl: metadata.cacheControl ?? {
|
||||
revalidate: false,
|
||||
expire: undefined
|
||||
},
|
||||
ssgNotFound
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=pages.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/export/routes/pages.ts"],"sourcesContent":["import type { ExportRouteResult } from '../types'\nimport type {\n PagesRenderContext,\n PagesSharedContext,\n RenderOpts,\n} from '../../server/render'\nimport type { LoadComponentsReturnType } from '../../server/load-components'\nimport type { AmpValidation } from '../types'\nimport type { NextParsedUrlQuery } from '../../server/request-meta'\nimport type { Params } from '../../server/request/params'\n\nimport RenderResult from '../../server/render-result'\nimport { join } from 'path'\nimport type {\n MockedRequest,\n MockedResponse,\n} from '../../server/lib/mock-request'\nimport { isInAmpMode } from '../../shared/lib/amp-mode'\nimport {\n NEXT_DATA_SUFFIX,\n SERVER_PROPS_EXPORT_ERROR,\n} from '../../lib/constants'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'\nimport { FileType, fileExists } from '../../lib/file-exists'\nimport { lazyRenderPagesPage } from '../../server/route-modules/pages/module.render'\nimport type { MultiFileWriter } from '../../lib/multi-file-writer'\n\n/**\n * Renders & exports a page associated with the /pages directory\n */\nexport async function exportPagesPage(\n req: MockedRequest,\n res: MockedResponse,\n path: string,\n page: string,\n query: NextParsedUrlQuery,\n params: Params | undefined,\n htmlFilepath: string,\n htmlFilename: string,\n ampPath: string,\n subFolders: boolean,\n outDir: string,\n ampValidatorPath: string | undefined,\n pagesDataDir: string,\n buildExport: boolean,\n isDynamic: boolean,\n sharedContext: PagesSharedContext,\n renderContext: PagesRenderContext,\n hasOrigQueryValues: boolean,\n renderOpts: RenderOpts,\n components: LoadComponentsReturnType,\n fileWriter: MultiFileWriter\n): Promise<ExportRouteResult | undefined> {\n const ampState = {\n ampFirst: components.pageConfig?.amp === true,\n hasQuery: Boolean(query.amp),\n hybrid: components.pageConfig?.amp === 'hybrid',\n }\n\n if (!ampValidatorPath) {\n ampValidatorPath = require.resolve(\n 'next/dist/compiled/amphtml-validator/validator_wasm.js'\n )\n }\n\n const inAmpMode = isInAmpMode(ampState)\n const hybridAmp = ampState.hybrid\n\n if (components.getServerSideProps) {\n throw new Error(`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`)\n }\n\n // for non-dynamic SSG pages we should have already\n // prerendered the file\n if (!buildExport && components.getStaticProps && !isDynamic) {\n return\n }\n\n // Pages router merges page params (e.g. [lang]) with query params\n // primarily to support them both being accessible on `useRouter().query`.\n // If we extracted dynamic params from the path, we need to merge them\n // back into the query object.\n const searchAndDynamicParams = {\n ...query,\n ...params,\n }\n\n if (components.getStaticProps && !htmlFilepath.endsWith('.html')) {\n // make sure it ends with .html if the name contains a dot\n htmlFilepath += '.html'\n htmlFilename += '.html'\n }\n\n let renderResult: RenderResult | undefined\n\n if (typeof components.Component === 'string') {\n renderResult = RenderResult.fromStatic(components.Component)\n\n if (hasOrigQueryValues) {\n throw new Error(\n `\\nError: you provided query values for ${path} which is an auto-exported page. These can not be applied since the page can no longer be re-rendered on the server. To disable auto-export for this page add \\`getInitialProps\\`\\n`\n )\n }\n } else {\n /**\n * This sets environment variable to be used at the time of SSR by head.tsx.\n * Using this from process.env allows targeting SSR by calling\n * `process.env.__NEXT_OPTIMIZE_CSS`.\n */\n if (renderOpts.optimizeCss) {\n process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)\n }\n try {\n renderResult = await lazyRenderPagesPage(\n req,\n res,\n page,\n searchAndDynamicParams,\n renderOpts,\n sharedContext,\n renderContext\n )\n } catch (err) {\n if (!isBailoutToCSRError(err)) throw err\n }\n }\n\n const ssgNotFound = renderResult?.metadata.isNotFound\n\n const ampValidations: AmpValidation[] = []\n\n const validateAmp = async (\n rawAmpHtml: string,\n ampPageName: string,\n validatorPath: string | undefined\n ) => {\n const validator = await AmpHtmlValidator.getInstance(validatorPath)\n const result = validator.validateString(rawAmpHtml)\n const errors = result.errors.filter((e) => e.severity === 'ERROR')\n const warnings = result.errors.filter((e) => e.severity !== 'ERROR')\n\n if (warnings.length || errors.length) {\n ampValidations.push({\n page: ampPageName,\n result: {\n errors,\n warnings,\n },\n })\n }\n }\n\n const html =\n renderResult && !rLine truncated
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export { };
|
||||
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/export/routes/types.ts"],"sourcesContent":["import type { OutgoingHttpHeaders } from 'node:http'\n\nexport type RouteMetadata = {\n status: number | undefined\n headers: OutgoingHttpHeaders | undefined\n postponed: string | undefined\n segmentPaths: Array<string> | undefined\n}\n"],"names":[],"mappings":"AAEA,WAKC"}
|
||||
Reference in new issue
Block a user