fixed version control heatmap and activity

This commit is contained in:
will
2026-04-02 20:38:56 +01:00
parent 1da5da43e1
commit 250a7030bf
1777 changed files with 170575 additions and 83 deletions

View File

@@ -0,0 +1,607 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "handleAction", {
enumerable: true,
get: function() {
return handleAction;
}
});
const _approuterheaders = require("../../client/components/app-router-headers");
const _notfound = require("../../client/components/not-found");
const _redirect = require("../../client/components/redirect");
const _renderresult = /*#__PURE__*/ _interop_require_default(require("../render-result"));
const _flightrenderresult = require("./flight-render-result");
const _utils = require("../lib/server-ipc/utils");
const _requestcookies = require("../web/spec-extension/adapters/request-cookies");
const _constants = require("../../lib/constants");
const _serveractionrequestmeta = require("../lib/server-action-request-meta");
const _csrfprotection = require("./csrf-protection");
const _log = require("../../build/output/log");
const _cookies = require("../web/spec-extension/cookies");
const _headers = require("../web/spec-extension/adapters/headers");
const _utils1 = require("../web/utils");
const _actionutils = require("./action-utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function formDataFromSearchQueryString(query) {
const searchParams = new URLSearchParams(query);
const formData = new FormData();
for (const [key, value] of searchParams){
formData.append(key, value);
}
return formData;
}
function nodeHeadersToRecord(headers) {
const record = {};
for (const [key, value] of Object.entries(headers)){
if (value !== undefined) {
record[key] = Array.isArray(value) ? value.join(", ") : `${value}`;
}
}
return record;
}
function getForwardedHeaders(req, res) {
// Get request headers and cookies
const requestHeaders = req.headers;
const requestCookies = new _cookies.RequestCookies(_headers.HeadersAdapter.from(requestHeaders));
// Get response headers and cookies
const responseHeaders = res.getHeaders();
const responseCookies = new _cookies.ResponseCookies((0, _utils1.fromNodeOutgoingHttpHeaders)(responseHeaders));
// Merge request and response headers
const mergedHeaders = (0, _utils.filterReqHeaders)({
...nodeHeadersToRecord(requestHeaders),
...nodeHeadersToRecord(responseHeaders)
}, _utils.actionsForbiddenHeaders);
// Merge cookies into requestCookies, so responseCookies always take precedence
// and overwrite/delete those from requestCookies.
responseCookies.getAll().forEach((cookie)=>{
if (typeof cookie.value === "undefined") {
requestCookies.delete(cookie.name);
} else {
requestCookies.set(cookie);
}
});
// Update the 'cookie' header with the merged cookies
mergedHeaders["cookie"] = requestCookies.toString();
// Remove headers that should not be forwarded
delete mergedHeaders["transfer-encoding"];
return new Headers(mergedHeaders);
}
async function addRevalidationHeader(res, { staticGenerationStore, requestStore }) {
var _staticGenerationStore_revalidatedTags;
await Promise.all(Object.values(staticGenerationStore.pendingRevalidates || []));
// If a tag was revalidated, the client router needs to invalidate all the
// client router cache as they may be stale. And if a path was revalidated, the
// client needs to invalidate all subtrees below that path.
// To keep the header size small, we use a tuple of
// [[revalidatedPaths], isTagRevalidated ? 1 : 0, isCookieRevalidated ? 1 : 0]
// instead of a JSON object.
// TODO-APP: Currently the prefetch cache doesn't have subtree information,
// so we need to invalidate the entire cache if a path was revalidated.
// TODO-APP: Currently paths are treated as tags, so the second element of the tuple
// is always empty.
const isTagRevalidated = ((_staticGenerationStore_revalidatedTags = staticGenerationStore.revalidatedTags) == null ? void 0 : _staticGenerationStore_revalidatedTags.length) ? 1 : 0;
const isCookieRevalidated = (0, _requestcookies.getModifiedCookieValues)(requestStore.mutableCookies).length ? 1 : 0;
res.setHeader("x-action-revalidated", JSON.stringify([
[],
isTagRevalidated,
isCookieRevalidated
]));
}
/**
* Forwards a server action request to a separate worker. Used when the requested action is not available in the current worker.
*/ async function createForwardedActionResponse(req, res, host, workerPathname, basePath, staticGenerationStore) {
var _staticGenerationStore_incrementalCache;
if (!host) {
throw new Error("Invariant: Missing `host` header from a forwarded Server Actions request.");
}
const forwardedHeaders = getForwardedHeaders(req, res);
// indicate that this action request was forwarded from another worker
// we use this to skip rendering the flight tree so that we don't update the UI
// with the response from the forwarded worker
forwardedHeaders.set("x-action-forwarded", "1");
const proto = ((_staticGenerationStore_incrementalCache = staticGenerationStore.incrementalCache) == null ? void 0 : _staticGenerationStore_incrementalCache.requestProtocol) || "https";
// For standalone or the serverful mode, use the internal origin directly
// other than the host headers from the request.
const origin = process.env.__NEXT_PRIVATE_ORIGIN || `${proto}://${host.value}`;
const fetchUrl = new URL(`${origin}${basePath}${workerPathname}`);
try {
let readableStream;
if (process.env.NEXT_RUNTIME === "edge") {
const webRequest = req;
if (!webRequest.body) {
throw new Error("invariant: Missing request body.");
}
readableStream = webRequest.body;
} else {
// Convert the Node.js readable stream to a Web Stream.
readableStream = new ReadableStream({
start (controller) {
req.on("data", (chunk)=>{
controller.enqueue(new Uint8Array(chunk));
});
req.on("end", ()=>{
controller.close();
});
req.on("error", (err)=>{
controller.error(err);
});
}
});
}
// Forward the request to the new worker
const response = await fetch(fetchUrl, {
method: "POST",
body: readableStream,
duplex: "half",
headers: forwardedHeaders,
next: {
// @ts-ignore
internal: 1
}
});
if (response.headers.get("content-type") === _approuterheaders.RSC_CONTENT_TYPE_HEADER) {
// copy the headers from the redirect response to the response we're sending
for (const [key, value] of response.headers){
if (!_utils.actionsForbiddenHeaders.includes(key)) {
res.setHeader(key, value);
}
}
return new _flightrenderresult.FlightRenderResult(response.body);
} else {
var // Since we aren't consuming the response body, we cancel it to avoid memory leaks
_response_body;
(_response_body = response.body) == null ? void 0 : _response_body.cancel();
}
} catch (err) {
// we couldn't stream the forwarded response, so we'll just do a normal redirect
console.error(`failed to forward action response`, err);
}
}
async function createRedirectRenderResult(req, res, originalHost, redirectUrl, basePath, staticGenerationStore) {
res.setHeader("x-action-redirect", redirectUrl);
// If we're redirecting to another route of this Next.js application, we'll
// try to stream the response from the other worker path. When that works,
// we can save an extra roundtrip and avoid a full page reload.
// When the redirect URL starts with a `/`, or to the same host as application,
// we treat it as an app-relative redirect.
const parsedRedirectUrl = new URL(redirectUrl, "http://n");
const isAppRelativeRedirect = redirectUrl.startsWith("/") || originalHost && originalHost.value === parsedRedirectUrl.host;
if (isAppRelativeRedirect) {
var _staticGenerationStore_incrementalCache;
if (!originalHost) {
throw new Error("Invariant: Missing `host` header from a forwarded Server Actions request.");
}
const forwardedHeaders = getForwardedHeaders(req, res);
forwardedHeaders.set(_approuterheaders.RSC_HEADER, "1");
const proto = ((_staticGenerationStore_incrementalCache = staticGenerationStore.incrementalCache) == null ? void 0 : _staticGenerationStore_incrementalCache.requestProtocol) || "https";
// For standalone or the serverful mode, use the internal origin directly
// other than the host headers from the request.
const origin = process.env.__NEXT_PRIVATE_ORIGIN || `${proto}://${originalHost.value}`;
const fetchUrl = new URL(`${origin}${basePath}${parsedRedirectUrl.pathname}${parsedRedirectUrl.search}`);
if (staticGenerationStore.revalidatedTags) {
var _staticGenerationStore_incrementalCache_prerenderManifest_preview, _staticGenerationStore_incrementalCache_prerenderManifest, _staticGenerationStore_incrementalCache1;
forwardedHeaders.set(_constants.NEXT_CACHE_REVALIDATED_TAGS_HEADER, staticGenerationStore.revalidatedTags.join(","));
forwardedHeaders.set(_constants.NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, ((_staticGenerationStore_incrementalCache1 = staticGenerationStore.incrementalCache) == null ? void 0 : (_staticGenerationStore_incrementalCache_prerenderManifest = _staticGenerationStore_incrementalCache1.prerenderManifest) == null ? void 0 : (_staticGenerationStore_incrementalCache_prerenderManifest_preview = _staticGenerationStore_incrementalCache_prerenderManifest.preview) == null ? void 0 : _staticGenerationStore_incrementalCache_prerenderManifest_preview.previewModeId) || "");
}
// Ensures that when the path was revalidated we don't return a partial response on redirects
forwardedHeaders.delete("next-router-state-tree");
try {
const response = await fetch(fetchUrl, {
method: "GET",
headers: forwardedHeaders,
next: {
// @ts-ignore
internal: 1
}
});
if (response.headers.get("content-type") === _approuterheaders.RSC_CONTENT_TYPE_HEADER) {
// copy the headers from the redirect response to the response we're sending
for (const [key, value] of response.headers){
if (!_utils.actionsForbiddenHeaders.includes(key)) {
res.setHeader(key, value);
}
}
return new _flightrenderresult.FlightRenderResult(response.body);
} else {
var // Since we aren't consuming the response body, we cancel it to avoid memory leaks
_response_body;
(_response_body = response.body) == null ? void 0 : _response_body.cancel();
}
} catch (err) {
// we couldn't stream the redirect response, so we'll just do a normal redirect
console.error(`failed to get redirect response`, err);
}
}
return _renderresult.default.fromStatic("{}");
}
var HostType;
/**
* Ensures the value of the header can't create long logs.
*/ function limitUntrustedHeaderValueForLogs(value) {
return value.length > 100 ? value.slice(0, 100) + "..." : value;
}
async function handleAction({ req, res, ComponentMod, serverModuleMap, generateFlight, staticGenerationStore, requestStore, serverActions, ctx }) {
const contentType = req.headers["content-type"];
const { serverActionsManifest, page } = ctx.renderOpts;
const { actionId, isURLEncodedAction, isMultipartAction, isFetchAction, isServerAction } = (0, _serveractionrequestmeta.getServerActionRequestMetadata)(req);
// If it's not a Server Action, skip handling.
if (!isServerAction) {
return;
}
if (staticGenerationStore.isStaticGeneration) {
throw new Error("Invariant: server actions can't be handled during static rendering");
}
// When running actions the default is no-store, you can still `cache: 'force-cache'`
staticGenerationStore.fetchCache = "default-no-store";
const originDomain = typeof req.headers["origin"] === "string" ? new URL(req.headers["origin"]).host : undefined;
const forwardedHostHeader = req.headers["x-forwarded-host"];
const hostHeader = req.headers["host"];
const host = forwardedHostHeader ? {
type: "x-forwarded-host",
value: forwardedHostHeader
} : hostHeader ? {
type: "host",
value: hostHeader
} : undefined;
let warning = undefined;
function warnBadServerActionRequest() {
if (warning) {
(0, _log.warn)(warning);
}
}
// This is to prevent CSRF attacks. If `x-forwarded-host` is set, we need to
// ensure that the request is coming from the same host.
if (!originDomain) {
// This might be an old browser that doesn't send `host` header. We ignore
// this case.
warning = "Missing `origin` header from a forwarded Server Actions request.";
} else if (!host || originDomain !== host.value) {
// If the customer sets a list of allowed origins, we'll allow the request.
// These are considered safe but might be different from forwarded host set
// by the infra (i.e. reverse proxies).
if ((0, _csrfprotection.isCsrfOriginAllowed)(originDomain, serverActions == null ? void 0 : serverActions.allowedOrigins)) {
// Ignore it
} else {
if (host) {
// This seems to be an CSRF attack. We should not proceed the action.
console.error(`\`${host.type}\` header with value \`${limitUntrustedHeaderValueForLogs(host.value)}\` does not match \`origin\` header with value \`${limitUntrustedHeaderValueForLogs(originDomain)}\` from a forwarded Server Actions request. Aborting the action.`);
} else {
// This is an attack. We should not proceed the action.
console.error(`\`x-forwarded-host\` or \`host\` headers are not provided. One of these is needed to compare the \`origin\` header from a forwarded Server Actions request. Aborting the action.`);
}
const error = new Error("Invalid Server Actions request.");
if (isFetchAction) {
res.statusCode = 500;
await Promise.all(Object.values(staticGenerationStore.pendingRevalidates || []));
const promise = Promise.reject(error);
try {
// we need to await the promise to trigger the rejection early
// so that it's already handled by the time we call
// the RSC runtime. Otherwise, it will throw an unhandled
// promise rejection error in the renderer.
await promise;
} catch {
// swallow error, it's gonna be handled on the client
}
return {
type: "done",
result: await generateFlight(ctx, {
actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated
})
};
}
throw error;
}
}
// ensure we avoid caching server actions unexpectedly
res.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
let bound = [];
const { actionAsyncStorage } = ComponentMod;
let actionResult;
let formState;
let actionModId;
const actionWasForwarded = Boolean(req.headers["x-action-forwarded"]);
if (actionId) {
const forwardedWorker = (0, _actionutils.selectWorkerForForwarding)(actionId, page, serverActionsManifest);
// If forwardedWorker is truthy, it means there isn't a worker for the action
// in the current handler, so we forward the request to a worker that has the action.
if (forwardedWorker) {
return {
type: "done",
result: await createForwardedActionResponse(req, res, host, forwardedWorker, ctx.renderOpts.basePath, staticGenerationStore)
};
}
}
try {
await actionAsyncStorage.run({
isAction: true
}, async ()=>{
if (process.env.NEXT_RUNTIME === "edge") {
// Use react-server-dom-webpack/server.edge
const { decodeReply, decodeAction, decodeFormState } = ComponentMod;
const webRequest = req;
if (!webRequest.body) {
throw new Error("invariant: Missing request body.");
}
if (isMultipartAction) {
// TODO-APP: Add streaming support
const formData = await webRequest.request.formData();
if (isFetchAction) {
bound = await decodeReply(formData, serverModuleMap);
} else {
const action = await decodeAction(formData, serverModuleMap);
if (typeof action === "function") {
// Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest();
const actionReturnedState = await action();
formState = decodeFormState(actionReturnedState, formData);
}
// Skip the fetch path
return;
}
} else {
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap);
} catch (err) {
if (actionId !== null) {
console.error(err);
}
return {
type: "not-found"
};
}
let actionData = "";
const reader = webRequest.body.getReader();
while(true){
const { done, value } = await reader.read();
if (done) {
break;
}
actionData += new TextDecoder().decode(value);
}
if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData);
bound = await decodeReply(formData, serverModuleMap);
} else {
bound = await decodeReply(actionData, serverModuleMap);
}
}
} else {
// Use react-server-dom-webpack/server.node which supports streaming
const { decodeReply, decodeReplyFromBusboy, decodeAction, decodeFormState } = require(`./react-server.node`);
if (isMultipartAction) {
if (isFetchAction) {
const readableLimit = (serverActions == null ? void 0 : serverActions.bodySizeLimit) ?? "1 MB";
const limit = require("next/dist/compiled/bytes").parse(readableLimit);
const busboy = require("busboy");
const bb = busboy({
headers: req.headers,
limits: {
fieldSize: limit
}
});
req.pipe(bb);
bound = await decodeReplyFromBusboy(bb, serverModuleMap);
} else {
// Convert the Node.js readable stream to a Web Stream.
const readableStream = new ReadableStream({
start (controller) {
req.on("data", (chunk)=>{
controller.enqueue(new Uint8Array(chunk));
});
req.on("end", ()=>{
controller.close();
});
req.on("error", (err)=>{
controller.error(err);
});
}
});
// React doesn't yet publish a busboy version of decodeAction
// so we polyfill the parsing of FormData.
const fakeRequest = new Request("http://localhost", {
method: "POST",
// @ts-expect-error
headers: {
"Content-Type": contentType
},
body: readableStream,
duplex: "half"
});
const formData = await fakeRequest.formData();
const action = await decodeAction(formData, serverModuleMap);
if (typeof action === "function") {
// Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest();
const actionReturnedState = await action();
formState = await decodeFormState(actionReturnedState, formData);
}
// Skip the fetch path
return;
}
} else {
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap);
} catch (err) {
if (actionId !== null) {
console.error(err);
}
return {
type: "not-found"
};
}
const chunks = [];
for await (const chunk of req){
chunks.push(Buffer.from(chunk));
}
const actionData = Buffer.concat(chunks).toString("utf-8");
const readableLimit = (serverActions == null ? void 0 : serverActions.bodySizeLimit) ?? "1 MB";
const limit = require("next/dist/compiled/bytes").parse(readableLimit);
if (actionData.length > limit) {
const { ApiError } = require("../api-utils");
throw new ApiError(413, `Body exceeded ${readableLimit} limit.
To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`);
}
if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData);
bound = await decodeReply(formData, serverModuleMap);
} else {
bound = await decodeReply(actionData, serverModuleMap);
}
}
}
// actions.js
// app/page.js
// action worker1
// appRender1
// app/foo/page.js
// action worker2
// appRender
// / -> fire action -> POST / -> appRender1 -> modId for the action file
// /foo -> fire action -> POST /foo -> appRender2 -> modId for the action file
try {
actionModId = actionModId ?? getActionModIdOrError(actionId, serverModuleMap);
} catch (err) {
if (actionId !== null) {
console.error(err);
}
return {
type: "not-found"
};
}
const actionHandler = (await ComponentMod.__next_app__.require(actionModId))[// `actionId` must exist if we got here, as otherwise we would have thrown an error above
actionId];
const returnVal = await actionHandler.apply(null, bound);
// For form actions, we need to continue rendering the page.
if (isFetchAction) {
await addRevalidationHeader(res, {
staticGenerationStore,
requestStore
});
actionResult = await generateFlight(ctx, {
actionResult: Promise.resolve(returnVal),
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated || actionWasForwarded
});
}
});
return {
type: "done",
result: actionResult,
formState
};
} catch (err) {
if ((0, _redirect.isRedirectError)(err)) {
const redirectUrl = (0, _redirect.getURLFromRedirectError)(err);
const statusCode = (0, _redirect.getRedirectStatusCodeFromError)(err);
await addRevalidationHeader(res, {
staticGenerationStore,
requestStore
});
// if it's a fetch action, we'll set the status code for logging/debugging purposes
// but we won't set a Location header, as the redirect will be handled by the client router
res.statusCode = statusCode;
if (isFetchAction) {
return {
type: "done",
result: await createRedirectRenderResult(req, res, host, redirectUrl, ctx.renderOpts.basePath, staticGenerationStore)
};
}
if (err.mutableCookies) {
const headers = new Headers();
// If there were mutable cookies set, we need to set them on the
// response.
if ((0, _requestcookies.appendMutableCookies)(headers, err.mutableCookies)) {
res.setHeader("set-cookie", Array.from(headers.values()));
}
}
res.setHeader("Location", redirectUrl);
return {
type: "done",
result: _renderresult.default.fromStatic("")
};
} else if ((0, _notfound.isNotFoundError)(err)) {
res.statusCode = 404;
await addRevalidationHeader(res, {
staticGenerationStore,
requestStore
});
if (isFetchAction) {
const promise = Promise.reject(err);
try {
// we need to await the promise to trigger the rejection early
// so that it's already handled by the time we call
// the RSC runtime. Otherwise, it will throw an unhandled
// promise rejection error in the renderer.
await promise;
} catch {
// swallow error, it's gonna be handled on the client
}
return {
type: "done",
result: await generateFlight(ctx, {
skipFlight: false,
actionResult: promise,
asNotFound: true
})
};
}
return {
type: "not-found"
};
}
if (isFetchAction) {
res.statusCode = 500;
await Promise.all(Object.values(staticGenerationStore.pendingRevalidates || []));
const promise = Promise.reject(err);
try {
// we need to await the promise to trigger the rejection early
// so that it's already handled by the time we call
// the RSC runtime. Otherwise, it will throw an unhandled
// promise rejection error in the renderer.
await promise;
} catch {
// swallow error, it's gonna be handled on the client
}
return {
type: "done",
result: await generateFlight(ctx, {
actionResult: promise,
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated || actionWasForwarded
})
};
}
throw err;
}
}
/**
* Attempts to find the module ID for the action from the module map. When this fails, it could be a deployment skew where
* the action came from a different deployment. It could also simply be an invalid POST request that is not a server action.
* In either case, we'll throw an error to be handled by the caller.
*/ function getActionModIdOrError(actionId, serverModuleMap) {
try {
var _serverModuleMap_actionId;
// if we're missing the action ID header, we can't do any further processing
if (!actionId) {
throw new Error("Invariant: Missing 'next-action' header.");
}
const actionModId = serverModuleMap == null ? void 0 : (_serverModuleMap_actionId = serverModuleMap[actionId]) == null ? void 0 : _serverModuleMap_actionId.id;
if (!actionModId) {
throw new Error("Invariant: Couldn't find action module ID from module map.");
}
return actionModId;
} catch (err) {
throw new Error(`Failed to find Server Action "${actionId}". This request might be from an older or newer deployment. ${err instanceof Error ? `Original error: ${err.message}` : ""}`);
}
}
//# sourceMappingURL=action-handler.js.map

View File

@@ -0,0 +1,65 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createServerModuleMap: null,
selectWorkerForForwarding: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createServerModuleMap: function() {
return createServerModuleMap;
},
selectWorkerForForwarding: function() {
return selectWorkerForForwarding;
}
});
const _apppaths = require("../../shared/lib/router/utils/app-paths");
const _pathhasprefix = require("../../shared/lib/router/utils/path-has-prefix");
const _removepathprefix = require("../../shared/lib/router/utils/remove-path-prefix");
function createServerModuleMap({ serverActionsManifest, pageName }) {
return new Proxy({}, {
get: (_, id)=>{
return {
id: serverActionsManifest[process.env.NEXT_RUNTIME === "edge" ? "edge" : "node"][id].workers[normalizeWorkerPageName(pageName)],
name: id,
chunks: []
};
}
});
}
function selectWorkerForForwarding(actionId, pageName, serverActionsManifest) {
var _serverActionsManifest__actionId;
const workers = (_serverActionsManifest__actionId = serverActionsManifest[process.env.NEXT_RUNTIME === "edge" ? "edge" : "node"][actionId]) == null ? void 0 : _serverActionsManifest__actionId.workers;
const workerName = normalizeWorkerPageName(pageName);
// no workers, nothing to forward to
if (!workers) return;
// if there is a worker for this page, no need to forward it.
if (workers[workerName]) {
return;
}
// otherwise, grab the first worker that has a handler for this action id
return denormalizeWorkerPageName(Object.keys(workers)[0]);
}
/**
* The flight entry loader keys actions by bundlePath.
* bundlePath corresponds with the relative path (including 'app') to the page entrypoint.
*/ function normalizeWorkerPageName(pageName) {
if ((0, _pathhasprefix.pathHasPrefix)(pageName, "app")) {
return pageName;
}
return "app" + pageName;
}
/**
* Converts a bundlePath (relative path to the entrypoint) to a routable page name
*/ function denormalizeWorkerPageName(bundlePath) {
return (0, _apppaths.normalizeAppPath)((0, _removepathprefix.removePathPrefix)(bundlePath, "app"));
}
//# sourceMappingURL=action-utils.js.map

View File

@@ -0,0 +1,974 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "renderToHTMLOrFlight", {
enumerable: true,
get: function() {
return renderToHTMLOrFlight;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default(require("react"));
const _renderresult = /*#__PURE__*/ _interop_require_default(require("../render-result"));
const _nodewebstreamshelper = require("../stream-utils/node-web-streams-helper");
const _matchsegments = require("../../client/components/match-segments");
const _internalutils = require("../internal-utils");
const _approuterheaders = require("../../client/components/app-router-headers");
const _metadata = require("../../lib/metadata/metadata");
const _requestasyncstoragewrapper = require("../async-storage/request-async-storage-wrapper");
const _staticgenerationasyncstoragewrapper = require("../async-storage/static-generation-async-storage-wrapper");
const _notfound = require("../../client/components/not-found");
const _redirect = require("../../client/components/redirect");
const _patchfetch = require("../lib/patch-fetch");
const _constants = require("../lib/trace/constants");
const _tracer = require("../lib/trace/tracer");
const _flightrenderresult = require("./flight-render-result");
const _createerrorhandler = require("./create-error-handler");
const _getshortdynamicparamtype = require("./get-short-dynamic-param-type");
const _getsegmentparam = require("./get-segment-param");
const _getscriptnoncefromheader = require("./get-script-nonce-from-header");
const _parseandvalidateflightrouterstate = require("./parse-and-validate-flight-router-state");
const _validateurl = require("./validate-url");
const _createflightrouterstatefromloadertree = require("./create-flight-router-state-from-loader-tree");
const _actionhandler = require("./action-handler");
const _bailouttocsr = require("../../shared/lib/lazy-dynamic/bailout-to-csr");
const _log = require("../../build/output/log");
const _requestcookies = require("../web/spec-extension/adapters/request-cookies");
const _serverinsertedhtml = require("./server-inserted-html");
const _requiredscripts = require("./required-scripts");
const _addpathprefix = require("../../shared/lib/router/utils/add-path-prefix");
const _makegetserverinsertedhtml = require("./make-get-server-inserted-html");
const _walktreewithflightrouterstate = require("./walk-tree-with-flight-router-state");
const _createcomponenttree = require("./create-component-tree");
const _getassetquerystring = require("./get-asset-query-string");
const _encryptionutils = require("./encryption-utils");
const _staticrenderer = require("./static/static-renderer");
const _hooksservercontext = require("../../client/components/hooks-server-context");
const _useflightresponse = require("./use-flight-response");
const _staticgenerationbailout = require("../../client/components/static-generation-bailout");
const _interceptionroutes = require("../future/helpers/interception-routes");
const _formatservererror = require("../../lib/format-server-error");
const _dynamicrendering = require("./dynamic-rendering");
const _clientcomponentrendererlogger = require("../client-component-renderer-logger");
const _actionutils = require("./action-utils");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function createNotFoundLoaderTree(loaderTree) {
// Align the segment with parallel-route-default in next-app-loader
return [
"",
{},
loaderTree[2]
];
}
/* This method is important for intercepted routes to function:
* when a route is intercepted, e.g. /blog/[slug], it will be rendered
* with the layout of the previous page, e.g. /profile/[id]. The problem is
* that the loader tree needs to know the dynamic param in order to render (id and slug in the example).
* Normally they are read from the path but since we are intercepting the route, the path would not contain id,
* so we need to read it from the router state.
*/ function findDynamicParamFromRouterState(flightRouterState, segment) {
if (!flightRouterState) {
return null;
}
const treeSegment = flightRouterState[0];
if ((0, _matchsegments.canSegmentBeOverridden)(segment, treeSegment)) {
if (!Array.isArray(treeSegment) || Array.isArray(segment)) {
return null;
}
return {
param: treeSegment[0],
value: treeSegment[1],
treeSegment: treeSegment,
type: treeSegment[2]
};
}
for (const parallelRouterState of Object.values(flightRouterState[1])){
const maybeDynamicParam = findDynamicParamFromRouterState(parallelRouterState, segment);
if (maybeDynamicParam) {
return maybeDynamicParam;
}
}
return null;
}
/**
* Returns a function that parses the dynamic segment and return the associated value.
*/ function makeGetDynamicParamFromSegment(params, flightRouterState) {
return function getDynamicParamFromSegment(// [slug] / [[slug]] / [...slug]
segment) {
const segmentParam = (0, _getsegmentparam.getSegmentParam)(segment);
if (!segmentParam) {
return null;
}
const key = segmentParam.param;
let value = params[key];
// this is a special marker that will be present for interception routes
if (value === "__NEXT_EMPTY_PARAM__") {
value = undefined;
}
if (Array.isArray(value)) {
value = value.map((i)=>encodeURIComponent(i));
} else if (typeof value === "string") {
value = encodeURIComponent(value);
}
if (!value) {
// Handle case where optional catchall does not have a value, e.g. `/dashboard/[...slug]` when requesting `/dashboard`
if (segmentParam.type === "optional-catchall") {
const type = _getshortdynamicparamtype.dynamicParamTypes[segmentParam.type];
return {
param: key,
value: null,
type: type,
// This value always has to be a string.
treeSegment: [
key,
"",
type
]
};
}
return findDynamicParamFromRouterState(flightRouterState, segment);
}
const type = (0, _getshortdynamicparamtype.getShortDynamicParamType)(segmentParam.type);
return {
param: key,
// The value that is passed to user code.
value: value,
// The value that is rendered in the router tree.
treeSegment: [
key,
Array.isArray(value) ? value.join("/") : value,
type
],
type: type
};
};
}
function NonIndex({ ctx }) {
const is404Page = ctx.pagePath === "/404";
const isInvalidStatusCode = typeof ctx.res.statusCode === "number" && ctx.res.statusCode > 400;
if (is404Page || isInvalidStatusCode) {
return /*#__PURE__*/ (0, _jsxruntime.jsx)("meta", {
name: "robots",
content: "noindex"
});
}
return null;
}
// Handle Flight render request. This is only used when client-side navigating. E.g. when you `router.push('/dashboard')` or `router.reload()`.
async function generateFlight(ctx, options) {
// Flight data that is going to be passed to the browser.
// Currently a single item array but in the future multiple patches might be combined in a single request.
let flightData = null;
const { componentMod: { tree: loaderTree, renderToReadableStream, createDynamicallyTrackedSearchParams }, getDynamicParamFromSegment, appUsingSizeAdjustment, staticGenerationStore: { urlPathname }, query, requestId, flightRouterState } = ctx;
if (!(options == null ? void 0 : options.skipFlight)) {
const [MetadataTree, MetadataOutlet] = (0, _metadata.createMetadataComponents)({
tree: loaderTree,
pathname: urlPathname,
trailingSlash: ctx.renderOpts.trailingSlash,
query,
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams
});
flightData = (await (0, _walktreewithflightrouterstate.walkTreeWithFlightRouterState)({
ctx,
createSegmentPath: (child)=>child,
loaderTreeToFilter: loaderTree,
parentParams: {},
flightRouterState,
isFirst: true,
// For flight, render metadata inside leaf page
rscPayloadHead: /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(NonIndex, {
ctx: ctx
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(MetadataTree, {}, requestId)
]
}),
injectedCSS: new Set(),
injectedJS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
asNotFound: ctx.isNotFoundPath || (options == null ? void 0 : options.asNotFound),
metadataOutlet: /*#__PURE__*/ (0, _jsxruntime.jsx)(MetadataOutlet, {})
})).map((path)=>path.slice(1)) // remove the '' (root) segment
;
}
const buildIdFlightDataPair = [
ctx.renderOpts.buildId,
flightData
];
// For app dir, use the bundled version of Flight server renderer (renderToReadableStream)
// which contains the subset React.
const flightReadableStream = renderToReadableStream(options ? [
options.actionResult,
buildIdFlightDataPair
] : buildIdFlightDataPair, ctx.clientReferenceManifest.clientModules, {
onError: ctx.flightDataRendererErrorHandler
});
return new _flightrenderresult.FlightRenderResult(flightReadableStream);
}
/**
* Creates a resolver that eagerly generates a flight payload that is then
* resolved when the resolver is called.
*/ function createFlightDataResolver(ctx) {
// Generate the flight data and as soon as it can, convert it into a string.
const promise = generateFlight(ctx).then(async (result)=>({
flightData: await result.toUnchunkedString(true)
}))// Otherwise if it errored, return the error.
.catch((err)=>({
err
}));
return async ()=>{
// Resolve the promise to get the flight data or error.
const result = await promise;
// If the flight data failed to render due to an error, re-throw the error
// here.
if ("err" in result) {
throw result.err;
}
// Otherwise, return the flight data.
return result.flightData;
};
}
// This is the root component that runs in the RSC context
async function ReactServerApp({ tree, ctx, asNotFound }) {
// Create full component tree from root to leaf.
const injectedCSS = new Set();
const injectedJS = new Set();
const injectedFontPreloadTags = new Set();
const missingSlots = new Set();
const { getDynamicParamFromSegment, query, appUsingSizeAdjustment, componentMod: { AppRouter, GlobalError, createDynamicallyTrackedSearchParams }, staticGenerationStore: { urlPathname } } = ctx;
const initialTree = (0, _createflightrouterstatefromloadertree.createFlightRouterStateFromLoaderTree)(tree, getDynamicParamFromSegment, query);
const [MetadataTree, MetadataOutlet] = (0, _metadata.createMetadataComponents)({
tree,
errorType: asNotFound ? "not-found" : undefined,
pathname: urlPathname,
trailingSlash: ctx.renderOpts.trailingSlash,
query,
getDynamicParamFromSegment: getDynamicParamFromSegment,
appUsingSizeAdjustment: appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams
});
const { seedData, styles } = await (0, _createcomponenttree.createComponentTree)({
ctx,
createSegmentPath: (child)=>child,
loaderTree: tree,
parentParams: {},
firstItem: true,
injectedCSS,
injectedJS,
injectedFontPreloadTags,
rootLayoutIncluded: false,
asNotFound: asNotFound,
metadataOutlet: /*#__PURE__*/ (0, _jsxruntime.jsx)(MetadataOutlet, {}),
missingSlots
});
// When the `vary` response header is present with `Next-URL`, that means there's a chance
// it could respond differently if there's an interception route. We provide this information
// to `AppRouter` so that it can properly seed the prefetch cache with a prefix, if needed.
const varyHeader = ctx.res.getHeader("vary");
const couldBeIntercepted = typeof varyHeader === "string" && varyHeader.includes(_approuterheaders.NEXT_URL);
return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
styles,
/*#__PURE__*/ (0, _jsxruntime.jsx)(AppRouter, {
buildId: ctx.renderOpts.buildId,
assetPrefix: ctx.assetPrefix,
initialCanonicalUrl: urlPathname,
// This is the router state tree.
initialTree: initialTree,
// This is the tree of React nodes that are seeded into the cache
initialSeedData: seedData,
couldBeIntercepted: couldBeIntercepted,
initialHead: /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(NonIndex, {
ctx: ctx
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(MetadataTree, {}, ctx.requestId)
]
}),
globalErrorComponent: GlobalError,
// This is used to provide debug information (when in development mode)
// about which slots were not filled by page components while creating the component tree.
missingSlots: missingSlots
})
]
});
}
// This is the root component that runs in the RSC context
async function ReactServerError({ tree, ctx, errorType }) {
const { getDynamicParamFromSegment, query, appUsingSizeAdjustment, componentMod: { AppRouter, GlobalError, createDynamicallyTrackedSearchParams }, staticGenerationStore: { urlPathname }, requestId } = ctx;
const [MetadataTree] = (0, _metadata.createMetadataComponents)({
tree,
pathname: urlPathname,
trailingSlash: ctx.renderOpts.trailingSlash,
errorType,
query,
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams
});
const head = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(NonIndex, {
ctx: ctx
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(MetadataTree, {}, requestId),
process.env.NODE_ENV === "development" && /*#__PURE__*/ (0, _jsxruntime.jsx)("meta", {
name: "next-error",
content: "not-found"
})
]
});
const initialTree = (0, _createflightrouterstatefromloadertree.createFlightRouterStateFromLoaderTree)(tree, getDynamicParamFromSegment, query);
// For metadata notFound error there's no global not found boundary on top
// so we create a not found page with AppRouter
const initialSeedData = [
initialTree[0],
{},
/*#__PURE__*/ (0, _jsxruntime.jsxs)("html", {
id: "__next_error__",
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)("head", {}),
/*#__PURE__*/ (0, _jsxruntime.jsx)("body", {})
]
}),
null
];
return /*#__PURE__*/ (0, _jsxruntime.jsx)(AppRouter, {
buildId: ctx.renderOpts.buildId,
assetPrefix: ctx.assetPrefix,
initialCanonicalUrl: urlPathname,
initialTree: initialTree,
initialHead: head,
globalErrorComponent: GlobalError,
initialSeedData: initialSeedData,
missingSlots: new Set()
});
}
// This component must run in an SSR context. It will render the RSC root component
function ReactServerEntrypoint({ reactServerStream, preinitScripts, clientReferenceManifest, nonce }) {
preinitScripts();
const response = (0, _useflightresponse.useFlightStream)(reactServerStream, clientReferenceManifest, nonce);
return _react.default.use(response);
}
async function renderToHTMLOrFlightImpl(req, res, pagePath, query, renderOpts, baseCtx, requestEndedState) {
var _getTracer_getRootSpanAttributes, _staticGenerationStore_prerenderState;
const isNotFoundPath = pagePath === "/404";
// A unique request timestamp used by development to ensure that it's
// consistent and won't change during this request. This is important to
// avoid that resources can be deduped by React Float if the same resource is
// rendered or preloaded multiple times: `<link href="a.css?v={Date.now()}"/>`.
const requestTimestamp = Date.now();
const { buildManifest, subresourceIntegrityManifest, serverActionsManifest, ComponentMod, dev, nextFontManifest, supportsDynamicHTML, serverActions, appDirDevErrorLogger, assetPrefix = "", enableTainting } = renderOpts;
// We need to expose the bundled `require` API globally for
// react-server-dom-webpack. This is a hack until we find a better way.
if (ComponentMod.__next_app__) {
const instrumented = (0, _clientcomponentrendererlogger.wrapClientComponentLoader)(ComponentMod);
// @ts-ignore
globalThis.__next_require__ = instrumented.require;
// @ts-ignore
globalThis.__next_chunk_load__ = instrumented.loadChunk;
}
if (typeof req.on === "function") {
req.on("end", ()=>{
requestEndedState.ended = true;
if ("performance" in globalThis) {
const metrics = (0, _clientcomponentrendererlogger.getClientComponentLoaderMetrics)({
reset: true
});
if (metrics) {
(0, _tracer.getTracer)().startSpan(_constants.NextNodeServerSpan.clientComponentLoading, {
startTime: metrics.clientComponentLoadStart,
attributes: {
"next.clientComponentLoadCount": metrics.clientComponentLoadCount
}
}).end(metrics.clientComponentLoadStart + metrics.clientComponentLoadTimes);
}
}
});
}
const metadata = {};
const appUsingSizeAdjustment = !!(nextFontManifest == null ? void 0 : nextFontManifest.appUsingSizeAdjust);
// TODO: fix this typescript
const clientReferenceManifest = renderOpts.clientReferenceManifest;
const serverModuleMap = (0, _actionutils.createServerModuleMap)({
serverActionsManifest,
pageName: renderOpts.page
});
(0, _encryptionutils.setReferenceManifestsSingleton)({
clientReferenceManifest,
serverActionsManifest,
serverModuleMap
});
const digestErrorsMap = new Map();
const allCapturedErrors = [];
const isNextExport = !!renderOpts.nextExport;
const { staticGenerationStore, requestStore } = baseCtx;
const { isStaticGeneration } = staticGenerationStore;
// when static generation fails during PPR, we log the errors separately. We intentionally
// silence the error logger in this case to avoid double logging.
const silenceStaticGenerationErrors = renderOpts.experimental.ppr && isStaticGeneration;
const serverComponentsErrorHandler = (0, _createerrorhandler.createErrorHandler)({
source: _createerrorhandler.ErrorHandlerSource.serverComponents,
dev,
isNextExport,
errorLogger: appDirDevErrorLogger,
digestErrorsMap,
silenceLogger: silenceStaticGenerationErrors
});
const flightDataRendererErrorHandler = (0, _createerrorhandler.createErrorHandler)({
source: _createerrorhandler.ErrorHandlerSource.flightData,
dev,
isNextExport,
errorLogger: appDirDevErrorLogger,
digestErrorsMap,
silenceLogger: silenceStaticGenerationErrors
});
const htmlRendererErrorHandler = (0, _createerrorhandler.createErrorHandler)({
source: _createerrorhandler.ErrorHandlerSource.html,
dev,
isNextExport,
errorLogger: appDirDevErrorLogger,
digestErrorsMap,
allCapturedErrors,
silenceLogger: silenceStaticGenerationErrors
});
ComponentMod.patchFetch();
/**
* Rules of Static & Dynamic HTML:
*
* 1.) We must generate static HTML unless the caller explicitly opts
* in to dynamic HTML support.
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for an AMP page.
*
* These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended.
*/ const generateStaticHTML = supportsDynamicHTML !== true;
// Pull out the hooks/references from the component.
const { tree: loaderTree, taintObjectReference } = ComponentMod;
if (enableTainting) {
taintObjectReference("Do not pass process.env to client components since it will leak sensitive data", process.env);
}
staticGenerationStore.fetchMetrics = [];
metadata.fetchMetrics = staticGenerationStore.fetchMetrics;
// don't modify original query object
query = {
...query
};
(0, _internalutils.stripInternalQueries)(query);
const isRSCRequest = req.headers[_approuterheaders.RSC_HEADER.toLowerCase()] !== undefined;
const isPrefetchRSCRequest = isRSCRequest && req.headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] !== undefined;
/**
* Router state provided from the client-side router. Used to handle rendering
* from the common layout down. This value will be undefined if the request
* is not a client-side navigation request or if the request is a prefetch
* request (except when it's a prefetch request for an interception route
* which is always dynamic).
*/ const shouldProvideFlightRouterState = isRSCRequest && (!isPrefetchRSCRequest || !renderOpts.experimental.ppr || // Interception routes currently depend on the flight router state to
// extract dynamic params.
(0, _interceptionroutes.isInterceptionRouteAppPath)(pagePath));
const parsedFlightRouterState = (0, _parseandvalidateflightrouterstate.parseAndValidateFlightRouterState)(req.headers[_approuterheaders.NEXT_ROUTER_STATE_TREE.toLowerCase()]);
/**
* The metadata items array created in next-app-loader with all relevant information
* that we need to resolve the final metadata.
*/ let requestId;
if (process.env.NEXT_RUNTIME === "edge") {
requestId = crypto.randomUUID();
} else {
requestId = require("next/dist/compiled/nanoid").nanoid();
}
/**
* Dynamic parameters. E.g. when you visit `/dashboard/vercel` which is rendered by `/dashboard/[slug]` the value will be {"slug": "vercel"}.
*/ const params = renderOpts.params ?? {};
const getDynamicParamFromSegment = makeGetDynamicParamFromSegment(params, // `FlightRouterState` is unconditionally provided here because this method uses it
// to extract dynamic params as a fallback if they're not present in the path.
parsedFlightRouterState);
const ctx = {
...baseCtx,
getDynamicParamFromSegment,
query,
isPrefetch: isPrefetchRSCRequest,
requestTimestamp,
appUsingSizeAdjustment,
flightRouterState: shouldProvideFlightRouterState ? parsedFlightRouterState : undefined,
requestId,
defaultRevalidate: false,
pagePath,
clientReferenceManifest,
assetPrefix,
flightDataRendererErrorHandler,
serverComponentsErrorHandler,
isNotFoundPath,
res
};
if (isRSCRequest && !isStaticGeneration) {
return generateFlight(ctx);
}
// Create the resolver that can get the flight payload when it's ready or
// throw the error if it occurred. If we are not generating static HTML, we
// don't need to generate the flight payload because it's a dynamic request
// which means we're either getting the flight payload only or just the
// regular HTML.
const flightDataResolver = isStaticGeneration ? createFlightDataResolver(ctx) : null;
// Get the nonce from the incoming request if it has one.
const csp = req.headers["content-security-policy"] || req.headers["content-security-policy-report-only"];
let nonce;
if (csp && typeof csp === "string") {
nonce = (0, _getscriptnoncefromheader.getScriptNonceFromHeader)(csp);
}
const validateRootLayout = dev;
const { HeadManagerContext } = require("../../shared/lib/head-manager-context.shared-runtime");
// On each render, create a new `ServerInsertedHTML` context to capture
// injected nodes from user code (`useServerInsertedHTML`).
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } = (0, _serverinsertedhtml.createServerInsertedHTML)();
(_getTracer_getRootSpanAttributes = (0, _tracer.getTracer)().getRootSpanAttributes()) == null ? void 0 : _getTracer_getRootSpanAttributes.set("next.route", pagePath);
const renderToStream = (0, _tracer.getTracer)().wrap(_constants.AppRenderSpan.getBodyResult, {
spanName: `render route (app) ${pagePath}`,
attributes: {
"next.route": pagePath
}
}, async ({ asNotFound, tree, formState })=>{
const polyfills = buildManifest.polyfillFiles.filter((polyfill)=>polyfill.endsWith(".js") && !polyfill.endsWith(".module.js")).map((polyfill)=>({
src: `${assetPrefix}/_next/${polyfill}${(0, _getassetquerystring.getAssetQueryString)(ctx, false)}`,
integrity: subresourceIntegrityManifest == null ? void 0 : subresourceIntegrityManifest[polyfill],
crossOrigin: renderOpts.crossOrigin,
noModule: true,
nonce
}));
const [preinitScripts, bootstrapScript] = (0, _requiredscripts.getRequiredScripts)(buildManifest, assetPrefix, renderOpts.crossOrigin, subresourceIntegrityManifest, (0, _getassetquerystring.getAssetQueryString)(ctx, true), nonce);
// We kick off the Flight Request (render) here. It is ok to initiate the render in an arbitrary
// place however it is critical that we only construct the Flight Response inside the SSR
// render so that directives like preloads are correctly piped through
const serverStream = ComponentMod.renderToReadableStream(/*#__PURE__*/ (0, _jsxruntime.jsx)(ReactServerApp, {
tree: tree,
ctx: ctx,
asNotFound: asNotFound
}), clientReferenceManifest.clientModules, {
onError: serverComponentsErrorHandler
});
// We are going to consume this render both for SSR and for inlining the flight data
let [renderStream, dataStream] = serverStream.tee();
const children = /*#__PURE__*/ (0, _jsxruntime.jsx)(HeadManagerContext.Provider, {
value: {
appDir: true,
nonce
},
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(ServerInsertedHTMLProvider, {
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(ReactServerEntrypoint, {
reactServerStream: renderStream,
preinitScripts: preinitScripts,
clientReferenceManifest: clientReferenceManifest,
nonce: nonce
})
})
});
const isResume = !!renderOpts.postponed;
const onHeaders = staticGenerationStore.prerenderState ? (headers)=>{
headers.forEach((value, key)=>{
metadata.headers ??= {};
metadata.headers[key] = value;
});
} : isStaticGeneration || isResume ? // ask React to emit headers. For Resume this is just not supported
// For static generation we know there will be an entire HTML document
// output and so moving from tag to header for preloading can only
// server to alter preloading priorities in unwanted ways
undefined : // early headers to the response
(headers)=>{
headers.forEach((value, key)=>{
res.appendHeader(key, value);
});
};
const getServerInsertedHTML = (0, _makegetserverinsertedhtml.makeGetServerInsertedHTML)({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath: renderOpts.basePath
});
const renderer = (0, _staticrenderer.createStaticRenderer)({
ppr: renderOpts.experimental.ppr,
isStaticGeneration,
// If provided, the postpone state should be parsed as JSON so it can be
// provided to React.
postponed: typeof renderOpts.postponed === "string" ? JSON.parse(renderOpts.postponed) : null,
streamOptions: {
onError: htmlRendererErrorHandler,
onHeaders,
maxHeadersLength: 600,
nonce,
bootstrapScripts: [
bootstrapScript
],
formState
}
});
try {
let { stream, postponed, resumed } = await renderer.render(children);
const prerenderState = staticGenerationStore.prerenderState;
if (prerenderState) {
/**
* When prerendering there are three outcomes to consider
*
* Dynamic HTML: The prerender has dynamic holes (caused by using Next.js Dynamic Rendering APIs)
* We will need to resume this result when requests are handled and we don't include
* any server inserted HTML or inlined flight data in the static HTML
*
* Dynamic Data: The prerender has no dynamic holes but dynamic APIs were used. We will not
* resume this render when requests are handled but we will generate new inlined
* flight data since it is dynamic and differences may end up reconciling on the client
*
* Static: The prerender has no dynamic holes and no dynamic APIs were used. We statically encode
* all server inserted HTML and flight data
*/ // First we check if we have any dynamic holes in our HTML prerender
if ((0, _dynamicrendering.usedDynamicAPIs)(prerenderState)) {
if (postponed != null) {
// This is the Dynamic HTML case.
metadata.postponed = JSON.stringify((0, _staticrenderer.getDynamicHTMLPostponedState)(postponed));
} else {
// This is the Dynamic Data case
metadata.postponed = JSON.stringify((0, _staticrenderer.getDynamicDataPostponedState)());
}
// Regardless of whether this is the Dynamic HTML or Dynamic Data case we need to ensure we include
// server inserted html in the static response because the html that is part of the prerender may depend on it
// It is possible in the set of stream transforms for Dynamic HTML vs Dynamic Data may differ but currently both states
// require the same set so we unify the code path here
return {
stream: await (0, _nodewebstreamshelper.continueDynamicPrerender)(stream, {
getServerInsertedHTML
})
};
} else {
// We may still be rendering the RSC stream even though the HTML is finished.
// We wait for the RSC stream to complete and check again if dynamic was used
const [original, flightSpy] = dataStream.tee();
dataStream = original;
await (0, _useflightresponse.flightRenderComplete)(flightSpy);
if ((0, _dynamicrendering.usedDynamicAPIs)(prerenderState)) {
// This is the same logic above just repeated after ensuring the RSC stream itself has completed
if (postponed != null) {
// This is the Dynamic HTML case.
metadata.postponed = JSON.stringify((0, _staticrenderer.getDynamicHTMLPostponedState)(postponed));
} else {
// This is the Dynamic Data case
metadata.postponed = JSON.stringify((0, _staticrenderer.getDynamicDataPostponedState)());
}
// Regardless of whether this is the Dynamic HTML or Dynamic Data case we need to ensure we include
// server inserted html in the static response because the html that is part of the prerender may depend on it
// It is possible in the set of stream transforms for Dynamic HTML vs Dynamic Data may differ but currently both states
// require the same set so we unify the code path here
return {
stream: await (0, _nodewebstreamshelper.continueDynamicPrerender)(stream, {
getServerInsertedHTML
})
};
} else {
// This is the Static case
// We still have not used any dynamic APIs. At this point we can produce an entirely static prerender response
let renderedHTMLStream = stream;
if (staticGenerationStore.forceDynamic) {
throw new _staticgenerationbailout.StaticGenBailoutError('Invariant: a Page with `dynamic = "force-dynamic"` did not trigger the dynamic pathway. This is a bug in Next.js');
}
if (postponed != null) {
// We postponed but nothing dynamic was used. We resume the render now and immediately abort it
// so we can set all the postponed boundaries to client render mode before we store the HTML response
const resumeRenderer = (0, _staticrenderer.createStaticRenderer)({
ppr: true,
isStaticGeneration: false,
postponed: (0, _staticrenderer.getDynamicHTMLPostponedState)(postponed),
streamOptions: {
signal: (0, _dynamicrendering.createPostponedAbortSignal)("static prerender resume"),
onError: htmlRendererErrorHandler,
nonce
}
});
// We don't actually want to render anything so we just pass a stream
// that never resolves. The resume call is going to abort immediately anyway
const foreverStream = new ReadableStream();
const resumeChildren = /*#__PURE__*/ (0, _jsxruntime.jsx)(HeadManagerContext.Provider, {
value: {
appDir: true,
nonce
},
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(ServerInsertedHTMLProvider, {
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(ReactServerEntrypoint, {
reactServerStream: foreverStream,
preinitScripts: ()=>{},
clientReferenceManifest: clientReferenceManifest,
nonce: nonce
})
})
});
const { stream: resumeStream } = await resumeRenderer.render(resumeChildren);
// First we write everything from the prerender, then we write everything from the aborted resume render
renderedHTMLStream = (0, _nodewebstreamshelper.chainStreams)(stream, resumeStream);
}
return {
stream: await (0, _nodewebstreamshelper.continueStaticPrerender)(renderedHTMLStream, {
inlinedDataStream: (0, _useflightresponse.createInlinedDataReadableStream)(dataStream, nonce, formState),
getServerInsertedHTML
})
};
}
}
} else if (renderOpts.postponed) {
// This is a continuation of either an Incomplete or Dynamic Data Prerender.
const inlinedDataStream = (0, _useflightresponse.createInlinedDataReadableStream)(dataStream, nonce, formState);
if (resumed) {
// We have new HTML to stream and we also need to include server inserted HTML
return {
stream: await (0, _nodewebstreamshelper.continueDynamicHTMLResume)(stream, {
inlinedDataStream,
getServerInsertedHTML
})
};
} else {
// We are continuing a Dynamic Data Prerender and simply need to append new inlined flight data
return {
stream: await (0, _nodewebstreamshelper.continueDynamicDataResume)(stream, {
inlinedDataStream
})
};
}
} else {
// This may be a static render or a dynamic render
// @TODO factor this further to make the render types more clearly defined and remove
// the deluge of optional params that passed to configure the various behaviors
return {
stream: await (0, _nodewebstreamshelper.continueFizzStream)(stream, {
inlinedDataStream: (0, _useflightresponse.createInlinedDataReadableStream)(dataStream, nonce, formState),
isStaticGeneration: isStaticGeneration || generateStaticHTML,
getServerInsertedHTML,
serverInsertedHTMLToHead: true,
validateRootLayout
})
};
}
} catch (err) {
if ((0, _staticgenerationbailout.isStaticGenBailoutError)(err) || typeof err === "object" && err !== null && "message" in err && typeof err.message === "string" && err.message.includes("https://nextjs.org/docs/advanced-features/static-html-export")) {
// Ensure that "next dev" prints the red error overlay
throw err;
}
// If this is a static generation error, we need to throw it so that it
// can be handled by the caller if we're in static generation mode.
if (isStaticGeneration && (0, _hooksservercontext.isDynamicServerError)(err)) {
throw err;
}
// If a bailout made it to this point, it means it wasn't wrapped inside
// a suspense boundary.
const shouldBailoutToCSR = (0, _bailouttocsr.isBailoutToCSRError)(err);
if (shouldBailoutToCSR) {
const stack = (0, _formatservererror.getStackWithoutErrorMessage)(err);
if (renderOpts.experimental.missingSuspenseWithCSRBailout) {
(0, _log.error)(`${err.reason} should be wrapped in a suspense boundary at page "${pagePath}". Read more: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n${stack}`);
throw err;
}
(0, _log.warn)(`Entire page "${pagePath}" deopted into client-side rendering due to "${err.reason}". Read more: https://nextjs.org/docs/messages/deopted-into-client-rendering\n${stack}`);
}
if ((0, _notfound.isNotFoundError)(err)) {
res.statusCode = 404;
}
let hasRedirectError = false;
if ((0, _redirect.isRedirectError)(err)) {
hasRedirectError = true;
res.statusCode = (0, _redirect.getRedirectStatusCodeFromError)(err);
if (err.mutableCookies) {
const headers = new Headers();
// If there were mutable cookies set, we need to set them on the
// response.
if ((0, _requestcookies.appendMutableCookies)(headers, err.mutableCookies)) {
res.setHeader("set-cookie", Array.from(headers.values()));
}
}
const redirectUrl = (0, _addpathprefix.addPathPrefix)((0, _redirect.getURLFromRedirectError)(err), renderOpts.basePath);
res.setHeader("Location", redirectUrl);
}
const is404 = ctx.res.statusCode === 404;
if (!is404 && !hasRedirectError && !shouldBailoutToCSR) {
res.statusCode = 500;
}
const errorType = is404 ? "not-found" : hasRedirectError ? "redirect" : undefined;
const [errorPreinitScripts, errorBootstrapScript] = (0, _requiredscripts.getRequiredScripts)(buildManifest, assetPrefix, renderOpts.crossOrigin, subresourceIntegrityManifest, (0, _getassetquerystring.getAssetQueryString)(ctx, false), nonce);
const errorServerStream = ComponentMod.renderToReadableStream(/*#__PURE__*/ (0, _jsxruntime.jsx)(ReactServerError, {
tree: tree,
ctx: ctx,
errorType: errorType
}), clientReferenceManifest.clientModules, {
onError: serverComponentsErrorHandler
});
try {
const fizzStream = await (0, _nodewebstreamshelper.renderToInitialFizzStream)({
ReactDOMServer: require("react-dom/server.edge"),
element: /*#__PURE__*/ (0, _jsxruntime.jsx)(ReactServerEntrypoint, {
reactServerStream: errorServerStream,
preinitScripts: errorPreinitScripts,
clientReferenceManifest: clientReferenceManifest,
nonce: nonce
}),
streamOptions: {
nonce,
// Include hydration scripts in the HTML
bootstrapScripts: [
errorBootstrapScript
],
formState
}
});
return {
// Returning the error that was thrown so it can be used to handle
// the response in the caller.
err,
stream: await (0, _nodewebstreamshelper.continueFizzStream)(fizzStream, {
inlinedDataStream: (0, _useflightresponse.createInlinedDataReadableStream)(// This is intentionally using the readable datastream from the
// main render rather than the flight data from the error page
// render
dataStream, nonce, formState),
isStaticGeneration,
getServerInsertedHTML: (0, _makegetserverinsertedhtml.makeGetServerInsertedHTML)({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: [],
basePath: renderOpts.basePath
}),
serverInsertedHTMLToHead: true,
validateRootLayout
})
};
} catch (finalErr) {
if (process.env.NODE_ENV === "development" && (0, _notfound.isNotFoundError)(finalErr)) {
const bailOnNotFound = require("../../client/components/dev-root-not-found-boundary").bailOnNotFound;
bailOnNotFound();
}
throw finalErr;
}
}
});
// For action requests, we handle them differently with a special render result.
const actionRequestResult = await (0, _actionhandler.handleAction)({
req,
res,
ComponentMod,
serverModuleMap,
generateFlight,
staticGenerationStore,
requestStore,
serverActions,
ctx
});
let formState = null;
if (actionRequestResult) {
if (actionRequestResult.type === "not-found") {
const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree);
const response = await renderToStream({
asNotFound: true,
tree: notFoundLoaderTree,
formState
});
return new _renderresult.default(response.stream, {
metadata
});
} else if (actionRequestResult.type === "done") {
if (actionRequestResult.result) {
actionRequestResult.result.assignMetadata(metadata);
return actionRequestResult.result;
} else if (actionRequestResult.formState) {
formState = actionRequestResult.formState;
}
}
}
const options = {
metadata
};
let response = await renderToStream({
asNotFound: isNotFoundPath,
tree: loaderTree,
formState
});
// If we have pending revalidates, wait until they are all resolved.
if (staticGenerationStore.pendingRevalidates) {
options.waitUntil = Promise.all(Object.values(staticGenerationStore.pendingRevalidates));
}
(0, _patchfetch.addImplicitTags)(staticGenerationStore);
if (staticGenerationStore.tags) {
metadata.fetchTags = staticGenerationStore.tags.join(",");
}
// Create the new render result for the response.
const result = new _renderresult.default(response.stream, options);
// If we aren't performing static generation, we can return the result now.
if (!isStaticGeneration) {
return result;
}
// If this is static generation, we should read this in now rather than
// sending it back to be sent to the client.
response.stream = await result.toUnchunkedString(true);
const buildFailingError = digestErrorsMap.size > 0 ? digestErrorsMap.values().next().value : null;
// If we're debugging partial prerendering, print all the dynamic API accesses
// that occurred during the render.
if (staticGenerationStore.prerenderState && (0, _dynamicrendering.usedDynamicAPIs)(staticGenerationStore.prerenderState) && ((_staticGenerationStore_prerenderState = staticGenerationStore.prerenderState) == null ? void 0 : _staticGenerationStore_prerenderState.isDebugSkeleton)) {
(0, _log.warn)("The following dynamic usage was detected:");
for (const access of (0, _dynamicrendering.formatDynamicAPIAccesses)(staticGenerationStore.prerenderState)){
(0, _log.warn)(access);
}
}
if (!flightDataResolver) {
throw new Error("Invariant: Flight data resolver is missing when generating static HTML");
}
// If we encountered any unexpected errors during build we fail the
// prerendering phase and the build.
if (buildFailingError) {
throw buildFailingError;
}
// Wait for and collect the flight payload data if we don't have it
// already
const flightData = await flightDataResolver();
if (flightData) {
metadata.flightData = flightData;
}
// If force static is specifically set to false, we should not revalidate
// the page.
if (staticGenerationStore.forceStatic === false) {
staticGenerationStore.revalidate = 0;
}
// Copy the revalidation value onto the render result metadata.
metadata.revalidate = staticGenerationStore.revalidate ?? ctx.defaultRevalidate;
// provide bailout info for debugging
if (metadata.revalidate === 0) {
metadata.staticBailoutInfo = {
description: staticGenerationStore.dynamicUsageDescription,
stack: staticGenerationStore.dynamicUsageStack
};
}
return new _renderresult.default(response.stream, options);
}
const renderToHTMLOrFlight = (req, res, pagePath, query, renderOpts)=>{
// TODO: this includes query string, should it?
const pathname = (0, _validateurl.validateURL)(req.url);
return _requestasyncstoragewrapper.RequestAsyncStorageWrapper.wrap(renderOpts.ComponentMod.requestAsyncStorage, {
req,
res,
renderOpts
}, (requestStore)=>_staticgenerationasyncstoragewrapper.StaticGenerationAsyncStorageWrapper.wrap(renderOpts.ComponentMod.staticGenerationAsyncStorage, {
urlPathname: pathname,
renderOpts,
requestEndedState: {
ended: false
}
}, (staticGenerationStore)=>renderToHTMLOrFlightImpl(req, res, pagePath, query, renderOpts, {
requestStore,
staticGenerationStore,
componentMod: renderOpts.ComponentMod,
renderOpts
}, staticGenerationStore.requestEndedState || {})));
};
//# sourceMappingURL=app-render.js.map

View File

@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createComponentStylesAndScripts", {
enumerable: true,
get: function() {
return createComponentStylesAndScripts;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default(require("react"));
const _interopdefault = require("./interop-default");
const _getcssinlinedlinktags = require("./get-css-inlined-link-tags");
const _getassetquerystring = require("./get-asset-query-string");
const _encodeuripath = require("../../shared/lib/encode-uri-path");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function createComponentStylesAndScripts({ filePath, getComponent, injectedCSS, injectedJS, ctx }) {
const { styles: cssHrefs, scripts: jsHrefs } = (0, _getcssinlinedlinktags.getLinkAndScriptTags)(ctx.clientReferenceManifest, filePath, injectedCSS, injectedJS);
const styles = cssHrefs ? cssHrefs.map((href, index)=>{
const fullHref = `${ctx.assetPrefix}/_next/${(0, _encodeuripath.encodeURIPath)(href)}${(0, _getassetquerystring.getAssetQueryString)(ctx, true)}`;
// `Precedence` is an opt-in signal for React to handle resource
// loading and deduplication, etc. It's also used as the key to sort
// resources so they will be injected in the correct order.
// During HMR, it's critical to use different `precedence` values
// for different stylesheets, so their order will be kept.
// https://github.com/facebook/react/pull/25060
const precedence = process.env.NODE_ENV === "development" ? "next_" + href : "next";
return /*#__PURE__*/ (0, _jsxruntime.jsx)("link", {
rel: "stylesheet",
href: fullHref,
// @ts-ignore
precedence: precedence,
crossOrigin: ctx.renderOpts.crossOrigin
}, index);
}) : null;
const scripts = jsHrefs ? jsHrefs.map((href)=>/*#__PURE__*/ (0, _jsxruntime.jsx)("script", {
src: `${ctx.assetPrefix}/_next/${(0, _encodeuripath.encodeURIPath)(href)}${(0, _getassetquerystring.getAssetQueryString)(ctx, true)}`,
async: true
})) : null;
const Comp = (0, _interopdefault.interopDefault)(await getComponent());
return [
Comp,
styles,
scripts
];
}
//# sourceMappingURL=create-component-styles-and-scripts.js.map

View File

@@ -0,0 +1,452 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createComponentTree", {
enumerable: true,
get: function() {
return createComponentTree;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default(require("react"));
const _clientreference = require("../../lib/client-reference");
const _appdirmodule = require("../lib/app-dir-module");
const _interopdefault = require("./interop-default");
const _parseloadertree = require("./parse-loader-tree");
const _createcomponentstylesandscripts = require("./create-component-styles-and-scripts");
const _getlayerassets = require("./get-layer-assets");
const _hasloadingcomponentintree = require("./has-loading-component-in-tree");
const _patchfetch = require("../lib/patch-fetch");
const _parallelroutedefault = require("../../client/components/parallel-route-default");
const _tracer = require("../lib/trace/tracer");
const _constants = require("../lib/trace/constants");
const _staticgenerationbailout = require("../../client/components/static-generation-bailout");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function createComponentTree(props) {
return (0, _tracer.getTracer)().trace(_constants.NextNodeServerSpan.createComponentTree, {
spanName: "build component tree"
}, ()=>createComponentTreeInternal(props));
}
async function createComponentTreeInternal({ createSegmentPath, loaderTree: tree, parentParams, firstItem, rootLayoutIncluded, injectedCSS, injectedJS, injectedFontPreloadTags, asNotFound, metadataOutlet, ctx, missingSlots }) {
const { renderOpts: { nextConfigOutput, experimental }, staticGenerationStore, componentMod: { NotFoundBoundary, LayoutRouter, RenderFromTemplateContext, ClientPageRoot, createUntrackedSearchParams, createDynamicallyTrackedSearchParams, serverHooks: { DynamicServerError }, Postpone }, pagePath, getDynamicParamFromSegment, isPrefetch, query } = ctx;
const { page, layoutOrPagePath, segment, components, parallelRoutes } = (0, _parseloadertree.parseLoaderTree)(tree);
const { layout, template, error, loading, "not-found": notFound } = components;
const injectedCSSWithCurrentLayout = new Set(injectedCSS);
const injectedJSWithCurrentLayout = new Set(injectedJS);
const injectedFontPreloadTagsWithCurrentLayout = new Set(injectedFontPreloadTags);
const layerAssets = (0, _getlayerassets.getLayerAssets)({
ctx,
layoutOrPagePath,
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout
});
const [Template, templateStyles, templateScripts] = template ? await (0, _createcomponentstylesandscripts.createComponentStylesAndScripts)({
ctx,
filePath: template[1],
getComponent: template[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout
}) : [
_react.default.Fragment
];
const [ErrorComponent, errorStyles, errorScripts] = error ? await (0, _createcomponentstylesandscripts.createComponentStylesAndScripts)({
ctx,
filePath: error[1],
getComponent: error[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout
}) : [];
const [Loading, loadingStyles, loadingScripts] = loading ? await (0, _createcomponentstylesandscripts.createComponentStylesAndScripts)({
ctx,
filePath: loading[1],
getComponent: loading[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout
}) : [];
const isLayout = typeof layout !== "undefined";
const isPage = typeof page !== "undefined";
const [layoutOrPageMod] = await (0, _tracer.getTracer)().trace(_constants.NextNodeServerSpan.getLayoutOrPageModule, {
hideSpan: !(isLayout || isPage),
spanName: "resolve segment modules",
attributes: {
"next.segment": segment
}
}, ()=>(0, _appdirmodule.getLayoutOrPageModule)(tree));
/**
* Checks if the current segment is a root layout.
*/ const rootLayoutAtThisLevel = isLayout && !rootLayoutIncluded;
/**
* Checks if the current segment or any level above it has a root layout.
*/ const rootLayoutIncludedAtThisLevelOrAbove = rootLayoutIncluded || rootLayoutAtThisLevel;
const [NotFound, notFoundStyles] = notFound ? await (0, _createcomponentstylesandscripts.createComponentStylesAndScripts)({
ctx,
filePath: notFound[1],
getComponent: notFound[0],
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout
}) : [];
let dynamic = layoutOrPageMod == null ? void 0 : layoutOrPageMod.dynamic;
if (nextConfigOutput === "export") {
if (!dynamic || dynamic === "auto") {
dynamic = "error";
} else if (dynamic === "force-dynamic") {
// force-dynamic is always incompatible with 'export'. We must interrupt the build
throw new _staticgenerationbailout.StaticGenBailoutError(`Page with \`dynamic = "force-dynamic"\` couldn't be exported. \`output: "export"\` requires all pages be renderable statically because there is not runtime server to dynamic render routes in this output format. Learn more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports`);
}
}
if (typeof dynamic === "string") {
// the nested most config wins so we only force-static
// if it's configured above any parent that configured
// otherwise
if (dynamic === "error") {
staticGenerationStore.dynamicShouldError = true;
} else if (dynamic === "force-dynamic") {
staticGenerationStore.forceDynamic = true;
// TODO: (PPR) remove this bailout once PPR is the default
if (staticGenerationStore.isStaticGeneration && !staticGenerationStore.prerenderState) {
// If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
const err = new DynamicServerError(`Page with \`dynamic = "force-dynamic"\` won't be rendered statically.`);
staticGenerationStore.dynamicUsageDescription = err.message;
staticGenerationStore.dynamicUsageStack = err.stack;
throw err;
}
} else {
staticGenerationStore.dynamicShouldError = false;
staticGenerationStore.forceStatic = dynamic === "force-static";
}
}
if (typeof (layoutOrPageMod == null ? void 0 : layoutOrPageMod.fetchCache) === "string") {
staticGenerationStore.fetchCache = layoutOrPageMod == null ? void 0 : layoutOrPageMod.fetchCache;
}
if (typeof (layoutOrPageMod == null ? void 0 : layoutOrPageMod.revalidate) !== "undefined") {
(0, _patchfetch.validateRevalidate)(layoutOrPageMod == null ? void 0 : layoutOrPageMod.revalidate, staticGenerationStore.urlPathname);
}
if (typeof (layoutOrPageMod == null ? void 0 : layoutOrPageMod.revalidate) === "number") {
ctx.defaultRevalidate = layoutOrPageMod.revalidate;
if (typeof staticGenerationStore.revalidate === "undefined" || typeof staticGenerationStore.revalidate === "number" && staticGenerationStore.revalidate > ctx.defaultRevalidate) {
staticGenerationStore.revalidate = ctx.defaultRevalidate;
}
if (!staticGenerationStore.forceStatic && staticGenerationStore.isStaticGeneration && ctx.defaultRevalidate === 0 && // If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
!staticGenerationStore.prerenderState) {
const dynamicUsageDescription = `revalidate: 0 configured ${segment}`;
staticGenerationStore.dynamicUsageDescription = dynamicUsageDescription;
throw new DynamicServerError(dynamicUsageDescription);
}
}
// If there's a dynamic usage error attached to the store, throw it.
if (staticGenerationStore.dynamicUsageErr) {
throw staticGenerationStore.dynamicUsageErr;
}
const LayoutOrPage = layoutOrPageMod ? (0, _interopdefault.interopDefault)(layoutOrPageMod) : undefined;
/**
* The React Component to render.
*/ let Component = LayoutOrPage;
const parallelKeys = Object.keys(parallelRoutes);
const hasSlotKey = parallelKeys.length > 1;
// TODO-APP: This is a hack to support unmatched parallel routes, which will throw `notFound()`.
// This ensures that a `NotFoundBoundary` is available for when that happens,
// but it's not ideal, as it needlessly invokes the `NotFound` component and renders the `RootLayout` twice.
// We should instead look into handling the fallback behavior differently in development mode so that it doesn't
// rely on the `NotFound` behavior.
if (hasSlotKey && rootLayoutAtThisLevel && LayoutOrPage) {
Component = (componentProps)=>{
const NotFoundComponent = NotFound;
const RootLayoutComponent = LayoutOrPage;
return /*#__PURE__*/ (0, _jsxruntime.jsx)(NotFoundBoundary, {
notFound: NotFoundComponent ? /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
layerAssets,
/*#__PURE__*/ (0, _jsxruntime.jsxs)(RootLayoutComponent, {
params: componentProps.params,
children: [
notFoundStyles,
/*#__PURE__*/ (0, _jsxruntime.jsx)(NotFoundComponent, {})
]
})
]
}) : undefined,
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(RootLayoutComponent, {
...componentProps
})
});
};
}
if (process.env.NODE_ENV === "development") {
const { isValidElementType } = require("next/dist/compiled/react-is");
if ((isPage || typeof Component !== "undefined") && !isValidElementType(Component)) {
throw new Error(`The default export is not a React Component in page: "${pagePath}"`);
}
if (typeof ErrorComponent !== "undefined" && !isValidElementType(ErrorComponent)) {
throw new Error(`The default export of error is not a React Component in page: ${segment}`);
}
if (typeof Loading !== "undefined" && !isValidElementType(Loading)) {
throw new Error(`The default export of loading is not a React Component in ${segment}`);
}
if (typeof NotFound !== "undefined" && !isValidElementType(NotFound)) {
throw new Error(`The default export of notFound is not a React Component in ${segment}`);
}
}
// Handle dynamic segment params.
const segmentParam = getDynamicParamFromSegment(segment);
/**
* Create object holding the parent params and current params
*/ const currentParams = // Handle null case where dynamic param is optional
segmentParam && segmentParam.value !== null ? {
...parentParams,
[segmentParam.param]: segmentParam.value
} : parentParams;
// Resolve the segment param
const actualSegment = segmentParam ? segmentParam.treeSegment : segment;
//
// TODO: Combine this `map` traversal with the loop below that turns the array
// into an object.
const parallelRouteMap = await Promise.all(Object.keys(parallelRoutes).map(async (parallelRouteKey)=>{
const isChildrenRouteKey = parallelRouteKey === "children";
const currentSegmentPath = firstItem ? [
parallelRouteKey
] : [
actualSegment,
parallelRouteKey
];
const parallelRoute = parallelRoutes[parallelRouteKey];
const notFoundComponent = NotFound && isChildrenRouteKey ? /*#__PURE__*/ (0, _jsxruntime.jsx)(NotFound, {}) : undefined;
// if we're prefetching and that there's a Loading component, we bail out
// otherwise we keep rendering for the prefetch.
// We also want to bail out if there's no Loading component in the tree.
let currentStyles = undefined;
let childCacheNodeSeedData = null;
if (// Before PPR, the way instant navigations work in Next.js is we
// prefetch everything up to the first route segment that defines a
// loading.tsx boundary. (We do the same if there's no loading
// boundary in the entire tree, because we don't want to prefetch too
// much) The rest of the tree is defered until the actual navigation.
// It does not take into account whether the data is dynamic — even if
// the tree is completely static, it will still defer everything
// inside the loading boundary.
//
// This behavior predates PPR and is only relevant if the
// PPR flag is not enabled.
isPrefetch && (Loading || !(0, _hasloadingcomponentintree.hasLoadingComponentInTree)(parallelRoute)) && // The approach with PPR is different — loading.tsx behaves like a
// regular Suspense boundary and has no special behavior.
//
// With PPR, we prefetch as deeply as possible, and only defer when
// dynamic data is accessed. If so, we only defer the nearest parent
// Suspense boundary of the dynamic data access, regardless of whether
// the boundary is defined by loading.tsx or a normal <Suspense>
// component in userspace.
//
// NOTE: In practice this usually means we'll end up prefetching more
// than we were before PPR, which may or may not be considered a
// performance regression by some apps. The plan is to address this
// before General Availability of PPR by introducing granular
// per-segment fetching, so we can reuse as much of the tree as
// possible during both prefetches and dynamic navigations. But during
// the beta period, we should be clear about this trade off in our
// communications.
!experimental.ppr) {
// Don't prefetch this child. This will trigger a lazy fetch by the
// client router.
} else {
// Create the child component
if (process.env.NODE_ENV === "development" && missingSlots) {
var _parsedTree_layoutOrPagePath;
// When we detect the default fallback (which triggers a 404), we collect the missing slots
// to provide more helpful debug information during development mode.
const parsedTree = (0, _parseloadertree.parseLoaderTree)(parallelRoute);
if ((_parsedTree_layoutOrPagePath = parsedTree.layoutOrPagePath) == null ? void 0 : _parsedTree_layoutOrPagePath.endsWith(_parallelroutedefault.PARALLEL_ROUTE_DEFAULT_PATH)) {
missingSlots.add(parallelRouteKey);
}
}
const { seedData, styles: childComponentStyles } = await createComponentTreeInternal({
createSegmentPath: (child)=>{
return createSegmentPath([
...currentSegmentPath,
...child
]);
},
loaderTree: parallelRoute,
parentParams: currentParams,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
asNotFound,
metadataOutlet,
ctx,
missingSlots
});
currentStyles = childComponentStyles;
childCacheNodeSeedData = seedData;
}
// This is turned back into an object below.
return [
parallelRouteKey,
/*#__PURE__*/ (0, _jsxruntime.jsx)(LayoutRouter, {
parallelRouterKey: parallelRouteKey,
segmentPath: createSegmentPath(currentSegmentPath),
// TODO-APP: Add test for loading returning `undefined`. This currently can't be tested as the `webdriver()` tab will wait for the full page to load before returning.
error: ErrorComponent,
errorStyles: errorStyles,
errorScripts: errorScripts,
template: /*#__PURE__*/ (0, _jsxruntime.jsx)(Template, {
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(RenderFromTemplateContext, {})
}),
templateStyles: templateStyles,
templateScripts: templateScripts,
notFound: notFoundComponent,
notFoundStyles: notFoundStyles,
styles: currentStyles
}),
childCacheNodeSeedData
];
}));
// Convert the parallel route map into an object after all promises have been resolved.
let parallelRouteProps = {};
let parallelRouteCacheNodeSeedData = {};
for (const parallelRoute of parallelRouteMap){
const [parallelRouteKey, parallelRouteProp, flightData] = parallelRoute;
parallelRouteProps[parallelRouteKey] = parallelRouteProp;
parallelRouteCacheNodeSeedData[parallelRouteKey] = flightData;
}
const loadingData = Loading ? [
/*#__PURE__*/ (0, _jsxruntime.jsx)(Loading, {}),
loadingStyles,
loadingScripts
] : null;
// When the segment does not have a layout or page we still have to add the layout router to ensure the path holds the loading component
if (!Component) {
return {
seedData: [
actualSegment,
parallelRouteCacheNodeSeedData,
// TODO: I don't think the extra fragment is necessary. React treats top
// level fragments as transparent, i.e. the runtime behavior should be
// identical even without it. But maybe there's some findDOMNode-related
// reason that I'm not aware of, so I'm leaving it as-is out of extreme
// caution, for now.
/*#__PURE__*/ (0, _jsxruntime.jsx)(_jsxruntime.Fragment, {
children: parallelRouteProps.children
}),
loadingData
],
styles: layerAssets
};
}
// If force-dynamic is used and the current render supports postponing, we
// replace it with a node that will postpone the render. This ensures that the
// postpone is invoked during the react render phase and not during the next
// render phase.
// @TODO this does not actually do what it seems like it would or should do. The idea is that
// if we are rendering in a force-dynamic mode and we can postpone we should only make the segments
// that ask for force-dynamic to be dynamic, allowing other segments to still prerender. However
// because this comes after the children traversal and the static generation store is mutated every segment
// along the parent path of a force-dynamic segment will hit this condition effectively making the entire
// render force-dynamic. We should refactor this function so that we can correctly track which segments
// need to be dynamic
if (staticGenerationStore.forceDynamic && staticGenerationStore.prerenderState) {
return {
seedData: [
actualSegment,
parallelRouteCacheNodeSeedData,
/*#__PURE__*/ (0, _jsxruntime.jsx)(Postpone, {
prerenderState: staticGenerationStore.prerenderState,
reason: 'dynamic = "force-dynamic" was used',
pathname: staticGenerationStore.urlPathname
}),
loadingData
],
styles: layerAssets
};
}
const isClientComponent = (0, _clientreference.isClientReference)(layoutOrPageMod);
// We avoid cloning this object because it gets consumed here exclusively.
const props = parallelRouteProps;
// If it's a not found route, and we don't have any matched parallel
// routes, we try to render the not found component if it exists.
if (NotFound && asNotFound && // In development, it could hit the parallel-route-default not found, so we only need to check the segment.
// Or if there's no parallel routes means it reaches the end.
!parallelRouteMap.length) {
props.children = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)("meta", {
name: "robots",
content: "noindex"
}),
process.env.NODE_ENV === "development" && /*#__PURE__*/ (0, _jsxruntime.jsx)("meta", {
name: "next-error",
content: "not-found"
}),
notFoundStyles,
/*#__PURE__*/ (0, _jsxruntime.jsx)(NotFound, {})
]
});
}
// Assign params to props
if (process.env.NODE_ENV === "development" && "params" in parallelRouteProps) {
// @TODO consider making this an error and running the check in build as well
console.error(`"params" is a reserved prop in Layouts and Pages and cannot be used as the name of a parallel route in ${segment}`);
}
props.params = currentParams;
let segmentElement;
if (isPage) {
// Assign searchParams to props if this is a page
if (isClientComponent) {
// When we are passing searchParams to a client component Page we don't want to track the dynamic access
// here in the RSC layer because the serialization will trigger a dynamic API usage.
// Instead we pass the searchParams untracked but we wrap the Page in a root client component
// which can among other things adds the dynamic tracking before rendering the page.
// @TODO make the root wrapper part of next-app-loader so we don't need the extra client component
props.searchParams = createUntrackedSearchParams(query);
segmentElement = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
metadataOutlet,
/*#__PURE__*/ (0, _jsxruntime.jsx)(ClientPageRoot, {
props: props,
Component: Component
})
]
});
} else {
// If we are passing searchParams to a server component Page we need to track their usage in case
// the current render mode tracks dynamic API usage.
props.searchParams = createDynamicallyTrackedSearchParams(query);
segmentElement = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
metadataOutlet,
/*#__PURE__*/ (0, _jsxruntime.jsx)(Component, {
...props
})
]
});
}
} else {
// For layouts we just render the component
segmentElement = /*#__PURE__*/ (0, _jsxruntime.jsx)(Component, {
...props
});
}
return {
seedData: [
actualSegment,
parallelRouteCacheNodeSeedData,
/*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
segmentElement,
null
]
}),
loadingData
],
styles: layerAssets
};
}
//# sourceMappingURL=create-component-tree.js.map

View File

@@ -0,0 +1,99 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ErrorHandlerSource: null,
createErrorHandler: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ErrorHandlerSource: function() {
return ErrorHandlerSource;
},
createErrorHandler: function() {
return createErrorHandler;
}
});
const _stringhash = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/string-hash"));
const _formatservererror = require("../../lib/format-server-error");
const _tracer = require("../lib/trace/tracer");
const _pipereadable = require("../pipe-readable");
const _isdynamicusageerror = require("../../export/helpers/is-dynamic-usage-error");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const ErrorHandlerSource = {
serverComponents: "serverComponents",
flightData: "flightData",
html: "html"
};
function createErrorHandler({ /**
* Used for debugging
*/ source, dev, isNextExport, errorLogger, digestErrorsMap, allCapturedErrors, silenceLogger }) {
return (err, errorInfo)=>{
var _err_message;
// If the error already has a digest, respect the original digest,
// so it won't get re-generated into another new error.
if (!err.digest) {
// TODO-APP: look at using webcrypto instead. Requires a promise to be awaited.
err.digest = (0, _stringhash.default)(err.message + ((errorInfo == null ? void 0 : errorInfo.stack) || err.stack || "")).toString();
}
const digest = err.digest;
if (allCapturedErrors) allCapturedErrors.push(err);
// These errors are expected. We return the digest
// so that they can be properly handled.
if ((0, _isdynamicusageerror.isDynamicUsageError)(err)) return err.digest;
// If the response was closed, we don't need to log the error.
if ((0, _pipereadable.isAbortError)(err)) return;
if (!digestErrorsMap.has(digest)) {
digestErrorsMap.set(digest, err);
} else if (source === ErrorHandlerSource.html) {
// For SSR errors, if we have the existing digest in errors map,
// we should use the existing error object to avoid duplicate error logs.
err = digestErrorsMap.get(digest);
}
// Format server errors in development to add more helpful error messages
if (dev) {
(0, _formatservererror.formatServerError)(err);
}
// Used for debugging error source
// console.error(source, err)
// Don't log the suppressed error during export
if (!(isNextExport && (err == null ? void 0 : (_err_message = err.message) == null ? void 0 : _err_message.includes("The specific message is omitted in production builds to avoid leaking sensitive details.")))) {
// Record exception in an active span, if available.
const span = (0, _tracer.getTracer)().getActiveScopeSpan();
if (span) {
span.recordException(err);
span.setStatus({
code: _tracer.SpanStatusCode.ERROR,
message: err.message
});
}
if (!silenceLogger) {
if (errorLogger) {
errorLogger(err).catch(()=>{});
} else {
// The error logger is currently not provided in the edge runtime.
// Use the exposed `__next_log_error__` instead.
// This will trace error traces to the original source code.
if (typeof __next_log_error__ === "function") {
__next_log_error__(err);
} else {
console.error(err);
}
}
}
}
return err.digest;
};
}
//# sourceMappingURL=create-error-handler.js.map

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
addSearchParamsIfPageSegment: null,
createFlightRouterStateFromLoaderTree: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
addSearchParamsIfPageSegment: function() {
return addSearchParamsIfPageSegment;
},
createFlightRouterStateFromLoaderTree: function() {
return createFlightRouterStateFromLoaderTree;
}
});
const _segment = require("../../shared/lib/segment");
function addSearchParamsIfPageSegment(segment, searchParams) {
const isPageSegment = segment === _segment.PAGE_SEGMENT_KEY;
if (isPageSegment) {
const stringifiedQuery = JSON.stringify(searchParams);
return stringifiedQuery !== "{}" ? segment + "?" + stringifiedQuery : segment;
}
return segment;
}
function createFlightRouterStateFromLoaderTree([segment, parallelRoutes, { layout }], getDynamicParamFromSegment, searchParams, rootLayoutIncluded = false) {
const dynamicParam = getDynamicParamFromSegment(segment);
const treeSegment = dynamicParam ? dynamicParam.treeSegment : segment;
const segmentTree = [
addSearchParamsIfPageSegment(treeSegment, searchParams),
{}
];
if (!rootLayoutIncluded && typeof layout !== "undefined") {
rootLayoutIncluded = true;
segmentTree[4] = true;
}
segmentTree[1] = Object.keys(parallelRoutes).reduce((existingValue, currentValue)=>{
existingValue[currentValue] = createFlightRouterStateFromLoaderTree(parallelRoutes[currentValue], getDynamicParamFromSegment, searchParams, rootLayoutIncluded);
return existingValue;
}, {});
return segmentTree;
}
//# sourceMappingURL=create-flight-router-state-from-loader-tree.js.map

View File

@@ -0,0 +1,90 @@
// micromatch is only available at node runtime, so it cannot be used here since the code path that calls this function
// can be run from edge. This is a simple implementation that safely achieves the required functionality.
// the goal is to match the functionality for remotePatterns as defined here -
// https://nextjs.org/docs/app/api-reference/components/image#remotepatterns
// TODO - retrofit micromatch to work in edge and use that instead
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "isCsrfOriginAllowed", {
enumerable: true,
get: function() {
return isCsrfOriginAllowed;
}
});
function matchWildcardDomain(domain, pattern) {
const domainParts = domain.split(".");
const patternParts = pattern.split(".");
if (patternParts.length < 1) {
// pattern is empty and therefore invalid to match against
return false;
}
if (domainParts.length < patternParts.length) {
// domain has too few segments and thus cannot match
return false;
}
let depth = 0;
while(patternParts.length && depth++ < 2){
const patternPart = patternParts.pop();
const domainPart = domainParts.pop();
switch(patternPart){
case "":
case "*":
case "**":
{
// invalid pattern. pattern segments must be non empty
// Additionally wildcards are only supported below the domain level
return false;
}
default:
{
if (domainPart !== patternPart) {
return false;
}
}
}
}
while(patternParts.length){
const patternPart = patternParts.pop();
const domainPart = domainParts.pop();
switch(patternPart){
case "":
{
// invalid pattern. pattern segments must be non empty
return false;
}
case "*":
{
// wildcard matches anything so we continue if the domain part is non-empty
if (domainPart) {
continue;
} else {
return false;
}
}
case "**":
{
// if this is not the last item in the pattern the pattern is invalid
if (patternParts.length > 0) {
return false;
}
// recursive wildcard matches anything so we terminate here if the domain part is non empty
return domainPart !== undefined;
}
default:
{
if (domainPart !== patternPart) {
return false;
}
}
}
}
// We exhausted the pattern. If we also exhausted the domain we have a match
return domainParts.length === 0;
}
const isCsrfOriginAllowed = (originDomain, allowedOrigins = [])=>{
return allowedOrigins.some((allowedOrigin)=>allowedOrigin && (allowedOrigin === originDomain || matchWildcardDomain(originDomain, allowedOrigin)));
};
//# sourceMappingURL=csrf-protection.js.map

View File

@@ -0,0 +1,195 @@
/**
* The functions provided by this module are used to communicate certain properties
* about the currently running code so that Next.js can make decisions on how to handle
* the current execution in different rendering modes such as pre-rendering, resuming, and SSR.
*
* Today Next.js treats all code as potentially static. Certain APIs may only make sense when dynamically rendering.
* Traditionally this meant deopting the entire render to dynamic however with PPR we can now deopt parts
* of a React tree as dynamic while still keeping other parts static. There are really two different kinds of
* Dynamic indications.
*
* The first is simply an intention to be dynamic. unstable_noStore is an example of this where
* the currently executing code simply declares that the current scope is dynamic but if you use it
* inside unstable_cache it can still be cached. This type of indication can be removed if we ever
* make the default dynamic to begin with because the only way you would ever be static is inside
* a cache scope which this indication does not affect.
*
* The second is an indication that a dynamic data source was read. This is a stronger form of dynamic
* because it means that it is inappropriate to cache this at all. using a dynamic data source inside
* unstable_cache should error. If you want to use some dynamic data inside unstable_cache you should
* read that data outside the cache and pass it in as an argument to the cached function.
*/ // Once postpone is in stable we should switch to importing the postpone export directly
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
Postpone: null,
createPostponedAbortSignal: null,
createPrerenderState: null,
formatDynamicAPIAccesses: null,
markCurrentScopeAsDynamic: null,
trackDynamicDataAccessed: null,
trackDynamicFetch: null,
usedDynamicAPIs: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
Postpone: function() {
return Postpone;
},
createPostponedAbortSignal: function() {
return createPostponedAbortSignal;
},
createPrerenderState: function() {
return createPrerenderState;
},
formatDynamicAPIAccesses: function() {
return formatDynamicAPIAccesses;
},
markCurrentScopeAsDynamic: function() {
return markCurrentScopeAsDynamic;
},
trackDynamicDataAccessed: function() {
return trackDynamicDataAccessed;
},
trackDynamicFetch: function() {
return trackDynamicFetch;
},
usedDynamicAPIs: function() {
return usedDynamicAPIs;
}
});
const _react = /*#__PURE__*/ _interop_require_default(require("react"));
const _hooksservercontext = require("../../client/components/hooks-server-context");
const _staticgenerationbailout = require("../../client/components/static-generation-bailout");
const _url = require("../../lib/url");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const hasPostpone = typeof _react.default.unstable_postpone === "function";
function createPrerenderState(isDebugSkeleton) {
return {
isDebugSkeleton,
dynamicAccesses: []
};
}
function markCurrentScopeAsDynamic(store, expression) {
const pathname = (0, _url.getPathname)(store.urlPathname);
if (store.isUnstableCacheCallback) {
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope
// creates a cache boundary. This is subtly different from reading a dynamic data source which is
// forbidden inside a cache scope.
return;
} else if (store.dynamicShouldError) {
throw new _staticgenerationbailout.StaticGenBailoutError(`Route ${pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);
} else if (// We are in a prerender (PPR enabled, during build)
store.prerenderState) {
// We track that we had a dynamic scope that postponed.
// This will be used by the renderer to decide whether
// the prerender requires a resume
postponeWithTracking(store.prerenderState, expression, pathname);
} else {
store.revalidate = 0;
if (store.isStaticGeneration) {
// We aren't prerendering but we are generating a static page. We need to bail out of static generation
const err = new _hooksservercontext.DynamicServerError(`Route ${pathname} couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`);
store.dynamicUsageDescription = expression;
store.dynamicUsageStack = err.stack;
throw err;
}
}
}
function trackDynamicDataAccessed(store, expression) {
const pathname = (0, _url.getPathname)(store.urlPathname);
if (store.isUnstableCacheCallback) {
throw new Error(`Route ${pathname} used "${expression}" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`);
} else if (store.dynamicShouldError) {
throw new _staticgenerationbailout.StaticGenBailoutError(`Route ${pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);
} else if (// We are in a prerender (PPR enabled, during build)
store.prerenderState) {
// We track that we had a dynamic scope that postponed.
// This will be used by the renderer to decide whether
// the prerender requires a resume
postponeWithTracking(store.prerenderState, expression, pathname);
} else {
store.revalidate = 0;
if (store.isStaticGeneration) {
// We aren't prerendering but we are generating a static page. We need to bail out of static generation
const err = new _hooksservercontext.DynamicServerError(`Route ${pathname} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`);
store.dynamicUsageDescription = expression;
store.dynamicUsageStack = err.stack;
throw err;
}
}
}
function Postpone({ reason, prerenderState, pathname }) {
postponeWithTracking(prerenderState, reason, pathname);
}
function trackDynamicFetch(store, expression) {
if (store.prerenderState) {
postponeWithTracking(store.prerenderState, expression, store.urlPathname);
}
}
function postponeWithTracking(prerenderState, expression, pathname) {
assertPostpone();
const reason = `Route ${pathname} needs to bail out of prerendering at this point because it used ${expression}. ` + `React throws this special object to indicate where. It should not be caught by ` + `your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`;
prerenderState.dynamicAccesses.push({
// When we aren't debugging, we don't need to create another error for the
// stack trace.
stack: prerenderState.isDebugSkeleton ? new Error().stack : undefined,
expression
});
_react.default.unstable_postpone(reason);
}
function usedDynamicAPIs(prerenderState) {
return prerenderState.dynamicAccesses.length > 0;
}
function formatDynamicAPIAccesses(prerenderState) {
return prerenderState.dynamicAccesses.filter((access)=>typeof access.stack === "string" && access.stack.length > 0).map(({ expression, stack })=>{
stack = stack.split("\n")// Remove the "Error: " prefix from the first line of the stack trace as
// well as the first 4 lines of the stack trace which is the distance
// from the user code and the `new Error().stack` call.
.slice(4).filter((line)=>{
// Exclude Next.js internals from the stack trace.
if (line.includes("node_modules/next/")) {
return false;
}
// Exclude anonymous functions from the stack trace.
if (line.includes(" (<anonymous>)")) {
return false;
}
// Exclude Node.js internals from the stack trace.
if (line.includes(" (node:")) {
return false;
}
return true;
}).join("\n");
return `Dynamic API Usage Debug - ${expression}:\n${stack}`;
});
}
function assertPostpone() {
if (!hasPostpone) {
throw new Error(`Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`);
}
}
function createPostponedAbortSignal(reason) {
assertPostpone();
const controller = new AbortController();
// We get our hands on a postpone instance by calling postpone and catching the throw
try {
_react.default.unstable_postpone(reason);
} catch (x) {
controller.abort(x);
}
return controller.signal;
}
//# sourceMappingURL=dynamic-rendering.js.map

View File

@@ -0,0 +1,174 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
arrayBufferToString: null,
decrypt: null,
encrypt: null,
generateEncryptionKeyBase64: null,
getActionEncryptionKey: null,
getClientReferenceManifestSingleton: null,
getServerModuleMap: null,
setReferenceManifestsSingleton: null,
stringToUint8Array: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
arrayBufferToString: function() {
return arrayBufferToString;
},
decrypt: function() {
return decrypt;
},
encrypt: function() {
return encrypt;
},
generateEncryptionKeyBase64: function() {
return generateEncryptionKeyBase64;
},
getActionEncryptionKey: function() {
return getActionEncryptionKey;
},
getClientReferenceManifestSingleton: function() {
return getClientReferenceManifestSingleton;
},
getServerModuleMap: function() {
return getServerModuleMap;
},
setReferenceManifestsSingleton: function() {
return setReferenceManifestsSingleton;
},
stringToUint8Array: function() {
return stringToUint8Array;
}
});
// Keep the key in memory as it should never change during the lifetime of the server in
// both development and production.
let __next_encryption_key_generation_promise = null;
let __next_loaded_action_key;
let __next_internal_development_raw_action_key;
function arrayBufferToString(buffer) {
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
// @anonrig: V8 has a limit of 65535 arguments in a function.
// For len < 65535, this is faster.
// https://github.com/vercel/next.js/pull/56377#pullrequestreview-1656181623
if (len < 65535) {
return String.fromCharCode.apply(null, bytes);
}
let binary = "";
for(let i = 0; i < len; i++){
binary += String.fromCharCode(bytes[i]);
}
return binary;
}
function stringToUint8Array(binary) {
const len = binary.length;
const arr = new Uint8Array(len);
for(let i = 0; i < len; i++){
arr[i] = binary.charCodeAt(i);
}
return arr;
}
function encrypt(key, iv, data) {
return crypto.subtle.encrypt({
name: "AES-GCM",
iv
}, key, data);
}
function decrypt(key, iv, data) {
return crypto.subtle.decrypt({
name: "AES-GCM",
iv
}, key, data);
}
async function generateEncryptionKeyBase64(dev) {
// For development, we just keep one key in memory for all actions.
// This makes things faster.
if (dev) {
if (typeof __next_internal_development_raw_action_key !== "undefined") {
return __next_internal_development_raw_action_key;
}
}
// This avoids it being generated multiple times in parallel.
if (!__next_encryption_key_generation_promise) {
__next_encryption_key_generation_promise = new Promise(async (resolve, reject)=>{
try {
const key = await crypto.subtle.generateKey({
name: "AES-GCM",
length: 256
}, true, [
"encrypt",
"decrypt"
]);
const exported = await crypto.subtle.exportKey("raw", key);
const b64 = btoa(arrayBufferToString(exported));
resolve([
key,
b64
]);
} catch (error) {
reject(error);
}
});
}
const [key, b64] = await __next_encryption_key_generation_promise;
__next_loaded_action_key = key;
if (dev) {
__next_internal_development_raw_action_key = b64;
}
return b64;
}
// This is a global singleton that is used to encode/decode the action bound args from
// the closure. This can't be using a AsyncLocalStorage as it might happen on the module
// level. Since the client reference manifest won't be mutated, let's use a global singleton
// to keep it.
const SERVER_ACTION_MANIFESTS_SINGLETON = Symbol.for("next.server.action-manifests");
function setReferenceManifestsSingleton({ clientReferenceManifest, serverActionsManifest, serverModuleMap }) {
// @ts-ignore
globalThis[SERVER_ACTION_MANIFESTS_SINGLETON] = {
clientReferenceManifest,
serverActionsManifest,
serverModuleMap
};
}
function getServerModuleMap() {
const serverActionsManifestSingleton = globalThis[SERVER_ACTION_MANIFESTS_SINGLETON];
if (!serverActionsManifestSingleton) {
throw new Error("Missing manifest for Server Actions. This is a bug in Next.js");
}
return serverActionsManifestSingleton.serverModuleMap;
}
function getClientReferenceManifestSingleton() {
const serverActionsManifestSingleton = globalThis[SERVER_ACTION_MANIFESTS_SINGLETON];
if (!serverActionsManifestSingleton) {
throw new Error("Missing manifest for Server Actions. This is a bug in Next.js");
}
return serverActionsManifestSingleton.clientReferenceManifest;
}
async function getActionEncryptionKey() {
if (__next_loaded_action_key) {
return __next_loaded_action_key;
}
const serverActionsManifestSingleton = globalThis[SERVER_ACTION_MANIFESTS_SINGLETON];
if (!serverActionsManifestSingleton) {
throw new Error("Missing manifest for Server Actions. This is a bug in Next.js");
}
const rawKey = process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY || serverActionsManifestSingleton.serverActionsManifest.encryptionKey;
if (rawKey === undefined) {
throw new Error("Missing encryption key for Server Actions");
}
__next_loaded_action_key = await crypto.subtle.importKey("raw", stringToUint8Array(atob(rawKey)), "AES-GCM", true, [
"encrypt",
"decrypt"
]);
return __next_loaded_action_key;
}
//# sourceMappingURL=encryption-utils.js.map

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "FlightRenderResult", {
enumerable: true,
get: function() {
return FlightRenderResult;
}
});
const _approuterheaders = require("../../client/components/app-router-headers");
const _renderresult = /*#__PURE__*/ _interop_require_default(require("../render-result"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
class FlightRenderResult extends _renderresult.default {
constructor(response){
super(response, {
contentType: _approuterheaders.RSC_CONTENT_TYPE_HEADER,
metadata: {}
});
}
}
//# sourceMappingURL=flight-render-result.js.map

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getAssetQueryString", {
enumerable: true,
get: function() {
return getAssetQueryString;
}
});
const isDev = process.env.NODE_ENV === "development";
const isTurbopack = !!process.env.TURBOPACK;
function getAssetQueryString(ctx, addTimestamp) {
let qs = "";
// In development we add the request timestamp to allow react to
// reload assets when a new RSC response is received.
// Turbopack handles HMR of assets itself and react doesn't need to reload them
// so this approach is not needed for Turbopack.
if (isDev && !isTurbopack && addTimestamp) {
qs += `?v=${ctx.requestTimestamp}`;
}
if (ctx.renderOpts.deploymentId) {
qs += `${isDev ? "&" : "?"}dpl=${ctx.renderOpts.deploymentId}`;
}
return qs;
}
//# sourceMappingURL=get-asset-query-string.js.map

View File

@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getLinkAndScriptTags", {
enumerable: true,
get: function() {
return getLinkAndScriptTags;
}
});
function getLinkAndScriptTags(clientReferenceManifest, filePath, injectedCSS, injectedScripts, collectNewImports) {
var _clientReferenceManifest_entryJSFiles;
const filePathWithoutExt = filePath.replace(/\.[^.]+$/, "");
const cssChunks = new Set();
const jsChunks = new Set();
const entryCSSFiles = clientReferenceManifest.entryCSSFiles[filePathWithoutExt];
const entryJSFiles = ((_clientReferenceManifest_entryJSFiles = clientReferenceManifest.entryJSFiles) == null ? void 0 : _clientReferenceManifest_entryJSFiles[filePathWithoutExt]) ?? [];
if (entryCSSFiles) {
for (const file of entryCSSFiles){
if (!injectedCSS.has(file)) {
if (collectNewImports) {
injectedCSS.add(file);
}
cssChunks.add(file);
}
}
}
if (entryJSFiles) {
for (const file of entryJSFiles){
if (!injectedScripts.has(file)) {
if (collectNewImports) {
injectedScripts.add(file);
}
jsChunks.add(file);
}
}
}
return {
styles: [
...cssChunks
],
scripts: [
...jsChunks
]
};
}
//# sourceMappingURL=get-css-inlined-link-tags.js.map

View File

@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getLayerAssets", {
enumerable: true,
get: function() {
return getLayerAssets;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default(require("react"));
const _getcssinlinedlinktags = require("./get-css-inlined-link-tags");
const _getpreloadablefonts = require("./get-preloadable-fonts");
const _getassetquerystring = require("./get-asset-query-string");
const _encodeuripath = require("../../shared/lib/encode-uri-path");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function getLayerAssets({ ctx, layoutOrPagePath, injectedCSS: injectedCSSWithCurrentLayout, injectedJS: injectedJSWithCurrentLayout, injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout }) {
const { styles: styleTags, scripts: scriptTags } = layoutOrPagePath ? (0, _getcssinlinedlinktags.getLinkAndScriptTags)(ctx.clientReferenceManifest, layoutOrPagePath, injectedCSSWithCurrentLayout, injectedJSWithCurrentLayout, true) : {
styles: [],
scripts: []
};
const preloadedFontFiles = layoutOrPagePath ? (0, _getpreloadablefonts.getPreloadableFonts)(ctx.renderOpts.nextFontManifest, layoutOrPagePath, injectedFontPreloadTagsWithCurrentLayout) : null;
if (preloadedFontFiles) {
if (preloadedFontFiles.length) {
for(let i = 0; i < preloadedFontFiles.length; i++){
const fontFilename = preloadedFontFiles[i];
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(fontFilename)[1];
const type = `font/${ext}`;
const href = `${ctx.assetPrefix}/_next/${(0, _encodeuripath.encodeURIPath)(fontFilename)}`;
ctx.componentMod.preloadFont(href, type, ctx.renderOpts.crossOrigin);
}
} else {
try {
let url = new URL(ctx.assetPrefix);
ctx.componentMod.preconnect(url.origin, "anonymous");
} catch (error) {
// assetPrefix must not be a fully qualified domain name. We assume
// we should preconnect to same origin instead
ctx.componentMod.preconnect("/", "anonymous");
}
}
}
const styles = styleTags ? styleTags.map((href, index)=>{
// In dev, Safari and Firefox will cache the resource during HMR:
// - https://github.com/vercel/next.js/issues/5860
// - https://bugs.webkit.org/show_bug.cgi?id=187726
// Because of this, we add a `?v=` query to bypass the cache during
// development. We need to also make sure that the number is always
// increasing.
const fullHref = `${ctx.assetPrefix}/_next/${(0, _encodeuripath.encodeURIPath)(href)}${(0, _getassetquerystring.getAssetQueryString)(ctx, true)}`;
// `Precedence` is an opt-in signal for React to handle resource
// loading and deduplication, etc. It's also used as the key to sort
// resources so they will be injected in the correct order.
// During HMR, it's critical to use different `precedence` values
// for different stylesheets, so their order will be kept.
// https://github.com/facebook/react/pull/25060
const precedence = process.env.NODE_ENV === "development" ? "next_" + href : "next";
ctx.componentMod.preloadStyle(fullHref, ctx.renderOpts.crossOrigin);
return /*#__PURE__*/ (0, _jsxruntime.jsx)("link", {
rel: "stylesheet",
href: fullHref,
// @ts-ignore
precedence: precedence,
crossOrigin: ctx.renderOpts.crossOrigin
}, index);
}) : [];
const scripts = scriptTags ? scriptTags.map((href, index)=>{
const fullSrc = `${ctx.assetPrefix}/_next/${(0, _encodeuripath.encodeURIPath)(href)}${(0, _getassetquerystring.getAssetQueryString)(ctx, true)}`;
return /*#__PURE__*/ (0, _jsxruntime.jsx)("script", {
src: fullSrc,
async: true
}, `script-${index}`);
}) : [];
return styles.length || scripts.length ? [
...styles,
...scripts
] : null;
}
//# sourceMappingURL=get-layer-assets.js.map

View File

@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getPreloadableFonts", {
enumerable: true,
get: function() {
return getPreloadableFonts;
}
});
function getPreloadableFonts(nextFontManifest, filePath, injectedFontPreloadTags) {
if (!nextFontManifest || !filePath) {
return null;
}
const filepathWithoutExtension = filePath.replace(/\.[^.]+$/, "");
const fontFiles = new Set();
let foundFontUsage = false;
const preloadedFontFiles = nextFontManifest.app[filepathWithoutExtension];
if (preloadedFontFiles) {
foundFontUsage = true;
for (const fontFile of preloadedFontFiles){
if (!injectedFontPreloadTags.has(fontFile)) {
fontFiles.add(fontFile);
injectedFontPreloadTags.add(fontFile);
}
}
}
if (fontFiles.size) {
return [
...fontFiles
].sort();
} else if (foundFontUsage && injectedFontPreloadTags.size === 0) {
return [];
} else {
return null;
}
}
//# sourceMappingURL=get-preloadable-fonts.js.map

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getScriptNonceFromHeader", {
enumerable: true,
get: function() {
return getScriptNonceFromHeader;
}
});
const _htmlescape = require("../htmlescape");
function getScriptNonceFromHeader(cspHeaderValue) {
var _directive_split_slice_map_find;
const directives = cspHeaderValue// Directives are split by ';'.
.split(";").map((directive)=>directive.trim());
// First try to find the directive for the 'script-src', otherwise try to
// fallback to the 'default-src'.
const directive = directives.find((dir)=>dir.startsWith("script-src")) || directives.find((dir)=>dir.startsWith("default-src"));
// If no directive could be found, then we're done.
if (!directive) {
return;
}
// Extract the nonce from the directive
const nonce = (_directive_split_slice_map_find = directive.split(" ")// Remove the 'strict-src'/'default-src' string, this can't be the nonce.
.slice(1).map((source)=>source.trim())// Find the first source with the 'nonce-' prefix.
.find((source)=>source.startsWith("'nonce-") && source.length > 8 && source.endsWith("'"))) == null ? void 0 : _directive_split_slice_map_find.slice(7, -1);
// If we could't find the nonce, then we're done.
if (!nonce) {
return;
}
// Don't accept the nonce value if it contains HTML escape characters.
// Technically, the spec requires a base64'd value, but this is just an
// extra layer.
if (_htmlescape.ESCAPE_REGEX.test(nonce)) {
throw new Error("Nonce value from Content-Security-Policy contained HTML escape characters.\nLearn more: https://nextjs.org/docs/messages/nonce-contained-invalid-characters");
}
return nonce;
}
//# sourceMappingURL=get-script-nonce-from-header.js.map

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getSegmentParam", {
enumerable: true,
get: function() {
return getSegmentParam;
}
});
const _interceptionroutes = require("../future/helpers/interception-routes");
function getSegmentParam(segment) {
const interceptionMarker = _interceptionroutes.INTERCEPTION_ROUTE_MARKERS.find((marker)=>segment.startsWith(marker));
// if an interception marker is part of the path segment, we need to jump ahead
// to the relevant portion for param parsing
if (interceptionMarker) {
segment = segment.slice(interceptionMarker.length);
}
if (segment.startsWith("[[...") && segment.endsWith("]]")) {
return {
// TODO-APP: Optional catchall does not currently work with parallel routes,
// so for now aren't handling a potential interception marker.
type: "optional-catchall",
param: segment.slice(5, -2)
};
}
if (segment.startsWith("[...") && segment.endsWith("]")) {
return {
type: interceptionMarker ? "catchall-intercepted" : "catchall",
param: segment.slice(4, -1)
};
}
if (segment.startsWith("[") && segment.endsWith("]")) {
return {
type: interceptionMarker ? "dynamic-intercepted" : "dynamic",
param: segment.slice(1, -1)
};
}
return null;
}
//# sourceMappingURL=get-segment-param.js.map

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
dynamicParamTypes: null,
getShortDynamicParamType: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
dynamicParamTypes: function() {
return dynamicParamTypes;
},
getShortDynamicParamType: function() {
return getShortDynamicParamType;
}
});
const dynamicParamTypes = {
catchall: "c",
"catchall-intercepted": "ci",
"optional-catchall": "oc",
dynamic: "d",
"dynamic-intercepted": "di"
};
function getShortDynamicParamType(type) {
const short = dynamicParamTypes[type];
if (!short) {
throw new Error("Unknown dynamic param type");
}
return short;
}
//# sourceMappingURL=get-short-dynamic-param-type.js.map

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "hasLoadingComponentInTree", {
enumerable: true,
get: function() {
return hasLoadingComponentInTree;
}
});
function hasLoadingComponentInTree(tree) {
const [, parallelRoutes, { loading }] = tree;
if (loading) {
return true;
}
return Object.values(parallelRoutes).some((parallelRoute)=>hasLoadingComponentInTree(parallelRoute));
}
//# sourceMappingURL=has-loading-component-in-tree.js.map

View File

@@ -0,0 +1,17 @@
/**
* Interop between "export default" and "module.exports".
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "interopDefault", {
enumerable: true,
get: function() {
return interopDefault;
}
});
function interopDefault(mod) {
return mod.default || mod;
}
//# sourceMappingURL=interop-default.js.map

View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "makeGetServerInsertedHTML", {
enumerable: true,
get: function() {
return makeGetServerInsertedHTML;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default(require("react"));
const _notfound = require("../../client/components/not-found");
const _redirect = require("../../client/components/redirect");
const _serveredge = require("react-dom/server.edge");
const _nodewebstreamshelper = require("../stream-utils/node-web-streams-helper");
const _redirectstatuscode = require("../../client/components/redirect-status-code");
const _addpathprefix = require("../../shared/lib/router/utils/add-path-prefix");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function makeGetServerInsertedHTML({ polyfills, renderServerInsertedHTML, serverCapturedErrors, basePath }) {
let flushedErrorMetaTagsUntilIndex = 0;
let hasUnflushedPolyfills = polyfills.length !== 0;
return async function getServerInsertedHTML() {
// Loop through all the errors that have been captured but not yet
// flushed.
const errorMetaTags = [];
while(flushedErrorMetaTagsUntilIndex < serverCapturedErrors.length){
const error = serverCapturedErrors[flushedErrorMetaTagsUntilIndex];
flushedErrorMetaTagsUntilIndex++;
if ((0, _notfound.isNotFoundError)(error)) {
errorMetaTags.push(/*#__PURE__*/ (0, _jsxruntime.jsx)("meta", {
name: "robots",
content: "noindex"
}, error.digest), process.env.NODE_ENV === "development" ? /*#__PURE__*/ (0, _jsxruntime.jsx)("meta", {
name: "next-error",
content: "not-found"
}, "next-error") : null);
} else if ((0, _redirect.isRedirectError)(error)) {
const redirectUrl = (0, _addpathprefix.addPathPrefix)((0, _redirect.getURLFromRedirectError)(error), basePath);
const statusCode = (0, _redirect.getRedirectStatusCodeFromError)(error);
const isPermanent = statusCode === _redirectstatuscode.RedirectStatusCode.PermanentRedirect ? true : false;
if (redirectUrl) {
errorMetaTags.push(/*#__PURE__*/ (0, _jsxruntime.jsx)("meta", {
id: "__next-page-redirect",
httpEquiv: "refresh",
content: `${isPermanent ? 0 : 1};url=${redirectUrl}`
}, error.digest));
}
}
}
const serverInsertedHTML = renderServerInsertedHTML();
// Skip React rendering if we know the content is empty.
if (!hasUnflushedPolyfills && errorMetaTags.length === 0 && Array.isArray(serverInsertedHTML) && serverInsertedHTML.length === 0) {
return "";
}
const stream = await (0, _serveredge.renderToReadableStream)(/*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/* Insert the polyfills if they haven't been flushed yet. */ hasUnflushedPolyfills && polyfills.map((polyfill)=>{
return /*#__PURE__*/ (0, _jsxruntime.jsx)("script", {
...polyfill
}, polyfill.src);
}),
serverInsertedHTML,
errorMetaTags
]
}), {
// Larger chunk because this isn't sent over the network.
// Let's set it to 1MB.
progressiveChunkSize: 1024 * 1024
});
hasUnflushedPolyfills = false;
// There's no need to wait for the stream to be ready
// e.g. calling `await stream.allReady` because `streamToString` will
// wait and decode the stream progressively with better parallelism.
return (0, _nodewebstreamshelper.streamToString)(stream);
};
}
//# sourceMappingURL=make-get-server-inserted-html.js.map

View File

@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "parseAndValidateFlightRouterState", {
enumerable: true,
get: function() {
return parseAndValidateFlightRouterState;
}
});
const _types = require("./types");
const _superstruct = require("next/dist/compiled/superstruct");
function parseAndValidateFlightRouterState(stateHeader) {
if (typeof stateHeader === "undefined") {
return undefined;
}
if (Array.isArray(stateHeader)) {
throw new Error("Multiple router state headers were sent. This is not allowed.");
}
// We limit the size of the router state header to ~40kb. This is to prevent
// a malicious user from sending a very large header and slowing down the
// resolving of the router state.
// This is around 2,000 nested or parallel route segment states:
// '{"children":["",{}]}'.length === 20.
if (stateHeader.length > 20 * 2000) {
throw new Error("The router state header was too large.");
}
try {
const state = JSON.parse(decodeURIComponent(stateHeader));
(0, _superstruct.assert)(state, _types.flightRouterStateSchema);
return state;
} catch {
throw new Error("The router state header was sent but could not be parsed.");
}
}
//# sourceMappingURL=parse-and-validate-flight-router-state.js.map

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "parseLoaderTree", {
enumerable: true,
get: function() {
return parseLoaderTree;
}
});
const _segment = require("../../shared/lib/segment");
function parseLoaderTree(tree) {
const [segment, parallelRoutes, components] = tree;
const { layout } = components;
let { page } = components;
// a __DEFAULT__ segment means that this route didn't match any of the
// segments in the route, so we should use the default page
page = segment === _segment.DEFAULT_SEGMENT_KEY ? components.defaultPage : page;
const layoutOrPagePath = (layout == null ? void 0 : layout[1]) || (page == null ? void 0 : page[1]);
return {
page,
segment,
components,
layoutOrPagePath,
parallelRoutes
};
}
//# sourceMappingURL=parse-loader-tree.js.map

View File

@@ -0,0 +1,35 @@
// This file should be opted into the react-server layer
// eslint-disable-next-line import/no-extraneous-dependencies
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
decodeAction: null,
decodeFormState: null,
decodeReply: null,
decodeReplyFromBusboy: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
decodeAction: function() {
return _servernode.decodeAction;
},
decodeFormState: function() {
return _servernode.decodeFormState;
},
decodeReply: function() {
return _servernode.decodeReply;
},
decodeReplyFromBusboy: function() {
return _servernode.decodeReplyFromBusboy;
}
});
const _servernode = require("react-server-dom-webpack/server.node");
//# sourceMappingURL=react-server.node.js.map

View File

@@ -0,0 +1,71 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getRequiredScripts", {
enumerable: true,
get: function() {
return getRequiredScripts;
}
});
const _encodeuripath = require("../../shared/lib/encode-uri-path");
const _reactdom = /*#__PURE__*/ _interop_require_default(require("react-dom"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function getRequiredScripts(buildManifest, assetPrefix, crossOrigin, SRIManifest, qs, nonce) {
let preinitScripts;
let preinitScriptCommands = [];
const bootstrapScript = {
src: "",
crossOrigin
};
const files = buildManifest.rootMainFiles.map(_encodeuripath.encodeURIPath);
if (files.length === 0) {
throw new Error("Invariant: missing bootstrap script. This is a bug in Next.js");
}
if (SRIManifest) {
bootstrapScript.src = `${assetPrefix}/_next/` + files[0] + qs;
bootstrapScript.integrity = SRIManifest[files[0]];
for(let i = 1; i < files.length; i++){
const src = `${assetPrefix}/_next/` + files[i] + qs;
const integrity = SRIManifest[files[i]];
preinitScriptCommands.push(src, integrity);
}
preinitScripts = ()=>{
// preinitScriptCommands is a double indexed array of src/integrity pairs
for(let i = 0; i < preinitScriptCommands.length; i += 2){
_reactdom.default.preinit(preinitScriptCommands[i], {
as: "script",
integrity: preinitScriptCommands[i + 1],
crossOrigin,
nonce
});
}
};
} else {
bootstrapScript.src = `${assetPrefix}/_next/` + files[0] + qs;
for(let i = 1; i < files.length; i++){
const src = `${assetPrefix}/_next/` + files[i] + qs;
preinitScriptCommands.push(src);
}
preinitScripts = ()=>{
// preinitScriptCommands is a singled indexed array of src values
for(let i = 0; i < preinitScriptCommands.length; i++){
_reactdom.default.preinit(preinitScriptCommands[i], {
as: "script",
nonce,
crossOrigin
});
}
};
}
return [
preinitScripts,
bootstrapScript
];
}
//# sourceMappingURL=required-scripts.js.map

View File

@@ -0,0 +1,41 @@
// Provider for the `useServerInsertedHTML` API to register callbacks to insert
// elements into the HTML stream.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createServerInsertedHTML", {
enumerable: true,
get: function() {
return createServerInsertedHTML;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default(require("react"));
const _serverinsertedhtmlsharedruntime = require("../../shared/lib/server-inserted-html.shared-runtime");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function createServerInsertedHTML() {
const serverInsertedHTMLCallbacks = [];
const addInsertedHtml = (handler)=>{
serverInsertedHTMLCallbacks.push(handler);
};
return {
ServerInsertedHTMLProvider ({ children }) {
return /*#__PURE__*/ (0, _jsxruntime.jsx)(_serverinsertedhtmlsharedruntime.ServerInsertedHTMLContext.Provider, {
value: addInsertedHtml,
children: children
});
},
renderServerInsertedHTML () {
return serverInsertedHTMLCallbacks.map((callback, index)=>/*#__PURE__*/ (0, _jsxruntime.jsx)(_react.default.Fragment, {
children: callback()
}, "__next_server_inserted__" + index));
}
};
}
//# sourceMappingURL=server-inserted-html.js.map

View File

@@ -0,0 +1,165 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
DYNAMIC_DATA: null,
DYNAMIC_HTML: null,
ServerRenderer: null,
VoidRenderer: null,
createStaticRenderer: null,
getDynamicDataPostponedState: null,
getDynamicHTMLPostponedState: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
DYNAMIC_DATA: function() {
return DYNAMIC_DATA;
},
DYNAMIC_HTML: function() {
return DYNAMIC_HTML;
},
ServerRenderer: function() {
return ServerRenderer;
},
VoidRenderer: function() {
return VoidRenderer;
},
createStaticRenderer: function() {
return createStaticRenderer;
},
getDynamicDataPostponedState: function() {
return getDynamicDataPostponedState;
},
getDynamicHTMLPostponedState: function() {
return getDynamicHTMLPostponedState;
}
});
class StaticRenderer {
constructor(options){
this.options = options;
this.prerender = process.env.__NEXT_EXPERIMENTAL_REACT ? require("react-dom/static.edge").prerender : null;
}
async render(children) {
const { prelude, postponed } = await this.prerender(children, this.options);
return {
stream: prelude,
postponed
};
}
}
class StaticResumeRenderer {
constructor(postponed, options){
this.postponed = postponed;
this.options = options;
this.resume = require("react-dom/server.edge").resume;
}
async render(children) {
const stream = await this.resume(children, this.postponed, this.options);
return {
stream,
resumed: true
};
}
}
class ServerRenderer {
constructor(options){
this.options = options;
this.renderToReadableStream = require("react-dom/server.edge").renderToReadableStream;
}
async render(children) {
const stream = await this.renderToReadableStream(children, this.options);
return {
stream
};
}
}
class VoidRenderer {
async render(_children) {
return {
stream: new ReadableStream({
start (controller) {
// Close the stream immediately
controller.close();
}
}),
resumed: false
};
}
}
const DYNAMIC_DATA = 1;
const DYNAMIC_HTML = 2;
function getDynamicHTMLPostponedState(data) {
return [
DYNAMIC_HTML,
data
];
}
function getDynamicDataPostponedState() {
return DYNAMIC_DATA;
}
function createStaticRenderer({ ppr, isStaticGeneration, postponed, streamOptions: { signal, onError, onPostpone, onHeaders, maxHeadersLength, nonce, bootstrapScripts, formState } }) {
if (ppr) {
if (isStaticGeneration) {
// This is a Prerender
return new StaticRenderer({
signal,
onError,
onPostpone,
// We want to capture headers because we may not end up with a shell
// and being able to send headers is the next best thing
onHeaders,
maxHeadersLength,
bootstrapScripts
});
} else {
// This is a Resume
if (postponed === DYNAMIC_DATA) {
// The HTML was complete, we don't actually need to render anything
return new VoidRenderer();
} else if (postponed) {
const reactPostponedState = postponed[1];
// The HTML had dynamic holes and we need to resume it
return new StaticResumeRenderer(reactPostponedState, {
signal,
onError,
onPostpone,
nonce
});
}
}
}
if (isStaticGeneration) {
// This is a static render (without PPR)
return new ServerRenderer({
signal,
onError,
// We don't pass onHeaders. In static builds we will either have no output
// or the entire page. In either case preload headers aren't necessary and could
// alter the prioritiy of relative loading of resources so we opt to keep them
// as tags exclusively.
nonce,
bootstrapScripts,
formState
});
}
// This is a dynamic render (without PPR)
return new ServerRenderer({
signal,
onError,
// Static renders are streamed in realtime so sending headers early is
// generally good because it will likely go out before the shell is ready.
onHeaders,
maxHeadersLength,
nonce,
bootstrapScripts,
formState
});
}
//# sourceMappingURL=static-renderer.js.map

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "stripFlightHeaders", {
enumerable: true,
get: function() {
return stripFlightHeaders;
}
});
const _approuterheaders = require("../../client/components/app-router-headers");
function stripFlightHeaders(headers) {
for (const [header] of _approuterheaders.FLIGHT_PARAMETERS){
delete headers[header.toLowerCase()];
}
}
//# sourceMappingURL=strip-flight-headers.js.map

View File

@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "flightRouterStateSchema", {
enumerable: true,
get: function() {
return flightRouterStateSchema;
}
});
const _superstruct = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/superstruct"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const dynamicParamTypesSchema = _superstruct.default.enums([
"c",
"ci",
"oc",
"d",
"di"
]);
const segmentSchema = _superstruct.default.union([
_superstruct.default.string(),
_superstruct.default.tuple([
_superstruct.default.string(),
_superstruct.default.string(),
dynamicParamTypesSchema
])
]);
const flightRouterStateSchema = _superstruct.default.tuple([
segmentSchema,
_superstruct.default.record(_superstruct.default.string(), _superstruct.default.lazy(()=>flightRouterStateSchema)),
_superstruct.default.optional(_superstruct.default.nullable(_superstruct.default.string())),
_superstruct.default.optional(_superstruct.default.nullable(_superstruct.default.union([
_superstruct.default.literal("refetch"),
_superstruct.default.literal("refresh")
]))),
_superstruct.default.optional(_superstruct.default.boolean())
]);
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1,126 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createInlinedDataReadableStream: null,
flightRenderComplete: null,
useFlightStream: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createInlinedDataReadableStream: function() {
return createInlinedDataReadableStream;
},
flightRenderComplete: function() {
return flightRenderComplete;
},
useFlightStream: function() {
return useFlightStream;
}
});
const _htmlescape = require("../htmlescape");
const isEdgeRuntime = process.env.NEXT_RUNTIME === "edge";
const INLINE_FLIGHT_PAYLOAD_BOOTSTRAP = 0;
const INLINE_FLIGHT_PAYLOAD_DATA = 1;
const INLINE_FLIGHT_PAYLOAD_FORM_STATE = 2;
const flightResponses = new WeakMap();
const encoder = new TextEncoder();
function useFlightStream(flightStream, clientReferenceManifest, nonce) {
const response = flightResponses.get(flightStream);
if (response) {
return response;
}
// react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly
let createFromReadableStream;
// @TODO: investigate why the aliasing for turbopack doesn't pick this up, requiring this runtime check
if (process.env.TURBOPACK) {
createFromReadableStream = // eslint-disable-next-line import/no-extraneous-dependencies
require("react-server-dom-turbopack/client.edge").createFromReadableStream;
} else {
createFromReadableStream = // eslint-disable-next-line import/no-extraneous-dependencies
require("react-server-dom-webpack/client.edge").createFromReadableStream;
}
const newResponse = createFromReadableStream(flightStream, {
ssrManifest: {
moduleLoading: clientReferenceManifest.moduleLoading,
moduleMap: isEdgeRuntime ? clientReferenceManifest.edgeSSRModuleMapping : clientReferenceManifest.ssrModuleMapping
},
nonce
});
flightResponses.set(flightStream, newResponse);
return newResponse;
}
async function flightRenderComplete(flightStream) {
const flightReader = flightStream.getReader();
while(true){
const { done } = await flightReader.read();
if (done) {
return;
}
}
}
function createInlinedDataReadableStream(flightStream, nonce, formState) {
const startScriptTag = nonce ? `<script nonce=${JSON.stringify(nonce)}>` : "<script>";
const decoder = new TextDecoder("utf-8", {
fatal: true
});
const decoderOptions = {
stream: true
};
const flightReader = flightStream.getReader();
const readable = new ReadableStream({
type: "bytes",
start (controller) {
try {
writeInitialInstructions(controller, startScriptTag, formState);
} catch (error) {
// during encoding or enqueueing forward the error downstream
controller.error(error);
}
},
async pull (controller) {
try {
const { done, value } = await flightReader.read();
if (done) {
const tail = decoder.decode(value, {
stream: false
});
if (tail.length) {
writeFlightDataInstruction(controller, startScriptTag, tail);
}
controller.close();
} else {
const chunkAsString = decoder.decode(value, decoderOptions);
writeFlightDataInstruction(controller, startScriptTag, chunkAsString);
}
} catch (error) {
// There was a problem in the upstream reader or during decoding or enqueuing
// forward the error downstream
controller.error(error);
}
}
});
return readable;
}
function writeInitialInstructions(controller, scriptStart, formState) {
controller.enqueue(encoder.encode(`${scriptStart}(self.__next_f=self.__next_f||[]).push(${(0, _htmlescape.htmlEscapeJsonString)(JSON.stringify([
INLINE_FLIGHT_PAYLOAD_BOOTSTRAP
]))});self.__next_f.push(${(0, _htmlescape.htmlEscapeJsonString)(JSON.stringify([
INLINE_FLIGHT_PAYLOAD_FORM_STATE,
formState
]))})</script>`));
}
function writeFlightDataInstruction(controller, scriptStart, chunkAsString) {
controller.enqueue(encoder.encode(`${scriptStart}self.__next_f.push(${(0, _htmlescape.htmlEscapeJsonString)(JSON.stringify([
INLINE_FLIGHT_PAYLOAD_DATA,
chunkAsString
]))})</script>`));
}
//# sourceMappingURL=use-flight-response.js.map

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "validateURL", {
enumerable: true,
get: function() {
return validateURL;
}
});
const DUMMY_ORIGIN = "http://n";
const INVALID_URL_MESSAGE = "Invalid request URL";
function validateURL(url) {
if (!url) {
throw new Error(INVALID_URL_MESSAGE);
}
try {
const parsed = new URL(url, DUMMY_ORIGIN);
// Avoid origin change by extra slashes in pathname
if (parsed.origin !== DUMMY_ORIGIN) {
throw new Error(INVALID_URL_MESSAGE);
}
return url;
} catch {
throw new Error(INVALID_URL_MESSAGE);
}
}
//# sourceMappingURL=validate-url.js.map

View File

@@ -0,0 +1,171 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "walkTreeWithFlightRouterState", {
enumerable: true,
get: function() {
return walkTreeWithFlightRouterState;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default(require("react"));
const _matchsegments = require("../../client/components/match-segments");
const _getcssinlinedlinktags = require("./get-css-inlined-link-tags");
const _getpreloadablefonts = require("./get-preloadable-fonts");
const _createflightrouterstatefromloadertree = require("./create-flight-router-state-from-loader-tree");
const _parseloadertree = require("./parse-loader-tree");
const _getlayerassets = require("./get-layer-assets");
const _hasloadingcomponentintree = require("./has-loading-component-in-tree");
const _createcomponenttree = require("./create-component-tree");
const _segment = require("../../shared/lib/segment");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function walkTreeWithFlightRouterState({ createSegmentPath, loaderTreeToFilter, parentParams, isFirst, flightRouterState, parentRendered, rscPayloadHead, injectedCSS, injectedJS, injectedFontPreloadTags, rootLayoutIncluded, asNotFound, metadataOutlet, ctx }) {
const { renderOpts: { nextFontManifest, experimental }, query, isPrefetch, getDynamicParamFromSegment, componentMod: { tree: loaderTree } } = ctx;
const [segment, parallelRoutes, components] = loaderTreeToFilter;
const parallelRoutesKeys = Object.keys(parallelRoutes);
const { layout } = components;
const isLayout = typeof layout !== "undefined";
/**
* Checks if the current segment is a root layout.
*/ const rootLayoutAtThisLevel = isLayout && !rootLayoutIncluded;
/**
* Checks if the current segment or any level above it has a root layout.
*/ const rootLayoutIncludedAtThisLevelOrAbove = rootLayoutIncluded || rootLayoutAtThisLevel;
// Because this function walks to a deeper point in the tree to start rendering we have to track the dynamic parameters up to the point where rendering starts
const segmentParam = getDynamicParamFromSegment(segment);
const currentParams = // Handle null case where dynamic param is optional
segmentParam && segmentParam.value !== null ? {
...parentParams,
[segmentParam.param]: segmentParam.value
} : parentParams;
const actualSegment = (0, _createflightrouterstatefromloadertree.addSearchParamsIfPageSegment)(segmentParam ? segmentParam.treeSegment : segment, query);
/**
* Decide if the current segment is where rendering has to start.
*/ const renderComponentsOnThisLevel = // No further router state available
!flightRouterState || // Segment in router state does not match current segment
!(0, _matchsegments.matchSegment)(actualSegment, flightRouterState[0]) || // Last item in the tree
parallelRoutesKeys.length === 0 || // Explicit refresh
flightRouterState[3] === "refetch";
const shouldSkipComponentTree = // loading.tsx has no effect on prefetching when PPR is enabled
!experimental.ppr && isPrefetch && !Boolean(components.loading) && (flightRouterState || // If there is no flightRouterState, we need to check the entire loader tree, as otherwise we'll be only checking the root
!(0, _hasloadingcomponentintree.hasLoadingComponentInTree)(loaderTree));
if (!parentRendered && renderComponentsOnThisLevel) {
const overriddenSegment = flightRouterState && (0, _matchsegments.canSegmentBeOverridden)(actualSegment, flightRouterState[0]) ? flightRouterState[0] : actualSegment;
const routerState = (0, _createflightrouterstatefromloadertree.createFlightRouterStateFromLoaderTree)(// Create router state using the slice of the loaderTree
loaderTreeToFilter, getDynamicParamFromSegment, query);
if (shouldSkipComponentTree) {
// Send only the router state
return [
[
overriddenSegment,
routerState,
null,
null
]
];
} else {
// Create component tree using the slice of the loaderTree
const { seedData } = await (0, _createcomponenttree.createComponentTree)(// This ensures flightRouterPath is valid and filters down the tree
{
ctx,
createSegmentPath,
loaderTree: loaderTreeToFilter,
parentParams: currentParams,
firstItem: isFirst,
injectedCSS,
injectedJS,
injectedFontPreloadTags,
// This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded,
asNotFound,
metadataOutlet
});
// Create head
const { layoutOrPagePath } = (0, _parseloadertree.parseLoaderTree)(loaderTreeToFilter);
const layerAssets = (0, _getlayerassets.getLayerAssets)({
ctx,
layoutOrPagePath,
injectedCSS: new Set(injectedCSS),
injectedJS: new Set(injectedJS),
injectedFontPreloadTags: new Set(injectedFontPreloadTags)
});
const head = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
layerAssets,
rscPayloadHead
]
});
return [
[
overriddenSegment,
routerState,
seedData,
head
]
];
}
}
// If we are not rendering on this level we need to check if the current
// segment has a layout. If so, we need to track all the used CSS to make
// the result consistent.
const layoutPath = layout == null ? void 0 : layout[1];
const injectedCSSWithCurrentLayout = new Set(injectedCSS);
const injectedJSWithCurrentLayout = new Set(injectedJS);
const injectedFontPreloadTagsWithCurrentLayout = new Set(injectedFontPreloadTags);
if (layoutPath) {
(0, _getcssinlinedlinktags.getLinkAndScriptTags)(ctx.clientReferenceManifest, layoutPath, injectedCSSWithCurrentLayout, injectedJSWithCurrentLayout, true);
(0, _getpreloadablefonts.getPreloadableFonts)(nextFontManifest, layoutPath, injectedFontPreloadTagsWithCurrentLayout);
}
// Walk through all parallel routes.
const paths = (await Promise.all(parallelRoutesKeys.map(async (parallelRouteKey)=>{
// for (const parallelRouteKey of parallelRoutesKeys) {
const parallelRoute = parallelRoutes[parallelRouteKey];
const currentSegmentPath = isFirst ? [
parallelRouteKey
] : [
actualSegment,
parallelRouteKey
];
const path = await walkTreeWithFlightRouterState({
ctx,
createSegmentPath: (child)=>{
return createSegmentPath([
...currentSegmentPath,
...child
]);
},
loaderTreeToFilter: parallelRoute,
parentParams: currentParams,
flightRouterState: flightRouterState && flightRouterState[1][parallelRouteKey],
parentRendered: parentRendered || renderComponentsOnThisLevel,
isFirst: false,
rscPayloadHead,
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
asNotFound,
metadataOutlet
});
return path.map((item)=>{
// we don't need to send over default routes in the flight data
// because they are always ignored by the client, unless it's a refetch
if (item[0] === _segment.DEFAULT_SEGMENT_KEY && flightRouterState && !!flightRouterState[1][parallelRouteKey][0] && flightRouterState[1][parallelRouteKey][3] !== "refetch") {
return null;
}
return [
actualSegment,
parallelRouteKey,
...item
];
}).filter(Boolean);
}))).flat();
return paths;
}
//# sourceMappingURL=walk-tree-with-flight-router-state.js.map