{"version":3,"sources":["../../../../../src/server/lib/router-utils/resolve-routes.ts"],"sourcesContent":["import type { FsOutput } from './filesystem'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { NextConfigRuntime } from '../../config-shared'\nimport type { RenderServer, initialize } from '../router-server'\nimport type { PatchMatcher } from '../../../shared/lib/router/utils/path-match'\nimport type { Redirect } from '../../../types'\nimport type { Header } from '../../../lib/load-custom-routes'\nimport type { UnwrapPromise } from '../../../lib/coalesced-function'\nimport type { NextUrlWithParsedQuery } from '../../request-meta'\n\nimport path from 'node:path'\nimport setupDebug from 'next/dist/compiled/debug'\nimport { getCloneableBody } from '../../body-streams'\nimport { filterReqHeaders, ipcForbiddenHeaders } from '../server-ipc/utils'\nimport { stringifyQuery } from '../../server-route-utils'\nimport { formatHostname } from '../format-hostname'\nimport { toNodeOutgoingHttpHeaders } from '../../web/utils'\nimport { isAbortError } from '../../pipe-readable'\nimport { getHostname } from '../../../shared/lib/get-hostname'\nimport {\n  getRedirectStatus,\n  allowedStatusCodes,\n} from '../../../lib/redirect-status'\nimport { normalizeRepeatedSlashes } from '../../../shared/lib/utils'\nimport { getRelativeURL } from '../../../shared/lib/router/utils/relativize-url'\nimport { addPathPrefix } from '../../../shared/lib/router/utils/add-path-prefix'\nimport { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'\nimport { parseUrl } from '../../../shared/lib/router/utils/parse-url'\nimport { detectDomainLocale } from '../../../shared/lib/i18n/detect-domain-locale'\nimport { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'\nimport { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'\nimport { NextDataPathnameNormalizer } from '../../normalizers/request/next-data'\nimport { BasePathPathnameNormalizer } from '../../normalizers/request/base-path'\n\nimport { addRequestMeta } from '../../request-meta'\nimport { isRSCRequestHeader } from '../is-rsc-request'\nimport {\n  compileNonPath,\n  matchHas,\n  prepareDestination,\n} from '../../../shared/lib/router/utils/prepare-destination'\nimport type { TLSSocket } from 'tls'\nimport {\n  NEXT_REWRITTEN_PATH_HEADER,\n  NEXT_REWRITTEN_QUERY_HEADER,\n  RSC_HEADER,\n} from '../../../client/components/app-router-headers'\n\nconst debug = setupDebug('next:router-server:resolve-routes')\n\nexport function getResolveRoutes(\n  fsChecker: UnwrapPromise<\n    ReturnType<typeof import('./filesystem').setupFsCheck>\n  >,\n  config: NextConfigRuntime,\n  opts: Parameters<typeof initialize>[0],\n  renderServer: RenderServer,\n  renderServerOpts: Parameters<RenderServer['initialize']>[0],\n  ensureMiddleware?: (url?: string) => Promise<void>\n) {\n  let clientHashes: Record<string, string> | undefined = undefined\n  if (process.env.__NEXT_TEST_MODE && process.env.IS_TURBOPACK_TEST) {\n    try {\n      clientHashes = JSON.parse(\n        (require('fs') as typeof import('fs')).readFileSync(\n          path.join(opts.dir, config.distDir, 'immutable-static-hashes.json'),\n          'utf8'\n        )\n      )\n    } catch {}\n  }\n\n  type Route = {\n    /**\n     * The path matcher to check if this route applies to this request.\n     */\n    match: PatchMatcher\n    check?: boolean\n    name?: string\n  } & Partial<Header> &\n    Partial<Redirect>\n\n  let routes: Route[] | null = null\n  const calculateRoutes = () => {\n    return [\n      // _next/data with middleware handling\n      { match: () => ({}), name: 'middleware_next_data' },\n\n      ...(opts.minimalMode ? [] : fsChecker.headers),\n      ...(opts.minimalMode ? [] : fsChecker.redirects),\n\n      // check middleware (using matchers)\n      { match: () => ({}), name: 'middleware' },\n\n      ...(opts.minimalMode ? [] : fsChecker.rewrites.beforeFiles),\n\n      // check middleware (using matchers)\n      { match: () => ({}), name: 'before_files_end' },\n\n      // we check exact matches on fs before continuing to\n      // after files rewrites\n      { match: () => ({}), name: 'check_fs' },\n\n      ...(opts.minimalMode ? [] : fsChecker.rewrites.afterFiles),\n\n      // we always do the check: true handling before continuing to\n      // fallback rewrites\n      {\n        check: true,\n        match: () => ({}),\n        name: 'after files check: true',\n      },\n\n      ...(opts.minimalMode ? [] : fsChecker.rewrites.fallback),\n    ]\n  }\n\n  async function resolveRoutes({\n    req,\n    res,\n    isUpgradeReq,\n    invokedOutputs,\n  }: {\n    req: IncomingMessage\n    res: ServerResponse\n    isUpgradeReq: boolean\n    signal: AbortSignal\n    invokedOutputs?: Set<string>\n  }): Promise<{\n    finished: boolean\n    statusCode?: number\n    bodyStream?: ReadableStream | null\n    resHeaders: Record<string, string | string[]> | null\n    parsedUrl: NextUrlWithParsedQuery\n    matchedOutput?: FsOutput | null\n  }> {\n    let finished = false\n    let resHeaders: Record<string, string | string[]> = {}\n    let matchedOutput: FsOutput | null = null\n    let parsedUrl = parseUrl(req.url || '') as NextUrlWithParsedQuery\n    let didRewrite = false\n\n    const urlParts = (req.url || '').split('?', 1)\n    const urlNoQuery = urlParts[0]\n\n    // Refresh the routes every time in development mode, but only initialize them\n    // once in production. We don't need to recompute these every time unless the routes\n    // are changing like in development, and the performance can be costly.\n    if (!routes || opts.dev) {\n      routes = calculateRoutes()\n    }\n\n    // this normalizes repeated slashes in the path e.g. hello//world ->\n    // hello/world or backslashes to forward slashes, this does not\n    // handle trailing slash as that is handled the same as a next.config.js\n    // redirect\n    if (urlNoQuery?.match(/(\\\\|\\/\\/)/)) {\n      parsedUrl = parseUrl(normalizeRepeatedSlashes(req.url!))\n      return {\n        parsedUrl,\n        resHeaders,\n        finished: true,\n        statusCode: 308,\n      }\n    }\n    // TODO: inherit this from higher up\n    const protocol =\n      (req?.socket as TLSSocket)?.encrypted ||\n      req.headers['x-forwarded-proto']?.includes('https')\n        ? 'https'\n        : 'http'\n\n    // When there are hostname and port we build an absolute URL\n    const initUrl = (config.experimental as any).trustHostHeader\n      ? `https://${req.headers.host || 'localhost'}${req.url}`\n      : opts.port\n        ? `${protocol}://${formatHostname(opts.hostname || 'localhost')}:${\n            opts.port\n          }${req.url}`\n        : req.url || ''\n\n    addRequestMeta(req, 'initURL', initUrl)\n    addRequestMeta(req, 'initQuery', { ...parsedUrl.query })\n    addRequestMeta(req, 'initProtocol', protocol)\n\n    if (!isUpgradeReq) {\n      const bodySizeLimit = config.experimental.proxyClientMaxBodySize as\n        | number\n        | undefined\n      addRequestMeta(req, 'clonableBody', getCloneableBody(req, bodySizeLimit))\n    }\n\n    const maybeAddTrailingSlash = (pathname: string) => {\n      if (\n        config.trailingSlash &&\n        !config.skipProxyUrlNormalize &&\n        !pathname.endsWith('/')\n      ) {\n        return `${pathname}/`\n      }\n      return pathname\n    }\n\n    const setIsNextDataRequest = () => {\n      addRequestMeta(req, 'isNextDataReq', true)\n      req.headers['x-nextjs-data'] = '1'\n    }\n\n    let domainLocale: ReturnType<typeof detectDomainLocale> | undefined\n    let defaultLocale: string | undefined\n    let initialLocaleResult:\n      | ReturnType<typeof normalizeLocalePath>\n      | undefined = undefined\n\n    if (config.i18n) {\n      const hadTrailingSlash = parsedUrl.pathname?.endsWith('/')\n      const hadBasePath = pathHasPrefix(\n        parsedUrl.pathname || '',\n        config.basePath\n      )\n      let normalizedPath = parsedUrl.pathname || '/'\n\n      if (config.basePath && pathHasPrefix(normalizedPath, config.basePath)) {\n        normalizedPath = removePathPrefix(normalizedPath, config.basePath)\n      } else if (\n        config.assetPrefix &&\n        pathHasPrefix(normalizedPath, config.assetPrefix)\n      ) {\n        normalizedPath = removePathPrefix(normalizedPath, config.assetPrefix)\n      }\n\n      initialLocaleResult = normalizeLocalePath(\n        normalizedPath,\n        config.i18n.locales\n      )\n\n      domainLocale = detectDomainLocale(\n        config.i18n.domains,\n        getHostname(parsedUrl, req.headers)\n      )\n      defaultLocale = domainLocale?.defaultLocale || config.i18n.defaultLocale\n\n      addRequestMeta(req, 'defaultLocale', defaultLocale)\n      addRequestMeta(\n        req,\n        'locale',\n        initialLocaleResult.detectedLocale || defaultLocale\n      )\n\n      // ensure locale is present for resolving routes\n      if (\n        !initialLocaleResult.detectedLocale &&\n        !initialLocaleResult.pathname.startsWith('/_next/')\n      ) {\n        parsedUrl.pathname = addPathPrefix(\n          initialLocaleResult.pathname === '/'\n            ? `/${defaultLocale}`\n            : addPathPrefix(\n                initialLocaleResult.pathname || '',\n                `/${defaultLocale}`\n              ),\n          hadBasePath ? config.basePath : ''\n        )\n\n        if (hadTrailingSlash) {\n          parsedUrl.pathname = maybeAddTrailingSlash(parsedUrl.pathname)\n        }\n      }\n    }\n\n    const checkLocaleApi = (pathname: string) => {\n      if (\n        config.i18n &&\n        pathname === urlNoQuery &&\n        initialLocaleResult?.detectedLocale &&\n        pathHasPrefix(initialLocaleResult.pathname, '/api')\n      ) {\n        return true\n      }\n    }\n\n    async function checkTrue() {\n      const pathname = parsedUrl.pathname || '/'\n\n      if (checkLocaleApi(pathname)) {\n        return\n      }\n      if (!invokedOutputs?.has(pathname)) {\n        const output = await fsChecker.getItem(pathname)\n\n        if (output) {\n          if (\n            config.useFileSystemPublicRoutes ||\n            didRewrite ||\n            (output.type !== 'appFile' && output.type !== 'pageFile')\n          ) {\n            return output\n          }\n        }\n      }\n      const dynamicRoutes = fsChecker.getDynamicRoutes()\n      let curPathname = parsedUrl.pathname\n\n      if (config.basePath) {\n        if (!pathHasPrefix(curPathname || '', config.basePath)) {\n          return\n        }\n        curPathname = curPathname?.substring(config.basePath.length) || '/'\n      }\n      const localeResult = fsChecker.handleLocale(curPathname || '')\n\n      for (const route of dynamicRoutes) {\n        // when resolving fallback: false the\n        // render worker may return a no-fallback response\n        // which signals we need to continue resolving.\n        // TODO: optimize this to collect static paths\n        // to use at the routing layer\n        if (invokedOutputs?.has(route.page)) {\n          continue\n        }\n        const params = route.match(localeResult.pathname)\n\n        if (params) {\n          const pageOutput = await fsChecker.getItem(\n            addPathPrefix(route.page, config.basePath || '')\n          )\n\n          // i18n locales aren't matched for app dir\n          if (\n            pageOutput?.type === 'appFile' &&\n            initialLocaleResult?.detectedLocale\n          ) {\n            continue\n          }\n\n          if (pageOutput && curPathname?.startsWith('/_next/data')) {\n            setIsNextDataRequest()\n          }\n\n          if (config.useFileSystemPublicRoutes || didRewrite) {\n            return pageOutput\n          }\n        }\n      }\n    }\n\n    const normalizers = {\n      basePath:\n        config.basePath && config.basePath !== '/'\n          ? new BasePathPathnameNormalizer(config.basePath)\n          : undefined,\n      data: new NextDataPathnameNormalizer(fsChecker.buildId),\n    }\n\n    async function handleRoute(\n      route: Route\n    ): Promise<UnwrapPromise<ReturnType<typeof resolveRoutes>> | void> {\n      let curPathname = parsedUrl.pathname || '/'\n\n      if (config.i18n && route.internal) {\n        const hadTrailingSlash = curPathname.endsWith('/')\n\n        if (config.basePath) {\n          curPathname = removePathPrefix(curPathname, config.basePath)\n        }\n        const hadBasePath = curPathname !== parsedUrl.pathname\n\n        const localeResult = normalizeLocalePath(\n          curPathname,\n          config.i18n.locales\n        )\n        const isDefaultLocale = localeResult.detectedLocale === defaultLocale\n\n        if (isDefaultLocale) {\n          curPathname =\n            localeResult.pathname === '/' && hadBasePath\n              ? config.basePath\n              : addPathPrefix(\n                  localeResult.pathname,\n                  hadBasePath ? config.basePath : ''\n                )\n        } else if (hadBasePath) {\n          curPathname =\n            curPathname === '/'\n              ? config.basePath\n              : addPathPrefix(curPathname, config.basePath)\n        }\n\n        if ((isDefaultLocale || hadBasePath) && hadTrailingSlash) {\n          curPathname = maybeAddTrailingSlash(curPathname)\n        }\n      }\n      let params = route.match(curPathname)\n\n      if ((route.has || route.missing) && params) {\n        const hasParams = matchHas(\n          req,\n          parsedUrl.query,\n          route.has,\n          route.missing\n        )\n        if (hasParams) {\n          Object.assign(params, hasParams)\n        } else {\n          params = false\n        }\n      }\n\n      if (params) {\n        if (\n          fsChecker.exportPathMapRoutes &&\n          route.name === 'before_files_end'\n        ) {\n          for (const exportPathMapRoute of fsChecker.exportPathMapRoutes) {\n            const result = await handleRoute(exportPathMapRoute)\n\n            if (result) {\n              return result\n            }\n          }\n        }\n\n        if (route.name === 'middleware_next_data' && parsedUrl.pathname) {\n          if (fsChecker.getMiddlewareMatchers()?.length) {\n            let normalized = parsedUrl.pathname\n\n            // Remove the base path if it exists.\n            const hadBasePath = normalizers.basePath?.match(parsedUrl.pathname)\n            if (hadBasePath && normalizers.basePath) {\n              normalized = normalizers.basePath.normalize(normalized, true)\n            }\n\n            const isNextDataPath =\n              pathHasPrefix(normalized, '/_next/data') &&\n              normalized.endsWith('.json')\n            const hasCurrentBuildIdDataPath = normalizers.data.match(normalized)\n\n            let updated = false\n            if (hasCurrentBuildIdDataPath) {\n              updated = true\n              normalized = normalizers.data.normalize(normalized, true)\n            }\n            if (isNextDataPath) {\n              setIsNextDataRequest()\n            }\n\n            if (config.i18n) {\n              const curLocaleResult = normalizeLocalePath(\n                normalized,\n                config.i18n.locales\n              )\n\n              if (curLocaleResult.detectedLocale) {\n                addRequestMeta(req, 'locale', curLocaleResult.detectedLocale)\n              } else if (\n                defaultLocale &&\n                !curLocaleResult.pathname.startsWith('/_next/')\n              ) {\n                // Match normalized _next/data requests against the same\n                // locale-prefixed internal pathname shape used by direct page\n                // requests when the default locale was inferred.\n                normalized = addPathPrefix(\n                  curLocaleResult.pathname === '/'\n                    ? `/${defaultLocale}`\n                    : addPathPrefix(\n                        curLocaleResult.pathname || '',\n                        `/${defaultLocale}`\n                      )\n                )\n              }\n            }\n\n            // If we updated the pathname, and it had a base path, re-add the\n            // base path.\n            if (updated) {\n              if (hadBasePath) {\n                normalized =\n                  normalized === '/'\n                    ? config.basePath\n                    : path.posix.join(config.basePath, normalized)\n              }\n\n              // Re-add the trailing slash (if required).\n              normalized = maybeAddTrailingSlash(normalized)\n\n              parsedUrl.pathname = normalized\n            }\n          }\n        }\n\n        if (route.name === 'check_fs') {\n          const pathname = parsedUrl.pathname || '/'\n\n          if (invokedOutputs?.has(pathname) || checkLocaleApi(pathname)) {\n            return\n          }\n          const output = await fsChecker.getItem(pathname)\n\n          if (\n            output &&\n            !(\n              config.i18n &&\n              initialLocaleResult?.detectedLocale &&\n              pathHasPrefix(pathname, '/api')\n            )\n          ) {\n            if (\n              config.useFileSystemPublicRoutes ||\n              didRewrite ||\n              (output.type !== 'appFile' && output.type !== 'pageFile')\n            ) {\n              matchedOutput = output\n\n              if (output.locale) {\n                addRequestMeta(req, 'locale', output.locale)\n              }\n\n              if (\n                process.env.__NEXT_TEST_MODE &&\n                process.env.IS_TURBOPACK_TEST &&\n                output.type === 'nextStaticFolder' &&\n                config.deploymentId\n              ) {\n                let useImmutableToken =\n                  config.experimental.immutableAssetToken &&\n                  clientHashes![`static${decodeURI(output.itemPath)}`]\n\n                const expectedToken = useImmutableToken\n                  ? config.experimental.immutableAssetToken\n                  : config.deploymentId\n                if (parsedUrl.query.dpl !== expectedToken) {\n                  console.error(\n                    `Invalid dpl query param: ${req.url}, expected: ${expectedToken}`\n                  )\n                  return {\n                    finished: true,\n                    parsedUrl,\n                    resHeaders,\n                    matchedOutput: null,\n                  }\n                }\n              }\n\n              return {\n                parsedUrl,\n                resHeaders,\n                finished: true,\n                matchedOutput,\n              }\n            }\n          }\n        }\n\n        if (!opts.minimalMode && route.name === 'middleware') {\n          const match = fsChecker.getMiddlewareMatchers()\n          let maybeDecodedPathname = parsedUrl.pathname || '/'\n\n          try {\n            maybeDecodedPathname = decodeURIComponent(maybeDecodedPathname)\n          } catch {\n            /* non-fatal we can't decode so can't match it */\n          }\n\n          if (\n            // @ts-expect-error BaseNextRequest stuff\n            match?.(parsedUrl.pathname, req, parsedUrl.query) ||\n            match?.(\n              maybeDecodedPathname,\n              // @ts-expect-error BaseNextRequest stuff\n              req,\n              parsedUrl.query\n            )\n          ) {\n            if (ensureMiddleware) {\n              await ensureMiddleware(req.url)\n            }\n\n            const serverResult =\n              await renderServer?.initialize(renderServerOpts)\n\n            if (!serverResult) {\n              throw new Error(`Failed to initialize render server \"middleware\"`)\n            }\n\n            addRequestMeta(req, 'invokePath', '')\n            addRequestMeta(req, 'invokeOutput', '')\n            addRequestMeta(req, 'invokeQuery', {})\n            addRequestMeta(req, 'middlewareInvoke', true)\n            if (opts.dev) {\n              addRequestMeta(\n                req,\n                'devRequestTimingMiddlewareStart',\n                process.hrtime.bigint()\n              )\n            }\n            debug('invoking middleware', req.url, req.headers)\n\n            let middlewareRes: Response | undefined = undefined\n            let bodyStream: ReadableStream | undefined = undefined\n            try {\n              try {\n                await serverResult.requestHandler(req, res, parsedUrl)\n              } catch (err: any) {\n                if (!('result' in err) || !('response' in err.result)) {\n                  throw err\n                }\n                middlewareRes = err.result.response as Response\n                res.statusCode = middlewareRes.status\n\n                if (middlewareRes.body) {\n                  bodyStream = middlewareRes.body\n                } else if (middlewareRes.status) {\n                  bodyStream = new ReadableStream({\n                    start(controller) {\n                      controller.enqueue('')\n                      controller.close()\n                    },\n                  })\n                }\n              } finally {\n                if (opts.dev) {\n                  addRequestMeta(\n                    req,\n                    'devRequestTimingMiddlewareEnd',\n                    process.hrtime.bigint()\n                  )\n                }\n              }\n            } catch (e) {\n              // If the client aborts before we can receive a response object\n              // (when the headers are flushed), then we can early exit without\n              // further processing.\n              if (isAbortError(e)) {\n                return {\n                  parsedUrl,\n                  resHeaders,\n                  finished: true,\n                }\n              }\n              throw e\n            }\n\n            if (res.closed || res.finished || !middlewareRes) {\n              return {\n                parsedUrl,\n                resHeaders,\n                finished: true,\n              }\n            }\n\n            const middlewareHeaders = toNodeOutgoingHttpHeaders(\n              middlewareRes.headers\n            ) as Record<string, string | string[] | undefined>\n\n            debug('middleware res', middlewareRes.status, middlewareHeaders)\n\n            if (middlewareHeaders['x-middleware-override-headers']) {\n              const overriddenHeaders: Set<string> = new Set()\n              let overrideHeaders: string | string[] =\n                middlewareHeaders['x-middleware-override-headers']\n\n              if (typeof overrideHeaders === 'string') {\n                overrideHeaders = overrideHeaders.split(',')\n              }\n\n              for (const key of overrideHeaders) {\n                overriddenHeaders.add(key.trim())\n              }\n              delete middlewareHeaders['x-middleware-override-headers']\n\n              // Delete headers.\n              for (const key of Object.keys(req.headers)) {\n                if (!overriddenHeaders.has(key)) {\n                  delete req.headers[key]\n                }\n              }\n\n              // Update or add headers.\n              for (const key of overriddenHeaders.keys()) {\n                const valueKey = 'x-middleware-request-' + key\n                const newValue = middlewareHeaders[valueKey]\n                const oldValue = req.headers[key]\n\n                if (oldValue !== newValue) {\n                  req.headers[key] = newValue === null ? undefined : newValue\n                }\n                delete middlewareHeaders[valueKey]\n              }\n            }\n\n            if (\n              !middlewareHeaders['x-middleware-rewrite'] &&\n              !middlewareHeaders['x-middleware-next'] &&\n              !middlewareHeaders['location']\n            ) {\n              middlewareHeaders['x-middleware-refresh'] = '1'\n            }\n            delete middlewareHeaders['x-middleware-next']\n\n            for (const [key, value] of Object.entries({\n              ...filterReqHeaders(middlewareHeaders, ipcForbiddenHeaders),\n            })) {\n              if (\n                [\n                  'content-length',\n                  'x-middleware-rewrite',\n                  'x-middleware-redirect',\n                  'x-middleware-refresh',\n                ].includes(key)\n              ) {\n                continue\n              }\n\n              // for set-cookie, the header shouldn't be added to the response\n              // as it's only needed for the request to the middleware function.\n              if (key === 'x-middleware-set-cookie') {\n                req.headers[key] = value\n                continue\n              }\n\n              if (value) {\n                resHeaders[key] = value\n                req.headers[key] = value\n              }\n            }\n\n            if (middlewareHeaders['x-middleware-rewrite']) {\n              const value = middlewareHeaders['x-middleware-rewrite'] as string\n              const destination = getRelativeURL(value, initUrl)\n              resHeaders['x-middleware-rewrite'] = destination\n\n              parsedUrl = parseUrl(destination)\n\n              if (parsedUrl.protocol) {\n                return {\n                  parsedUrl,\n                  resHeaders,\n                  finished: true,\n                }\n              }\n\n              if (config.i18n) {\n                const curLocaleResult = normalizeLocalePath(\n                  parsedUrl.pathname || '',\n                  config.i18n.locales\n                )\n\n                if (curLocaleResult.detectedLocale) {\n                  addRequestMeta(req, 'locale', curLocaleResult.detectedLocale)\n                }\n              }\n            }\n\n            if (middlewareHeaders['location']) {\n              const value = middlewareHeaders['location'] as string\n\n              // Only process Location header as a redirect if it has a proper redirect status\n              // This prevents a Location header with non-redirect status from being treated as a redirect\n              const isRedirectStatus = allowedStatusCodes.has(\n                middlewareRes.status\n              )\n\n              if (isRedirectStatus) {\n                // Process as redirect: update parsedUrl and convert to relative URL\n                const rel = getRelativeURL(value, initUrl)\n                resHeaders['location'] = rel\n                parsedUrl = parseUrl(rel)\n\n                return {\n                  parsedUrl,\n                  resHeaders,\n                  finished: true,\n                  statusCode: middlewareRes.status,\n                }\n              } else {\n                // Not a redirect: just pass through the Location header\n                resHeaders['location'] = value\n\n                return {\n                  parsedUrl,\n                  resHeaders,\n                  finished: true,\n                  bodyStream,\n                  statusCode: middlewareRes.status,\n                }\n              }\n            }\n\n            if (middlewareHeaders['x-middleware-refresh']) {\n              return {\n                parsedUrl,\n                resHeaders,\n                finished: true,\n                bodyStream,\n                statusCode: middlewareRes.status,\n              }\n            }\n          }\n        }\n\n        // handle redirect\n        if (\n          ('statusCode' in route || 'permanent' in route) &&\n          route.destination\n        ) {\n          const { parsedDestination } = prepareDestination({\n            appendParamsToQuery: false,\n            destination: route.destination,\n            params: params,\n            query: parsedUrl.query,\n          })\n\n          const { query } = parsedDestination\n          delete (parsedDestination as any).query\n\n          parsedDestination.search = stringifyQuery(req as any, query)\n\n          parsedDestination.pathname = normalizeRepeatedSlashes(\n            parsedDestination.pathname\n          )\n\n          return {\n            finished: true,\n            parsedUrl: parsedDestination,\n            resHeaders: null,\n            statusCode: getRedirectStatus(route),\n          }\n        }\n\n        // handle headers\n        if (route.headers) {\n          const hasParams = Object.keys(params).length > 0\n          for (const header of route.headers) {\n            let { key, value } = header\n            if (hasParams) {\n              key = compileNonPath(key, params)\n              value = compileNonPath(value, params)\n            }\n\n            if (key.toLowerCase() === 'set-cookie') {\n              if (!Array.isArray(resHeaders[key])) {\n                const val = resHeaders[key]\n                resHeaders[key] = typeof val === 'string' ? [val] : []\n              }\n              ;(resHeaders[key] as string[]).push(value)\n            } else {\n              resHeaders[key] = value\n            }\n          }\n        }\n\n        // handle rewrite\n        if (route.destination) {\n          let rewriteParams = params\n\n          const { parsedDestination } = prepareDestination({\n            appendParamsToQuery: true,\n            destination: route.destination,\n            params: rewriteParams,\n            query: parsedUrl.query,\n          })\n\n          // Check to see if this is a non-relative rewrite. If it is, we need\n          // to check to see if it's an allowed origin to receive the rewritten\n          // headers.\n          const parsedDestinationOrigin = parsedDestination.origin\n          const isAllowedOrigin = parsedDestinationOrigin\n            ? config.experimental.clientParamParsingOrigins?.some((origin) =>\n                new RegExp(origin).test(parsedDestinationOrigin)\n              )\n            : false\n\n          // Set the rewrite headers only if this is a RSC request.\n          if (\n            isRSCRequestHeader(req.headers[RSC_HEADER]) &&\n            (!parsedDestination.origin || isAllowedOrigin)\n          ) {\n            // We set the rewritten path and query headers on the response now\n            // that we know that the it's not an external rewrite.\n            if (parsedUrl.pathname !== parsedDestination.pathname) {\n              res.setHeader(\n                NEXT_REWRITTEN_PATH_HEADER,\n                parsedDestination.pathname\n              )\n            }\n            if (parsedUrl.search !== parsedDestination.search) {\n              res.setHeader(\n                NEXT_REWRITTEN_QUERY_HEADER,\n                // remove the leading ? from the search\n                parsedDestination.search.slice(1)\n              )\n            }\n          }\n\n          if (parsedDestination.protocol) {\n            return {\n              parsedUrl: parsedDestination,\n              resHeaders: null,\n              finished: true,\n            }\n          }\n\n          if (config.i18n) {\n            const curLocaleResult = normalizeLocalePath(\n              removePathPrefix(parsedDestination.pathname, config.basePath),\n              config.i18n.locales\n            )\n\n            if (curLocaleResult.detectedLocale) {\n              addRequestMeta(req, 'locale', curLocaleResult.detectedLocale)\n            }\n          }\n          didRewrite = true\n          parsedUrl.pathname = parsedDestination.pathname\n          Object.assign(parsedUrl.query, parsedDestination.query)\n        }\n\n        // handle check: true\n        if (route.check) {\n          const output = await checkTrue()\n\n          if (output) {\n            return {\n              parsedUrl,\n              resHeaders,\n              finished: true,\n              matchedOutput: output,\n            }\n          }\n        }\n      }\n    }\n\n    for (const route of routes) {\n      const result = await handleRoute(route)\n      if (result) {\n        if (result.matchedOutput) {\n          // handle onMatchHeaders\n          for (const onMatchHeaders of fsChecker.onMatchHeaders) {\n            await handleRoute(onMatchHeaders)\n          }\n        }\n        return result\n      }\n    }\n\n    return {\n      finished,\n      parsedUrl,\n      resHeaders,\n      matchedOutput,\n    }\n  }\n\n  return resolveRoutes\n}\n"],"names":["path","setupDebug","getCloneableBody","filterReqHeaders","ipcForbiddenHeaders","stringifyQuery","formatHostname","toNodeOutgoingHttpHeaders","isAbortError","getHostname","getRedirectStatus","allowedStatusCodes","normalizeRepeatedSlashes","getRelativeURL","addPathPrefix","pathHasPrefix","parseUrl","detectDomainLocale","normalizeLocalePath","removePathPrefix","NextDataPathnameNormalizer","BasePathPathnameNormalizer","addRequestMeta","isRSCRequestHeader","compileNonPath","matchHas","prepareDestination","NEXT_REWRITTEN_PATH_HEADER","NEXT_REWRITTEN_QUERY_HEADER","RSC_HEADER","debug","getResolveRoutes","fsChecker","config","opts","renderServer","renderServerOpts","ensureMiddleware","clientHashes","undefined","process","env","__NEXT_TEST_MODE","IS_TURBOPACK_TEST","JSON","parse","require","readFileSync","join","dir","distDir","routes","calculateRoutes","match","name","minimalMode","headers","redirects","rewrites","beforeFiles","afterFiles","check","fallback","resolveRoutes","req","res","isUpgradeReq","invokedOutputs","finished","resHeaders","matchedOutput","parsedUrl","url","didRewrite","urlParts","split","urlNoQuery","dev","statusCode","protocol","socket","encrypted","includes","initUrl","experimental","trustHostHeader","host","port","hostname","query","bodySizeLimit","proxyClientMaxBodySize","maybeAddTrailingSlash","pathname","trailingSlash","skipProxyUrlNormalize","endsWith","setIsNextDataRequest","domainLocale","defaultLocale","initialLocaleResult","i18n","hadTrailingSlash","hadBasePath","basePath","normalizedPath","assetPrefix","locales","domains","detectedLocale","startsWith","checkLocaleApi","checkTrue","has","output","getItem","useFileSystemPublicRoutes","type","dynamicRoutes","getDynamicRoutes","curPathname","substring","length","localeResult","handleLocale","route","page","params","pageOutput","normalizers","data","buildId","handleRoute","internal","isDefaultLocale","missing","hasParams","Object","assign","exportPathMapRoutes","exportPathMapRoute","result","getMiddlewareMatchers","normalized","normalize","isNextDataPath","hasCurrentBuildIdDataPath","updated","curLocaleResult","posix","locale","deploymentId","useImmutableToken","immutableAssetToken","decodeURI","itemPath","expectedToken","dpl","console","error","maybeDecodedPathname","decodeURIComponent","serverResult","initialize","Error","hrtime","bigint","middlewareRes","bodyStream","requestHandler","err","response","status","body","ReadableStream","start","controller","enqueue","close","e","closed","middlewareHeaders","overriddenHeaders","Set","overrideHeaders","key","add","trim","keys","valueKey","newValue","oldValue","value","entries","destination","isRedirectStatus","rel","parsedDestination","appendParamsToQuery","search","header","toLowerCase","Array","isArray","val","push","rewriteParams","parsedDestinationOrigin","origin","isAllowedOrigin","clientParamParsingOrigins","some","RegExp","test","setHeader","slice","onMatchHeaders"],"mappings":"AAUA,OAAOA,UAAU,YAAW;AAC5B,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,gBAAgB,QAAQ,qBAAoB;AACrD,SAASC,gBAAgB,EAAEC,mBAAmB,QAAQ,sBAAqB;AAC3E,SAASC,cAAc,QAAQ,2BAA0B;AACzD,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,yBAAyB,QAAQ,kBAAiB;AAC3D,SAASC,YAAY,QAAQ,sBAAqB;AAClD,SAASC,WAAW,QAAQ,mCAAkC;AAC9D,SACEC,iBAAiB,EACjBC,kBAAkB,QACb,+BAA8B;AACrC,SAASC,wBAAwB,QAAQ,4BAA2B;AACpE,SAASC,cAAc,QAAQ,kDAAiD;AAChF,SAASC,aAAa,QAAQ,mDAAkD;AAChF,SAASC,aAAa,QAAQ,mDAAkD;AAChF,SAASC,QAAQ,QAAQ,6CAA4C;AACrE,SAASC,kBAAkB,QAAQ,gDAA+C;AAClF,SAASC,mBAAmB,QAAQ,iDAAgD;AACpF,SAASC,gBAAgB,QAAQ,sDAAqD;AACtF,SAASC,0BAA0B,QAAQ,sCAAqC;AAChF,SAASC,0BAA0B,QAAQ,sCAAqC;AAEhF,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,kBAAkB,QAAQ,oBAAmB;AACtD,SACEC,cAAc,EACdC,QAAQ,EACRC,kBAAkB,QACb,uDAAsD;AAE7D,SACEC,0BAA0B,EAC1BC,2BAA2B,EA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