/
app-renderer.tsx
327 lines (298 loc) · 8.36 KB
/
app-renderer.tsx
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
// Provided by the rust generate code
type FileType =
| 'layout'
| 'template'
| 'error'
| 'loading'
| 'not-found'
| 'head'
declare global {
// an tree of all layouts and the page
const LOADER_TREE: LoaderTree
// array of chunks for the bootstrap script
const BOOTSTRAP: string[]
const IPC: Ipc<unknown, unknown>
}
import type { Ipc } from '@vercel/turbopack-node/ipc/index'
import type { IncomingMessage } from 'node:http'
import type { ClientReferenceManifest } from 'next/dist/build/webpack/plugins/flight-manifest-plugin'
import type { RenderData } from 'types/turbopack'
import type { RenderOpts } from 'next/dist/server/app-render/types'
import { renderToHTMLOrFlight } from 'next/dist/server/app-render/app-render'
import { RSC_VARY_HEADER } from 'next/dist/client/components/app-router-headers'
import { headersFromEntries, initProxiedHeaders } from '../internal/headers'
import { parse, ParsedUrlQuery } from 'node:querystring'
import { PassThrough } from 'node:stream'
;('TURBOPACK { transition: next-layout-entry; chunking-type: isolatedParallel }')
// @ts-ignore
import layoutEntry from './app/layout-entry'
import { createServerResponse } from '../internal/http'
globalThis.__next_require__ = (data) => {
const [, , ssr_id] = JSON.parse(data)
return __turbopack_require__(ssr_id)
}
globalThis.__next_chunk_load__ = () => Promise.resolve()
process.env.__NEXT_NEW_LINK_BEHAVIOR = 'true'
const ipc = IPC as Ipc<IpcIncomingMessage, IpcOutgoingMessage>
type IpcIncomingMessage = {
type: 'headers'
data: RenderData
}
type IpcOutgoingMessage =
| {
type: 'headers'
data: {
status: number
headers: [string, string][]
}
}
| {
type: 'bodyChunk'
data: number[]
}
| {
type: 'bodyEnd'
}
const MIME_TEXT_HTML_UTF8 = 'text/html; charset=utf-8'
;(async () => {
while (true) {
const msg = await ipc.recv()
let renderData: RenderData
switch (msg.type) {
case 'headers': {
renderData = msg.data
break
}
default: {
console.error('unexpected message type', msg.type)
process.exit(1)
}
}
const result = await runOperation(renderData)
if (result == null) {
throw new Error('no html returned')
}
ipc.send({
type: 'headers',
data: {
status: result.statusCode,
headers: result.headers,
},
})
for await (const chunk of result.body) {
ipc.send({
type: 'bodyChunk',
data: (chunk as Buffer).toJSON().data,
})
}
ipc.send({ type: 'bodyEnd' })
}
})().catch((err) => {
ipc.sendError(err)
})
// TODO expose these types in next.js
type ComponentModule = () => any
type ModuleReference = [componentModule: ComponentModule, filePath: string]
export type ComponentsType = {
[componentKey in FileType]?: ModuleReference
} & {
page?: ModuleReference
}
type LoaderTree = [
segment: string,
parallelRoutes: { [parallelRouterKey: string]: LoaderTree },
components: ComponentsType
]
async function runOperation(renderData: RenderData) {
const proxyMethodsForModule = (
id: string
): ProxyHandler<ClientReferenceManifest['ssrModuleMapping']> => {
return {
get(_target, prop: string) {
return {
id,
chunks: JSON.parse(id)[1],
name: prop,
}
},
}
}
const proxyMethodsNested = (
type: 'ssrModuleMapping' | 'clientModules' | 'entryCSSFiles'
): ProxyHandler<
| ClientReferenceManifest['ssrModuleMapping']
| ClientReferenceManifest['clientModules']
| ClientReferenceManifest['entryCSSFiles']
> => {
return {
get(_target, key: string) {
if (type === 'ssrModuleMapping') {
return new Proxy({}, proxyMethodsForModule(key as string))
}
if (type === 'clientModules') {
// The key is a `${file}#${name}`, but `file` can contain `#` itself.
// There are 2 possibilities:
// "file#" => id = "file", name = ""
// "file#foo" => id = "file", name = "foo"
const pos = key.lastIndexOf('#')
let id = key
let name = ''
if (pos !== -1) {
id = key.slice(0, pos)
name = key.slice(pos + 1)
} else {
throw new Error('keys need to be formatted as {file}#{name}')
}
return {
id,
name,
chunks: JSON.parse(id)[1],
}
}
if (type === 'entryCSSFiles') {
const cssChunks = JSON.parse(key)
// TODO(WEB-856) subscribe to changes
return {
modules: [],
files: cssChunks.filter(filterAvailable).map(toPath),
}
}
},
}
}
const proxyMethods = (): ProxyHandler<ClientReferenceManifest> => {
const clientModulesProxy = new Proxy(
{},
proxyMethodsNested('clientModules')
)
const ssrModuleMappingProxy = new Proxy(
{},
proxyMethodsNested('ssrModuleMapping')
)
const entryCSSFilesProxy = new Proxy(
{},
proxyMethodsNested('entryCSSFiles')
)
return {
get(_target: any, prop: string) {
if (prop === 'ssrModuleMapping') {
return ssrModuleMappingProxy
}
if (prop === 'clientModules') {
return clientModulesProxy
}
if (prop === 'entryCSSFiles') {
return entryCSSFilesProxy
}
},
}
}
const availableModules = new Set()
const toPath = (chunk: ChunkData) =>
typeof chunk === 'string' ? chunk : chunk.path
/// determines if a chunk is needed based on the current available modules
const filterAvailable = (chunk: ChunkData) => {
if (typeof chunk === 'string') {
return true
} else {
let includedList = chunk.included || []
if (includedList.length === 0) {
return true
}
let needed = false
for (const item of includedList) {
if (!availableModules.has(item)) {
availableModules.add(item)
needed = true
}
}
return needed
}
}
const manifest: ClientReferenceManifest = new Proxy({} as any, proxyMethods())
const req: IncomingMessage = {
url: renderData.originalUrl,
method: renderData.method,
headers: initProxiedHeaders(
headersFromEntries(renderData.rawHeaders),
renderData.data?.serverInfo
),
} as any
const res = createServerResponse(req, renderData.path)
const query = parse(renderData.rawQuery)
const renderOpt: Omit<
RenderOpts,
'App' | 'Document' | 'Component' | 'pathname'
> & {
params: ParsedUrlQuery
} = {
// TODO: give an actual buildId when next build is supported
buildId: 'development',
params: renderData.params,
supportsDynamicHTML: true,
dev: true,
buildManifest: {
polyfillFiles: [],
rootMainFiles: BOOTSTRAP.filter((path) => path.endsWith('.js')),
devFiles: [],
ampDevFiles: [],
lowPriorityFiles: [],
pages: {
'/_app': [],
},
ampFirstPages: [],
},
ComponentMod: {
...layoutEntry,
default: undefined,
tree: LOADER_TREE,
pages: ['page.js'],
},
clientReferenceManifest: manifest,
runtime: 'nodejs',
serverComponents: true,
assetPrefix: '',
pageConfig: {},
reactLoadableManifest: {},
nextConfigOutput: renderData.data?.nextConfigOutput,
}
const result = await renderToHTMLOrFlight(
req,
res,
renderData.path,
query,
renderOpt as any as RenderOpts
)
if (!result || result.isNull())
throw new Error('rendering was not successful')
const body = new PassThrough()
if (result.isDynamic()) {
result.pipe(body)
} else {
body.write(result.toUnchunkedString())
}
return {
statusCode: res.statusCode,
headers: [
['Content-Type', result.contentType() ?? MIME_TEXT_HTML_UTF8],
['Vary', RSC_VARY_HEADER],
] as [string, string][],
body,
}
}
// This utility is based on https://github.com/zertosh/htmlescape
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
const ESCAPE_LOOKUP = {
'&': '\\u0026',
'>': '\\u003e',
'<': '\\u003c',
'\u2028': '\\u2028',
'\u2029': '\\u2029',
}
const ESCAPE_REGEX = /[&><\u2028\u2029]/g
export function htmlEscapeJsonString(str: string) {
return str.replace(
ESCAPE_REGEX,
(match) => ESCAPE_LOOKUP[match as keyof typeof ESCAPE_LOOKUP]
)
}