| "use strict"; |
| Object.defineProperty(exports, "__esModule", { |
| value: true |
| }); |
| 0 && (module.exports = { |
| handleAction: null, |
| parseHostHeader: null |
| }); |
| function _export(target, all) { |
| for(var name in all)Object.defineProperty(target, name, { |
| enumerable: true, |
| get: all[name] |
| }); |
| } |
| _export(exports, { |
| handleAction: function() { |
| return handleAction; |
| }, |
| parseHostHeader: function() { |
| return parseHostHeader; |
| } |
| }); |
| const _approuterheaders = require("../../client/components/app-router-headers"); |
| const _httpaccessfallback = require("../../client/components/http-access-fallback/http-access-fallback"); |
| const _redirect = require("../../client/components/redirect"); |
| const _redirecterror = require("../../client/components/redirect-error"); |
| const _renderresult = _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"); |
| const _helpers = require("../base-http/helpers"); |
| const _redirectstatuscode = require("../../client/components/redirect-status-code"); |
| const _requeststore = require("../async-storage/request-store"); |
| const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); |
| const _invarianterror = require("../../shared/lib/invariant-error"); |
| const _revalidationutils = require("../revalidation-utils"); |
| const _requestmeta = require("../request-meta"); |
| const _setcachebustingsearchparam = require("../../client/components/router-reducer/set-cache-busting-search-param"); |
| function _interop_require_default(obj) { |
| return obj && obj.__esModule ? obj : { |
| default: obj |
| }; |
| } |
| |
| |
| function hasServerActions(manifest) { |
| return Object.keys(manifest.node).length > 0 || Object.keys(manifest.edge).length > 0; |
| } |
| 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) { |
| |
| const requestHeaders = req.headers; |
| const requestCookies = new _cookies.RequestCookies(_headers.HeadersAdapter.from(requestHeaders)); |
| |
| const responseHeaders = res.getHeaders(); |
| const responseCookies = new _cookies.ResponseCookies((0, _utils1.fromNodeOutgoingHttpHeaders)(responseHeaders)); |
| |
| const mergedHeaders = (0, _utils.filterReqHeaders)({ |
| ...nodeHeadersToRecord(requestHeaders), |
| ...nodeHeadersToRecord(responseHeaders) |
| }, _utils.actionsForbiddenHeaders); |
| |
| |
| responseCookies.getAll().forEach((cookie)=>{ |
| if (typeof cookie.value === 'undefined') { |
| requestCookies.delete(cookie.name); |
| } else { |
| requestCookies.set(cookie); |
| } |
| }); |
| |
| mergedHeaders['cookie'] = requestCookies.toString(); |
| |
| delete mergedHeaders['transfer-encoding']; |
| return new Headers(mergedHeaders); |
| } |
| function addRevalidationHeader(res, { workStore, requestStore }) { |
| var _workStore_pendingRevalidatedTags; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| const isTagRevalidated = ((_workStore_pendingRevalidatedTags = workStore.pendingRevalidatedTags) == null ? void 0 : _workStore_pendingRevalidatedTags.length) ? 1 : 0; |
| const isCookieRevalidated = (0, _requestcookies.getModifiedCookieValues)(requestStore.mutableCookies).length ? 1 : 0; |
| res.setHeader('x-action-revalidated', JSON.stringify([ |
| [], |
| isTagRevalidated, |
| isCookieRevalidated |
| ])); |
| } |
| |
| |
| async function createForwardedActionResponse(req, res, host, workerPathname, basePath) { |
| var _getRequestMeta; |
| if (!host) { |
| throw Object.defineProperty(new Error('Invariant: Missing `host` header from a forwarded Server Actions request.'), "__NEXT_ERROR_CODE", { |
| value: "E226", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| const forwardedHeaders = getForwardedHeaders(req, res); |
| |
| |
| |
| forwardedHeaders.set('x-action-forwarded', '1'); |
| const proto = ((_getRequestMeta = (0, _requestmeta.getRequestMeta)(req, 'initProtocol')) == null ? void 0 : _getRequestMeta.replace(/:+$/, '')) || 'https'; |
| |
| |
| const origin = process.env.__NEXT_PRIVATE_ORIGIN || `${proto}://${host.value}`; |
| const fetchUrl = new URL(`${origin}${basePath}${workerPathname}`); |
| try { |
| var _response_headers_get; |
| let body; |
| if ( |
| |
| process.env.NEXT_RUNTIME === 'edge' && (0, _helpers.isWebNextRequest)(req)) { |
| if (!req.body) { |
| throw Object.defineProperty(new Error('Invariant: missing request body.'), "__NEXT_ERROR_CODE", { |
| value: "E333", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| body = req.body; |
| } else if ( |
| |
| process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextRequest)(req)) { |
| body = req.stream(); |
| } else { |
| throw Object.defineProperty(new Error('Invariant: Unknown request type.'), "__NEXT_ERROR_CODE", { |
| value: "E114", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| |
| const response = await fetch(fetchUrl, { |
| method: 'POST', |
| body, |
| duplex: 'half', |
| headers: forwardedHeaders, |
| redirect: 'manual', |
| next: { |
| |
| internal: 1 |
| } |
| }); |
| if ((_response_headers_get = response.headers.get('content-type')) == null ? void 0 : _response_headers_get.startsWith(_approuterheaders.RSC_CONTENT_TYPE_HEADER)) { |
| |
| for (const [key, value] of response.headers){ |
| if (!_utils.actionsForbiddenHeaders.includes(key)) { |
| res.setHeader(key, value); |
| } |
| } |
| return new _flightrenderresult.FlightRenderResult(response.body); |
| } else { |
| var |
| _response_body; |
| (_response_body = response.body) == null ? void 0 : _response_body.cancel(); |
| } |
| } catch (err) { |
| |
| console.error(`failed to forward action response`, err); |
| } |
| return _renderresult.default.fromStatic('{}', _constants.JSON_CONTENT_TYPE_HEADER); |
| } |
| |
| |
| |
| |
| |
| |
| function getAppRelativeRedirectUrl(basePath, host, redirectUrl) { |
| if (redirectUrl.startsWith('/') || redirectUrl.startsWith('.')) { |
| |
| return new URL(`${basePath}${redirectUrl}`, 'http://n'); |
| } |
| const parsedRedirectUrl = new URL(redirectUrl); |
| if ((host == null ? void 0 : host.value) !== parsedRedirectUrl.host) { |
| return null; |
| } |
| |
| |
| return parsedRedirectUrl.pathname.startsWith(basePath) ? parsedRedirectUrl : null; |
| } |
| async function createRedirectRenderResult(req, res, originalHost, redirectUrl, redirectType, basePath, workStore) { |
| res.setHeader('x-action-redirect', `${redirectUrl};${redirectType}`); |
| |
| |
| |
| |
| |
| const appRelativeRedirectUrl = getAppRelativeRedirectUrl(basePath, originalHost, redirectUrl); |
| if (appRelativeRedirectUrl) { |
| var _getRequestMeta; |
| if (!originalHost) { |
| throw Object.defineProperty(new Error('Invariant: Missing `host` header from a forwarded Server Actions request.'), "__NEXT_ERROR_CODE", { |
| value: "E226", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| const forwardedHeaders = getForwardedHeaders(req, res); |
| forwardedHeaders.set(_approuterheaders.RSC_HEADER, '1'); |
| const proto = ((_getRequestMeta = (0, _requestmeta.getRequestMeta)(req, 'initProtocol')) == null ? void 0 : _getRequestMeta.replace(/:+$/, '')) || 'https'; |
| |
| |
| const origin = process.env.__NEXT_PRIVATE_ORIGIN || `${proto}://${originalHost.value}`; |
| const fetchUrl = new URL(`${origin}${appRelativeRedirectUrl.pathname}${appRelativeRedirectUrl.search}`); |
| if (workStore.pendingRevalidatedTags) { |
| var _workStore_incrementalCache_prerenderManifest_preview, _workStore_incrementalCache_prerenderManifest, _workStore_incrementalCache; |
| forwardedHeaders.set(_constants.NEXT_CACHE_REVALIDATED_TAGS_HEADER, workStore.pendingRevalidatedTags.join(',')); |
| forwardedHeaders.set(_constants.NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, ((_workStore_incrementalCache = workStore.incrementalCache) == null ? void 0 : (_workStore_incrementalCache_prerenderManifest = _workStore_incrementalCache.prerenderManifest) == null ? void 0 : (_workStore_incrementalCache_prerenderManifest_preview = _workStore_incrementalCache_prerenderManifest.preview) == null ? void 0 : _workStore_incrementalCache_prerenderManifest_preview.previewModeId) || ''); |
| } |
| |
| forwardedHeaders.delete(_approuterheaders.NEXT_ROUTER_STATE_TREE_HEADER); |
| |
| |
| forwardedHeaders.delete(_approuterheaders.ACTION_HEADER); |
| try { |
| var _response_headers_get; |
| (0, _setcachebustingsearchparam.setCacheBustingSearchParam)(fetchUrl, { |
| [_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER]: forwardedHeaders.get(_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER) ? '1' : undefined, |
| [_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: forwardedHeaders.get(_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER) ?? undefined, |
| [_approuterheaders.NEXT_ROUTER_STATE_TREE_HEADER]: forwardedHeaders.get(_approuterheaders.NEXT_ROUTER_STATE_TREE_HEADER) ?? undefined, |
| [_approuterheaders.NEXT_URL]: forwardedHeaders.get(_approuterheaders.NEXT_URL) ?? undefined |
| }); |
| const response = await fetch(fetchUrl, { |
| method: 'GET', |
| headers: forwardedHeaders, |
| next: { |
| |
| internal: 1 |
| } |
| }); |
| if ((_response_headers_get = response.headers.get('content-type')) == null ? void 0 : _response_headers_get.startsWith(_approuterheaders.RSC_CONTENT_TYPE_HEADER)) { |
| |
| for (const [key, value] of response.headers){ |
| if (!_utils.actionsForbiddenHeaders.includes(key)) { |
| res.setHeader(key, value); |
| } |
| } |
| return new _flightrenderresult.FlightRenderResult(response.body); |
| } else { |
| var |
| _response_body; |
| (_response_body = response.body) == null ? void 0 : _response_body.cancel(); |
| } |
| } catch (err) { |
| |
| console.error(`failed to get redirect response`, err); |
| } |
| } |
| return _renderresult.default.EMPTY; |
| } |
| |
| |
| function limitUntrustedHeaderValueForLogs(value) { |
| return value.length > 100 ? value.slice(0, 100) + '...' : value; |
| } |
| function parseHostHeader(headers, originDomain) { |
| var _forwardedHostHeader_split_, _forwardedHostHeader_split; |
| const forwardedHostHeader = headers['x-forwarded-host']; |
| const forwardedHostHeaderValue = forwardedHostHeader && Array.isArray(forwardedHostHeader) ? forwardedHostHeader[0] : forwardedHostHeader == null ? void 0 : (_forwardedHostHeader_split = forwardedHostHeader.split(',')) == null ? void 0 : (_forwardedHostHeader_split_ = _forwardedHostHeader_split[0]) == null ? void 0 : _forwardedHostHeader_split_.trim(); |
| const hostHeader = headers['host']; |
| if (originDomain) { |
| return forwardedHostHeaderValue === originDomain ? { |
| type: "x-forwarded-host", |
| value: forwardedHostHeaderValue |
| } : hostHeader === originDomain ? { |
| type: "host", |
| value: hostHeader |
| } : undefined; |
| } |
| return forwardedHostHeaderValue ? { |
| type: "x-forwarded-host", |
| value: forwardedHostHeaderValue |
| } : hostHeader ? { |
| type: "host", |
| value: hostHeader |
| } : undefined; |
| } |
| async function handleAction({ req, res, ComponentMod, serverModuleMap, generateFlight, workStore, requestStore, serverActions, ctx, metadata }) { |
| const contentType = req.headers['content-type']; |
| const { serverActionsManifest, page } = ctx.renderOpts; |
| const { actionId, isMultipartAction, isFetchAction, isURLEncodedAction, isPossibleServerAction } = (0, _serveractionrequestmeta.getServerActionRequestMetadata)(req); |
| const handleUnrecognizedFetchAction = (err)=>{ |
| |
| |
| console.warn(err); |
| |
| |
| |
| |
| res.setHeader(_approuterheaders.NEXT_ACTION_NOT_FOUND_HEADER, '1'); |
| res.setHeader('content-type', 'text/plain'); |
| res.statusCode = 404; |
| return { |
| type: 'done', |
| result: _renderresult.default.fromStatic('Server action not found.', 'text/plain') |
| }; |
| }; |
| |
| |
| |
| if (!isPossibleServerAction) { |
| return null; |
| } |
| |
| |
| if (isURLEncodedAction) { |
| if (isFetchAction) { |
| return { |
| type: 'not-found' |
| }; |
| } else { |
| |
| return null; |
| } |
| } |
| |
| if (!hasServerActions(serverActionsManifest)) { |
| return handleUnrecognizedFetchAction(getActionNotFoundError(actionId)); |
| } |
| if (workStore.isStaticGeneration) { |
| throw Object.defineProperty(new Error("Invariant: server actions can't be handled during static rendering"), "__NEXT_ERROR_CODE", { |
| value: "E359", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| let temporaryReferences; |
| |
| workStore.fetchCache = 'default-no-store'; |
| const originDomain = typeof req.headers['origin'] === 'string' ? new URL(req.headers['origin']).host : undefined; |
| const host = parseHostHeader(req.headers); |
| let warning = undefined; |
| function warnBadServerActionRequest() { |
| if (warning) { |
| (0, _log.warn)(warning); |
| } |
| } |
| |
| |
| if (!originDomain) { |
| |
| |
| warning = 'Missing `origin` header from a forwarded Server Actions request.'; |
| } else if (!host || originDomain !== host.value) { |
| |
| |
| |
| if ((0, _csrfprotection.isCsrfOriginAllowed)(originDomain, serverActions == null ? void 0 : serverActions.allowedOrigins)) { |
| |
| } else { |
| if (host) { |
| |
| 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 { |
| |
| 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 = Object.defineProperty(new Error('Invalid Server Actions request.'), "__NEXT_ERROR_CODE", { |
| value: "E80", |
| enumerable: false, |
| configurable: true |
| }); |
| if (isFetchAction) { |
| res.statusCode = 500; |
| metadata.statusCode = 500; |
| const promise = Promise.reject(error); |
| try { |
| |
| |
| |
| |
| await promise; |
| } catch { |
| |
| } |
| return { |
| type: 'done', |
| result: await generateFlight(req, ctx, requestStore, { |
| actionResult: promise, |
| |
| skipFlight: true, |
| temporaryReferences |
| }) |
| }; |
| } |
| throw error; |
| } |
| } |
| |
| res.setHeader('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate'); |
| const { actionAsyncStorage } = ComponentMod; |
| const actionWasForwarded = Boolean(req.headers['x-action-forwarded']); |
| if (actionId) { |
| const forwardedWorker = (0, _actionutils.selectWorkerForForwarding)(actionId, page, serverActionsManifest); |
| |
| |
| if (forwardedWorker) { |
| return { |
| type: 'done', |
| result: await createForwardedActionResponse(req, res, host, forwardedWorker, ctx.renderOpts.basePath) |
| }; |
| } |
| } |
| try { |
| return await actionAsyncStorage.run({ |
| isAction: true |
| }, async ()=>{ |
| |
| let actionModId; |
| let boundActionArguments = []; |
| if ( |
| |
| process.env.NEXT_RUNTIME === 'edge' && (0, _helpers.isWebNextRequest)(req)) { |
| if (!req.body) { |
| throw Object.defineProperty(new Error('invariant: Missing request body.'), "__NEXT_ERROR_CODE", { |
| value: "E364", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| |
| |
| const { createTemporaryReferenceSet, decodeReply, decodeAction, decodeFormState } = ComponentMod; |
| temporaryReferences = createTemporaryReferenceSet(); |
| if (isMultipartAction) { |
| |
| const formData = await req.request.formData(); |
| if (isFetchAction) { |
| |
| try { |
| actionModId = getActionModIdOrError(actionId, serverModuleMap); |
| } catch (err) { |
| return handleUnrecognizedFetchAction(err); |
| } |
| boundActionArguments = await decodeReply(formData, serverModuleMap, { |
| temporaryReferences |
| }); |
| } else { |
| |
| |
| if (areAllActionIdsValid(formData, serverModuleMap) === false) { |
| |
| |
| throw Object.defineProperty(new Error(`Failed to find Server Action. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`), "__NEXT_ERROR_CODE", { |
| value: "E787", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| const action = await decodeAction(formData, serverModuleMap); |
| if (typeof action === 'function') { |
| |
| |
| warnBadServerActionRequest(); |
| const actionReturnedState = await executeActionAndPrepareForRender(action, [], workStore, requestStore); |
| const formState = await decodeFormState(actionReturnedState, formData, serverModuleMap); |
| |
| |
| return { |
| type: 'done', |
| result: undefined, |
| formState |
| }; |
| } else { |
| |
| return null; |
| } |
| } |
| } else { |
| |
| |
| |
| if (!isFetchAction) { |
| return null; |
| } |
| try { |
| actionModId = getActionModIdOrError(actionId, serverModuleMap); |
| } catch (err) { |
| return handleUnrecognizedFetchAction(err); |
| } |
| |
| |
| |
| const chunks = []; |
| const reader = req.body.getReader(); |
| while(true){ |
| const { done, value } = await reader.read(); |
| if (done) { |
| break; |
| } |
| chunks.push(value); |
| } |
| const actionData = Buffer.concat(chunks).toString('utf-8'); |
| boundActionArguments = await decodeReply(actionData, serverModuleMap, { |
| temporaryReferences |
| }); |
| } |
| } else if ( |
| |
| process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextRequest)(req)) { |
| |
| const { createTemporaryReferenceSet, decodeReply, decodeReplyFromBusboy, decodeAction, decodeFormState } = require(`./react-server.node`); |
| temporaryReferences = createTemporaryReferenceSet(); |
| const { Transform, pipeline } = require('node:stream'); |
| const defaultBodySizeLimit = '1 MB'; |
| const bodySizeLimit = (serverActions == null ? void 0 : serverActions.bodySizeLimit) ?? defaultBodySizeLimit; |
| const bodySizeLimitBytes = bodySizeLimit !== defaultBodySizeLimit ? require('next/dist/compiled/bytes').parse(bodySizeLimit) : 1024 * 1024 |
| ; |
| let size = 0; |
| const sizeLimitTransform = new Transform({ |
| transform (chunk, encoding, callback) { |
| size += Buffer.byteLength(chunk, encoding); |
| if (size > bodySizeLimitBytes) { |
| const { ApiError } = require('../api-utils'); |
| callback(Object.defineProperty(new ApiError(413, `Body exceeded ${bodySizeLimit} limit.\n` + `To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`), "__NEXT_ERROR_CODE", { |
| value: "E394", |
| enumerable: false, |
| configurable: true |
| })); |
| return; |
| } |
| callback(null, chunk); |
| } |
| }); |
| const sizeLimitedBody = pipeline(req.body, sizeLimitTransform, |
| |
| ()=>{}); |
| if (isMultipartAction) { |
| if (isFetchAction) { |
| |
| try { |
| actionModId = getActionModIdOrError(actionId, serverModuleMap); |
| } catch (err) { |
| return handleUnrecognizedFetchAction(err); |
| } |
| const busboy = require('next/dist/compiled/busboy')({ |
| defParamCharset: 'utf8', |
| headers: req.headers, |
| limits: { |
| fieldSize: bodySizeLimitBytes |
| } |
| }); |
| |
| pipeline(sizeLimitedBody, busboy, |
| |
| ()=>{}); |
| boundActionArguments = await decodeReplyFromBusboy(busboy, serverModuleMap, { |
| temporaryReferences |
| }); |
| } else { |
| |
| |
| |
| |
| const fakeRequest = new Request('http://localhost', { |
| method: 'POST', |
| |
| headers: { |
| 'Content-Type': contentType |
| }, |
| body: new ReadableStream({ |
| start: (controller)=>{ |
| sizeLimitedBody.on('data', (chunk)=>{ |
| controller.enqueue(new Uint8Array(chunk)); |
| }); |
| sizeLimitedBody.on('end', ()=>{ |
| controller.close(); |
| }); |
| sizeLimitedBody.on('error', (err)=>{ |
| controller.error(err); |
| }); |
| } |
| }), |
| duplex: 'half' |
| }); |
| const formData = await fakeRequest.formData(); |
| if (areAllActionIdsValid(formData, serverModuleMap) === false) { |
| |
| |
| throw Object.defineProperty(new Error(`Failed to find Server Action. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`), "__NEXT_ERROR_CODE", { |
| value: "E787", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| |
| |
| const action = await decodeAction(formData, serverModuleMap); |
| if (typeof action === 'function') { |
| |
| |
| warnBadServerActionRequest(); |
| const actionReturnedState = await executeActionAndPrepareForRender(action, [], workStore, requestStore); |
| const formState = await decodeFormState(actionReturnedState, formData, serverModuleMap); |
| |
| |
| return { |
| type: 'done', |
| result: undefined, |
| formState |
| }; |
| } else { |
| |
| return null; |
| } |
| } |
| } else { |
| |
| |
| |
| if (!isFetchAction) { |
| return null; |
| } |
| try { |
| actionModId = getActionModIdOrError(actionId, serverModuleMap); |
| } catch (err) { |
| return handleUnrecognizedFetchAction(err); |
| } |
| |
| |
| |
| const chunks = []; |
| for await (const chunk of sizeLimitedBody){ |
| chunks.push(Buffer.from(chunk)); |
| } |
| const actionData = Buffer.concat(chunks).toString('utf-8'); |
| boundActionArguments = await decodeReply(actionData, serverModuleMap, { |
| temporaryReferences |
| }); |
| } |
| } else { |
| throw Object.defineProperty(new Error('Invariant: Unknown request type.'), "__NEXT_ERROR_CODE", { |
| value: "E114", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| const actionMod = await ComponentMod.__next_app__.require(actionModId); |
| const actionHandler = actionMod[ |
| actionId]; |
| const returnVal = await executeActionAndPrepareForRender(actionHandler, boundActionArguments, workStore, requestStore).finally(()=>{ |
| addRevalidationHeader(res, { |
| workStore, |
| requestStore |
| }); |
| }); |
| |
| if (isFetchAction) { |
| const actionResult = await generateFlight(req, ctx, requestStore, { |
| actionResult: Promise.resolve(returnVal), |
| |
| skipFlight: !workStore.pathWasRevalidated || actionWasForwarded, |
| temporaryReferences |
| }); |
| return { |
| type: 'done', |
| result: actionResult |
| }; |
| } else { |
| |
| |
| return null; |
| } |
| }); |
| } catch (err) { |
| if ((0, _redirecterror.isRedirectError)(err)) { |
| const redirectUrl = (0, _redirect.getURLFromRedirectError)(err); |
| const redirectType = (0, _redirect.getRedirectTypeFromError)(err); |
| |
| |
| res.statusCode = _redirectstatuscode.RedirectStatusCode.SeeOther; |
| metadata.statusCode = _redirectstatuscode.RedirectStatusCode.SeeOther; |
| if (isFetchAction) { |
| return { |
| type: 'done', |
| result: await createRedirectRenderResult(req, res, host, redirectUrl, redirectType, ctx.renderOpts.basePath, workStore) |
| }; |
| } |
| |
| res.setHeader('Location', redirectUrl); |
| return { |
| type: 'done', |
| result: _renderresult.default.EMPTY |
| }; |
| } else if ((0, _httpaccessfallback.isHTTPAccessFallbackError)(err)) { |
| res.statusCode = (0, _httpaccessfallback.getAccessFallbackHTTPStatus)(err); |
| metadata.statusCode = res.statusCode; |
| if (isFetchAction) { |
| const promise = Promise.reject(err); |
| try { |
| |
| |
| |
| |
| await promise; |
| } catch { |
| |
| } |
| return { |
| type: 'done', |
| result: await generateFlight(req, ctx, requestStore, { |
| skipFlight: false, |
| actionResult: promise, |
| temporaryReferences |
| }) |
| }; |
| } |
| |
| return { |
| type: 'not-found' |
| }; |
| } |
| |
| |
| if (isFetchAction) { |
| |
| |
| |
| res.statusCode = 500; |
| metadata.statusCode = 500; |
| const promise = Promise.reject(err); |
| try { |
| |
| |
| |
| |
| await promise; |
| } catch { |
| |
| } |
| return { |
| type: 'done', |
| result: await generateFlight(req, ctx, requestStore, { |
| actionResult: promise, |
| |
| skipFlight: !workStore.pathWasRevalidated || actionWasForwarded, |
| temporaryReferences |
| }) |
| }; |
| } |
| |
| throw err; |
| } |
| } |
| async function executeActionAndPrepareForRender(action, args, workStore, requestStore) { |
| requestStore.phase = 'action'; |
| try { |
| return await _workunitasyncstorageexternal.workUnitAsyncStorage.run(requestStore, ()=>action.apply(null, args)); |
| } finally{ |
| requestStore.phase = 'render'; |
| |
| |
| |
| |
| (0, _requeststore.synchronizeMutableCookies)(requestStore); |
| |
| |
| workStore.isDraftMode = requestStore.draftMode.isEnabled; |
| |
| |
| await (0, _revalidationutils.executeRevalidates)(workStore); |
| } |
| } |
| |
| |
| |
| |
| function getActionModIdOrError(actionId, serverModuleMap) { |
| var _serverModuleMap_actionId; |
| |
| if (!actionId) { |
| throw Object.defineProperty(new _invarianterror.InvariantError("Missing 'next-action' header."), "__NEXT_ERROR_CODE", { |
| value: "E664", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| const actionModId = (_serverModuleMap_actionId = serverModuleMap[actionId]) == null ? void 0 : _serverModuleMap_actionId.id; |
| if (!actionModId) { |
| throw getActionNotFoundError(actionId); |
| } |
| return actionModId; |
| } |
| function getActionNotFoundError(actionId) { |
| return Object.defineProperty(new Error(`Failed to find Server Action${actionId ? ` "${actionId}"` : ''}. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`), "__NEXT_ERROR_CODE", { |
| value: "E788", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| const $ACTION_ = '$ACTION_'; |
| const $ACTION_REF_ = '$ACTION_REF_'; |
| const $ACTION_ID_ = '$ACTION_ID_'; |
| const ACTION_ID_EXPECTED_LENGTH = 42; |
| |
| |
| |
| |
| function areAllActionIdsValid(mpaFormData, serverModuleMap) { |
| let hasAtLeastOneAction = false; |
| |
| |
| for (let key of mpaFormData.keys()){ |
| if (!key.startsWith($ACTION_)) { |
| continue; |
| } |
| if (key.startsWith($ACTION_ID_)) { |
| |
| if (isInvalidActionIdFieldName(key, serverModuleMap)) { |
| return false; |
| } |
| hasAtLeastOneAction = true; |
| } else if (key.startsWith($ACTION_REF_)) { |
| |
| const actionDescriptorField = $ACTION_ + key.slice($ACTION_REF_.length) + ':0'; |
| const actionFields = mpaFormData.getAll(actionDescriptorField); |
| if (actionFields.length !== 1) { |
| return false; |
| } |
| const actionField = actionFields[0]; |
| if (typeof actionField !== 'string') { |
| return false; |
| } |
| if (isInvalidStringActionDescriptor(actionField, serverModuleMap)) { |
| return false; |
| } |
| hasAtLeastOneAction = true; |
| } |
| } |
| return hasAtLeastOneAction; |
| } |
| const ACTION_DESCRIPTOR_ID_PREFIX = '{"id":"'; |
| function isInvalidStringActionDescriptor(actionDescriptor, serverModuleMap) { |
| if (actionDescriptor.startsWith(ACTION_DESCRIPTOR_ID_PREFIX) === false) { |
| return true; |
| } |
| const from = ACTION_DESCRIPTOR_ID_PREFIX.length; |
| const to = from + ACTION_ID_EXPECTED_LENGTH; |
| |
| const actionId = actionDescriptor.slice(from, to); |
| if (actionId.length !== ACTION_ID_EXPECTED_LENGTH || actionDescriptor[to] !== '"') { |
| return true; |
| } |
| const entry = serverModuleMap[actionId]; |
| if (entry == null) { |
| return true; |
| } |
| return false; |
| } |
| function isInvalidActionIdFieldName(actionIdFieldName, serverModuleMap) { |
| |
| |
| |
| if (actionIdFieldName.length !== $ACTION_ID_.length + ACTION_ID_EXPECTED_LENGTH) { |
| |
| return true; |
| } |
| const actionId = actionIdFieldName.slice($ACTION_ID_.length); |
| const entry = serverModuleMap[actionId]; |
| if (entry == null) { |
| return true; |
| } |
| return false; |
| } |
|
|
| |