-
Notifications
You must be signed in to change notification settings - Fork 26.1k
/
app-render.tsx
952 lines (840 loc) · 27.8 KB
/
app-render.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
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'http'
import type { LoadComponentsReturnType } from './load-components'
import type { ServerRuntime } from './config-shared'
import React from 'react'
import { ParsedUrlQuery, stringify as stringifyQuery } from 'querystring'
import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-webpack'
import { renderToReadableStream } from 'next/dist/compiled/react-server-dom-webpack/writer.browser.server'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
import { NextParsedUrlQuery } from './request-meta'
import RenderResult from './render-result'
import {
readableStreamTee,
encodeText,
decodeText,
renderToInitialStream,
createBufferedTransformStream,
continueFromInitialStream,
createPrefixStream,
} from './node-web-streams-helper'
import { isDynamicRoute } from '../shared/lib/router/utils'
import { tryGetPreviewData } from './api-utils/node'
import { htmlEscapeJsonString } from './htmlescape'
import { shouldUseReactRoot, stripInternalQueries } from './utils'
import { NextApiRequestCookies } from './api-utils'
import { matchSegment } from '../client/components/match-segments'
// this needs to be required lazily so that `next-server` can set
// the env before we require
const ReactDOMServer = shouldUseReactRoot
? require('react-dom/server.browser')
: require('react-dom/server')
export type RenderOptsPartial = {
err?: Error | null
dev?: boolean
serverComponentManifest?: any
supportsDynamicHTML?: boolean
runtime?: ServerRuntime
serverComponents?: boolean
}
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
function interopDefault(mod: any) {
return mod.default || mod
}
const rscCache = new Map()
// Shadowing check does not work with TypeScript enums
// eslint-disable-next-line no-shadow
const enum RecordStatus {
Pending,
Resolved,
Rejected,
}
type Record = {
status: RecordStatus
value: any
}
function createRecordFromThenable(thenable: Promise<any>) {
const record: Record = {
status: RecordStatus.Pending,
value: thenable,
}
thenable.then(
function (value) {
if (record.status === RecordStatus.Pending) {
const resolvedRecord = record
resolvedRecord.status = RecordStatus.Resolved
resolvedRecord.value = value
}
},
function (err) {
if (record.status === RecordStatus.Pending) {
const rejectedRecord = record
rejectedRecord.status = RecordStatus.Rejected
rejectedRecord.value = err
}
}
)
return record
}
function readRecordValue(record: Record) {
if (record.status === RecordStatus.Resolved) {
return record.value
} else {
throw record.value
}
}
function preloadDataFetchingRecord(
map: Map<string, Record>,
key: string,
fetcher: () => Promise<any> | any
) {
let record = map.get(key)
if (!record) {
const thenable = fetcher()
record = createRecordFromThenable(thenable)
map.set(key, record)
}
return record
}
function useFlightResponse(
writable: WritableStream<Uint8Array>,
cachePrefix: string,
req: ReadableStream<Uint8Array>,
serverComponentManifest: any,
cssFlightData: string
) {
const id = cachePrefix + ',' + (React as any).useId()
let entry = rscCache.get(id)
if (!entry) {
const [renderStream, forwardStream] = readableStreamTee(req)
entry = createFromReadableStream(renderStream, {
moduleMap: serverComponentManifest.__ssr_module_mapping__,
})
rscCache.set(id, entry)
let bootstrapped = false
// We only attach CSS chunks to the inlined data.
const forwardReader = forwardStream
.pipeThrough(createPrefixStream(cssFlightData))
.getReader()
const writer = writable.getWriter()
function process() {
forwardReader.read().then(({ done, value }) => {
if (!bootstrapped) {
bootstrapped = true
writer.write(
encodeText(
`<script>(self.__next_s=self.__next_s||[]).push(${htmlEscapeJsonString(
JSON.stringify([0, id])
)})</script>`
)
)
}
if (done) {
rscCache.delete(id)
writer.close()
} else {
const responsePartial = decodeText(value)
const scripts = `<script>(self.__next_s=self.__next_s||[]).push(${htmlEscapeJsonString(
JSON.stringify([1, id, responsePartial])
)})</script>`
writer.write(encodeText(scripts))
process()
}
})
}
process()
}
return entry
}
// Create the wrapper component for a Flight stream.
function createServerComponentRenderer(
ComponentToRender: React.ComponentType,
ComponentMod: any,
{
cachePrefix,
transformStream,
serverComponentManifest,
serverContexts,
}: {
cachePrefix: string
transformStream: TransformStream<Uint8Array, Uint8Array>
serverComponentManifest: NonNullable<RenderOpts['serverComponentManifest']>
serverContexts: Array<[ServerContextName: string, JSONValue: any]>
},
dev: boolean
) {
// We need to expose the `__webpack_require__` API globally for
// react-server-dom-webpack. This is a hack until we find a better way.
if (ComponentMod.__next_app_webpack_require__ || ComponentMod.__next_rsc__) {
// @ts-ignore
globalThis.__next_require__ =
ComponentMod.__next_app_webpack_require__ ||
ComponentMod.__next_rsc__.__webpack_require__
// @ts-ignore
globalThis.__next_chunk_load__ = () => Promise.resolve()
}
const cssFlightData = getCssFlightData(
ComponentMod,
serverComponentManifest,
dev
)
let RSCStream: ReadableStream<Uint8Array>
const createRSCStream = () => {
if (!RSCStream) {
RSCStream = renderToReadableStream(
<ComponentToRender />,
serverComponentManifest,
{
context: serverContexts,
}
)
}
return RSCStream
}
const writable = transformStream.writable
return function ServerComponentWrapper() {
const reqStream = createRSCStream()
const response = useFlightResponse(
writable,
cachePrefix,
reqStream,
serverComponentManifest,
cssFlightData
)
return response.readRoot()
}
}
type DynamicParamTypes = 'catchall' | 'optional-catchall' | 'dynamic'
// c = catchall
// oc = optional catchall
// d = dynamic
export type DynamicParamTypesShort = 'c' | 'oc' | 'd'
function getShortDynamicParamType(
type: DynamicParamTypes
): DynamicParamTypesShort {
switch (type) {
case 'catchall':
return 'c'
case 'optional-catchall':
return 'oc'
case 'dynamic':
return 'd'
default:
throw new Error('Unknown dynamic param type')
}
}
export type Segment =
| string
| [param: string, value: string, type: DynamicParamTypesShort]
type LoaderTree = [
segment: string,
parallelRoutes: { [parallelRouterKey: string]: LoaderTree },
components: {
layout?: () => any
loading?: () => any
page?: () => any
}
]
export type FlightRouterState = [
segment: Segment,
parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },
url?: string,
refresh?: 'refetch'
]
export type FlightSegmentPath =
| any[]
// Looks somewhat like this
| [
segment: Segment,
parallelRouterKey: string,
segment: Segment,
parallelRouterKey: string,
segment: Segment,
parallelRouterKey: string
]
export type FlightDataPath =
| any[]
// Looks somewhat like this
| [
segment: Segment,
parallelRoute: string,
segment: Segment,
parallelRoute: string,
segment: Segment,
parallelRoute: string,
tree: FlightRouterState,
subTreeData: React.ReactNode
]
export type FlightData = Array<FlightDataPath> | string
export type ChildProp = {
current: React.ReactNode
segment: Segment
}
function getSegmentParam(segment: string): {
param: string
type: DynamicParamTypes
} | null {
if (segment.startsWith('[[...') && segment.endsWith(']]')) {
return {
type: 'optional-catchall',
param: segment.slice(5, -2),
}
}
if (segment.startsWith('[...') && segment.endsWith(']')) {
return {
type: 'catchall',
param: segment.slice(4, -1),
}
}
if (segment.startsWith('[') && segment.endsWith(']')) {
return {
type: 'dynamic',
param: segment.slice(1, -1),
}
}
return null
}
function getCSSInlinedLinkTags(
ComponentMod: any,
serverComponentManifest: any,
dev: boolean
) {
if (dev) return []
const importedServerCSSFiles: string[] =
ComponentMod.__client__?.__next_rsc_css__ || []
return Array.from(
new Set(
importedServerCSSFiles
.map((css) =>
css.endsWith('.css')
? serverComponentManifest[css].default.chunks
: []
)
.flat()
)
)
}
function getCssFlightData(
ComponentMod: any,
serverComponentManifest: any,
dev: boolean
) {
const importedServerCSSFiles: string[] =
ComponentMod.__client__?.__next_rsc_css__ || []
const cssFiles = importedServerCSSFiles.map(
(css) => serverComponentManifest[css].default
)
if (dev) {
// Keep `id` in dev mode css flight to require the css module
return cssFiles.map((css) => `CSS:${JSON.stringify(css)}`).join('\n') + '\n'
}
// Multiple css chunks could be merged into one by mini-css-extract-plugin,
// we use a set here to dedupe the css chunks in production.
const cssSet: Set<string> = cssFiles.reduce((res, css) => {
res.add(...css.chunks)
return res
}, new Set())
return cssSet.size ? `CSS:${JSON.stringify({ chunks: [...cssSet] })}\n` : ''
}
export async function renderToHTML(
req: IncomingMessage,
res: ServerResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: RenderOpts,
isPagesDir: boolean
): Promise<RenderResult | null> {
// @ts-expect-error createServerContext exists in react@experimental + react-dom@experimental
if (typeof React.createServerContext === 'undefined') {
throw new Error(
'"app" directory requires React.createServerContext which is not available in the version of React you are using. Please update to react@experimental and react-dom@experimental.'
)
}
// don't modify original query object
query = Object.assign({}, query)
const {
buildManifest,
serverComponentManifest,
supportsDynamicHTML,
runtime,
ComponentMod,
} = renderOpts
const dev = !!renderOpts.dev
const isFlight = query.__flight__ !== undefined
if (isFlight && isPagesDir) {
stripInternalQueries(query)
const search = stringifyQuery(query)
// Empty so that the client-side router will do a full page navigation.
const flightData: FlightData = pathname + (search ? `?${search}` : '')
return new RenderResult(
renderToReadableStream(flightData, serverComponentManifest).pipeThrough(
createBufferedTransformStream()
)
)
}
// TODO-APP: verify the tree is valid
// TODO-APP: verify query param is single value (not an array)
// TODO-APP: verify tree can't grow out of control
const providedFlightRouterState: FlightRouterState = isFlight
? query.__flight_router_state_tree__
? JSON.parse(query.__flight_router_state_tree__ as string)
: {}
: undefined
stripInternalQueries(query)
const hasConcurrentFeatures = !!runtime
const pageIsDynamic = isDynamicRoute(pathname)
const LayoutRouter =
ComponentMod.LayoutRouter as typeof import('../client/components/layout-router.client').default
const HotReloader = ComponentMod.HotReloader as
| typeof import('../client/components/hot-reloader.client').default
| null
const headers = req.headers
// @ts-expect-error TODO-APP: fix type of req
const cookies = req.cookies
const tree: LoaderTree = ComponentMod.tree
// Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless.
const previewData = tryGetPreviewData(
req,
res,
(renderOpts as any).previewProps
)
const isPreview = previewData !== false
const serverContexts: Array<[string, any]> = [
['WORKAROUND', null], // TODO-APP: First value has a bug currently where the value is not set on the second request
['HeadersContext', headers],
['CookiesContext', cookies],
['PreviewDataContext', previewData],
]
const dataCache = new Map<string, Record>()
type CreateSegmentPath = (child: FlightSegmentPath) => FlightSegmentPath
const pathParams = (renderOpts as any).params as ParsedUrlQuery
const getDynamicParamFromSegment = (
// [id] or [slug]
segment: string
): {
param: string
value: string | string[] | null
treeValue: string
type: DynamicParamTypesShort
} | null => {
// TODO-APP: use correct matching for dynamic routes to get segment param
const segmentParam = getSegmentParam(segment)
if (!segmentParam) {
return null
}
const key = segmentParam.param
const value = pathParams[key]
if (!value) {
if (segmentParam.type === 'optional-catchall') {
return {
param: key,
value: null,
type: getShortDynamicParamType(segmentParam.type),
treeValue: '',
}
}
return null
}
return {
param: key,
value: value,
treeValue: Array.isArray(value) ? value.join('/') : value,
type: getShortDynamicParamType(segmentParam.type),
}
}
const createFlightRouterStateFromLoaderTree = ([
segment,
parallelRoutes,
]: LoaderTree): FlightRouterState => {
const dynamicParam = getDynamicParamFromSegment(segment)
const segmentTree: FlightRouterState = [
dynamicParam
? [dynamicParam.param, dynamicParam.treeValue, dynamicParam.type]
: segment,
{},
]
if (parallelRoutes) {
segmentTree[1] = Object.keys(parallelRoutes).reduce(
(existingValue, currentValue) => {
existingValue[currentValue] = createFlightRouterStateFromLoaderTree(
parallelRoutes[currentValue]
)
return existingValue
},
{} as FlightRouterState[1]
)
}
return segmentTree
}
const createComponentTree = ({
createSegmentPath,
tree: [segment, parallelRoutes, { layout, loading, page }],
parentParams,
firstItem,
}: {
createSegmentPath: CreateSegmentPath
tree: LoaderTree
parentParams: { [key: string]: any }
firstItem?: boolean
}): { Component: React.ComponentType } => {
const Loading = loading ? interopDefault(loading()) : undefined
const layoutOrPageMod = layout ? layout() : page ? page() : undefined
const isPage = typeof page !== undefined
const isClientComponentModule =
layoutOrPageMod && !layoutOrPageMod.hasOwnProperty('__next_rsc__')
// Only server components can have getServerSideProps / getStaticProps
// TODO-APP: friendly error with correct stacktrace. Potentially this can be part of the compiler instead.
if (isClientComponentModule) {
if (layoutOrPageMod.getServerSideProps) {
throw new Error(
'getServerSideProps is not supported on Client Components'
)
}
if (layoutOrPageMod.getStaticProps) {
throw new Error('getStaticProps is not supported on Client Components')
}
}
const Component = layoutOrPageMod
? interopDefault(layoutOrPageMod)
: undefined
const segmentParam = getDynamicParamFromSegment(segment)
const currentParams =
// Handle null case where dynamic param is optional
segmentParam && segmentParam.value !== null
? {
...parentParams,
[segmentParam.param]: segmentParam.value,
}
: parentParams
const actualSegment = segmentParam
? [segmentParam.param, segmentParam.treeValue]
: segment
// This happens outside of rendering in order to eagerly kick off data fetching for layouts / the page further down
const parallelRouteComponents = Object.keys(parallelRoutes).reduce(
(list, currentValue) => {
const currentSegmentPath = firstItem
? [currentValue]
: [actualSegment, currentValue]
const { Component: ChildComponent } = createComponentTree({
createSegmentPath: (child) => {
return createSegmentPath([...currentSegmentPath, ...child])
},
tree: parallelRoutes[currentValue],
parentParams: currentParams,
})
const childSegmentParam = getDynamicParamFromSegment(
parallelRoutes[currentValue][0]
)
const childProp: ChildProp = {
current: <ChildComponent />,
segment: childSegmentParam
? [
childSegmentParam.param,
childSegmentParam.treeValue,
childSegmentParam.type,
]
: parallelRoutes[currentValue][0],
}
list[currentValue] = (
<LayoutRouter
parallelRouterKey={currentValue}
segmentPath={createSegmentPath(currentSegmentPath)}
loading={Loading ? <Loading /> : undefined}
childProp={childProp}
/>
)
return list
},
{} as { [key: string]: React.ReactNode }
)
// When the segment does not have a layout/page we still have to add the layout router to ensure the path holds the loading component
if (!Component) {
return {
Component: () => <>{parallelRouteComponents.children}</>,
}
}
const segmentPath = createSegmentPath([actualSegment])
const dataCacheKey = JSON.stringify(segmentPath)
let fetcher: (() => Promise<any>) | null = null
type GetServerSidePropsContext = {
// TODO-APP: has to be serializable
headers: IncomingHttpHeaders
cookies: NextApiRequestCookies
layoutSegments: FlightSegmentPath
params?: { [key: string]: string | string[] }
preview?: boolean
previewData?: string | object | undefined
}
type getServerSidePropsContextPage = GetServerSidePropsContext & {
query: URLSearchParams
pathname: string
}
// TODO-APP: pass a shared cache from previous getStaticProps/getServerSideProps calls?
if (layoutOrPageMod.getServerSideProps) {
// TODO-APP: recommendation for i18n
// locales: (renderOpts as any).locales, // always the same
// locale: (renderOpts as any).locale, // /nl/something -> nl
// defaultLocale: (renderOpts as any).defaultLocale, // changes based on domain
const getServerSidePropsContext:
| GetServerSidePropsContext
| getServerSidePropsContextPage = {
headers,
cookies,
layoutSegments: segmentPath,
// TODO-APP: Currently query holds params and pathname is not the actual pathname, it holds the dynamic parameter
...(isPage ? { query, pathname } : {}),
...(pageIsDynamic ? { params: currentParams } : undefined),
...(isPreview
? { preview: true, previewData: previewData }
: undefined),
}
fetcher = () =>
Promise.resolve(
layoutOrPageMod.getServerSideProps(getServerSidePropsContext)
)
}
// TODO-APP: implement layout specific caching for getStaticProps
if (layoutOrPageMod.getStaticProps) {
const getStaticPropsContext = {
layoutSegments: segmentPath,
// TODO-APP: change this to be URLSearchParams instead?
...(isPage ? { pathname } : {}),
...(pageIsDynamic ? { params: currentParams } : undefined),
...(isPreview
? { preview: true, previewData: previewData }
: undefined),
}
fetcher = () =>
Promise.resolve(layoutOrPageMod.getStaticProps(getStaticPropsContext))
}
if (fetcher) {
// Kick off data fetching before rendering, this ensures there is no waterfall for layouts as
// all data fetching required to render the page is kicked off simultaneously
preloadDataFetchingRecord(dataCache, dataCacheKey, fetcher)
}
return {
Component: () => {
let props
if (fetcher) {
// The data fetching was kicked off before rendering (see above)
// if the data was not resolved yet the layout rendering will be suspended
const record = preloadDataFetchingRecord(
dataCache,
dataCacheKey,
fetcher
)
// Result of calling getStaticProps or getServerSideProps. If promise is not resolve yet it will suspend.
const recordValue = readRecordValue(record)
if (props) {
props = Object.assign({}, props, recordValue.props)
} else {
props = recordValue.props
}
}
return (
<Component
{...props}
{...parallelRouteComponents}
// TODO-APP: params and query have to be blocked parallel route names. Might have to add a reserved name list.
// Params are always the current params that apply to the layout
// If you have a `/dashboard/[team]/layout.js` it will provide `team` as a param but not anything further down.
params={currentParams}
// Query is only provided to page
{...(isPage ? { query } : {})}
/>
)
},
}
}
if (isFlight) {
// TODO-APP: throw on invalid flightRouterState
const walkTreeWithFlightRouterState = (
treeToFilter: LoaderTree,
parentParams: { [key: string]: string | string[] },
flightRouterState?: FlightRouterState,
parentRendered?: boolean
): FlightDataPath => {
const [segment, parallelRoutes] = treeToFilter
const parallelRoutesKeys = Object.keys(parallelRoutes)
const segmentParam = getDynamicParamFromSegment(segment)
const currentParams =
// Handle null case where dynamic param is optional
segmentParam && segmentParam.value !== null
? {
...parentParams,
[segmentParam.param]: segmentParam.value,
}
: parentParams
const actualSegment: Segment = segmentParam
? [segmentParam.param, segmentParam.treeValue, segmentParam.type]
: segment
const renderComponentsOnThisLevel =
!flightRouterState ||
!matchSegment(actualSegment, flightRouterState[0]) ||
// Last item in the tree
parallelRoutesKeys.length === 0 ||
// Explicit refresh
flightRouterState[3] === 'refetch'
if (!parentRendered && renderComponentsOnThisLevel) {
return [
actualSegment,
createFlightRouterStateFromLoaderTree(treeToFilter),
React.createElement(
createComponentTree(
// This ensures flightRouterPath is valid and filters down the tree
{
createSegmentPath: (child) => child,
tree: treeToFilter,
parentParams: currentParams,
firstItem: true,
}
).Component
),
]
}
for (const parallelRouteKey of parallelRoutesKeys) {
const parallelRoute = parallelRoutes[parallelRouteKey]
const path = walkTreeWithFlightRouterState(
parallelRoute,
currentParams,
flightRouterState && flightRouterState[1][parallelRouteKey],
parentRendered || renderComponentsOnThisLevel
)
if (typeof path[path.length - 1] !== 'string') {
return [actualSegment, parallelRouteKey, ...path]
}
}
return [actualSegment]
}
const cssFlightData = getCssFlightData(
ComponentMod,
serverComponentManifest,
dev
)
const flightData: FlightData = [
// TODO-APP: change walk to output without ''
walkTreeWithFlightRouterState(tree, {}, providedFlightRouterState).slice(
1
),
]
return new RenderResult(
renderToReadableStream(flightData, serverComponentManifest, {
context: serverContexts,
})
.pipeThrough(createPrefixStream(cssFlightData))
.pipeThrough(createBufferedTransformStream())
)
}
const search = stringifyQuery(query)
// TODO-APP: validate req.url as it gets passed to render.
const initialCanonicalUrl = req.url!
// TODO-APP: change tree to accommodate this
// /blog/[...slug]/page.js -> /blog/hello-world/b/c/d -> ['children', 'blog', 'children', ['slug', 'hello-world/b/c/d']]
// /blog/[slug] /blog/hello-world -> ['children', 'blog', 'children', ['slug', 'hello-world']]
const initialTree = createFlightRouterStateFromLoaderTree(tree)
const initialStylesheets: string[] = getCSSInlinedLinkTags(
ComponentMod,
serverComponentManifest,
dev
)
const { Component: ComponentTree } = createComponentTree({
createSegmentPath: (child) => child,
tree,
parentParams: {},
firstItem: true,
})
const AppRouter =
ComponentMod.AppRouter as typeof import('../client/components/app-router.client').default
const {
QueryContext,
PathnameContext,
// ParamsContext,
// LayoutSegmentsContext,
} = ComponentMod.hooksClientContext as typeof import('../client/components/hooks-client-context')
const WrappedComponentTreeWithRouter = () => {
return (
<QueryContext.Provider value={query}>
<PathnameContext.Provider value={pathname}>
{/* <ParamsContext.Provider value={pathParams}> */}
<AppRouter
hotReloader={HotReloader && <HotReloader assetPrefix="" />}
initialCanonicalUrl={initialCanonicalUrl}
initialTree={initialTree}
initialStylesheets={initialStylesheets}
>
<ComponentTree />
</AppRouter>
{/* </ParamsContext.Provider> */}
</PathnameContext.Provider>
</QueryContext.Provider>
)
}
const bootstrapScripts = buildManifest.rootMainFiles.map(
(src) => '/_next/' + src
)
let serverComponentsInlinedTransformStream: TransformStream<
Uint8Array,
Uint8Array
> | null = null
serverComponentsInlinedTransformStream = new TransformStream()
const Component = createServerComponentRenderer(
WrappedComponentTreeWithRouter,
ComponentMod,
{
cachePrefix: pathname + (search ? `?${search}` : ''),
transformStream: serverComponentsInlinedTransformStream,
serverComponentManifest,
serverContexts,
},
dev
)
const jsxStyleRegistry = createStyleRegistry()
const styledJsxFlushEffect = () => {
const styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
return <>{styles}</>
}
const AppContainer = ({ children }: { children: JSX.Element }) => (
<StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>
)
/**
* Rules of Static & Dynamic HTML:
*
* 1.) We must generate static HTML unless the caller explicitly opts
* in to dynamic HTML support.
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for an AMP page.
*
* These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended.
*/
const generateStaticHTML = supportsDynamicHTML !== true
const bodyResult = async () => {
const content = (
<AppContainer>
<Component />
</AppContainer>
)
const renderStream = await renderToInitialStream({
ReactDOMServer,
element: content,
streamOptions: {
bootstrapScripts,
},
})
const flushEffectHandler = (): string => {
const flushed = ReactDOMServer.renderToString(styledJsxFlushEffect())
return flushed
}
return await continueFromInitialStream(renderStream, {
dev,
dataStream: serverComponentsInlinedTransformStream?.readable,
generateStaticHTML: generateStaticHTML || !hasConcurrentFeatures,
flushEffectHandler,
})
}
return new RenderResult(await bodyResult())
}