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27
28
29
30
31
32
33
34
35
36
37
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
468
469
470
471
472
473
474
475
476
477
478
import {
  AppRouteRouteModule,
  type AppRouteRouteHandlerContext,
  type AppRouteRouteModuleOptions,
} from '../../server/route-modules/app-route/module.compiled'
import { RouteKind } from '../../server/route-kind'
import { patchFetch as _patchFetch } from '../../server/lib/patch-fetch'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { getRequestMeta } from '../../server/request-meta'
import { getTracer, type Span, SpanKind } from '../../server/lib/trace/tracer'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'
import {
  NextRequestAdapter,
  signalFromNodeResponse,
} from '../../server/web/spec-extension/adapters/next-request'
import { BaseServerSpan } from '../../server/lib/trace/constants'
import { getRevalidateReason } from '../../server/instrumentation/utils'
import { sendResponse } from '../../server/send-response'
import {
  fromNodeOutgoingHttpHeaders,
  toNodeOutgoingHttpHeaders,
} from '../../server/web/utils'
import { getCacheControlHeader } from '../../server/lib/cache-control'
import { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants'
import { NoFallbackError } from '../../shared/lib/no-fallback-error.external'
import {
  CachedRouteKind,
  type ResponseCacheEntry,
  type ResponseGenerator,
} from '../../server/response-cache'

import * as userland from 'VAR_USERLAND'

// These are injected by the loader afterwards. This is injected as a variable
// instead of a replacement because this could also be `undefined` instead of
// an empty string.
declare const nextConfigOutput: AppRouteRouteModuleOptions['nextConfigOutput']

// We inject the nextConfigOutput here so that we can use them in the route
// module.
// INJECT:nextConfigOutput

const routeModule = new AppRouteRouteModule({
  definition: {
    kind: RouteKind.APP_ROUTE,
    page: 'VAR_DEFINITION_PAGE',
    pathname: 'VAR_DEFINITION_PATHNAME',
    filename: 'VAR_DEFINITION_FILENAME',
    bundlePath: 'VAR_DEFINITION_BUNDLE_PATH',
  },
  distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
  relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
  resolvedPagePath: 'VAR_RESOLVED_PAGE_PATH',
  nextConfigOutput,
  userland,
})

// Pull out the exports that we need to expose from the module. This should
// be eliminated when we've moved the other routes to the new format. These
// are used to hook into the route.
const { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule

function patchFetch() {
  return _patchFetch({
    workAsyncStorage,
    workUnitAsyncStorage,
  })
}

export {
  routeModule,
  workAsyncStorage,
  workUnitAsyncStorage,
  serverHooks,
  patchFetch,
}

export async function handler(
  req: IncomingMessage,
  res: ServerResponse,
  ctx: {
    waitUntil: (prom: Promise<void>) => void
  }
) {
  let srcPage = 'VAR_DEFINITION_PAGE'

  // turbopack doesn't normalize `/index` in the page name
  // so we need to to process dynamic routes properly
  // TODO: fix turbopack providing differing value from webpack
  if (process.env.TURBOPACK) {
    srcPage = srcPage.replace(/\/index$/, '') || '/'
  } else if (srcPage === '/index') {
    // we always normalize /index specifically
    srcPage = '/'
  }
  const multiZoneDraftMode = process.env
    .__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean

  const prepareResult = await routeModule.prepare(req, res, {
    srcPage,
    multiZoneDraftMode,
  })

  if (!prepareResult) {
    res.statusCode = 400
    res.end('Bad Request')
    ctx.waitUntil?.(Promise.resolve())
    return null
  }

  const {
    buildId,
    params,
    nextConfig,
    isDraftMode,
    prerenderManifest,
    routerServerContext,
    isOnDemandRevalidate,
    revalidateOnlyGenerated,
    resolvedPathname,
  } = prepareResult

  const normalizedSrcPage = normalizeAppPath(srcPage)

  let isIsr = Boolean(
    prerenderManifest.dynamicRoutes[normalizedSrcPage] ||
      prerenderManifest.routes[resolvedPathname]
  )

  if (isIsr && !isDraftMode) {
    const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname])
    const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage]

    if (prerenderInfo) {
      if (prerenderInfo.fallback === false && !isPrerendered) {
        throw new NoFallbackError()
      }
    }
  }

  let cacheKey: string | null = null

  if (isIsr && !routeModule.isDev && !isDraftMode) {
    cacheKey = resolvedPathname
    // ensure /index and / is normalized to one key
    cacheKey = cacheKey === '/index' ? '/' : cacheKey
  }

  const supportsDynamicResponse: boolean =
    // If we're in development, we always support dynamic HTML
    routeModule.isDev === true ||
    // If this is not SSG or does not have static paths, then it supports
    // dynamic HTML.
    !isIsr

  // This is a revalidation request if the request is for a static
  // page and it is not being resumed from a postponed render and
  // it is not a dynamic RSC request then it is a revalidation
  // request.
  const isRevalidate = isIsr && !supportsDynamicResponse

  const method = req.method || 'GET'
  const tracer = getTracer()
  const activeSpan = tracer.getActiveScopeSpan()

  const context: AppRouteRouteHandlerContext = {
    params,
    prerenderManifest,
    renderOpts: {
      experimental: {
        cacheComponents: Boolean(nextConfig.experimental.cacheComponents),
        authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
      },
      supportsDynamicResponse,
      incrementalCache: getRequestMeta(req, 'incrementalCache'),
      cacheLifeProfiles: nextConfig.experimental?.cacheLife,
      isRevalidate,
      waitUntil: ctx.waitUntil,
      onClose: (cb) => {
        res.on('close', cb)
      },
      onAfterTaskError: undefined,
      onInstrumentationRequestError: (error, _request, errorContext) =>
        routeModule.onRequestError(
          req,
          error,
          errorContext,
          routerServerContext
        ),
    },
    sharedContext: {
      buildId,
    },
  }
  const nodeNextReq = new NodeNextRequest(req)
  const nodeNextRes = new NodeNextResponse(res)

  const nextReq = NextRequestAdapter.fromNodeNextRequest(
    nodeNextReq,
    signalFromNodeResponse(res)
  )

  try {
    const invokeRouteModule = async (span?: Span) => {
      return routeModule.handle(nextReq, context).finally(() => {
        if (!span) return

        span.setAttributes({
          'http.status_code': res.statusCode,
          'next.rsc': false,
        })

        const rootSpanAttributes = tracer.getRootSpanAttributes()
        // We were unable to get attributes, probably OTEL is not enabled
        if (!rootSpanAttributes) {
          return
        }

        if (
          rootSpanAttributes.get('next.span_type') !==
          BaseServerSpan.handleRequest
        ) {
          console.warn(
            `Unexpected root span type '${rootSpanAttributes.get(
              'next.span_type'
            )}'. Please report this Next.js issue https://github.com/vercel/next.js`
          )
          return
        }

        const route = rootSpanAttributes.get('next.route')
        if (route) {
          const name = `${method} ${route}`

          span.setAttributes({
            'next.route': route,
            'http.route': route,
            'next.span_name': name,
          })
          span.updateName(name)
        } else {
          span.updateName(`${method} ${req.url}`)
        }
      })
    }

    const handleResponse = async (currentSpan?: Span) => {
      const responseGenerator: ResponseGenerator = async ({
        previousCacheEntry,
      }) => {
        try {
          if (
            !getRequestMeta(req, 'minimalMode') &&
            isOnDemandRevalidate &&
            revalidateOnlyGenerated &&
            !previousCacheEntry
          ) {
            res.statusCode = 404
            // on-demand revalidate always sets this header
            res.setHeader('x-nextjs-cache', 'REVALIDATED')
            res.end('This page could not be found')
            return null
          }

          const response = await invokeRouteModule(currentSpan)

          ;(req as any).fetchMetrics = (context.renderOpts as any).fetchMetrics
          let pendingWaitUntil = context.renderOpts.pendingWaitUntil

          // Attempt using provided waitUntil if available
          // if it's not we fallback to sendResponse's handling
          if (pendingWaitUntil) {
            if (ctx.waitUntil) {
              ctx.waitUntil(pendingWaitUntil)
              pendingWaitUntil = undefined
            }
          }
          const cacheTags = context.renderOpts.collectedTags

          // If the request is for a static response, we can cache it so long
          // as it's not edge.
          if (isIsr) {
            const blob = await response.blob()

            // Copy the headers from the response.
            const headers = toNodeOutgoingHttpHeaders(response.headers)

            if (cacheTags) {
              headers[NEXT_CACHE_TAGS_HEADER] = cacheTags
            }

            if (!headers['content-type'] && blob.type) {
              headers['content-type'] = blob.type
            }

            const revalidate =
              typeof context.renderOpts.collectedRevalidate === 'undefined' ||
              context.renderOpts.collectedRevalidate >= INFINITE_CACHE
                ? false
                : context.renderOpts.collectedRevalidate

            const expire =
              typeof context.renderOpts.collectedExpire === 'undefined' ||
              context.renderOpts.collectedExpire >= INFINITE_CACHE
                ? undefined
                : context.renderOpts.collectedExpire

            // Create the cache entry for the response.
            const cacheEntry: ResponseCacheEntry = {
              value: {
                kind: CachedRouteKind.APP_ROUTE,
                status: response.status,
                body: Buffer.from(await blob.arrayBuffer()),
                headers,
              },
              cacheControl: { revalidate, expire },
            }

            return cacheEntry
          } else {
            // send response without caching if not ISR
            await sendResponse(
              nodeNextReq,
              nodeNextRes,
              response,
              context.renderOpts.pendingWaitUntil
            )
            return null
          }
        } catch (err) {
          // if this is a background revalidate we need to report
          // the request error here as it won't be bubbled
          if (previousCacheEntry?.isStale) {
            await routeModule.onRequestError(
              req,
              err,
              {
                routerKind: 'App Router',
                routePath: srcPage,
                routeType: 'route',
                revalidateReason: getRevalidateReason({
                  isRevalidate,
                  isOnDemandRevalidate,
                }),
              },
              routerServerContext
            )
          }
          throw err
        }
      }

      const cacheEntry = await routeModule.handleResponse({
        req,
        nextConfig,
        cacheKey,
        routeKind: RouteKind.APP_ROUTE,
        isFallback: false,
        prerenderManifest,
        isRoutePPREnabled: false,
        isOnDemandRevalidate,
        revalidateOnlyGenerated,
        responseGenerator,
        waitUntil: ctx.waitUntil,
      })

      // we don't create a cacheEntry for ISR
      if (!isIsr) {
        return null
      }

      if (cacheEntry?.value?.kind !== CachedRouteKind.APP_ROUTE) {
        throw new Error(
          `Invariant: app-route received invalid cache entry ${cacheEntry?.value?.kind}`
        )
      }

      if (!getRequestMeta(req, 'minimalMode')) {
        res.setHeader(
          'x-nextjs-cache',
          isOnDemandRevalidate
            ? 'REVALIDATED'
            : cacheEntry.isMiss
              ? 'MISS'
              : cacheEntry.isStale
                ? 'STALE'
                : 'HIT'
        )
      }

      // Draft mode should never be cached
      if (isDraftMode) {
        res.setHeader(
          'Cache-Control',
          'private, no-cache, no-store, max-age=0, must-revalidate'
        )
      }

      const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers)

      if (!(getRequestMeta(req, 'minimalMode') && isIsr)) {
        headers.delete(NEXT_CACHE_TAGS_HEADER)
      }

      // If cache control is already set on the response we don't
      // override it to allow users to customize it via next.config
      if (
        cacheEntry.cacheControl &&
        !res.getHeader('Cache-Control') &&
        !headers.get('Cache-Control')
      ) {
        headers.set(
          'Cache-Control',
          getCacheControlHeader(cacheEntry.cacheControl)
        )
      }

      await sendResponse(
        nodeNextReq,
        nodeNextRes,
        new Response(cacheEntry.value.body, {
          headers,
          status: cacheEntry.value.status || 200,
        })
      )
      return null
    }

    // TODO: activeSpan code path is for when wrapped by
    // next-server can be removed when this is no longer used
    if (activeSpan) {
      await handleResponse(activeSpan)
    } else {
      await tracer.withPropagatedContext(req.headers, () =>
        tracer.trace(
          BaseServerSpan.handleRequest,
          {
            spanName: `${method} ${req.url}`,
            kind: SpanKind.SERVER,
            attributes: {
              'http.method': method,
              'http.target': req.url,
            },
          },
          handleResponse
        )
      )
    }
  } catch (err) {
    // if we aren't wrapped by base-server handle here
    if (!activeSpan && !(err instanceof NoFallbackError)) {
      await routeModule.onRequestError(req, err, {
        routerKind: 'App Router',
        routePath: normalizedSrcPage,
        routeType: 'route',
        revalidateReason: getRevalidateReason({
          isRevalidate,
          isOnDemandRevalidate,
        }),
      })
    }

    // rethrow so that we can handle serving error page

    // If this is during static generation, throw the error again.
    if (isIsr) throw err

    // Otherwise, send a 500 response.
    await sendResponse(
      nodeNextReq,
      nodeNextRes,
      new Response(null, { status: 500 })
    )
    return null
  }
}