-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
Copy pathmodule.ts
474 lines (420 loc) · 17.6 KB
/
module.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
import type { NextConfig } from '../../../config-shared'
import type { AppRouteRouteDefinition } from '../../route-definitions/app-route-route-definition'
import type { AppConfig } from '../../../../build/utils'
import type { NextRequest } from '../../../web/spec-extension/request'
import type { PrerenderManifest } from '../../../../build'
import {
RouteModule,
type RouteModuleHandleContext,
type RouteModuleOptions,
} from '../route-module'
import {
RequestAsyncStorageWrapper,
type RequestContext,
} from '../../../async-storage/request-async-storage-wrapper'
import {
StaticGenerationAsyncStorageWrapper,
type StaticGenerationContext,
} from '../../../async-storage/static-generation-async-storage-wrapper'
import {
handleBadRequestResponse,
handleInternalServerErrorResponse,
} from '../helpers/response-handlers'
import { type HTTP_METHOD, HTTP_METHODS, isHTTPMethod } from '../../../web/http'
import { addImplicitTags, patchFetch } from '../../../lib/patch-fetch'
import { getTracer } from '../../../lib/trace/tracer'
import { AppRouteRouteHandlersSpan } from '../../../lib/trace/constants'
import { getPathnameFromAbsolutePath } from './helpers/get-pathname-from-absolute-path'
import { proxyRequest } from './helpers/proxy-request'
import { resolveHandlerError } from './helpers/resolve-handler-error'
import * as Log from '../../../../build/output/log'
import { autoImplementMethods } from './helpers/auto-implement-methods'
import { getNonStaticMethods } from './helpers/get-non-static-methods'
import { appendMutableCookies } from '../../../web/spec-extension/adapters/request-cookies'
import { parsedUrlQueryToParams } from './helpers/parsed-url-query-to-params'
import * as serverHooks from '../../../../client/components/hooks-server-context'
import * as headerHooks from '../../../../client/components/headers'
import { staticGenerationBailout } from '../../../../client/components/static-generation-bailout'
import { requestAsyncStorage } from '../../../../client/components/request-async-storage.external'
import { staticGenerationAsyncStorage } from '../../../../client/components/static-generation-async-storage.external'
import { actionAsyncStorage } from '../../../../client/components/action-async-storage.external'
import * as sharedModules from './shared-modules'
import { getIsServerAction } from '../../../lib/server-action-request-meta'
/**
* The AppRouteModule is the type of the module exported by the bundled App
* Route module.
*/
export type AppRouteModule =
typeof import('../../../../build/templates/app-route')
/**
* AppRouteRouteHandlerContext is the context that is passed to the route
* handler for app routes.
*/
export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext {
renderOpts: StaticGenerationContext['renderOpts']
prerenderManifest: PrerenderManifest
}
/**
* AppRouteHandlerFnContext is the context that is passed to the handler as the
* second argument.
*/
type AppRouteHandlerFnContext = {
params?: Record<string, string | string[]>
}
/**
* Handler function for app routes. If a non-Response value is returned, an error
* will be thrown.
*/
export type AppRouteHandlerFn = (
/**
* Incoming request object.
*/
req: NextRequest,
/**
* Context properties on the request (including the parameters if this was a
* dynamic route).
*/
ctx: AppRouteHandlerFnContext
) => unknown
/**
* AppRouteHandlers describes the handlers for app routes that is provided by
* the userland module.
*/
export type AppRouteHandlers = {
[method in HTTP_METHOD]?: AppRouteHandlerFn
}
/**
* AppRouteUserlandModule is the userland module that is provided for app
* routes. This contains all the user generated code.
*/
export type AppRouteUserlandModule = AppRouteHandlers &
Pick<AppConfig, 'dynamic' | 'revalidate' | 'dynamicParams' | 'fetchCache'> & {
// TODO: (wyattjoh) create a type for this
generateStaticParams?: any
}
/**
* AppRouteRouteModuleOptions is the options that are passed to the app route
* module from the bundled code.
*/
export interface AppRouteRouteModuleOptions
extends RouteModuleOptions<AppRouteRouteDefinition, AppRouteUserlandModule> {
readonly resolvedPagePath: string
readonly nextConfigOutput: NextConfig['output']
}
/**
* AppRouteRouteHandler is the handler for app routes.
*/
export class AppRouteRouteModule extends RouteModule<
AppRouteRouteDefinition,
AppRouteUserlandModule
> {
/**
* A reference to the request async storage.
*/
public readonly requestAsyncStorage = requestAsyncStorage
/**
* A reference to the static generation async storage.
*/
public readonly staticGenerationAsyncStorage = staticGenerationAsyncStorage
/**
* An interface to call server hooks which interact with the underlying
* storage.
*/
public readonly serverHooks = serverHooks
/**
* An interface to call header hooks which interact with the underlying
* request storage.
*/
public readonly headerHooks = headerHooks
/**
* An interface to call static generation bailout hooks which interact with
* the underlying static generation storage.
*/
public readonly staticGenerationBailout = staticGenerationBailout
public static readonly sharedModules = sharedModules
/**
* A reference to the mutation related async storage, such as mutations of
* cookies.
*/
public readonly actionAsyncStorage = actionAsyncStorage
public readonly resolvedPagePath: string
public readonly nextConfigOutput: NextConfig['output'] | undefined
private readonly methods: Record<HTTP_METHOD, AppRouteHandlerFn>
private readonly nonStaticMethods: ReadonlyArray<HTTP_METHOD> | false
private readonly dynamic: AppRouteUserlandModule['dynamic']
constructor({
userland,
definition,
resolvedPagePath,
nextConfigOutput,
}: AppRouteRouteModuleOptions) {
super({ userland, definition })
this.resolvedPagePath = resolvedPagePath
this.nextConfigOutput = nextConfigOutput
// Automatically implement some methods if they aren't implemented by the
// userland module.
this.methods = autoImplementMethods(userland)
// Get the non-static methods for this route.
this.nonStaticMethods = getNonStaticMethods(userland)
// Get the dynamic property from the userland module.
this.dynamic = this.userland.dynamic
if (this.nextConfigOutput === 'export') {
if (!this.dynamic || this.dynamic === 'auto') {
this.dynamic = 'error'
} else if (this.dynamic === 'force-dynamic') {
throw new Error(
`export const dynamic = "force-dynamic" on page "${definition.pathname}" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`
)
}
}
// We only warn in development after here, so return if we're not in
// development.
if (process.env.NODE_ENV === 'development') {
// Print error in development if the exported handlers are in lowercase, only
// uppercase handlers are supported.
const lowercased = HTTP_METHODS.map((method) => method.toLowerCase())
for (const method of lowercased) {
if (method in this.userland) {
Log.error(
`Detected lowercase method '${method}' in '${
this.resolvedPagePath
}'. Export the uppercase '${method.toUpperCase()}' method name to fix this error.`
)
}
}
// Print error if the module exports a default handler, they must use named
// exports for each HTTP method.
if ('default' in this.userland) {
Log.error(
`Detected default export in '${this.resolvedPagePath}'. Export a named export for each HTTP method instead.`
)
}
// If there is no methods exported by this module, then return a not found
// response.
if (!HTTP_METHODS.some((method) => method in this.userland)) {
Log.error(
`No HTTP methods exported in '${this.resolvedPagePath}'. Export a named export for each HTTP method.`
)
}
}
}
/**
* Resolves the handler function for the given method.
*
* @param method the requested method
* @returns the handler function for the given method
*/
private resolve(method: string): AppRouteHandlerFn {
// Ensure that the requested method is a valid method (to prevent RCE's).
if (!isHTTPMethod(method)) return handleBadRequestResponse
// Return the handler.
return this.methods[method]
}
/**
* Executes the route handler.
*/
private async execute(
request: NextRequest,
context: AppRouteRouteHandlerContext
): Promise<Response> {
// Get the handler function for the given method.
const handler = this.resolve(request.method)
// Get the context for the request.
const requestContext: RequestContext = {
req: request,
}
// TODO: types for renderOpts should include previewProps
;(requestContext as any).renderOpts = {
previewProps: context.prerenderManifest.preview,
}
// Get the context for the static generation.
const staticGenerationContext: StaticGenerationContext = {
urlPathname: request.nextUrl.pathname,
renderOpts: context.renderOpts,
}
// Add the fetchCache option to the renderOpts.
staticGenerationContext.renderOpts.fetchCache = this.userland.fetchCache
// Run the handler with the request AsyncLocalStorage to inject the helper
// support. We set this to `unknown` because the type is not known until
// runtime when we do a instanceof check below.
const response: unknown = await this.actionAsyncStorage.run(
{
isAppRoute: true,
isAction: getIsServerAction(request),
},
() =>
RequestAsyncStorageWrapper.wrap(
this.requestAsyncStorage,
requestContext,
() =>
StaticGenerationAsyncStorageWrapper.wrap(
this.staticGenerationAsyncStorage,
staticGenerationContext,
(staticGenerationStore) => {
// Check to see if we should bail out of static generation based on
// having non-static methods.
if (this.nonStaticMethods) {
this.staticGenerationBailout(
`non-static methods used ${this.nonStaticMethods.join(
', '
)}`
)
}
// Update the static generation store based on the dynamic property.
switch (this.dynamic) {
case 'force-dynamic':
// The dynamic property is set to force-dynamic, so we should
// force the page to be dynamic.
staticGenerationStore.forceDynamic = true
this.staticGenerationBailout(`force-dynamic`, {
dynamic: this.dynamic,
})
break
case 'force-static':
// The dynamic property is set to force-static, so we should
// force the page to be static.
staticGenerationStore.forceStatic = true
break
case 'error':
// The dynamic property is set to error, so we should throw an
// error if the page is being statically generated.
staticGenerationStore.dynamicShouldError = true
break
default:
break
}
// If the static generation store does not have a revalidate value
// set, then we should set it the revalidate value from the userland
// module or default to false.
staticGenerationStore.revalidate ??=
this.userland.revalidate ?? false
// Wrap the request so we can add additional functionality to cases
// that might change it's output or affect the rendering.
const wrappedRequest = proxyRequest(
request,
{ dynamic: this.dynamic },
{
headerHooks: this.headerHooks,
serverHooks: this.serverHooks,
staticGenerationBailout: this.staticGenerationBailout,
}
)
// TODO: propagate this pathname from route matcher
const route = getPathnameFromAbsolutePath(this.resolvedPagePath)
getTracer().getRootSpanAttributes()?.set('next.route', route)
return getTracer().trace(
AppRouteRouteHandlersSpan.runHandler,
{
spanName: `executing api route (app) ${route}`,
attributes: {
'next.route': route,
},
},
async () => {
// Patch the global fetch.
patchFetch({
serverHooks: this.serverHooks,
staticGenerationAsyncStorage:
this.staticGenerationAsyncStorage,
})
const res = await handler(wrappedRequest, {
params: context.params
? parsedUrlQueryToParams(context.params)
: undefined,
})
if (!(res instanceof Response)) {
throw new Error(
`No response is returned from route handler '${this.resolvedPagePath}'. Ensure you return a \`Response\` or a \`NextResponse\` in all branches of your handler.`
)
}
;(context.renderOpts as any).fetchMetrics =
staticGenerationStore.fetchMetrics
context.renderOpts.waitUntil = Promise.all(
Object.values(
staticGenerationStore.pendingRevalidates || []
)
)
addImplicitTags(staticGenerationStore)
;(context.renderOpts as any).fetchTags =
staticGenerationStore.tags?.join(',')
// It's possible cookies were set in the handler, so we need
// to merge the modified cookies and the returned response
// here.
const requestStore = this.requestAsyncStorage.getStore()
if (requestStore && requestStore.mutableCookies) {
const headers = new Headers(res.headers)
if (
appendMutableCookies(
headers,
requestStore.mutableCookies
)
) {
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers,
})
}
}
return res
}
)
}
)
)
)
// If the handler did't return a valid response, then return the internal
// error response.
if (!(response instanceof Response)) {
// TODO: validate the correct handling behavior, maybe log something?
return handleInternalServerErrorResponse()
}
if (response.headers.has('x-middleware-rewrite')) {
// TODO: move this error into the `NextResponse.rewrite()` function.
// TODO-APP: re-enable support below when we can proxy these type of requests
throw new Error(
'NextResponse.rewrite() was used in a app route handler, this is not currently supported. Please remove the invocation to continue.'
)
// // This is a rewrite created via `NextResponse.rewrite()`. We need to send
// // the response up so it can be handled by the backing server.
// // If the server is running in minimal mode, we just want to forward the
// // response (including the rewrite headers) upstream so it can perform the
// // redirect for us, otherwise return with the special condition so this
// // server can perform a rewrite.
// if (!minimalMode) {
// return { response, condition: 'rewrite' }
// }
// // Relativize the url so it's relative to the base url. This is so the
// // outgoing headers upstream can be relative.
// const rewritePath = response.headers.get('x-middleware-rewrite')!
// const initUrl = getRequestMeta(req, 'initURL')!
// const { pathname } = parseUrl(relativizeURL(rewritePath, initUrl))
// response.headers.set('x-middleware-rewrite', pathname)
}
if (response.headers.get('x-middleware-next') === '1') {
// TODO: move this error into the `NextResponse.next()` function.
throw new Error(
'NextResponse.next() was used in a app route handler, this is not supported. See here for more info: https://nextjs.org/docs/messages/next-response-next-in-app-route-handler'
)
}
return response
}
public async handle(
request: NextRequest,
context: AppRouteRouteHandlerContext
): Promise<Response> {
try {
// Execute the route to get the response.
const response = await this.execute(request, context)
// The response was handled, return it.
return response
} catch (err) {
// Try to resolve the error to a response, else throw it again.
const response = resolveHandlerError(err)
if (!response) throw err
// The response was resolved, return it.
return response
}
}
}
export default AppRouteRouteModule