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38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
import type { RequestData, FetchEventResult } from './types'
import type { RequestInit } from './spec-extension/request'
import { PageSignatureError } from './error'
import { fromNodeOutgoingHttpHeaders, normalizeNextQueryParam } from './utils'
import {
  NextFetchEvent,
  getWaitUntilPromiseFromEvent,
} from './spec-extension/fetch-event'
import { NextRequest } from './spec-extension/request'
import { NextResponse } from './spec-extension/response'
import {
  parseRelativeURL,
  getRelativeURL,
} from '../../shared/lib/router/utils/relativize-url'
import { NextURL } from './next-url'
import { stripInternalSearchParams } from '../internal-utils'
import { normalizeRscURL } from '../../shared/lib/router/utils/app-paths'
import {
  FLIGHT_HEADERS,
  NEXT_REWRITTEN_PATH_HEADER,
  NEXT_REWRITTEN_QUERY_HEADER,
  RSC_HEADER,
} from '../../client/components/app-router-headers'
import { ensureInstrumentationRegistered } from './globals'
import { createRequestStoreForAPI } from '../async-storage/request-store'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { createWorkStore } from '../async-storage/work-store'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { NEXT_ROUTER_PREFETCH_HEADER } from '../../client/components/app-router-headers'
import { getTracer } from '../lib/trace/tracer'
import type { TextMapGetter } from 'next/dist/compiled/@opentelemetry/api'
import { MiddlewareSpan } from '../lib/trace/constants'
import { CloseController } from './web-on-close'
import { getEdgePreviewProps } from './get-edge-preview-props'
import { getBuiltinRequestContext } from '../after/builtin-request-context'
import { getImplicitTags } from '../lib/implicit-tags'

export class NextRequestHint extends NextRequest {
  sourcePage: string
  fetchMetrics: FetchEventResult['fetchMetrics'] | undefined

  constructor(params: {
    init: RequestInit
    input: Request | string
    page: string
  }) {
    super(params.input, params.init)
    this.sourcePage = params.page
  }

  get request() {
    throw new PageSignatureError({ page: this.sourcePage })
  }

  respondWith() {
    throw new PageSignatureError({ page: this.sourcePage })
  }

  waitUntil() {
    throw new PageSignatureError({ page: this.sourcePage })
  }
}

const headersGetter: TextMapGetter<Headers> = {
  keys: (headers) => Array.from(headers.keys()),
  get: (headers, key) => headers.get(key) ?? undefined,
}

export type AdapterOptions = {
  handler: (req: NextRequestHint, event: NextFetchEvent) => Promise<Response>
  page: string
  request: RequestData
  IncrementalCache?: typeof import('../lib/incremental-cache').IncrementalCache
  incrementalCacheHandler?: typeof import('../lib/incremental-cache').CacheHandler
  bypassNextUrl?: boolean
}

let propagator: <T>(request: NextRequestHint, fn: () => T) => T = (
  request,
  fn
) => {
  const tracer = getTracer()
  return tracer.withPropagatedContext(request.headers, fn, headersGetter)
}

let testApisIntercepted = false

function ensureTestApisIntercepted() {
  if (!testApisIntercepted) {
    testApisIntercepted = true
    if (process.env.NEXT_PRIVATE_TEST_PROXY === 'true') {
      const { interceptTestApis, wrapRequestHandler } =
        // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm
        require('next/dist/experimental/testmode/server-edge') as typeof import('../../experimental/testmode/server-edge')
      interceptTestApis()
      propagator = wrapRequestHandler(propagator)
    }
  }
}

export async function adapter(
  params: AdapterOptions
): Promise<FetchEventResult> {
  ensureTestApisIntercepted()
  await ensureInstrumentationRegistered()

  // TODO-APP: use explicit marker for this
  const isEdgeRendering =
    typeof (globalThis as any).__BUILD_MANIFEST !== 'undefined'

  params.request.url = normalizeRscURL(params.request.url)

  const requestURL = params.bypassNextUrl
    ? new URL(params.request.url)
    : new NextURL(params.request.url, {
        headers: params.request.headers,
        nextConfig: params.request.nextConfig,
      })

  // Iterator uses an index to keep track of the current iteration. Because of deleting and appending below we can't just use the iterator.
  // Instead we use the keys before iteration.
  const keys = [...requestURL.searchParams.keys()]
  for (const key of keys) {
    const value = requestURL.searchParams.getAll(key)

    const normalizedKey = normalizeNextQueryParam(key)
    if (normalizedKey) {
      requestURL.searchParams.delete(normalizedKey)
      for (const val of value) {
        requestURL.searchParams.append(normalizedKey, val)
      }
      requestURL.searchParams.delete(key)
    }
  }

  // Ensure users only see page requests, never data requests.
  let buildId = process.env.__NEXT_BUILD_ID || ''
  if ('buildId' in requestURL) {
    buildId = (requestURL as NextURL).buildId || ''
    requestURL.buildId = ''
  }

  const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers)
  const isNextDataRequest = requestHeaders.has('x-nextjs-data')
  const isRSCRequest = requestHeaders.get(RSC_HEADER) === '1'

  if (isNextDataRequest && requestURL.pathname === '/index') {
    requestURL.pathname = '/'
  }

  const flightHeaders = new Map()

  // Headers should only be stripped for middleware
  if (!isEdgeRendering) {
    for (const header of FLIGHT_HEADERS) {
      const key = header.toLowerCase()
      const value = requestHeaders.get(key)
      if (value !== null) {
        flightHeaders.set(key, value)
        requestHeaders.delete(key)
      }
    }
  }

  const normalizeURL = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE
    ? new URL(params.request.url)
    : requestURL

  const request = new NextRequestHint({
    page: params.page,
    // Strip internal query parameters off the request.
    input: stripInternalSearchParams(normalizeURL).toString(),
    init: {
      body: params.request.body,
      headers: requestHeaders,
      method: params.request.method,
      nextConfig: params.request.nextConfig,
      signal: params.request.signal,
    },
  })

  /**
   * This allows to identify the request as a data request. The user doesn't
   * need to know about this property neither use it. We add it for testing
   * purposes.
   */
  if (isNextDataRequest) {
    Object.defineProperty(request, '__isData', {
      enumerable: false,
      value: true,
    })
  }

  if (
    // If we are inside of the next start sandbox
    // leverage the shared instance if not we need
    // to create a fresh cache instance each time
    !(globalThis as any).__incrementalCacheShared &&
    (params as any).IncrementalCache
  ) {
    ;(globalThis as any).__incrementalCache = new (
      params as {
        IncrementalCache: typeof import('../lib/incremental-cache').IncrementalCache
      }
    ).IncrementalCache({
      CurCacheHandler: params.incrementalCacheHandler,
      minimalMode: process.env.NODE_ENV !== 'development',
      fetchCacheKeyPrefix: process.env.__NEXT_FETCH_CACHE_KEY_PREFIX,
      dev: process.env.NODE_ENV === 'development',
      requestHeaders: params.request.headers as any,

      getPrerenderManifest: () => {
        return {
          version: -1 as any, // letting us know this doesn't conform to spec
          routes: {},
          dynamicRoutes: {},
          notFoundRoutes: [],
          preview: getEdgePreviewProps(),
        }
      },
    })
  }

  // if we're in an edge runtime sandbox, we should use the waitUntil
  // that we receive from the enclosing NextServer
  const outerWaitUntil =
    params.request.waitUntil ?? getBuiltinRequestContext()?.waitUntil

  const event = new NextFetchEvent({
    request,
    page: params.page,
    context: outerWaitUntil ? { waitUntil: outerWaitUntil } : undefined,
  })
  let response
  let cookiesFromResponse

  response = await propagator(request, () => {
    // we only care to make async storage available for middleware
    const isMiddleware =
      params.page === '/middleware' || params.page === '/src/middleware'

    if (isMiddleware) {
      // if we're in an edge function, we only get a subset of `nextConfig` (no `experimental`),
      // so we have to inject it via DefinePlugin.
      // in `next start` this will be passed normally (see `NextNodeServer.runMiddleware`).

      const waitUntil = event.waitUntil.bind(event)
      const closeController = new CloseController()

      return getTracer().trace(
        MiddlewareSpan.execute,
        {
          spanName: `middleware ${request.method} ${request.nextUrl.pathname}`,
          attributes: {
            'http.target': request.nextUrl.pathname,
            'http.method': request.method,
          },
        },
        async () => {
          try {
            const onUpdateCookies = (cookies: Array<string>) => {
              cookiesFromResponse = cookies
            }
            const previewProps = getEdgePreviewProps()
            const page = '/' // Fake Work
            const fallbackRouteParams = null

            const implicitTags = await getImplicitTags(
              page,
              request.nextUrl,
              fallbackRouteParams
            )

            const requestStore = createRequestStoreForAPI(
              request,
              request.nextUrl,
              implicitTags,
              onUpdateCookies,
              previewProps
            )

            const workStore = createWorkStore({
              page,
              renderOpts: {
                cacheLifeProfiles:
                  params.request.nextConfig?.experimental?.cacheLife,
                experimental: {
                  isRoutePPREnabled: false,
                  cacheComponents: false,
                  authInterrupts:
                    !!params.request.nextConfig?.experimental?.authInterrupts,
                },
                supportsDynamicResponse: true,
                waitUntil,
                onClose: closeController.onClose.bind(closeController),
                onAfterTaskError: undefined,
              },
              requestEndedState: { ended: false },
              isPrefetchRequest: request.headers.has(
                NEXT_ROUTER_PREFETCH_HEADER
              ),
              buildId: buildId ?? '',
              previouslyRevalidatedTags: [],
            })

            return await workAsyncStorage.run(workStore, () =>
              workUnitAsyncStorage.run(
                requestStore,
                params.handler,
                request,
                event
              )
            )
          } finally {
            // middleware cannot stream, so we can consider the response closed
            // as soon as the handler returns.
            // we can delay running it until a bit later --
            // if it's needed, we'll have a `waitUntil` lock anyway.
            setTimeout(() => {
              closeController.dispatchClose()
            }, 0)
          }
        }
      )
    }
    return params.handler(request, event)
  })

  // check if response is a Response object
  if (response && !(response instanceof Response)) {
    throw new TypeError('Expected an instance of Response to be returned')
  }

  if (response && cookiesFromResponse) {
    response.headers.set('set-cookie', cookiesFromResponse)
  }

  /**
   * For rewrites we must always include the locale in the final pathname
   * so we re-create the NextURL forcing it to include it when the it is
   * an internal rewrite. Also we make sure the outgoing rewrite URL is
   * a data URL if the request was a data request.
   */
  const rewrite = response?.headers.get('x-middleware-rewrite')
  if (response && rewrite && (isRSCRequest || !isEdgeRendering)) {
    const destination = new NextURL(rewrite, {
      forceLocale: true,
      headers: params.request.headers,
      nextConfig: params.request.nextConfig,
    })

    if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE && !isEdgeRendering) {
      if (destination.host === request.nextUrl.host) {
        destination.buildId = buildId || destination.buildId
        response.headers.set('x-middleware-rewrite', String(destination))
      }
    }

    /**
     * When the request is a data request we must show if there was a rewrite
     * with an internal header so the client knows which component to load
     * from the data request.
     */
    const { url: relativeDestination, isRelative } = parseRelativeURL(
      destination.toString(),
      requestURL.toString()
    )

    if (
      !isEdgeRendering &&
      isNextDataRequest &&
      // if the rewrite is external and external rewrite
      // resolving config is enabled don't add this header
      // so the upstream app can set it instead
      !(
        process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE &&
        relativeDestination.match(/http(s)?:\/\//)
      )
    ) {
      response.headers.set('x-nextjs-rewrite', relativeDestination)
    }

    // If this is an RSC request, and the pathname or search has changed, and
    // this isn't an external rewrite, we need to set the rewritten pathname and
    // query headers.
    if (isRSCRequest && isRelative) {
      if (requestURL.pathname !== destination.pathname) {
        response.headers.set(NEXT_REWRITTEN_PATH_HEADER, destination.pathname)
      }
      if (requestURL.search !== destination.search) {
        response.headers.set(
          NEXT_REWRITTEN_QUERY_HEADER,
          // remove the leading ? from the search string
          destination.search.slice(1)
        )
      }
    }
  }

  /**
   * For redirects we will not include the locale in case when it is the
   * default and we must also make sure the outgoing URL is a data one if
   * the incoming request was a data request.
   */
  const redirect = response?.headers.get('Location')
  if (response && redirect && !isEdgeRendering) {
    const redirectURL = new NextURL(redirect, {
      forceLocale: false,
      headers: params.request.headers,
      nextConfig: params.request.nextConfig,
    })

    /**
     * Responses created from redirects have immutable headers so we have
     * to clone the response to be able to modify it.
     */
    response = new Response(response.body, response)

    if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {
      if (redirectURL.host === requestURL.host) {
        redirectURL.buildId = buildId || redirectURL.buildId
        response.headers.set('Location', redirectURL.toString())
      }
    }

    /**
     * When the request is a data request we can't use the location header as
     * it may end up with CORS error. Instead we map to an internal header so
     * the client knows the destination.
     */
    if (isNextDataRequest) {
      response.headers.delete('Location')
      response.headers.set(
        'x-nextjs-redirect',
        getRelativeURL(redirectURL.toString(), requestURL.toString())
      )
    }
  }

  const finalResponse = response ? response : NextResponse.next()

  // Flight headers are not overridable / removable so they are applied at the end.
  const middlewareOverrideHeaders = finalResponse.headers.get(
    'x-middleware-override-headers'
  )
  const overwrittenHeaders: string[] = []
  if (middlewareOverrideHeaders) {
    for (const [key, value] of flightHeaders) {
      finalResponse.headers.set(`x-middleware-request-${key}`, value)
      overwrittenHeaders.push(key)
    }

    if (overwrittenHeaders.length > 0) {
      finalResponse.headers.set(
        'x-middleware-override-headers',
        middlewareOverrideHeaders + ',' + overwrittenHeaders.join(',')
      )
    }
  }

  return {
    response: finalResponse,
    waitUntil: getWaitUntilPromiseFromEvent(event) ?? Promise.resolve(),
    fetchMetrics: request.fetchMetrics,
  }
}