forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp-route.ts
More file actions
165 lines (146 loc) · 5.1 KB
/
Copy pathapp-route.ts
File metadata and controls
165 lines (146 loc) · 5.1 KB
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
import type { ExportRouteResult, FileWriter } from '../types'
import type AppRouteRouteModule from '../../server/route-modules/app-route/module'
import type { AppRouteRouteHandlerContext } from '../../server/route-modules/app-route/module'
import type { IncrementalCache } from '../../server/lib/incremental-cache'
import { join } from 'path'
import {
NEXT_BODY_SUFFIX,
NEXT_CACHE_TAGS_HEADER,
NEXT_META_SUFFIX,
} from '../../lib/constants'
import { NodeNextRequest } from '../../server/base-http/node'
import { RouteModuleLoader } from '../../server/lib/module-loader/route-module-loader'
import {
NextRequestAdapter,
signalFromNodeResponse,
} from '../../server/web/spec-extension/adapters/next-request'
import { toNodeOutgoingHttpHeaders } from '../../server/web/utils'
import type {
MockedRequest,
MockedResponse,
} from '../../server/lib/mock-request'
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'
import { SERVER_DIRECTORY } from '../../shared/lib/constants'
import { hasNextSupport } from '../../server/ci-info'
import { isStaticGenEnabled } from '../../server/route-modules/app-route/helpers/is-static-gen-enabled'
import type { ExperimentalConfig } from '../../server/config-shared'
import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import type { Params } from '../../server/request/params'
export const enum ExportedAppRouteFiles {
BODY = 'BODY',
META = 'META',
}
export async function exportAppRoute(
req: MockedRequest,
res: MockedResponse,
params: Params | undefined,
page: string,
incrementalCache: IncrementalCache | undefined,
distDir: string,
htmlFilepath: string,
fileWriter: FileWriter,
experimental: Required<Pick<ExperimentalConfig, 'after' | 'dynamicIO'>>,
buildId: string
): Promise<ExportRouteResult> {
// Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}`
// Adapt the request and response to the Next.js request and response.
const request = NextRequestAdapter.fromNodeNextRequest(
new NodeNextRequest(req),
signalFromNodeResponse(res)
)
// Create the context for the handler. This contains the params from
// the route and the context for the request.
const context: AppRouteRouteHandlerContext = {
params,
prerenderManifest: {
version: 4,
routes: {},
dynamicRoutes: {},
preview: {
previewModeEncryptionKey: '',
previewModeId: '',
previewModeSigningKey: '',
},
notFoundRoutes: [],
},
renderOpts: {
experimental,
nextExport: true,
supportsDynamicResponse: false,
incrementalCache,
waitUntil: undefined,
onClose: undefined,
buildId,
},
}
if (hasNextSupport) {
context.renderOpts.isRevalidate = true
}
// This is a route handler, which means it has it's handler in the
// bundled file already, we should just use that.
const filename = join(distDir, SERVER_DIRECTORY, 'app', page)
try {
// Route module loading and handling.
const module = await RouteModuleLoader.load<AppRouteRouteModule>(filename)
const userland = module.userland
// we don't bail from the static optimization for
// metadata routes
const normalizedPage = normalizeAppPath(page)
const isMetadataRoute = isMetadataRouteFile(normalizedPage, [], false)
if (
!isStaticGenEnabled(userland) &&
!isMetadataRoute &&
// We don't disable static gen when dynamicIO is enabled because we
// expect that anything dynamic in the GET handler will make it dynamic
// and thus avoid the cache surprises that led to us removing static gen
// unless specifically opted into
experimental.dynamicIO !== true
) {
return { revalidate: 0 }
}
const response = await module.handle(request, context)
const isValidStatus = response.status < 400 || response.status === 404
if (!isValidStatus) {
return { revalidate: 0 }
}
const blob = await response.blob()
const revalidate =
typeof context.renderOpts.store?.revalidate === 'undefined'
? false
: context.renderOpts.store.revalidate
const headers = toNodeOutgoingHttpHeaders(response.headers)
const cacheTags = (context.renderOpts as any).fetchTags
if (cacheTags) {
headers[NEXT_CACHE_TAGS_HEADER] = cacheTags
}
if (!headers['content-type'] && blob.type) {
headers['content-type'] = blob.type
}
// Writing response body to a file.
const body = Buffer.from(await blob.arrayBuffer())
await fileWriter(
ExportedAppRouteFiles.BODY,
htmlFilepath.replace(/\.html$/, NEXT_BODY_SUFFIX),
body,
'utf8'
)
// Write the request metadata to a file.
const meta = { status: response.status, headers }
await fileWriter(
ExportedAppRouteFiles.META,
htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX),
JSON.stringify(meta)
)
return {
revalidate: revalidate,
metadata: meta,
}
} catch (err) {
if (!isDynamicUsageError(err)) {
throw err
}
return { revalidate: 0 }
}
}