{"version":3,"sources":["../../../src/server/web/adapter.ts"],"sourcesContent":["import type { RequestData, FetchEventResult } from './types'\nimport type { RequestInit } from './spec-extension/request'\nimport { PageSignatureError } from './error'\nimport { fromNodeOutgoingHttpHeaders, normalizeNextQueryParam } from './utils'\nimport {\n  NextFetchEvent,\n  getWaitUntilPromiseFromEvent,\n} from './spec-extension/fetch-event'\nimport { NextRequest } from './spec-extension/request'\nimport { NextResponse } from './spec-extension/response'\nimport {\n  parseRelativeURL,\n  getRelativeURL,\n} from '../../shared/lib/router/utils/relativize-url'\nimport { NextURL } from './next-url'\nimport { stripInternalSearchParams } from '../internal-utils'\nimport { normalizeRscURL } from '../../shared/lib/router/utils/app-paths'\nimport {\n  FLIGHT_HEADERS,\n  NEXT_REWRITTEN_PATH_HEADER,\n  NEXT_REWRITTEN_QUERY_HEADER,\n  NEXT_RSC_UNION_QUERY,\n  RSC_HEADER,\n} from '../../client/components/app-router-headers'\nimport { ensureInstrumentationRegistered } from './globals'\nimport { createRequestStoreForAPI } from '../async-storage/request-store'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createWorkStore } from '../async-storage/work-store'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { ResolvedCacheLifeProfiles } from '../config-shared'\nimport { NEXT_ROUTER_PREFETCH_HEADER } from '../../client/components/app-router-headers'\nimport { getTracer } from '../lib/trace/tracer'\nimport type { TextMapGetter } from 'next/dist/compiled/@opentelemetry/api'\nimport { MiddlewareSpan } from '../lib/trace/constants'\nimport { CloseController } from './web-on-close'\nimport { getEdgePreviewProps } from './get-edge-preview-props'\nimport { getBuiltinRequestContext } from '../after/builtin-request-context'\nimport { getImplicitTags } from '../lib/implicit-tags'\nimport { isRSCRequestHeader } from '../lib/is-rsc-request'\nimport { setRequestMeta } from '../request-meta'\n\n// The proxy (middleware) does not support `'use cache'`, so this work store\n// never reaches the code that reads `cacheLife` (and `'use cache'` is\n// disallowed on the edge runtime anyway). This sentinel satisfies the\n// non-optional type while throwing if `default` is ever read, matching the\n// \"never read\" sentinels used for the proxy's other unused renderOpts fields\n// (`staticPageGenerationTimeout: 0`, `useCacheTimeout: 0`). It surfaces loudly\n// rather than silently serving a misleading profile.\nconst proxyCacheLifeProfiles: ResolvedCacheLifeProfiles = {\n  get default(): never {\n    throw new InvariantError(\n      'Proxy does not support `use cache`, so reading its `default` cacheLife profile is unexpected.'\n    )\n  },\n}\n\nexport class NextRequestHint extends NextRequest {\n  sourcePage: string\n  fetchMetrics: FetchEventResult['fetchMetrics'] | undefined\n\n  constructor(params: {\n    init: RequestInit\n    input: Request | string\n    page: string\n  }) {\n    super(params.input, params.init)\n    this.sourcePage = params.page\n  }\n\n  get request() {\n    throw new PageSignatureError({ page: this.sourcePage })\n  }\n\n  respondWith() {\n    throw new PageSignatureError({ page: this.sourcePage })\n  }\n\n  waitUntil() {\n    throw new PageSignatureError({ page: this.sourcePage })\n  }\n}\n\nconst headersGetter: TextMapGetter<Headers> = {\n  keys: (headers) => Array.from(headers.keys()),\n  get: (headers, key) => headers.get(key) ?? undefined,\n}\n\nexport type AdapterOptions = {\n  handler: (req: NextRequestHint, event: NextFetchEvent) => Promise<Response>\n  page: string\n  request: RequestData\n  IncrementalCache?: typeof import('../lib/incremental-cache').IncrementalCache\n  incrementalCacheHandler?: typeof import('../lib/incremental-cache').CacheHandler\n  bypassNextUrl?: boolean\n}\n\n// This has to be compatible with what the Vercel builder does as well:\n// https://github.com/vercel/vercel/blob/0e0a6eb9f12216202ae2f5ee37e4ada1796361fd/packages/next/src/edge-function-source/get-edge-function.ts#L112-L136\nexport type EdgeHandler = (opts: {\n  request: AdapterOptions['request']\n}) => Promise<FetchEventResult>\n\nlet propagator: <T>(request: NextRequestHint, fn: () => T) => T = (\n  request,\n  fn\n) => {\n  const tracer = getTracer()\n  return tracer.withPropagatedContext(request.headers, fn, headersGetter)\n}\n\nlet testApisIntercepted = false\n\nfunction ensureTestApisIntercepted() {\n  if (!testApisIntercepted) {\n    testApisIntercepted = true\n    if (process.env.NEXT_PRIVATE_TEST_PROXY === 'true') {\n      const { interceptTestApis, wrapRequestHandler } =\n        // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n        require('next/dist/experimental/testmode/server-edge') as typeof import('../../experimental/testmode/server-edge')\n      interceptTestApis()\n      propagator = wrapRequestHandler(propagator)\n    }\n  }\n}\n\nexport async function adapter(\n  params: AdapterOptions\n): Promise<FetchEventResult> {\n  ensureTestApisIntercepted()\n  await ensureInstrumentationRegistered()\n\n  // TODO-APP: use explicit marker for this\n  const isEdgeRendering =\n    typeof (globalThis as any).__BUILD_MANIFEST !== 'undefined'\n\n  params.request.url = normalizeRscURL(params.request.url)\n\n  const requestURL = params.bypassNextUrl\n    ? new URL(params.request.url)\n    : new NextURL(params.request.url, {\n        headers: params.request.headers,\n        nextConfig: params.request.nextConfig,\n      })\n\n  // Iterator uses an index to keep track of the current iteration. Because of deleting and appending below we can't just use the iterator.\n  // Instead we use the keys before iteration.\n  const keys = [...requestURL.searchParams.keys()]\n  for (const key of keys) {\n    const value = requestURL.searchParams.getAll(key)\n\n    const normalizedKey = normalizeNextQueryParam(key)\n    if (normalizedKey) {\n      requestURL.searchParams.delete(normalizedKey)\n      for (const val of value) {\n        requestURL.searchParams.append(normalizedKey, val)\n      }\n      requestURL.searchParams.delete(key)\n    }\n  }\n\n  // Ensure users only see page requests, never data requests.\n  let buildId = process.env.__NEXT_BUILD_ID || ''\n  if ('buildId' in requestURL) {\n    buildId = (requestURL as NextURL).buildId || ''\n    requestURL.buildId = ''\n  }\n  let deploymentId = process.env.NEXT_DEPLOYMENT_ID\n\n  const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers)\n  const isNextDataRequest = requestHeaders.has('x-nextjs-data')\n  const isRSCRequest = isRSCRequestHeader(requestHeaders.get(RSC_HEADER))\n\n  if (isNextDataRequest && requestURL.pathname === '/index') {\n    requestURL.pathname = '/'\n  }\n\n  const flightHeaders = new Map()\n\n  // Headers should only be stripped for middleware\n  if (!isEdgeRendering && !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {\n    for (const header of FLIGHT_HEADERS) {\n      const value = requestHeaders.get(header)\n      if (value !== null) {\n        flightHeaders.set(header, value)\n        requestHeaders.delete(header)\n      }\n    }\n  }\n\n  const normalizeURL = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n    ? new URL(params.request.url)\n    : requestURL\n\n  const rscHash = normalizeURL.searchParams.get(NEXT_RSC_UNION_QUERY)\n\n  const request = new NextRequestHint({\n    page: params.page,\n    // Strip internal query parameters off the request.\n    input: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n      ? normalizeURL.toString()\n      : stripInternalSearchParams(normalizeURL).toString(),\n    init: {\n      body: params.request.body,\n      headers: requestHeaders,\n      method: params.request.method,\n      nextConfig: params.request.nextConfig,\n      signal: params.request.signal,\n    },\n  })\n\n  if (params.request.requestMeta) {\n    setRequestMeta(request, params.request.requestMeta)\n  }\n\n  /**\n   * This allows to identify the request as a data request. The user doesn't\n   * need to know about this property neither use it. We add it for testing\n   * purposes.\n   */\n  if (isNextDataRequest) {\n    Object.defineProperty(request, '__isData', {\n      enumerable: false,\n      value: true,\n    })\n  }\n\n  if (\n    // If we are inside of the next start sandbox\n    // leverage the shared instance if not we need\n    // to create a fresh cache instance each time\n    !(globalThis as any).__incrementalCacheShared &&\n    (params as any).IncrementalCache\n  ) {\n    ;(globalThis as any).__incrementalCache = new (\n      params as {\n        IncrementalCache: typeof import('../lib/incremental-cache').IncrementalCache\n      }\n    ).IncrementalCache({\n      CurCacheHandler: params.incrementalCacheHandler,\n      minimalMode: process.env.NODE_ENV !== 'development',\n      fetchCacheKeyPrefix: process.env.__NEXT_FETCH_CACHE_KEY_PREFIX,\n      dev: process.env.NODE_ENV === 'development',\n      requestHeaders: params.request.headers as any,\n\n      getPrerenderManifest: () => {\n        return {\n          version: -1 as any, // letting us know this doesn't conform to spec\n          routes: {},\n          dynamicRoutes: {},\n          notFoundRoutes: [],\n          preview: getEdgePreviewProps(),\n        }\n      },\n    })\n  }\n\n  // if we're in an edge runtime sandbox, we should use the waitUntil\n  // that we receive from the enclosing NextServer\n  const outerWaitUntil =\n    params.request.waitUntil ?? getBuiltinRequestContext()?.waitUntil\n\n  const event = new NextFetchEvent({\n    request,\n    page: params.page,\n    context: outerWaitUntil ? { waitUntil: outerWaitUntil } : undefined,\n  })\n  let response\n  let cookiesFromResponse\n\n  response = await propagator(request, () => {\n    // we only care to make async storage available for middleware\n    const isMiddleware =\n      params.page === '/middleware' ||\n      params.page === '/src/middleware' ||\n      params.page === '/proxy' ||\n      params.page === '/src/proxy'\n\n    if (isMiddleware) {\n      // if we're in an edge function, we only get a subset of `nextConfig` (no `experimental`),\n      // so we have to inject it via DefinePlugin.\n      // in `next start` this will be passed normally (see `NextNodeServer.runMiddleware`).\n\n      const waitUntil = event.waitUntil.bind(event)\n      const closeController = new CloseController()\n\n      return getTracer().trace(\n        MiddlewareSpan.execute,\n        {\n          spanName: `middleware ${request.method}`,\n          attributes: {\n            'http.target': request.nextUrl.pathname,\n            'http.method': request.method,\n          },\n        },\n        async () => {\n          try {\n            const onUpdateCookies = (cookies: Array<string>) => {\n              cookiesFromResponse = cookies\n            }\n            const previewProps = getEdgePreviewProps()\n            const page = '/' // Fake Work\n            const fallbackRouteParams = null\n\n            const implicitTags = await getImplicitTags(\n              page,\n              request.nextUrl.pathname,\n              fallbackRouteParams\n            )\n\n            const requestStore = createRequestStoreForAPI(\n              request,\n              request.nextUrl,\n              implicitTags,\n              onUpdateCookies,\n              previewProps,\n              // Edge route handlers can't use `\"use cache\"`, so there's no HMR\n              // refresh hash to thread through here.\n              undefined\n            )\n\n            const workStore = createWorkStore({\n              page,\n              renderOpts: {\n                cacheLifeProfiles: proxyCacheLifeProfiles,\n                // Proxy doesn't do static generation, so this value does not\n                // apply here. 0 is a sentinel: if something ever reads it,\n                // it'll surface loudly instead of silently using a misleading\n                // default.\n                staticPageGenerationTimeout: 0,\n                cacheComponents: false,\n                // Proxy doesn't run instant validation; the level value is\n                // irrelevant here.\n                // TODO: remove validationLevel and other global config from renderOpts\n                validationLevel: 'warning',\n                experimental: {\n                  isRoutePPREnabled: false,\n                  authInterrupts:\n                    !!params.request.nextConfig?.experimental?.authInterrupts,\n                  // Proxy doesn't fill Cache Components entries, so this value\n                  // is never read. 0 is a sentinel: if something ever reads it,\n                  // the cache fill will time out immediately and surface the\n                  // bug.\n                  useCacheTimeout: 0,\n                },\n                supportsDynamicResponse: true,\n                waitUntil,\n                onClose: closeController.onClose.bind(closeController),\n                onAfterTaskError: undefined,\n              },\n              isPrefetchRequest:\n                request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1',\n              buildId: buildId ?? '',\n              deploymentId: deploymentId ?? '',\n              previouslyRevalidatedTags: [],\n            })\n\n            return await workAsyncStorage.run(workStore, () =>\n              workUnitAsyncStorage.run(\n                requestStore,\n                params.handler,\n                request,\n                event\n              )\n            )\n          } finally {\n            // middleware cannot stream, so we can consider the response closed\n            // as soon as the handler returns.\n            // we can delay running it until a bit later --\n            // if it's needed, we'll have a `waitUntil` lock anyway.\n            setTimeout(() => {\n              closeController.dispatchClose()\n            }, 0)\n          }\n        }\n      )\n    }\n    return params.handler(request, event)\n  })\n\n  // check if response is a Response object\n  if (response && !(response instanceof Response)) {\n    throw new TypeError('Expected an instance of Response to be returned')\n  }\n\n  if (response && cookiesFromResponse) {\n    response.headers.set('set-cookie', cookiesFromResponse)\n  }\n\n  /**\n   * For rewrites we must always include the locale in the final pathname\n   * so we re-create the NextURL forcing it to include it when the it is\n   * an internal rewrite. Also we make sure the outgoing rewrite URL is\n   * a data URL if the request was a data request.\n   */\n  const rewrite = response?.headers.get('x-middleware-rewrite')\n  if (response && rewrite && (isRSCRequest || !isEdgeRendering)) {\n    const destination = new NextURL(rewrite, {\n      forceLocale: true,\n      headers: params.request.headers,\n      nextConfig: params.request.nextConfig,\n    })\n\n    if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE && !isEdgeRendering) {\n      if (destination.host === request.nextUrl.host) {\n        destination.buildId = buildId || destination.buildId\n        response.headers.set('x-middleware-rewrite', String(destination))\n      }\n    }\n\n    /**\n     * When the request is a data request we must show if there was a rewrite\n     * with an internal header so the client knows which component to load\n     * from the data request.\n     */\n    const { url: relativeDestination, isRelative } = parseRelativeURL(\n      destination.toString(),\n      requestURL.toString()\n    )\n\n    if (\n      !isEdgeRendering &&\n      isNextDataRequest &&\n      // if the rewrite is external and external rewrite\n      // resolving config is enabled don't add this header\n      // so the upstream app can set it instead\n      !(\n        process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE &&\n        relativeDestination.match(/http(s)?:\\/\\//)\n      )\n    ) {\n      response.headers.set('x-nextjs-rewrite', relativeDestination)\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 isAllowedOrigin = !isRelative\n      ? params.request.nextConfig?.experimental?.clientParamParsingOrigins?.some(\n          (origin) => new RegExp(origin).test(destination.origin)\n        )\n      : false\n\n    // If this is an RSC request, and the pathname or search has changed, and\n    // this isn't an external rewrite, we need to set the rewritten pathname and\n    // query headers.\n    if (isRSCRequest && (isRelative || isAllowedOrigin)) {\n      if (requestURL.pathname !== destination.pathname) {\n        response.headers.set(NEXT_REWRITTEN_PATH_HEADER, destination.pathname)\n      }\n      if (requestURL.search !== destination.search) {\n        response.headers.set(\n          NEXT_REWRITTEN_QUERY_HEADER,\n          // remove the leading ? from the search string\n          destination.search.slice(1)\n        )\n      }\n    }\n  }\n\n  /**\n   * Always forward the `_rsc` search parameter to the rewritten URL for RSC requests,\n   * unless it's already present. This is necessary to ensure that RSC hash validation\n   * works correctly after a rewrite. For internal rewrites, the server can validate the\n   * RSC hash using the original URL, so forwarding the `_rsc` parameter is less critical.\n   * However, for external rewrites (where the request is proxied to another Next.js server),\n   * the external server does not have access to the original URL or its search parameters.\n   * In these cases, forwarding the `_rsc` parameter is essential so that the external server\n   * can perform the correct RSC hash validation.\n   */\n  if (response && rewrite && isRSCRequest && rscHash) {\n    const rewriteURL = new URL(rewrite)\n    if (!rewriteURL.searchParams.has(NEXT_RSC_UNION_QUERY)) {\n      rewriteURL.searchParams.set(NEXT_RSC_UNION_QUERY, rscHash)\n      response.headers.set('x-middleware-rewrite', rewriteURL.toString())\n    }\n  }\n\n  /**\n   * For redirects we will not include the locale in case when it is the\n   * default and we must also make sure the outgoing URL is a data one if\n   * the incoming request was a data request.\n   */\n  const redirect = response?.headers.get('Location')\n  if (response && redirect && !isEdgeRendering) {\n    const redirectURL = new NextURL(redirect, {\n      forceLocale: false,\n      headers: params.request.headers,\n      nextConfig: params.request.nextConfig,\n    })\n\n    /**\n     * Responses created from redirects have immutable headers so we have\n     * to clone the response to be able to modify it.\n     */\n    response = new Response(response.body, response)\n\n    if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {\n      if (redirectURL.host === requestURL.host) {\n        redirectURL.buildId = buildId || redirectURL.buildId\n        response.headers.set(\n          'Location',\n          getRelativeURL(redirectURL, requestURL)\n        )\n      }\n    }\n\n    /**\n     * When the request is a data request we can't use the location header as\n     * it may end up with CORS error. Instead we map to an internal header so\n     * the client knows the destination.\n     */\n    if (isNextDataRequest) {\n      response.headers.delete('Location')\n      response.headers.set(\n        'x-nextjs-redirect',\n        getRelativeURL(redirectURL.toString(), requestURL.toString())\n      )\n    }\n  }\n\n  const finalResponse = response ? response : NextResponse.next()\n\n  // Flight headers are not overridable / removable so they are applied at the end.\n  const middlewareOverrideHeaders = finalResponse.headers.get(\n    'x-middleware-override-headers'\n  )\n  const overwrittenHeaders: string[] = []\n  if (middlewareOverrideHeaders) {\n    for (const [key, value] of flightHeaders) {\n      finalResponse.headers.set(`x-middleware-request-${key}`, value)\n      overwrittenHeaders.push(key)\n    }\n\n    if (overwrittenHeaders.length > 0) {\n      finalResponse.headers.set(\n        'x-middleware-override-headers',\n        middlewareOverrideHeaders + ',' + overwrittenHeaders.join(',')\n      )\n    }\n  }\n\n  return {\n    response: finalResponse,\n    waitUntil: getWaitUntilPromiseFromEvent(event) ?? Promise.resolve(),\n    fetchMetrics: request.fetchMetrics,\n  }\n}\n"],"names":["NextRequestHint","adapter","proxyCacheLifeProfiles","default","InvariantError","NextRequest","constructor","params","input","init","sourcePage","page","request","PageSignatureError","respondWith","waitUntil","headersGetter","keys","headers","Array","from","get","key","undefined","propagator","fn","tracer","getTracer","withPropagatedContext","testApisIntercepted","ensureTestApisIntercepted","process","env","NEXT_PRIVATE_TEST_PROXY","interceptTestApis","wrapRequestHandler","require","getBuiltinRequestContext","ensureInstrumentationRegistered","isEdgeRendering","globalThis","__BUILD_MANIFEST","url","normalizeRscURL","requestURL","bypassNextUrl","URL","NextURL","nextConfig","searchParams","value","getAll","normalizedKey","normalizeNextQueryParam","delete","val","append","buildId","__NEXT_BUILD_ID","deploymentId","NEXT_DEPLOYMENT_ID","requestHeaders","fromNodeOutgoingHttpHeaders","isNextDataRequest","has","isRSCRequest","isRSCRequestHeader","RSC_HEADER","pathname","flightHeaders","Map","__NEXT_NO_MIDDLEWARE_URL_NORMALIZE","header","FLIGHT_HEADERS","set","normalizeURL","rscHash","NEXT_RSC_UNION_QUERY","toString","stripInternalSearchParams","body","method","signal","requestMeta","setRequestMeta","Object","defineProperty","enumerable","__incrementalCacheShared","IncrementalCache","__incrementalCache","CurCacheHandler","incrementalCacheHandler","minimalMode","NODE_ENV","fetchCacheKeyPrefix","__NEXT_FETCH_CACHE_KEY_PREFIX","dev","getPrerenderManifest","version","routes","dynamicRoutes","notFoundRoutes","preview","getEdgePreviewProps","outerWaitUntil","event","NextFetchEvent","context","response","cookiesFromResponse","isMiddleware","bind","closeController","CloseController","trace","MiddlewareSpan","execute","spanName","attributes","nextUrl","onUpdateCookies","cookies","previewProps","fallbackRouteParams","implicitTags","getImplicitTags","requestStore","createRequestStoreForAPI","workStore","createWorkStore","renderOpts","cacheLifeProfiles","staticPageGenerationTimeout","cacheComponents","validationLevel","experimental","isRoutePPREnabled","authInterrupts","useCacheTimeout","supportsDynamicResponse","onClose","onAfterTaskError","isPrefetchRequest","NEXT_ROUTER_PREFETCH_HEADER","previouslyRevalidatedTags","workAsyncStorage","run","workUnitAsyncStorage","handler","setTimeout","dispatchClose","Response","TypeError","rewrite","destination","forceLocale","host","String","relativeDestination","isRelative","parseRelativeURL","__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE","match","isAllowedOrigin","clientParamParsingOrigins","some","origin","RegExp","test","NEXT_REWRITTEN_PATH_HEADER","search","NEXT_REWRITTEN_QUERY_HEADER","slice","rewriteURL","redirect","redirectURL","getRelativeURL","finalResponse","NextResponse","next","middlewareOverrideHeaders","overwrittenHeaders","push","length","join","getWaitUntilPromiseFromEvent","Promise","resolve","fetchMetrics"],"mappings":";;;;;;;;;;;;;;;IAyDaA,eAAe;eAAfA;;IAqESC,OAAO;eAAPA;;;uBA5Ha;uBACkC;4BAI9D;yBACqB;0BACC;+BAItB;yBACiB;+BACkB;0BACV;kCAOzB;yBACyC;8BACP;8CACJ;2BACL;0CACC;gCACF;wBAGL;2BAEK;4BACC;qCACI;uCACK;8BACT;8BACG;6BACJ;AAE/B,4EAA4E;AAC5E,sEAAsE;AACtE,sEAAsE;AACtE,2EAA2E;AAC3E,6EAA6E;AAC7E,+EAA+E;AAC/E,qDAAqD;AACrD,MAAMC,yBAAoD;IACxD,IAAIC,WAAiB;QACnB,MAAM,qBAEL,CAFK,IAAIC,8BAAc,CACtB,kGADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;AACF;AAEO,MAAMJ,wBAAwBK,oBAAW;IAI9CC,YAAYC,MAIX,CAAE;QACD,KAAK,CAACA,OAAOC,KAAK,EAAED,OAAOE,IAAI;QAC/B,IAAI,CAACC,UAAU,GAAGH,OAAOI,IAAI;IAC/B;IAEA,IAAIC,UAAU;Q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